text
stringlengths 54
60.6k
|
---|
<commit_before>/*
* Copyright (C) 2008-2010 Manjeet Dahiya
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include <iostream>
#include <QTextStream>
#include <QFile>
#include <QTime>
#include "QXmppLogger.h"
QXmppLogger* QXmppLogger::m_logger = 0;
static const char *typeName(QXmppLogger::MessageType type)
{
switch (type)
{
case QXmppLogger::DebugMessage:
return "DEBUG";
case QXmppLogger::InformationMessage:
return "INFO";
case QXmppLogger::WarningMessage:
return "WARNING";
case QXmppLogger::ReceivedMessage:
return "SERVER";
case QXmppLogger::SentMessage:
return "CLIENT";
default:
return "";
}
}
QXmppLogger::QXmppLogger(QObject *parent)
: QObject(parent), m_loggingType(QXmppLogger::NONE)
{
}
QXmppLogger* QXmppLogger::getLogger()
{
if(!m_logger)
{
m_logger = new QXmppLogger();
m_logger->setLoggingType(FILE);
}
return m_logger;
}
void QXmppLogger::setLoggingType(QXmppLogger::LoggingType log)
{
m_loggingType = log;
}
QXmppLogger::LoggingType QXmppLogger::loggingType()
{
return m_loggingType;
}
void QXmppLogger::log(QXmppLogger::MessageType type, const QString& str)
{
switch(m_loggingType)
{
case QXmppLogger::FILE:
{
QFile file("QXmppClientLog.log");
file.open(QIODevice::Append);
QTextStream stream(&file);
stream << QTime::currentTime().toString("hh:mm:ss.zzz") <<
" " << typeName(type) << " " <<
str << "\n\n";
}
break;
case QXmppLogger::STDOUT:
std::cout << typeName(type) << " " << qPrintable(str) << std::endl;
break;
default:
break;
}
emit message(type, str);
}
QXmppLogger::LoggingType QXmppLogger::getLoggingType()
{
return m_loggingType;
}
<commit_msg>don't emit signal when there is no logging<commit_after>/*
* Copyright (C) 2008-2010 Manjeet Dahiya
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include <iostream>
#include <QTextStream>
#include <QFile>
#include <QTime>
#include "QXmppLogger.h"
QXmppLogger* QXmppLogger::m_logger = 0;
static const char *typeName(QXmppLogger::MessageType type)
{
switch (type)
{
case QXmppLogger::DebugMessage:
return "DEBUG";
case QXmppLogger::InformationMessage:
return "INFO";
case QXmppLogger::WarningMessage:
return "WARNING";
case QXmppLogger::ReceivedMessage:
return "SERVER";
case QXmppLogger::SentMessage:
return "CLIENT";
default:
return "";
}
}
QXmppLogger::QXmppLogger(QObject *parent)
: QObject(parent), m_loggingType(QXmppLogger::NONE)
{
}
QXmppLogger* QXmppLogger::getLogger()
{
if(!m_logger)
{
m_logger = new QXmppLogger();
m_logger->setLoggingType(FILE);
}
return m_logger;
}
void QXmppLogger::setLoggingType(QXmppLogger::LoggingType log)
{
m_loggingType = log;
}
QXmppLogger::LoggingType QXmppLogger::loggingType()
{
return m_loggingType;
}
void QXmppLogger::log(QXmppLogger::MessageType type, const QString& str)
{
bool emitMessageSignal = true;
switch(m_loggingType)
{
case QXmppLogger::FILE:
{
QFile file("QXmppClientLog.log");
file.open(QIODevice::Append);
QTextStream stream(&file);
stream << QTime::currentTime().toString("hh:mm:ss.zzz") <<
" " << typeName(type) << " " <<
str << "\n\n";
}
break;
case QXmppLogger::STDOUT:
std::cout << typeName(type) << " " << qPrintable(str) << std::endl;
break;
default:
emitMessageSignal = false;
break;
}
if(emitMessageSignal)
emit message(type, str);
}
QXmppLogger::LoggingType QXmppLogger::getLoggingType()
{
return m_loggingType;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008-2009 Manjeet Dahiya
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "QXmppStanza.h"
#include "QXmppUtils.h"
#include "QXmppConstants.h"
#include <QDomElement>
#include <QXmlStreamWriter>
uint QXmppStanza::s_uniqeIdNo = 0;
QXmppStanza::Error::Error():
m_code(0),
m_type(static_cast<QXmppStanza::Error::Type>(-1)),
m_condition(static_cast<QXmppStanza::Error::Condition>(-1)),
m_text("")
{
}
QXmppStanza::Error::Error(Type type, Condition cond, const QString& text):
m_code(0),
m_type(type),
m_condition(cond),
m_text(text)
{
}
QXmppStanza::Error::Error(const QString& type, const QString& cond,
const QString& text):
m_code(0),
m_text(text)
{
setTypeFromStr(type);
setConditionFromStr(cond);
}
void QXmppStanza::Error::setText(const QString& text)
{
m_text = text;
}
void QXmppStanza::Error::setCode(int code)
{
m_code = code;
}
void QXmppStanza::Error::setCondition(QXmppStanza::Error::Condition cond)
{
m_condition = cond;
}
void QXmppStanza::Error::setType(QXmppStanza::Error::Type type)
{
m_type = type;
}
QString QXmppStanza::Error::getText() const
{
return m_text;
}
int QXmppStanza::Error::getCode() const
{
return m_code;
}
QXmppStanza::Error::Condition QXmppStanza::Error::getCondition() const
{
return m_condition;
}
QXmppStanza::Error::Type QXmppStanza::Error::getType() const
{
return m_type;
}
QString QXmppStanza::Error::getTypeStr() const
{
switch(m_type)
{
case Cancel:
return "cancel";
case Continue:
return "continue";
case Modify:
return "modify";
case Auth:
return "auth";
case Wait:
return "wait";
default:
return "";
}
}
QString QXmppStanza::Error::getConditionStr() const
{
switch(m_condition)
{
case BadRequest:
return "bad-request";
case Conflict:
return "conflict";
case FeatureNotImplemented:
return "feature-not-implemented";
case Forbidden:
return "forbidden";
case Gone:
return "gone";
case InternalServerError:
return "internal-server-error";
case ItemNotFound:
return "item-not-found";
case JidMalformed:
return "jid-malformed";
case NotAcceptable:
return "not-acceptable";
case NotAllowed:
return "not-allowed";
case NotAuthorized:
return "not-authorized";
case PaymentRequired:
return "payment-required";
case RecipientUnavailable:
return "recipient-unavailable";
case Redirect:
return "redirect";
case RegistrationRequired:
return "registration-required";
case RemoteServerNotFound:
return "remote-server-not-found";
case RemoteServerTimeout:
return "remote-server-timeout";
case ResourceConstraint:
return "resource-constraint";
case ServiceUnavailable:
return "service-unavailable";
case SubscriptionRequired:
return "subscription-required";
case UndefinedCondition:
return "undefined-condition";
case UnexpectedRequest:
return "unexpected-request";
default:
return "";
}
}
void QXmppStanza::Error::setTypeFromStr(const QString& type)
{
if(type == "cancel")
setType(Cancel);
else if(type == "continue")
setType(Continue);
else if(type == "modify")
setType(Modify);
else if(type == "auth")
setType(Auth);
else if(type == "wait")
setType(Wait);
else
setType(static_cast<QXmppStanza::Error::Type>(-1));
}
void QXmppStanza::Error::setConditionFromStr(const QString& type)
{
if(type == "bad-request")
setCondition(BadRequest);
else if(type == "conflict")
setCondition(Conflict);
else if(type == "feature-not-implemented")
setCondition(FeatureNotImplemented);
else if(type == "forbidden")
setCondition(Forbidden);
else if(type == "gone")
setCondition(Gone);
else if(type == "internal-server-error")
setCondition(InternalServerError);
else if(type == "item-not-found")
setCondition(ItemNotFound);
else if(type == "jid-malformed")
setCondition(JidMalformed);
else if(type == "not-acceptable")
setCondition(NotAcceptable);
else if(type == "not-allowed")
setCondition(NotAllowed);
else if(type == "not-authorized")
setCondition(NotAuthorized);
else if(type == "payment-required")
setCondition(PaymentRequired);
else if(type == "recipient-unavailable")
setCondition(RecipientUnavailable);
else if(type == "redirect")
setCondition(Redirect);
else if(type == "registration-required")
setCondition(RegistrationRequired);
else if(type == "remote-server-not-found")
setCondition(RemoteServerNotFound);
else if(type == "remote-server-timeout")
setCondition(RemoteServerTimeout);
else if(type == "resource-constraint")
setCondition(ResourceConstraint);
else if(type == "service-unavailable")
setCondition(ServiceUnavailable);
else if(type == "subscription-required")
setCondition(SubscriptionRequired);
else if(type == "undefined-condition")
setCondition(UndefinedCondition);
else if(type == "unexpected-request")
setCondition(UnexpectedRequest);
else
setCondition(static_cast<QXmppStanza::Error::Condition>(-1));
}
bool QXmppStanza::Error::isValid()
{
return !(getTypeStr().isEmpty() && getConditionStr().isEmpty());
}
void QXmppStanza::Error::parse(const QDomElement &errorElement)
{
setCode(errorElement.attribute("code").toInt());
setTypeFromStr(errorElement.attribute("type"));
QString text;
QString cond;
QDomElement element = errorElement.firstChildElement();
while(!element.isNull())
{
if(element.tagName() == "text")
text = element.text();
else if(element.namespaceURI() == ns_stanza)
{
cond = element.tagName();
}
element = element.nextSiblingElement();
}
setConditionFromStr(cond);
setText(text);
}
void QXmppStanza::Error::toXml( QXmlStreamWriter *writer ) const
{
QString cond = getConditionStr();
QString type = getTypeStr();
if(cond.isEmpty() && type.isEmpty())
return;
writer->writeStartElement("error");
helperToXmlAddAttribute(writer, "type", type);
if (m_code > 0)
helperToXmlAddAttribute(writer, "code", QString::number(m_code));
if(!cond.isEmpty())
{
writer->writeStartElement(cond);
helperToXmlAddAttribute(writer,"xmlns", ns_stanza);
writer->writeEndElement();
}
if(!m_text.isEmpty())
{
writer->writeStartElement("text");
helperToXmlAddAttribute(writer,"xml:lang", "en");
helperToXmlAddAttribute(writer,"xmlns", ns_stanza);
writer->writeCharacters(m_text);
writer->writeEndElement();
}
writer->writeEndElement();
}
QXmppStanza::QXmppStanza(const QString& from, const QString& to) : QXmppPacket(),
m_to(to), m_from(from)
{
}
QXmppStanza::~QXmppStanza()
{
}
QString QXmppStanza::to() const
{
return m_to;
}
void QXmppStanza::setTo(const QString& to)
{
m_to = to;
}
QString QXmppStanza::from() const
{
return m_from;
}
void QXmppStanza::setFrom(const QString& from)
{
m_from = from;
}
QString QXmppStanza::id() const
{
return m_id;
}
void QXmppStanza::setId(const QString& id)
{
m_id = id;
}
QString QXmppStanza::lang() const
{
return m_lang;
}
void QXmppStanza::setLang(const QString& lang)
{
m_lang = lang;
}
QXmppStanza::Error QXmppStanza::error() const
{
return m_error;
}
void QXmppStanza::setError(QXmppStanza::Error& error)
{
m_error = error;
}
QXmppElementList QXmppStanza::extensions() const
{
return m_extensions;
}
void QXmppStanza::setExtensions(const QXmppElementList &extensions)
{
m_extensions = extensions;
}
void QXmppStanza::generateAndSetNextId()
{
// get back
++s_uniqeIdNo;
m_id = "qxmpp" + QString::number(s_uniqeIdNo);
}
bool QXmppStanza::isErrorStanza()
{
return m_error.isValid();
}
void QXmppStanza::parse(const QDomElement &element)
{
m_from = element.attribute("from");
m_to = element.attribute("to");
m_id = element.attribute("id");
m_lang = element.attribute("lang");
QDomElement errorElement = element.firstChildElement("error");
if(!errorElement.isNull())
m_error.parse(errorElement);
}
// deprecated
QString QXmppStanza::getTo() const
{
return m_to;
}
QString QXmppStanza::getFrom() const
{
return m_from;
}
QString QXmppStanza::getId() const
{
return m_id;
}
QString QXmppStanza::getLang() const
{
return m_lang;
}
QXmppStanza::Error QXmppStanza::getError() const
{
return m_error;
}
<commit_msg>cleanup QXmppStanza::Error API<commit_after>/*
* Copyright (C) 2008-2009 Manjeet Dahiya
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "QXmppStanza.h"
#include "QXmppUtils.h"
#include "QXmppConstants.h"
#include <QDomElement>
#include <QXmlStreamWriter>
uint QXmppStanza::s_uniqeIdNo = 0;
QXmppStanza::Error::Error():
m_code(0),
m_type(static_cast<QXmppStanza::Error::Type>(-1)),
m_condition(static_cast<QXmppStanza::Error::Condition>(-1)),
m_text("")
{
}
QXmppStanza::Error::Error(Type type, Condition cond, const QString& text):
m_code(0),
m_type(type),
m_condition(cond),
m_text(text)
{
}
QXmppStanza::Error::Error(const QString& type, const QString& cond,
const QString& text):
m_code(0),
m_text(text)
{
setTypeFromStr(type);
setConditionFromStr(cond);
}
QString QXmppStanza::Error::text() const
{
return m_text;
}
void QXmppStanza::Error::setText(const QString& text)
{
m_text = text;
}
int QXmppStanza::Error::code() const
{
return m_code;
}
void QXmppStanza::Error::setCode(int code)
{
m_code = code;
}
QXmppStanza::Error::Condition QXmppStanza::Error::condition() const
{
return m_condition;
}
void QXmppStanza::Error::setCondition(QXmppStanza::Error::Condition cond)
{
m_condition = cond;
}
QXmppStanza::Error::Type QXmppStanza::Error::type() const
{
return m_type;
}
void QXmppStanza::Error::setType(QXmppStanza::Error::Type type)
{
m_type = type;
}
QString QXmppStanza::Error::getTypeStr() const
{
switch(m_type)
{
case Cancel:
return "cancel";
case Continue:
return "continue";
case Modify:
return "modify";
case Auth:
return "auth";
case Wait:
return "wait";
default:
return "";
}
}
QString QXmppStanza::Error::getConditionStr() const
{
switch(m_condition)
{
case BadRequest:
return "bad-request";
case Conflict:
return "conflict";
case FeatureNotImplemented:
return "feature-not-implemented";
case Forbidden:
return "forbidden";
case Gone:
return "gone";
case InternalServerError:
return "internal-server-error";
case ItemNotFound:
return "item-not-found";
case JidMalformed:
return "jid-malformed";
case NotAcceptable:
return "not-acceptable";
case NotAllowed:
return "not-allowed";
case NotAuthorized:
return "not-authorized";
case PaymentRequired:
return "payment-required";
case RecipientUnavailable:
return "recipient-unavailable";
case Redirect:
return "redirect";
case RegistrationRequired:
return "registration-required";
case RemoteServerNotFound:
return "remote-server-not-found";
case RemoteServerTimeout:
return "remote-server-timeout";
case ResourceConstraint:
return "resource-constraint";
case ServiceUnavailable:
return "service-unavailable";
case SubscriptionRequired:
return "subscription-required";
case UndefinedCondition:
return "undefined-condition";
case UnexpectedRequest:
return "unexpected-request";
default:
return "";
}
}
void QXmppStanza::Error::setTypeFromStr(const QString& type)
{
if(type == "cancel")
setType(Cancel);
else if(type == "continue")
setType(Continue);
else if(type == "modify")
setType(Modify);
else if(type == "auth")
setType(Auth);
else if(type == "wait")
setType(Wait);
else
setType(static_cast<QXmppStanza::Error::Type>(-1));
}
void QXmppStanza::Error::setConditionFromStr(const QString& type)
{
if(type == "bad-request")
setCondition(BadRequest);
else if(type == "conflict")
setCondition(Conflict);
else if(type == "feature-not-implemented")
setCondition(FeatureNotImplemented);
else if(type == "forbidden")
setCondition(Forbidden);
else if(type == "gone")
setCondition(Gone);
else if(type == "internal-server-error")
setCondition(InternalServerError);
else if(type == "item-not-found")
setCondition(ItemNotFound);
else if(type == "jid-malformed")
setCondition(JidMalformed);
else if(type == "not-acceptable")
setCondition(NotAcceptable);
else if(type == "not-allowed")
setCondition(NotAllowed);
else if(type == "not-authorized")
setCondition(NotAuthorized);
else if(type == "payment-required")
setCondition(PaymentRequired);
else if(type == "recipient-unavailable")
setCondition(RecipientUnavailable);
else if(type == "redirect")
setCondition(Redirect);
else if(type == "registration-required")
setCondition(RegistrationRequired);
else if(type == "remote-server-not-found")
setCondition(RemoteServerNotFound);
else if(type == "remote-server-timeout")
setCondition(RemoteServerTimeout);
else if(type == "resource-constraint")
setCondition(ResourceConstraint);
else if(type == "service-unavailable")
setCondition(ServiceUnavailable);
else if(type == "subscription-required")
setCondition(SubscriptionRequired);
else if(type == "undefined-condition")
setCondition(UndefinedCondition);
else if(type == "unexpected-request")
setCondition(UnexpectedRequest);
else
setCondition(static_cast<QXmppStanza::Error::Condition>(-1));
}
bool QXmppStanza::Error::isValid()
{
return !(getTypeStr().isEmpty() && getConditionStr().isEmpty());
}
void QXmppStanza::Error::parse(const QDomElement &errorElement)
{
setCode(errorElement.attribute("code").toInt());
setTypeFromStr(errorElement.attribute("type"));
QString text;
QString cond;
QDomElement element = errorElement.firstChildElement();
while(!element.isNull())
{
if(element.tagName() == "text")
text = element.text();
else if(element.namespaceURI() == ns_stanza)
{
cond = element.tagName();
}
element = element.nextSiblingElement();
}
setConditionFromStr(cond);
setText(text);
}
void QXmppStanza::Error::toXml( QXmlStreamWriter *writer ) const
{
QString cond = getConditionStr();
QString type = getTypeStr();
if(cond.isEmpty() && type.isEmpty())
return;
writer->writeStartElement("error");
helperToXmlAddAttribute(writer, "type", type);
if (m_code > 0)
helperToXmlAddAttribute(writer, "code", QString::number(m_code));
if(!cond.isEmpty())
{
writer->writeStartElement(cond);
helperToXmlAddAttribute(writer,"xmlns", ns_stanza);
writer->writeEndElement();
}
if(!m_text.isEmpty())
{
writer->writeStartElement("text");
helperToXmlAddAttribute(writer,"xml:lang", "en");
helperToXmlAddAttribute(writer,"xmlns", ns_stanza);
writer->writeCharacters(m_text);
writer->writeEndElement();
}
writer->writeEndElement();
}
QXmppStanza::QXmppStanza(const QString& from, const QString& to) : QXmppPacket(),
m_to(to), m_from(from)
{
}
QXmppStanza::~QXmppStanza()
{
}
QString QXmppStanza::to() const
{
return m_to;
}
void QXmppStanza::setTo(const QString& to)
{
m_to = to;
}
QString QXmppStanza::from() const
{
return m_from;
}
void QXmppStanza::setFrom(const QString& from)
{
m_from = from;
}
QString QXmppStanza::id() const
{
return m_id;
}
void QXmppStanza::setId(const QString& id)
{
m_id = id;
}
QString QXmppStanza::lang() const
{
return m_lang;
}
void QXmppStanza::setLang(const QString& lang)
{
m_lang = lang;
}
QXmppStanza::Error QXmppStanza::error() const
{
return m_error;
}
void QXmppStanza::setError(QXmppStanza::Error& error)
{
m_error = error;
}
QXmppElementList QXmppStanza::extensions() const
{
return m_extensions;
}
void QXmppStanza::setExtensions(const QXmppElementList &extensions)
{
m_extensions = extensions;
}
void QXmppStanza::generateAndSetNextId()
{
// get back
++s_uniqeIdNo;
m_id = "qxmpp" + QString::number(s_uniqeIdNo);
}
bool QXmppStanza::isErrorStanza()
{
return m_error.isValid();
}
void QXmppStanza::parse(const QDomElement &element)
{
m_from = element.attribute("from");
m_to = element.attribute("to");
m_id = element.attribute("id");
m_lang = element.attribute("lang");
QDomElement errorElement = element.firstChildElement("error");
if(!errorElement.isNull())
m_error.parse(errorElement);
}
// deprecated
QString QXmppStanza::Error::getText() const
{
return m_text;
}
int QXmppStanza::Error::getCode() const
{
return m_code;
}
QXmppStanza::Error::Condition QXmppStanza::Error::getCondition() const
{
return m_condition;
}
QXmppStanza::Error::Type QXmppStanza::Error::getType() const
{
return m_type;
}
QString QXmppStanza::getTo() const
{
return m_to;
}
QString QXmppStanza::getFrom() const
{
return m_from;
}
QString QXmppStanza::getId() const
{
return m_id;
}
QString QXmppStanza::getLang() const
{
return m_lang;
}
QXmppStanza::Error QXmppStanza::getError() const
{
return m_error;
}
<|endoftext|>
|
<commit_before>#include <array>
namespace {
std::array<int, 12> lengths = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
constexpr bool leap(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
}
int p19() {
int result = 0;
int weekday = 1;
for (int y = 1900; y <= 2000; y++) {
for (int m = 0; m < 12; m++) {
int max = lengths[m];
max += (m == 1 && leap(y));
result += (y > 1900 && weekday % 7 == 0);
weekday += max;
}
}
return result;
}
<commit_msg>p19: constexpr the result<commit_after>#include <array>
namespace {
constexpr std::array<int, 12> lengths = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
constexpr bool leap(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
constexpr int p() {
int result = 0;
int weekday = 1;
for (int y = 1900; y <= 2000; y++) {
for (int m = 0; m < 12; m++) {
int max = lengths[m];
max += (m == 1 && leap(y));
result += (y > 1900 && weekday % 7 == 0);
weekday += max;
}
}
return result;
}
}
int p19() {
return p();
}
<|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. *
**************************************************************************/
/* $Id$ */
//_________________________________________________________________________
// Geometry class for PHOS : EMCA (Electromagnetic Calorimeter)
// Its data members provide geometry parametrization of EMCA
// which can be changed in the constructor only.
// Author : Yves Schutz (SUBATECH)
// Modified : Yuri Kharlov (IHEP, Protvino)
// 13 September 2000
// --- AliRoot header files ---
#include "AliPHOSEMCAGeometry.h"
ClassImp(AliPHOSEMCAGeometry) ;
//____________________________________________________________________________
AliPHOSEMCAGeometry::AliPHOSEMCAGeometry()
{
// Initializes the EMC parameters
fNPhi = 64 ;
fNZ = 64 ;
fXtlSize[0] = 2.2 ;
fXtlSize[1] = 22.0 ;
fXtlSize[2] = 2.2 ;
// all these numbers coming next are subject to changes
fOuterBoxThickness[0] = 2.5 ;
fOuterBoxThickness[1] = 5.0 ;
fOuterBoxThickness[2] = 5.0 ;
fUpperPlateThickness = 4.0 ;
fSecondUpperPlateThickness = 5.0 ;
fCrystalSupportHeight = 6.95 ;
fCrystalWrapThickness = 0.01 ;
fCrystalHolderThickness = 0.005 ;
fModuleBoxThickness = 2.0 ;
fIPtoOuterCoverDistance = 447.0 ;
fIPtoCrystalSurface = 460.0 ;
fPinDiodeSize[0] = 1.71 ; //Values given by Odd Harald feb 2000
fPinDiodeSize[1] = 0.0280 ; // 0.0280 is the depth of active layer in the silicon
fPinDiodeSize[2] = 1.61 ;
fUpperCoolingPlateThickness = 0.06 ;
fSupportPlateThickness = 10.0 ;
fLowerThermoPlateThickness = 3.0 ;
fLowerTextolitPlateThickness = 1.0 ;
fGapBetweenCrystals = 0.03 ;
fTextolitBoxThickness[0] = 1.5 ;
fTextolitBoxThickness[1] = 0.0 ;
fTextolitBoxThickness[2] = 3.0 ;
fAirThickness[0] = 0.4 ;
fAirThickness[1] = 20.5175 ;
fAirThickness[2] = 2.48 ;
Float_t xtalModulePhiSize = fNPhi * ( fXtlSize[0] + 2 * fGapBetweenCrystals ) ;
Float_t xtalModuleZSize = fNZ * ( fXtlSize[2] + 2 * fGapBetweenCrystals ) ;
// The next dimensions are calculated from the above parameters
fOuterBoxSize[0] = xtalModulePhiSize + 2 * ( fAirThickness[0] + fModuleBoxThickness
+ fTextolitBoxThickness[0] + fOuterBoxThickness[0] ) ;
fOuterBoxSize[1] = ( fXtlSize[1] + fCrystalSupportHeight + fCrystalWrapThickness + fCrystalHolderThickness )
+ 2 * (fAirThickness[1] + fModuleBoxThickness + fTextolitBoxThickness[1] + fOuterBoxThickness[1] ) ;
fOuterBoxSize[2] = xtalModuleZSize + 2 * ( fAirThickness[2] + fModuleBoxThickness
+ fTextolitBoxThickness[2] + fOuterBoxThickness[2] ) ;
fTextolitBoxSize[0] = fOuterBoxSize[0] - 2 * fOuterBoxThickness[0] ;
fTextolitBoxSize[1] = fOuterBoxSize[1] - fOuterBoxThickness[1] - fUpperPlateThickness ;
fTextolitBoxSize[2] = fOuterBoxSize[2] - 2 * fOuterBoxThickness[2] ;
fAirFilledBoxSize[0] = fTextolitBoxSize[0] - 2 * fTextolitBoxThickness[0] ;
fAirFilledBoxSize[1] = fTextolitBoxSize[1] - fSecondUpperPlateThickness ;
fAirFilledBoxSize[2] = fTextolitBoxSize[2] - 2 * fTextolitBoxThickness[2] ;
}
//____________________________________________________________________________
<commit_msg>Pointer set to zero in the constructor (Sun)<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. *
**************************************************************************/
/* $Id$ */
//_________________________________________________________________________
// Geometry class for PHOS : EMCA (Electromagnetic Calorimeter)
// Its data members provide geometry parametrization of EMCA
// which can be changed in the constructor only.
// Author : Yves Schutz (SUBATECH)
// Modified : Yuri Kharlov (IHEP, Protvino)
// 13 September 2000
// --- AliRoot header files ---
#include "AliPHOSEMCAGeometry.h"
ClassImp(AliPHOSEMCAGeometry) ;
//____________________________________________________________________________
AliPHOSEMCAGeometry::AliPHOSEMCAGeometry()
{
// Initializes the EMC parameters
fNPhi = 64 ;
fNZ = 64 ;
fXtlSize[0] = 2.2 ;
fXtlSize[1] = 22.0 ;
fXtlSize[2] = 2.2 ;
// all these numbers coming next are subject to changes
fOuterBoxThickness[0] = 2.5 ;
fOuterBoxThickness[1] = 5.0 ;
fOuterBoxThickness[2] = 5.0 ;
fUpperPlateThickness = 4.0 ;
fSecondUpperPlateThickness = 5.0 ;
fCrystalSupportHeight = 6.95 ;
fCrystalWrapThickness = 0.01 ;
fCrystalHolderThickness = 0.005 ;
fModuleBoxThickness = 2.0 ;
fIPtoOuterCoverDistance = 447.0 ;
fIPtoCrystalSurface = 460.0 ;
fPinDiodeSize[0] = 1.71 ; //Values given by Odd Harald feb 2000
fPinDiodeSize[1] = 0.0280 ; // 0.0280 is the depth of active layer in the silicon
fPinDiodeSize[2] = 1.61 ;
fUpperCoolingPlateThickness = 0.06 ;
fSupportPlateThickness = 10.0 ;
fLowerThermoPlateThickness = 3.0 ;
fLowerTextolitPlateThickness = 1.0 ;
fGapBetweenCrystals = 0.03 ;
fTextolitBoxThickness[0] = 1.5 ;
fTextolitBoxThickness[1] = 0.0 ;
fTextolitBoxThickness[2] = 3.0 ;
fAirThickness[0] = 0.4 ;
fAirThickness[1] = 20.5175 ;
fAirThickness[2] = 2.48 ;
Float_t xtalModulePhiSize = fNPhi * ( fXtlSize[0] + 2 * fGapBetweenCrystals ) ;
Float_t xtalModuleZSize = fNZ * ( fXtlSize[2] + 2 * fGapBetweenCrystals ) ;
// The next dimensions are calculated from the above parameters
fOuterBoxSize[0] = xtalModulePhiSize + 2 * ( fAirThickness[0] + fModuleBoxThickness
+ fTextolitBoxThickness[0] + fOuterBoxThickness[0] ) ;
fOuterBoxSize[1] = ( fXtlSize[1] + fCrystalSupportHeight + fCrystalWrapThickness + fCrystalHolderThickness )
+ 2 * (fAirThickness[1] + fModuleBoxThickness + fTextolitBoxThickness[1] + fOuterBoxThickness[1] ) ;
fOuterBoxSize[2] = xtalModuleZSize + 2 * ( fAirThickness[2] + fModuleBoxThickness
+ fTextolitBoxThickness[2] + fOuterBoxThickness[2] ) ;
fTextolitBoxSize[0] = fOuterBoxSize[0] - 2 * fOuterBoxThickness[0] ;
fTextolitBoxSize[1] = fOuterBoxSize[1] - fOuterBoxThickness[1] - fUpperPlateThickness ;
fTextolitBoxSize[2] = fOuterBoxSize[2] - 2 * fOuterBoxThickness[2] ;
fAirFilledBoxSize[0] = fTextolitBoxSize[0] - 2 * fTextolitBoxThickness[0] ;
fAirFilledBoxSize[1] = fTextolitBoxSize[1] - fSecondUpperPlateThickness ;
fAirFilledBoxSize[2] = fTextolitBoxSize[2] - 2 * fTextolitBoxThickness[2] ;
fRotMatrixArray = 0;
}
//____________________________________________________________________________
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#ifndef SOFA_COMPONENT_FORCEFIELD_RESTSHAPESPRINGFORCEFIELD_INL
#define SOFA_COMPONENT_FORCEFIELD_RESTSHAPESPRINGFORCEFIELD_INL
#include <sofa/core/behavior/ForceField.inl>
#include "RestShapeSpringsForceField.h"
#include <sofa/helper/system/config.h>
#include <sofa/defaulttype/VecTypes.h>
#include <sofa/defaulttype/RigidTypes.h>
#include <sofa/helper/gl/template.h>
#include <assert.h>
#include <iostream>
namespace sofa
{
namespace component
{
namespace forcefield
{
template<class DataTypes>
RestShapeSpringsForceField<DataTypes>::RestShapeSpringsForceField()
: points(initData(&points, "points", "points controlled by the rest shape springs"))
, stiffness(initData(&stiffness, "stiffness", "stiffness values between the actual position and the rest shape position"))
, angularStiffness(initData(&angularStiffness, "angularStiffness", "angularStiffness assigned when controlling the rotation of the points"))
, external_rest_shape(initData(&external_rest_shape, "external_rest_shape", "rest_shape can be defined by the position of an external Mechanical State"))
, external_points(initData(&external_points, "external_points", "points from the external Mechancial State that define the rest shape springs"))
, recompute_indices(initData(&recompute_indices, false, "recompute_indices", "Recompute indices (should be false for BBOX)"))
, restMState(NULL)
// , pp_0(NULL)
{
}
template<class DataTypes>
void RestShapeSpringsForceField<DataTypes>::init()
{
core::behavior::ForceField<DataTypes>::init();
if (stiffness.getValue().empty())
{
std::cout << "RestShapeSpringsForceField : No stiffness is defined, assuming equal stiffness on each node, k = 100.0 " << std::endl;
VecReal stiffs;
stiffs.push_back(100.0);
stiffness.setValue(stiffs);
}
const std::string path = external_rest_shape.getValue();
restMState = NULL;
if (path.size() > 0)
{
this->getContext()->get(restMState ,path);
}
if (!restMState)
{
useRestMState = false;
if (path.size() > 0)
{
std::cout << "RestShapeSpringsForceField : " << external_rest_shape.getValue() << "not found\n";
}
}
else
{
useRestMState = true;
std::cout << "RestShapeSpringsForceField : Mechanical state named " << restMState->getName()
<< " found for RestShapeSpringFF named " << this->getName() << std::endl;
}
this->k = stiffness.getValue();
recomputeIndices();
}
template<class DataTypes>
void RestShapeSpringsForceField<DataTypes>::recomputeIndices()
{
m_indices.clear();
m_ext_indices.clear();
for (unsigned int i = 0; i < points.getValue().size(); i++)
m_indices.push_back(points.getValue()[i]);
for (unsigned int i = 0; i < external_points.getValue().size(); i++)
m_ext_indices.push_back(external_points.getValue()[i]);
if (m_indices.size()==0)
{
// std::cout << "in RestShapeSpringsForceField no point are defined, default case: points = all points " << std::endl;
for (unsigned int i = 0; i < (unsigned)this->mstate->getSize(); i++)
{
m_indices.push_back(i);
}
}
if (m_ext_indices.size()==0)
{
// std::cout << "in RestShapeSpringsForceField no external_points are defined, default case: points = all points " << std::endl;
if (useRestMState)
{
for (unsigned int i = 0; i < (unsigned)restMState->getSize(); i++)
{
m_ext_indices.push_back(i);
}
}
else
{
for (unsigned int i = 0; i < (unsigned)this->mstate->getSize(); i++)
{
m_ext_indices.push_back(i);
}
}
}
if (m_indices.size() > m_ext_indices.size())
{
std::cerr << "Error : the dimention of the source and the targeted points are different " << std::endl;
m_indices.clear();
}
}
template<class DataTypes>
void RestShapeSpringsForceField<DataTypes>::addForce(const core::MechanicalParams* /* mparams */ /* PARAMS FIRST */, DataVecDeriv& f, const DataVecCoord& x, const DataVecDeriv& /* v */)
{
sofa::helper::WriteAccessor< core::objectmodel::Data< VecDeriv > > f1 = f;
sofa::helper::ReadAccessor< core::objectmodel::Data< VecCoord > > p1 = x;
sofa::helper::ReadAccessor< core::objectmodel::Data< VecCoord > > p0 = *(useRestMState ? restMState->read(core::VecCoordId::position()) : this->mstate->read(core::VecCoordId::restPosition()));
f1.resize(p1.size());
if (recompute_indices.getValue())
{
recomputeIndices();
}
Springs_dir.resize(m_indices.size() );
if ( k.size()!= m_indices.size() )
{
//sout << "WARNING : stiffness is not defined on each point, first stiffness is used" << sendl;
for (unsigned int i=0; i<m_indices.size(); i++)
{
const unsigned int index = m_indices[i];
const unsigned int ext_index = m_ext_indices[i];
Deriv dx = p1[index] - p0[ext_index];
Springs_dir[i] = p1[index] - p0[ext_index];
Springs_dir[i].normalize();
f1[index] -= dx * k[0] ;
// if (dx.norm()>0.00000001)
// std::cout<<"force on point "<<index<<std::endl;
// Deriv dx = p[i] - p_0[i];
// f[ indices[i] ] -= dx * k[0] ;
}
}
else
{
for (unsigned int i=0; i<m_indices.size(); i++)
{
const unsigned int index = m_indices[i];
const unsigned int ext_index = m_ext_indices[i];
Deriv dx = p1[index] - p0[ext_index];
Springs_dir[i] = p1[index] - p0[ext_index];
Springs_dir[i].normalize();
f1[index] -= dx * k[index] ;
// if (dx.norm()>0.00000001)
// std::cout<<"force on point "<<index<<std::endl;
// Deriv dx = p[i] - p_0[i];
// f[ indices[i] ] -= dx * k[i] ;
}
}
}
template<class DataTypes>
void RestShapeSpringsForceField<DataTypes>::addDForce(const core::MechanicalParams* mparams /* PARAMS FIRST */, DataVecDeriv& df, const DataVecDeriv& dx)
{
// remove to be able to build in parallel
// const VecIndex& indices = points.getValue();
// const VecReal& k = stiffness.getValue();
sofa::helper::WriteAccessor< core::objectmodel::Data< VecDeriv > > df1 = df;
sofa::helper::ReadAccessor< core::objectmodel::Data< VecDeriv > > dx1 = dx;
double kFactor = mparams->kFactor();
if (k.size()!= m_indices.size() )
{
sout << "WARNING : stiffness is not defined on each point, first stiffness is used" << sendl;
for (unsigned int i=0; i<m_indices.size(); i++)
{
df1[m_indices[i]] -= dx1[m_indices[i]] * k[0] * kFactor;
}
}
else
{
for (unsigned int i=0; i<m_indices.size(); i++)
{
df1[m_indices[i]] -= dx1[m_indices[i]] * k[m_indices[i]] * kFactor ;
}
}
}
template<class DataTypes>
void RestShapeSpringsForceField<DataTypes>::addKToMatrix(const core::MechanicalParams* mparams /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* matrix )
{
// remove to be able to build in parallel
// const VecIndex& indices = points.getValue();
// const VecReal& k = stiffness.getValue();
sofa::core::behavior::MultiMatrixAccessor::MatrixRef mref = matrix->getMatrix(this->mstate);
sofa::defaulttype::BaseMatrix* mat = mref.matrix;
unsigned int offset = mref.offset;
double kFact = mparams->kFactor();
const int N = Coord::total_size;
unsigned int curIndex = 0;
if (k.size()!= m_indices.size() )
{
for (unsigned int index = 0; index < m_indices.size(); index++)
{
curIndex = m_indices[index];
for(int i = 0; i < N; i++)
{
// for (unsigned int j = 0; j < N; j++)
// {
// mat->add(offset + N * curIndex + i, offset + N * curIndex + j, kFact * k[0]);
// }
mat->add(offset + N * curIndex + i, offset + N * curIndex + i, -kFact * k[0]);
}
}
}
else
{
for (unsigned int index = 0; index < m_indices.size(); index++)
{
curIndex = m_indices[index];
for(int i = 0; i < N; i++)
{
// for (unsigned int j = 0; j < N; j++)
// {
// mat->add(offset + N * curIndex + i, offset + N * curIndex + j, kFact * k[curIndex]);
// }
mat->add(offset + N * curIndex + i, offset + N * curIndex + i, -kFact * k[curIndex]);
}
}
}
}
template<class DataTypes>
void RestShapeSpringsForceField<DataTypes>::draw(const core::visual::VisualParams* )
{
}
template <class DataTypes>
bool RestShapeSpringsForceField<DataTypes>::addBBox(double*, double* )
{
return false;
}
} // namespace forcefield
} // namespace component
} // namespace sofa
#endif // SOFA_COMPONENT_FORCEFIELD_RESTSHAPESPRINGFORCEFIELD_INL
<commit_msg>r10469/sofa-dev : Remove verbose message from forcefield to have a cleaner console...<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#ifndef SOFA_COMPONENT_FORCEFIELD_RESTSHAPESPRINGFORCEFIELD_INL
#define SOFA_COMPONENT_FORCEFIELD_RESTSHAPESPRINGFORCEFIELD_INL
#include <sofa/core/behavior/ForceField.inl>
#include "RestShapeSpringsForceField.h"
#include <sofa/helper/system/config.h>
#include <sofa/defaulttype/VecTypes.h>
#include <sofa/defaulttype/RigidTypes.h>
#include <sofa/helper/gl/template.h>
#include <assert.h>
#include <iostream>
namespace sofa
{
namespace component
{
namespace forcefield
{
template<class DataTypes>
RestShapeSpringsForceField<DataTypes>::RestShapeSpringsForceField()
: points(initData(&points, "points", "points controlled by the rest shape springs"))
, stiffness(initData(&stiffness, "stiffness", "stiffness values between the actual position and the rest shape position"))
, angularStiffness(initData(&angularStiffness, "angularStiffness", "angularStiffness assigned when controlling the rotation of the points"))
, external_rest_shape(initData(&external_rest_shape, "external_rest_shape", "rest_shape can be defined by the position of an external Mechanical State"))
, external_points(initData(&external_points, "external_points", "points from the external Mechancial State that define the rest shape springs"))
, recompute_indices(initData(&recompute_indices, false, "recompute_indices", "Recompute indices (should be false for BBOX)"))
, restMState(NULL)
// , pp_0(NULL)
{
}
template<class DataTypes>
void RestShapeSpringsForceField<DataTypes>::init()
{
core::behavior::ForceField<DataTypes>::init();
if (stiffness.getValue().empty())
{
std::cout << "RestShapeSpringsForceField : No stiffness is defined, assuming equal stiffness on each node, k = 100.0 " << std::endl;
VecReal stiffs;
stiffs.push_back(100.0);
stiffness.setValue(stiffs);
}
const std::string path = external_rest_shape.getValue();
restMState = NULL;
if (path.size() > 0)
{
this->getContext()->get(restMState ,path);
}
if (!restMState)
{
useRestMState = false;
if (path.size() > 0)
{
std::cout << "RestShapeSpringsForceField : " << external_rest_shape.getValue() << "not found\n";
}
}
else
{
useRestMState = true;
// std::cout << "RestShapeSpringsForceField : Mechanical state named " << restMState->getName() << " found for RestShapeSpringFF named " << this->getName() << std::endl;
}
this->k = stiffness.getValue();
recomputeIndices();
}
template<class DataTypes>
void RestShapeSpringsForceField<DataTypes>::recomputeIndices()
{
m_indices.clear();
m_ext_indices.clear();
for (unsigned int i = 0; i < points.getValue().size(); i++)
m_indices.push_back(points.getValue()[i]);
for (unsigned int i = 0; i < external_points.getValue().size(); i++)
m_ext_indices.push_back(external_points.getValue()[i]);
if (m_indices.size()==0)
{
// std::cout << "in RestShapeSpringsForceField no point are defined, default case: points = all points " << std::endl;
for (unsigned int i = 0; i < (unsigned)this->mstate->getSize(); i++)
{
m_indices.push_back(i);
}
}
if (m_ext_indices.size()==0)
{
// std::cout << "in RestShapeSpringsForceField no external_points are defined, default case: points = all points " << std::endl;
if (useRestMState)
{
for (unsigned int i = 0; i < (unsigned)restMState->getSize(); i++)
{
m_ext_indices.push_back(i);
}
}
else
{
for (unsigned int i = 0; i < (unsigned)this->mstate->getSize(); i++)
{
m_ext_indices.push_back(i);
}
}
}
if (m_indices.size() > m_ext_indices.size())
{
std::cerr << "Error : the dimention of the source and the targeted points are different " << std::endl;
m_indices.clear();
}
}
template<class DataTypes>
void RestShapeSpringsForceField<DataTypes>::addForce(const core::MechanicalParams* /* mparams */ /* PARAMS FIRST */, DataVecDeriv& f, const DataVecCoord& x, const DataVecDeriv& /* v */)
{
sofa::helper::WriteAccessor< core::objectmodel::Data< VecDeriv > > f1 = f;
sofa::helper::ReadAccessor< core::objectmodel::Data< VecCoord > > p1 = x;
sofa::helper::ReadAccessor< core::objectmodel::Data< VecCoord > > p0 = *(useRestMState ? restMState->read(core::VecCoordId::position()) : this->mstate->read(core::VecCoordId::restPosition()));
f1.resize(p1.size());
if (recompute_indices.getValue())
{
recomputeIndices();
}
Springs_dir.resize(m_indices.size() );
if ( k.size()!= m_indices.size() )
{
//sout << "WARNING : stiffness is not defined on each point, first stiffness is used" << sendl;
for (unsigned int i=0; i<m_indices.size(); i++)
{
const unsigned int index = m_indices[i];
const unsigned int ext_index = m_ext_indices[i];
Deriv dx = p1[index] - p0[ext_index];
Springs_dir[i] = p1[index] - p0[ext_index];
Springs_dir[i].normalize();
f1[index] -= dx * k[0] ;
// if (dx.norm()>0.00000001)
// std::cout<<"force on point "<<index<<std::endl;
// Deriv dx = p[i] - p_0[i];
// f[ indices[i] ] -= dx * k[0] ;
}
}
else
{
for (unsigned int i=0; i<m_indices.size(); i++)
{
const unsigned int index = m_indices[i];
const unsigned int ext_index = m_ext_indices[i];
Deriv dx = p1[index] - p0[ext_index];
Springs_dir[i] = p1[index] - p0[ext_index];
Springs_dir[i].normalize();
f1[index] -= dx * k[index] ;
// if (dx.norm()>0.00000001)
// std::cout<<"force on point "<<index<<std::endl;
// Deriv dx = p[i] - p_0[i];
// f[ indices[i] ] -= dx * k[i] ;
}
}
}
template<class DataTypes>
void RestShapeSpringsForceField<DataTypes>::addDForce(const core::MechanicalParams* mparams /* PARAMS FIRST */, DataVecDeriv& df, const DataVecDeriv& dx)
{
// remove to be able to build in parallel
// const VecIndex& indices = points.getValue();
// const VecReal& k = stiffness.getValue();
sofa::helper::WriteAccessor< core::objectmodel::Data< VecDeriv > > df1 = df;
sofa::helper::ReadAccessor< core::objectmodel::Data< VecDeriv > > dx1 = dx;
double kFactor = mparams->kFactor();
if (k.size()!= m_indices.size() )
{
sout << "WARNING : stiffness is not defined on each point, first stiffness is used" << sendl;
for (unsigned int i=0; i<m_indices.size(); i++)
{
df1[m_indices[i]] -= dx1[m_indices[i]] * k[0] * kFactor;
}
}
else
{
for (unsigned int i=0; i<m_indices.size(); i++)
{
df1[m_indices[i]] -= dx1[m_indices[i]] * k[m_indices[i]] * kFactor ;
}
}
}
template<class DataTypes>
void RestShapeSpringsForceField<DataTypes>::addKToMatrix(const core::MechanicalParams* mparams /* PARAMS FIRST */, const sofa::core::behavior::MultiMatrixAccessor* matrix )
{
// remove to be able to build in parallel
// const VecIndex& indices = points.getValue();
// const VecReal& k = stiffness.getValue();
sofa::core::behavior::MultiMatrixAccessor::MatrixRef mref = matrix->getMatrix(this->mstate);
sofa::defaulttype::BaseMatrix* mat = mref.matrix;
unsigned int offset = mref.offset;
double kFact = mparams->kFactor();
const int N = Coord::total_size;
unsigned int curIndex = 0;
if (k.size()!= m_indices.size() )
{
for (unsigned int index = 0; index < m_indices.size(); index++)
{
curIndex = m_indices[index];
for(int i = 0; i < N; i++)
{
// for (unsigned int j = 0; j < N; j++)
// {
// mat->add(offset + N * curIndex + i, offset + N * curIndex + j, kFact * k[0]);
// }
mat->add(offset + N * curIndex + i, offset + N * curIndex + i, -kFact * k[0]);
}
}
}
else
{
for (unsigned int index = 0; index < m_indices.size(); index++)
{
curIndex = m_indices[index];
for(int i = 0; i < N; i++)
{
// for (unsigned int j = 0; j < N; j++)
// {
// mat->add(offset + N * curIndex + i, offset + N * curIndex + j, kFact * k[curIndex]);
// }
mat->add(offset + N * curIndex + i, offset + N * curIndex + i, -kFact * k[curIndex]);
}
}
}
}
template<class DataTypes>
void RestShapeSpringsForceField<DataTypes>::draw(const core::visual::VisualParams* )
{
}
template <class DataTypes>
bool RestShapeSpringsForceField<DataTypes>::addBBox(double*, double* )
{
return false;
}
} // namespace forcefield
} // namespace component
} // namespace sofa
#endif // SOFA_COMPONENT_FORCEFIELD_RESTSHAPESPRINGFORCEFIELD_INL
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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.
*********************************************************************/
/* Author: Wim Meeussen */
#include "kdl_parser/kdl_parser.hpp"
#include <kdl/frames_io.hpp>
using namespace std;
using namespace KDL;
namespace kdl_parser{
// construct vector
Vector toKdl(urdf::Vector3 v)
{
return Vector(v.x, v.y, v.z);
}
// construct rotation
Rotation toKdl(urdf::Rotation r)
{
double roll, pitch, yaw;
r.getRPY(roll, pitch, yaw);
return Rotation::RPY(roll, pitch, yaw);
}
// construct pose
Frame toKdl(urdf::Pose p)
{
return Frame(toKdl(p.rotation), toKdl(p.position));
}
// construct joint
Joint toKdl(boost::shared_ptr<urdf::Joint> jnt)
{
Frame F_parent_jnt = toKdl(jnt->parent_to_joint_origin_transform);
switch (jnt->type){
case urdf::Joint::FIXED:{
return Joint(jnt->name, Joint::None);
}
case urdf::Joint::REVOLUTE:{
Vector axis = toKdl(jnt->axis);
return Joint(jnt->name, F_parent_jnt.p, F_parent_jnt.M * axis, Joint::RotAxis);
}
case urdf::Joint::CONTINUOUS:{
Vector axis = toKdl(jnt->axis);
return Joint(jnt->name, F_parent_jnt.p, F_parent_jnt.M * axis, Joint::RotAxis);
}
case urdf::Joint::PRISMATIC:{
Vector axis = toKdl(jnt->axis);
return Joint(jnt->name, F_parent_jnt.p, F_parent_jnt.M * axis, Joint::TransAxis);
}
default:{
ROS_WARN("Converting unknown joint type of joint '%s' into a fixed joint", jnt->name.c_str());
return Joint(jnt->name, Joint::None);
}
}
return Joint();
}
// construct inertia
RigidBodyInertia toKdl(boost::shared_ptr<urdf::Inertial> i)
{
Frame origin = toKdl(i->origin);
// kdl specifies the inertia in the reference frame of the link, the urdf specifies the inertia in the inertia reference frame
return origin.M * RigidBodyInertia(i->mass, origin.p, RotationalInertia(i->ixx, i->iyy, i->izz, i->ixy, i->ixz, i->iyz));
}
// recursive function to walk through tree
bool addChildrenToTree(boost::shared_ptr<const urdf::Link> root, Tree& tree)
{
std::vector<boost::shared_ptr<urdf::Link> > children = root->child_links;
ROS_DEBUG("Link %s had %i children", root->name.c_str(), (int)children.size());
// constructs the optional inertia
RigidBodyInertia inert(0);
if (root->inertial)
inert = toKdl(root->inertial);
// constructs the kdl joint
Joint jnt = toKdl(root->parent_joint);
// construct the kdl segment
Segment sgm(root->name, jnt, toKdl(root->parent_joint->parent_to_joint_origin_transform), inert);
// add segment to tree
tree.addSegment(sgm, root->parent_joint->parent_link_name);
// recurslively add all children
for (size_t i=0; i<children.size(); i++){
if (!addChildrenToTree(children[i], tree))
return false;
}
return true;
}
bool treeFromFile(const string& file, Tree& tree)
{
TiXmlDocument urdf_xml;
urdf_xml.LoadFile(file);
return treeFromXml(&urdf_xml, tree);
}
bool treeFromParam(const string& param, Tree& tree)
{
urdf::Model robot_model;
if (!robot_model.initParam(param)){
ROS_ERROR("Could not generate robot model");
return false;
}
return treeFromUrdfModel(robot_model, tree);
}
bool treeFromString(const string& xml, Tree& tree)
{
TiXmlDocument urdf_xml;
urdf_xml.Parse(xml.c_str());
return treeFromXml(&urdf_xml, tree);
}
bool treeFromXml(TiXmlDocument *xml_doc, Tree& tree)
{
urdf::Model robot_model;
if (!robot_model.initXml(xml_doc)){
ROS_ERROR("Could not generate robot model");
return false;
}
return treeFromUrdfModel(robot_model, tree);
}
bool treeFromUrdfModel(const urdf::Model& robot_model, Tree& tree)
{
tree = Tree(robot_model.getRoot()->name);
// add all children
for (size_t i=0; i<robot_model.getRoot()->child_links.size(); i++)
if (!addChildrenToTree(robot_model.getRoot()->child_links[i], tree))
return false;
return true;
}
}
<commit_msg>construct kdl object directly from quaternion<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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.
*********************************************************************/
/* Author: Wim Meeussen */
#include "kdl_parser/kdl_parser.hpp"
#include <kdl/frames_io.hpp>
using namespace std;
using namespace KDL;
namespace kdl_parser{
// construct vector
Vector toKdl(urdf::Vector3 v)
{
return Vector(v.x, v.y, v.z);
}
// construct rotation
Rotation toKdl(urdf::Rotation r)
{
return Rotation::Quaternion(r.x, r.y, r.z, r.w);
}
// construct pose
Frame toKdl(urdf::Pose p)
{
return Frame(toKdl(p.rotation), toKdl(p.position));
}
// construct joint
Joint toKdl(boost::shared_ptr<urdf::Joint> jnt)
{
Frame F_parent_jnt = toKdl(jnt->parent_to_joint_origin_transform);
switch (jnt->type){
case urdf::Joint::FIXED:{
return Joint(jnt->name, Joint::None);
}
case urdf::Joint::REVOLUTE:{
Vector axis = toKdl(jnt->axis);
return Joint(jnt->name, F_parent_jnt.p, F_parent_jnt.M * axis, Joint::RotAxis);
}
case urdf::Joint::CONTINUOUS:{
Vector axis = toKdl(jnt->axis);
return Joint(jnt->name, F_parent_jnt.p, F_parent_jnt.M * axis, Joint::RotAxis);
}
case urdf::Joint::PRISMATIC:{
Vector axis = toKdl(jnt->axis);
return Joint(jnt->name, F_parent_jnt.p, F_parent_jnt.M * axis, Joint::TransAxis);
}
default:{
ROS_WARN("Converting unknown joint type of joint '%s' into a fixed joint", jnt->name.c_str());
return Joint(jnt->name, Joint::None);
}
}
return Joint();
}
// construct inertia
RigidBodyInertia toKdl(boost::shared_ptr<urdf::Inertial> i)
{
Frame origin = toKdl(i->origin);
// kdl specifies the inertia in the reference frame of the link, the urdf specifies the inertia in the inertia reference frame
return origin.M * RigidBodyInertia(i->mass, origin.p, RotationalInertia(i->ixx, i->iyy, i->izz, i->ixy, i->ixz, i->iyz));
}
// recursive function to walk through tree
bool addChildrenToTree(boost::shared_ptr<const urdf::Link> root, Tree& tree)
{
std::vector<boost::shared_ptr<urdf::Link> > children = root->child_links;
ROS_DEBUG("Link %s had %i children", root->name.c_str(), (int)children.size());
// constructs the optional inertia
RigidBodyInertia inert(0);
if (root->inertial)
inert = toKdl(root->inertial);
// constructs the kdl joint
Joint jnt = toKdl(root->parent_joint);
// construct the kdl segment
Segment sgm(root->name, jnt, toKdl(root->parent_joint->parent_to_joint_origin_transform), inert);
// add segment to tree
tree.addSegment(sgm, root->parent_joint->parent_link_name);
// recurslively add all children
for (size_t i=0; i<children.size(); i++){
if (!addChildrenToTree(children[i], tree))
return false;
}
return true;
}
bool treeFromFile(const string& file, Tree& tree)
{
TiXmlDocument urdf_xml;
urdf_xml.LoadFile(file);
return treeFromXml(&urdf_xml, tree);
}
bool treeFromParam(const string& param, Tree& tree)
{
urdf::Model robot_model;
if (!robot_model.initParam(param)){
ROS_ERROR("Could not generate robot model");
return false;
}
return treeFromUrdfModel(robot_model, tree);
}
bool treeFromString(const string& xml, Tree& tree)
{
TiXmlDocument urdf_xml;
urdf_xml.Parse(xml.c_str());
return treeFromXml(&urdf_xml, tree);
}
bool treeFromXml(TiXmlDocument *xml_doc, Tree& tree)
{
urdf::Model robot_model;
if (!robot_model.initXml(xml_doc)){
ROS_ERROR("Could not generate robot model");
return false;
}
return treeFromUrdfModel(robot_model, tree);
}
bool treeFromUrdfModel(const urdf::Model& robot_model, Tree& tree)
{
tree = Tree(robot_model.getRoot()->name);
// add all children
for (size_t i=0; i<robot_model.getRoot()->child_links.size(); i++)
if (!addChildrenToTree(robot_model.getRoot()->child_links[i], tree))
return false;
return true;
}
}
<|endoftext|>
|
<commit_before><commit_msg>1.0/09.03.2014:0340<commit_after>#include "ioput.h"
template <class T>
IOput<T>::IOput(){}
template <class T>
IOput<T>::IOput(const char* dir_name){
cwd_ = new ss(dir_name);
sst aux;
aux << "mkdir -p " << *cwd_ << "/";
system(aux.str().c_str());
}
template <class T>
IOput<T>::IOput(ss dir_name){
cwd_ = new ss(dir_name);
mkdir(*cwd_);
}
template <class T>
ss IOput<T>::cwd(){
return *cwd_;
}
template <class T>
ss IOput<T>::full_cwd(){
system("echo $PWD > .temp_full_cwd_path");
ifstream in(".temp_full_cwd_path");
ss aux;
getline(in,aux);
aux += ss("/") + *cwd_;
in.close();
system("rm .temp_full_cwd_path");
return aux;
}
template <class T>
void IOput<T>::change_cwd(ss new_dir_name){
*cwd_ = new_dir_name;
mkdir(*cwd_);
}
template <class T>
void IOput<T>::mkdir(ss s){
sst aux;
aux << "mkdir -p " + s + "/";
system(aux.str().c_str());
}
template class IOput<int>;
template class IOput<float>;
template class IOput<double>;
template class IOput<ss>;
template class IOput<char>;
<|endoftext|>
|
<commit_before>// Copyright (c) 2015-2016 The Khronos Group Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "print.h"
#if defined(SPIRV_ANDROID) || defined(SPIRV_LINUX) || defined(SPIRV_MAC) || defined(SPIRV_FREEBSD)
namespace libspirv {
clr::reset::operator const char*() { return "\x1b[0m"; }
clr::grey::operator const char*() { return "\x1b[1;30m"; }
clr::red::operator const char*() { return "\x1b[31m"; }
clr::green::operator const char*() { return "\x1b[32m"; }
clr::yellow::operator const char*() { return "\x1b[33m"; }
clr::blue::operator const char*() { return "\x1b[34m"; }
} // namespace libspirv
#elif defined(SPIRV_WINDOWS)
#include <windows.h>
namespace libspirv {
static void SetConsoleForegroundColorPrimary(HANDLE hConsole, WORD color)
{
// Get screen buffer information from console handle
CONSOLE_SCREEN_BUFFER_INFO bufInfo;
GetConsoleScreenBufferInfo(hConsole, &bufInfo);
// Get background color
color |= (bufInfo.wAttributes & 0xfff0);
// Set foreground color
SetConsoleTextAttribute(hConsole, color);
}
static void SetConsoleForegroundColor(WORD color)
{
SetConsoleForegroundColorPrimary(GetStdHandle(STD_OUTPUT_HANDLE), color);
SetConsoleForegroundColorPrimary(GetStdHandle(STD_ERROR_HANDLE), color);
}
clr::reset::operator const char*() {
SetConsoleForegroundColor(0xf);
return "";
}
clr::grey::operator const char*() {
SetConsoleForegroundColor(FOREGROUND_INTENSITY);
return "";
}
clr::red::operator const char*() {
SetConsoleForegroundColor(FOREGROUND_RED);
return "";
}
clr::green::operator const char*() {
SetConsoleForegroundColor(FOREGROUND_GREEN);
return "";
}
clr::yellow::operator const char*() {
SetConsoleForegroundColor(FOREGROUND_RED | FOREGROUND_GREEN);
return "";
}
clr::blue::operator const char*() {
// Blue all by itself is hard to see against a black background (the
// default on command shell), or a medium blue background (the default
// on PowerShell). So increase its intensity.
SetConsoleForegroundColor(FOREGROUND_BLUE | FOREGROUND_INTENSITY);
return "";
}
} // namespace libspirv
#else
namespace libspirv {
clr::reset::operator const char*() { return ""; }
clr::grey::operator const char*() { return ""; }
clr::red::operator const char*() { return ""; }
clr::green::operator const char*() { return ""; }
clr::yellow::operator const char*() { return ""; }
clr::blue::operator const char*() { return ""; }
} // namespace libspirv
#endif
<commit_msg>Fix mingw build (source/print.cpp)<commit_after>// Copyright (c) 2015-2016 The Khronos Group Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "print.h"
#if defined(SPIRV_ANDROID) || defined(SPIRV_LINUX) || defined(SPIRV_MAC) || defined(SPIRV_FREEBSD)
namespace libspirv {
clr::reset::operator const char*() { return "\x1b[0m"; }
clr::grey::operator const char*() { return "\x1b[1;30m"; }
clr::red::operator const char*() { return "\x1b[31m"; }
clr::green::operator const char*() { return "\x1b[32m"; }
clr::yellow::operator const char*() { return "\x1b[33m"; }
clr::blue::operator const char*() { return "\x1b[34m"; }
} // namespace libspirv
#elif defined(SPIRV_WINDOWS)
#include <windows.h>
namespace libspirv {
static void SetConsoleForegroundColorPrimary(HANDLE hConsole, WORD color)
{
// Get screen buffer information from console handle
CONSOLE_SCREEN_BUFFER_INFO bufInfo;
GetConsoleScreenBufferInfo(hConsole, &bufInfo);
// Get background color
color = WORD(color | (bufInfo.wAttributes & 0xfff0));
// Set foreground color
SetConsoleTextAttribute(hConsole, color);
}
static void SetConsoleForegroundColor(WORD color)
{
SetConsoleForegroundColorPrimary(GetStdHandle(STD_OUTPUT_HANDLE), color);
SetConsoleForegroundColorPrimary(GetStdHandle(STD_ERROR_HANDLE), color);
}
clr::reset::operator const char*() {
SetConsoleForegroundColor(0xf);
return "";
}
clr::grey::operator const char*() {
SetConsoleForegroundColor(FOREGROUND_INTENSITY);
return "";
}
clr::red::operator const char*() {
SetConsoleForegroundColor(FOREGROUND_RED);
return "";
}
clr::green::operator const char*() {
SetConsoleForegroundColor(FOREGROUND_GREEN);
return "";
}
clr::yellow::operator const char*() {
SetConsoleForegroundColor(FOREGROUND_RED | FOREGROUND_GREEN);
return "";
}
clr::blue::operator const char*() {
// Blue all by itself is hard to see against a black background (the
// default on command shell), or a medium blue background (the default
// on PowerShell). So increase its intensity.
SetConsoleForegroundColor(FOREGROUND_BLUE | FOREGROUND_INTENSITY);
return "";
}
} // namespace libspirv
#else
namespace libspirv {
clr::reset::operator const char*() { return ""; }
clr::grey::operator const char*() { return ""; }
clr::red::operator const char*() { return ""; }
clr::green::operator const char*() { return ""; }
clr::yellow::operator const char*() { return ""; }
clr::blue::operator const char*() { return ""; }
} // namespace libspirv
#endif
<|endoftext|>
|
<commit_before>/*
Parámetros de entrada del programa:
· Número de usuarios en sede 1
· Número de usuarios en sede 2
· Distintas velocidades de enlace que se pueden contratar con el operador
· Tasa media de ocurrencia de llamadas de los usuarios
· Calidad de servicio requerida
· Intervalo de la tasa de bits del códec de audio.
Parámetros de salida del programa:
· Número de enlaces y velocidad a contratar con el operador.
· Número máximo de usuarios que pueden hablar a la vez.
· Parámetros de calidad conseguidos finalmente (retardo etc.)
· Gráficas:
· Una gráfica para cada número de enlaces con la evolución de la QoS respecto a la capacidad de enlace.
· Una gráfica para cada número de enlaces con la evolución de los parámetros usados para medir la QoS según la capacidad de enlace.
*/
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/gnuplot.h"
#include "Observador.h"
#define DURACION 120.0
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("Simvoip");
// Punto 3D
typedef struct {
uint8_t enlaces;
uint8_t velocidad;
double qos;
}Punto;
/*
* Recibe el n�mero de enlaces y su velocidad y el objeto observador a utilizar
* devuelve la QoS conseguida
*/
double simular(Punto * resultado, std::map<uint8_t, DataRate> velocidades, Observador *observador,uint16_t telef1,uint16_t telef2);
using namespace ns3;
int main(int argc, char *argv[])
{
double qos_objetivo = 1.0;
uint32_t telef1 = 100;
uint32_t telef2 = 100;
std::string sVelocidades = "1Mbps;2Mbps;5Mbps;10Mbps;20Mbps;30Mbps;50Mbps;100Mbps;200Mbps;300Mbps";
double tasaLlamadas = 0.67;
std::string sTasaCodec = "64kbps;96kbps";
DataRate tasaCodec[2]; // Forman el intervalo en el que estará la tasa distribuida uniformemente
std::map<uint8_t, DataRate> velocidades; // Velocidades permitidas
// Obtener parámetros de cmd
CommandLine cmd;
cmd.AddValue("qos", "Calidad de servicio objetivo", qos_objetivo);
cmd.AddValue("tA", "Número de usuarios en la sede A", telef1);
cmd.AddValue("tB", "Número de usuarios en la sede B", telef2);
cmd.AddValue("velocidades", "velocidades de enlace que se pueden contratar con el operador separadas por ;", sVelocidades);
cmd.AddValue("tasaLlamadas", "Tasa media de ocurrencia de llamadas de los usuarios", tasaLlamadas);
cmd.AddValue("tasaCodec", "Intervalo de la tasa de bits del códec de audio", sTasaCodec);
cmd.Parse(argc, argv);
// Parsear cadena introduciendo velocidades de enlace posibles en el map
size_t posicion = 0;
uint8_t n = 0;
while ((posicion = sVelocidades.find(";")) != std::string::npos) {
// Guardar cada elemento en el map
velocidades[n] = DataRate(sVelocidades.substr(0, posicion));
sVelocidades.erase(0, posicion + 1);
}
// Parsear intervalo de tasa del codec
n = 0;
while ((posicion = sTasaCodec.find(";")) != std::string::npos) {
tasaCodec[n] = DataRate(sTasaCodec.substr(0, posicion));
sTasaCodec.erase(0, posicion + 1);
}
// TODO Preparar gráficas
// Gráfica 1
Gnuplot plot1;
plot1.SetTitle("---");
plot1.SetLegend("Tiempo medio de permanencia en el estado On", "Porcentaje de paquetes correctamente transmitidos");
// Gráfica 2
Gnuplot plot2;
plot2.SetTitle("---");
plot2.SetLegend("Tiempo medio de permanencia en el estado On", "Latencia (us)");
Time::SetResolution(Time::US);
Observador * observador = new Observador();
Punto anterior = { 0,0,0.0 };
Punto resultado;
// Los resultados de las simulaciones se guardan en una estructura para el algoritmo de predicci�n
while (resultado.qos < qos_objetivo)
{
simular(&resultado, velocidades, observador, telef1, telef2);
// ALGORITMO DE PREDICCIÓN LINEALIZANDO
// y = mx + n
// m = dy/dx (delta)
// x = enlaces*velocidad
double m = ((resultado.qos - anterior.qos) / ((resultado.enlaces*velocidades[resultado.velocidad].GetBitRate() / 1e6) - (anterior.enlaces*velocidades[anterior.velocidad].GetBitRate() / 1e6)));
// qos = mx -> x = qos/m
uint32_t x = qos_objetivo / m;
// Pasar el resultado al anterior
anterior = resultado;
// Cambiar coordenadas de resultado para la siguiente iteración
// Enlaces mínimos
resultado.enlaces = 0;
resultado.velocidad = 0;
while ((x / velocidades[resultado.velocidad].GetBitRate() / 1e6)>resultado.enlaces)
{
if (resultado.velocidad == (velocidades.size() - 1))
{
resultado.enlaces++;
resultado.velocidad = 0;
}
else
{
resultado.velocidad++;
}
}
delete observador;
}
return 0;
}
//todo decidir que velocidades tendra la red interna de cada sede, por ahora supongo
//velocidades de 100Mbps
//todo posible error: a los Routers les estoy instalando las apps que llevan los telefonos y les estoy dando direccionamiento
//solucionar eso
double simular(Punto * resultado, std::map<uint8_t, DataRate> velocidades, Observador *observador, uint16_t telef1, uint16_t telef2)
{
// Preparar escenario
NodeContainer Sedes; //Creamos 2 sedes que vamos a interconectar
Sedes.Create(2); //Son nodos p2p
//todo supongo que
//Creo telefonos de sede 1
NodeContainer telefonosSede1;
telefonosSede1.Add( Sedes.Get(0) );
telefonosSede1.Create(telef1); //Creo el numero de telefonos que se le pase por parametros
//Creo telefonos de sede 2
NodeContainer telefonosSede2;
telefonosSede2.Add( Sedes.Get(1) );
telefonosSede2.Create(telef2);
//Instalo dispositivo en Routers entre sedes
PointToPointHelper pointToPoint;
NetDeviceContainer p2pDevices;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("1Gbps")); //todo supongo datos, ya se cambiara
pointToPoint.SetChannelAttribute ("Delay", StringValue ("0.1ms"));
p2pDevices = pointToPoint.Install (Sedes);
//Instalo dispositivo en telefonos Sede 1
PointToPointHelper pointToPointSede1;
NetDeviceContainer p2pDevicesSede1;
pointToPointSede1.SetDeviceAttribute ("DataRate", StringValue ("100Mbps")); //todo supongo datos, ya se cambiara
pointToPointSede1.SetChannelAttribute ("Delay", StringValue ("2ms"));
p2pDevicesSede1 = pointToPoint.Install (telefonosSede1);
//Instalo dispositivo en telefonos Sede 2
PointToPointHelper pointToPointSede2;
NetDeviceContainer p2pDevicesSede2;
pointToPointSede2.SetDeviceAttribute ("DataRate", StringValue ("100Mbps")); //todo supongo datos, ya se cambiara
pointToPointSede2.SetChannelAttribute ("Delay", StringValue ("2ms"));
p2pDevicesSede2 = pointToPoint.Install (telefonosSede2);
//Instalo pila TCP/IP en todos los nodos
InternetStackHelper stack;
stack.Install(telefonosSede1); //todo tengo que instalar pila tcp/ip en Routers?
stack.Install(telefonosSede2);
//Direccionamiento IP
Ipv4AddressHelper address;
Ipv4InterfaceContainer p2pInterfacesSede1;
address.SetBase("10.1.1.0","255.255.0.0");
p2pInterfacesSede1 = address.Assign(p2pDevicesSede1);
Ipv4InterfaceContainer p2pInterfacesSede2;
address.SetBase("10.1.2.0","255.255.0.0");
p2pInterfacesSede2 = address.Assign(p2pDevicesSede2);
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
//Establezco un sumidero de paquetes en cada telefono
//Utilizamos el puerto 9 para el sumidero
uint16_t port = 9;
PacketSinkHelper sink ("ns3::UdpSocketFactory", Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
ApplicationContainer sumidero = sink.Install(telefonosSede1);
ApplicationContainer sumidero = sink.Install(telefonosSede2);
//todo Crear aplicacion OnOff (mirar voip.cc y añadirlo a cada telefono)
// Ejecutar simulaci�n
// Utilizar valores de la estructura resultado
// Para obtener la velocidad: velocidades[resultado->velocidad]
// Calcular calidad de servicio y devolverla
return(1.0);
}
<commit_msg>Escenario terminado, todo: detalles de app voip y balanceo de carga<commit_after>/*
Parámetros de entrada del programa:
· Número de usuarios en sede 1
· Número de usuarios en sede 2
· Distintas velocidades de enlace que se pueden contratar con el operador
· Tasa media de ocurrencia de llamadas de los usuarios
· Calidad de servicio requerida
· Intervalo de la tasa de bits del códec de audio.
Parámetros de salida del programa:
· Número de enlaces y velocidad a contratar con el operador.
· Número máximo de usuarios que pueden hablar a la vez.
· Parámetros de calidad conseguidos finalmente (retardo etc.)
· Gráficas:
· Una gráfica para cada número de enlaces con la evolución de la QoS respecto a la capacidad de enlace.
· Una gráfica para cada número de enlaces con la evolución de los parámetros usados para medir la QoS según la capacidad de enlace.
*/
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/ipv4-global-routing-helper.h"
#include "ns3/gnuplot.h"
#include "Observador.h"
#define DURACION 120.0
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("Simvoip");
// Punto 3D
typedef struct {
uint8_t enlaces;
uint8_t velocidad;
double qos;
}Punto;
/*
* Recibe el n�mero de enlaces y su velocidad y el objeto observador a utilizar
* devuelve la QoS conseguida
*/
double simular(Punto * resultado, std::map<uint8_t, DataRate> velocidades, Observador *observador,uint16_t telef1,uint16_t telef2, uint8_t enlaces);
using namespace ns3;
int main(int argc, char *argv[])
{
double qos_objetivo = 1.0;
uint32_t telef1 = 100;
uint32_t telef2 = 100;
std::string sVelocidades = "1Mbps;2Mbps;5Mbps;10Mbps;20Mbps;30Mbps;50Mbps;100Mbps;200Mbps;300Mbps";
double tasaLlamadas = 0.67;
std::string sTasaCodec = "64kbps;96kbps";
DataRate tasaCodec[2]; // Forman el intervalo en el que estará la tasa distribuida uniformemente
std::map<uint8_t, DataRate> velocidades; // Velocidades permitidas
// Obtener parámetros de cmd
CommandLine cmd;
cmd.AddValue("qos", "Calidad de servicio objetivo", qos_objetivo);
cmd.AddValue("tA", "Número de usuarios en la sede A", telef1);
cmd.AddValue("tB", "Número de usuarios en la sede B", telef2);
cmd.AddValue("velocidades", "velocidades de enlace que se pueden contratar con el operador separadas por ;", sVelocidades);
cmd.AddValue("tasaLlamadas", "Tasa media de ocurrencia de llamadas de los usuarios", tasaLlamadas);
cmd.AddValue("tasaCodec", "Intervalo de la tasa de bits del códec de audio", sTasaCodec);
cmd.Parse(argc, argv);
// Parsear cadena introduciendo velocidades de enlace posibles en el map
size_t posicion = 0;
uint8_t n = 0;
while ((posicion = sVelocidades.find(";")) != std::string::npos) {
// Guardar cada elemento en el map
velocidades[n] = DataRate(sVelocidades.substr(0, posicion));
sVelocidades.erase(0, posicion + 1);
}
// Parsear intervalo de tasa del codec
n = 0;
while ((posicion = sTasaCodec.find(";")) != std::string::npos) {
tasaCodec[n] = DataRate(sTasaCodec.substr(0, posicion));
sTasaCodec.erase(0, posicion + 1);
}
// TODO Preparar gráficas
// Gráfica 1
Gnuplot plot1;
plot1.SetTitle("---");
plot1.SetLegend("Tiempo medio de permanencia en el estado On", "Porcentaje de paquetes correctamente transmitidos");
// Gráfica 2
Gnuplot plot2;
plot2.SetTitle("---");
plot2.SetLegend("Tiempo medio de permanencia en el estado On", "Latencia (us)");
Time::SetResolution(Time::US);
Observador * observador = new Observador();
Punto anterior = { 0,0,0.0 };
Punto resultado;
// Los resultados de las simulaciones se guardan en una estructura para el algoritmo de predicci�n
while (resultado.qos < qos_objetivo)
{
simular(&resultado, velocidades, observador, telef1, telef2);
// ALGORITMO DE PREDICCIÓN LINEALIZANDO
// y = mx + n
// m = dy/dx (delta)
// x = enlaces*velocidad
double m = ((resultado.qos - anterior.qos) / ((resultado.enlaces*velocidades[resultado.velocidad].GetBitRate() / 1e6) - (anterior.enlaces*velocidades[anterior.velocidad].GetBitRate() / 1e6)));
// qos = mx -> x = qos/m
uint32_t x = qos_objetivo / m;
// Pasar el resultado al anterior
anterior = resultado;
// Cambiar coordenadas de resultado para la siguiente iteración
// Enlaces mínimos
resultado.enlaces = 0;
resultado.velocidad = 0;
while ((x / velocidades[resultado.velocidad].GetBitRate() / 1e6)>resultado.enlaces)
{
if (resultado.velocidad == (velocidades.size() - 1))
{
resultado.enlaces++;
resultado.velocidad = 0;
}
else
{
resultado.velocidad++;
}
}
delete observador;
}
return 0;
}
//todo decidir que velocidades tendra la red interna de cada sede, por ahora supongo
//velocidades de 100Mbps
//todo posible error: a los Routers les estoy instalando las apps que llevan los telefonos y les estoy dando direccionamiento
//solucionar eso
/*
* velocidades[resultado->velocidad]; ---> velocidad que utilizo en los enlaces.
*
*
*
*/
double simular(Punto * resultado, std::map<uint8_t, DataRate> velocidades, Observador *observador, uint16_t telef1, uint16_t telef2)
{
Ptr<UniformRandomVariable> varon;
Ptr<UniformRandomVariable> varoff;
//primero creamos los R de salida de cada central
NodeContainer R;
R.Create(2);
//Estos nodos irán unidos por enlaces p2p
//Configuro la topologia p2p
PointToPointHelper p2p;
p2p.SetDeviceAttribute ("DataRate", DataRateValue (velocidades[resultado->velocidad]));
p2p.SetChannelAttribute ("Delay", StringValue ("2ms"));
//Creo los enlaces p2p entre centrales
NetDeviceContainer Rdevices;
for (uint8_t j=0;j<resultado->enlaces;j++){
NetDeviceContainer enlaceRouters = p2p.Install (NodeContainer (R.Get(0), R.Get(1) ) );
Rdevices.Add (enlaceRouters.Get(0));
Rdevices.Add (enlaceRouters.Get(1));
}
//----Esto seria para las centrales. Ahora los telefonos/bridges
NodeContainer terminales1; //Sede1
NodeContainer terminales2; //Sede 2
terminales1.Create(telef1);
terminales2.Create(telef2);
//Añado el R al nodecontainer de los telefonos para realizar los enlaces despues
terminales1.Add(R.Get(0));
terminales2.Add(R.Get(1));
NodeContainer Bridge1;//Sede 1
NodeContainer Bridge2;//Sede 2
PointToPointHelper p2pInterno;
p2pInterno.SetDeviceAttribute ("DataRate", StringValue ("100Mbps"));
p2pInterno.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer terminales1Devices;
NetDeviceContainer Bridge1Devices;
for(uint16_t j=0;j<telef1+1;j++){
NetDeviceContainer enlace1 = p2pInterno.Install (NodeContainer(terminales1.Get(j),Bridge1) );
terminales1Devices.Add (enlace1.Get(0));
Bridge1Devices.Add (enlace1.Get(1));
}
NetDeviceContainer terminales2Devices;
NetDeviceContainer Bridge2Devices;
for(uint16_t j=0;j<telef2+1;j++){
NetDeviceContainer enlace2 = p2pInterno.Install (NodeContainer(terminales2.Get(j),Bridge2) );
terminales2Devices.Add (enlace2.Get(0));
Bridge2Devices.Add (enlace2.Get(1));
}
//Una vez todos los enlaces creados, creo el bridge que conmutara paquetes
Ptr<Node> Puente1 = Bridge1.Get (0);
BridgeHelper b1;
b1.Install (Puente1, Bridge1Devices);
Ptr<Node> Puente2 = Bridge1.Get (0);
BridgeHelper b2;
b2.Install (Puente2, Bridge2Devices);
//Añado la pila TCP/IP a los dispositivos
InternetStackHelper stack;
stack.Install(R);
stack.Install(terminales1);
stack.Install(terminales2);
Ipv4AddressHelper ipv4;
Ipv4InterfaceContainer telefonosSede1;
ipv4.SetBase ("10.1.0.0","255.255.0.0");
telefonosSede1 = ipv4.Assign (terminales1Devices);
Ipv4AddressHelper ipv4v2;
Ipv4InterfaceContainer telefonosSede2;
ipv4v2.SetBase ("10.2.0.0","255.255.0.0");
telefonosSede2 = ipv4v2.Assign (terminales2Devices);
Ipv4AddressHelper ipv4v3;
Ipv4InterfaceContainer routers;
ipv4v3.SetBase ("10.3.0.0","255.255.255.0");
routers = ipv4v3.Assign (Rdevices);
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
//Creo aplicacion UDP sumidero y tal.
//Establezco un sumidero de paquetes en cada telefono
//Utilizamos el puerto 5600 para el sumidero
uint16_t port = 5600;
PacketSinkHelper sink ("ns3::UdpSocketFactory", Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
ApplicationContainer sumidero1 = sink.Install(terminales1);
ApplicationContainer sumidero2 = sink.Install(terminales2);
//Creo aplicacion que envia paquetes ON/OFF para simular llamada voip
//Problema con direccionamiento
OnOffHelper clientes ("ns3::UdpSocketFactory",
Address (InetSocketAddress (Ipv4Address::GetAny (), port)));
ApplicationContainer tx1 = clientes.Install(terminales1);
ApplicationContainer tx2 = clientes.Install(terminales2);
#define MAXONVOIP 0.1
#define MINONVOIP 0.2
#define MAXOFFVOIP 0.8
#define MINOFFVOIP 0.9
varon=CreateObject<UniformRandomVariable>();
varon->SetAttribute("Max", DoubleValue(MAXONVOIP));
varon->SetAttribute("Min", DoubleValue(MINONVOIP));
varoff=CreateObject<UniformRandomVariable>();
varoff->SetAttribute("Max", DoubleValue(MAXOFFVOIP));
varoff->SetAttribute("Min", DoubleValue(MINOFFVOIP));
//Configuramos la aplicación OnOff
clientes.SetConstantRate (DataRate ("64kbps"));
clientes.SetAttribute("OnTime", PointerValue(varon));
clientes.SetAttribute("OffTime", PointerValue(varoff));
//Cambio de cola de ROUTER 1 (por si hace falta)
PointerValue tmp;
R.Get(0)->GetObject<NetDevice>()->GetAttribute("TxQueue",tmp);
Ptr<Object> txQueue = tmp.GetObject();
Ptr<DropTailQueue> dtq = txQueue->GetObject <DropTailQueue>();
NS_ASSERT (dtq!=0);
UintegerValue limit;
dtq->GetAttribute("MaxPackets",limit);
NS_LOG_INFO ("Tamaño de la cola del Router 1: "<<limit.Get()<<" paquetes" );
dtq->SetAttribute("MaxPackets",UintegerValue(100));
dtq->GetAttribute("MaxPackets",limit);
NS_LOG_INFO("Tamaño de la cola del Router 1 cambiado a: "<<limit.Get()<<" paquetes");
//Cambio de cola de ROUTER 2 (por si hace falta)
PointerValue tmp;
R.Get(1)->GetObject<NetDevice>()->GetAttribute("TxQueue",tmp);
Ptr<Object> txQueue = tmp.GetObject();
Ptr<DropTailQueue> dtq = txQueue->GetObject <DropTailQueue>();
NS_ASSERT (dtq!=0);
UintegerValue limit;
dtq->GetAttribute("MaxPackets",limit);
NS_LOG_INFO ("Tamaño de la cola del Router 2: "<<limit.Get()<<" paquetes" );
dtq->SetAttribute("MaxPackets",UintegerValue(100));
dtq->GetAttribute("MaxPackets",limit);
NS_LOG_INFO("Tamaño de la cola del Router 2 cambiado a: "<<limit.Get()<<" paquetes");
//SUSCRIPCION DE TRAZAS
tx1.Start (Seconds (2.0));
tx2.Start (Seconds (2.0));
tx1.Stop (Seconds (15.0));
tx2.Stop (Seconds (15.0));
Simulator::Run ();
Simulator::Destroy ();
}
<|endoftext|>
|
<commit_before>/***************************************************************************
FilterEudoraAb.cxx - description
------------------------------------
begin : Fri Jun 30 2000
copyright : (C) 2000 by Hans Dijkema
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "filter_eudora_ab.hxx"
#include <klocale.h>
#include <kfiledialog.h>
#define CTRL_C 3
FilterEudoraAb::FilterEudoraAb() : Filter(i18n("Import Filter for Eudora Light Addressbook"),"Hans Dijkema")
, LINES(0)
{
}
FilterEudoraAb::~FilterEudoraAb()
{
}
void FilterEudoraAb::import(FilterInfo *info)
{
QString file;
QWidget *parent=info->parent();
if (!kabStart(info)) return;
file=KFileDialog::getOpenFileName(QDir::homeDirPath() ,"*.[tT][xX][tT]",parent);
if (file.length()==0)
{
info->alert(i18n("No address book chosen"));
return;
}
QFile F(file);
if (! F.open(IO_ReadOnly)) {
info->alert(i18n("Unable to open file '%1'").arg(file));
return;
}
info->from(file);
info->to(i18n("KAddressBook"));
info->current(i18n("Currently converting Eudora Light addresses to address book"));
convert(F,info);
{int i,N;
LINES=keys.size();
for(i=0,N=keys.size();i<N;i++) {
/* printf("%s %s %s %s %s %s\n",keys[i].latin1(),emails[i].latin1(),
names[i].latin1(),adr[i].latin1(),
phones[i].latin1(),comments[i].latin1()
);
*/
{
QString msg=i18n("Adding/Merging '%1' email '%2'").arg(keys[i]).arg(emails[i]);
info->log(msg);
}
QString comment;
if(adr[i].isEmpty())
comment=comments[i];
else
comment=adr[i]+"\n"+comments[i];
kabAddress(info,"Eudora Light",
keys[i],(emails[i].isEmpty()) ? QString::null : emails[i],
QString::null,QString::null,QString::null,
(names[i].isEmpty()) ? QString::null : names[i],
QString::null,
QString::null,QString::null,
QString::null,QString::null,
QString::null,
QString::null,QString::null,
QString::null,QString::null,
(phones[i].isNull()) ? QString::null : phones[i],QString::null,
QString::null,QString::null,
QString::null,QString::null,
(comments[i].isNull()) ? QString::null : comments[i], QString::null
);
{
info->overall(100*i/LINES);
}
}
{
info->log(i18n("Added %1 keys").arg(keys.size()));
}
}
kabStop(info);
info->current(i18n("Finished converting Eudora Light addresses to KAddressBook"));
F.close();
info->overall(100);
}
#define LINELEN 10240
void FilterEudoraAb::convert(QFile& f,FilterInfo *info)
{
QCString line(LINELEN+1);
int e;
int LINE=0;
while(f.readLine(line.data(),LINELEN)) { LINES+=1; }
f.reset();
while(f.readLine(line.data(),LINELEN)) {
LINE+=1;
info->current(100 * LINE / LINES );
if (line.left(5) == "alias") {
QString k = key(line);
e=find(k);
keys[e]=k;
emails[e]=email(line);
{
QString msg=i18n("Reading '%1', email '%2'").arg(k).arg(emails[e]);
info->log(msg);
}
}
else if (line.left(4) == "note") {
QString k = key(line);
e=find(k);
keys[e]=k;
comments[e]=comment(line);
names[e]=get(line,"name");
adr[e]=get(line, "address");
phones[e]=get(line, "phone");
}
}
info->current(100);
}
QString FilterEudoraAb::key(const QString& line) const
{
int b,e;
QString result;
b=line.find('\"',0);if (b==-1) {
b=line.find(' ');
if (b==-1) { return result; }
b+=1;
e=line.find(' ',b);
result=line.mid(b,e-b);
return result;
}
b+=1;
e=line.find('\"',b);if (e==-1) { return result; }
result=line.mid(b,e-b);
return result;
}
QString FilterEudoraAb::email(const QString& line) const
{
int b;
QString result;
b=line.findRev('\"');if (b==-1) {
b=line.findRev(' ');if(b==-1) { return result; }
}
result=line.mid(b+1);
return result;
}
QString FilterEudoraAb::comment(const QString& line) const
{
int b;
QString result;
unsigned int i;
b=line.findRev('>');if (b==-1) {
b=line.findRev('\"');if (b==-1) { return result; }
}
result=line.mid(b+1);
for(i=0;i<result.length();i++) {
if (result[i]==CTRL_C) { result[i]='\n'; }
}
return result;
}
QString FilterEudoraAb::get(const QString& line,const QString& key) const
{
QString result;
QString fd="<"+key+":";
int b,e;
unsigned int i;
b=line.find(fd);if (b==-1) { return result; }
b+=fd.length();
e=line.find('>',b);if (e==-1) { return result; }
e-=1;
result=line.mid(b,e-b+1);
for(i=0;i<result.length();i++) {
if (result[i]==CTRL_C) { result[i]='\n'; }
}
return result;
}
int FilterEudoraAb::find(const QString& key) const
{
return keys.findIndex(key);
}
// vim: ts=2 sw=2 et
<commit_msg>Little fix to my last commit<commit_after>/***************************************************************************
FilterEudoraAb.cxx - description
------------------------------------
begin : Fri Jun 30 2000
copyright : (C) 2000 by Hans Dijkema
email : [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "filter_eudora_ab.hxx"
#include <klocale.h>
#include <kfiledialog.h>
#define CTRL_C 3
FilterEudoraAb::FilterEudoraAb() : Filter(i18n("Import Filter for Eudora Light Addressbook"),"Hans Dijkema")
, LINES(0)
{
}
FilterEudoraAb::~FilterEudoraAb()
{
}
void FilterEudoraAb::import(FilterInfo *info)
{
QString file;
QWidget *parent=info->parent();
if (!kabStart(info)) return;
file=KFileDialog::getOpenFileName(QDir::homeDirPath() ,"*.[tT][xX][tT]",parent);
if (file.length()==0)
{
info->alert(i18n("No address book chosen"));
return;
}
QFile F(file);
if (! F.open(IO_ReadOnly)) {
info->alert(i18n("Unable to open file '%1'").arg(file));
return;
}
info->from(file);
info->to(i18n("KAddressBook"));
info->current(i18n("Currently converting Eudora Light addresses to address book"));
convert(F,info);
{int i,N;
LINES=keys.size();
for(i=0,N=keys.size();i<N;i++) {
/* printf("%s %s %s %s %s %s\n",keys[i].latin1(),emails[i].latin1(),
names[i].latin1(),adr[i].latin1(),
phones[i].latin1(),comments[i].latin1()
);
*/
{
QString msg=i18n("Adding/Merging '%1' email '%2'").arg(keys[i]).arg(emails[i]);
info->log(msg);
}
QString comment;
if(adr[i].isEmpty())
comment=comments[i];
else
comment=adr[i]+"\n"+comments[i];
kabAddress(info,"Eudora Light",
keys[i],(emails[i].isEmpty()) ? QString::null : emails[i],
QString::null,QString::null,QString::null,
(names[i].isEmpty()) ? QString::null : names[i],
QString::null,
QString::null,QString::null,
QString::null,QString::null,
QString::null,
QString::null,QString::null,
QString::null,QString::null,
(phones[i].isNull()) ? QString::null : phones[i],QString::null,
QString::null,QString::null,
QString::null,QString::null,
(comments[i].isNull()) ? QString::null : comments[i], QString::null
);
{
info->overall(100*i/LINES);
}
}
{
info->log(i18n("Added %1 keys").arg(keys.size()));
}
}
kabStop(info);
info->current(i18n("Finished converting Eudora Light addresses to KAddressBook"));
F.close();
info->overall(100);
}
#define LINELEN 10240
void FilterEudoraAb::convert(QFile& f,FilterInfo *info)
{
QCString line(LINELEN+1);
int e, i;
int LINE=0;
while(f.readLine(line.data(),LINELEN)) { LINES+=1; }
f.reset();
while(f.readLine(line.data(),LINELEN)) {
LINE+=1;
info->current(100 * LINE / LINES );
for(i=0;line[i]!='\n' && line[i]!='\0';i++);
line[i]='\0'; // Strip newline
if (line.left(5) == "alias") {
QString k = key(line);
e=find(k);
keys[e]=k;
emails[e]=email(line);
{
QString msg=i18n("Reading '%1', email '%2'").arg(k).arg(emails[e]);
info->log(msg);
}
}
else if (line.left(4) == "note") {
QString k = key(line);
e=find(k);
keys[e]=k;
comments[e]=comment(line);
names[e]=get(line,"name");
adr[e]=get(line, "address");
phones[e]=get(line, "phone");
}
}
info->current(100);
}
QString FilterEudoraAb::key(const QString& line) const
{
int b,e;
QString result;
b=line.find('\"',0);if (b==-1) {
b=line.find(' ');
if (b==-1) { return result; }
b+=1;
e=line.find(' ',b);
result=line.mid(b,e-b);
return result;
}
b+=1;
e=line.find('\"',b);if (e==-1) { return result; }
result=line.mid(b,e-b);
return result;
}
QString FilterEudoraAb::email(const QString& line) const
{
int b;
QString result;
b=line.findRev('\"');if (b==-1) {
b=line.findRev(' ');if(b==-1) { return result; }
}
result=line.mid(b+1);
return result;
}
QString FilterEudoraAb::comment(const QString& line) const
{
int b;
QString result;
unsigned int i;
b=line.findRev('>');if (b==-1) {
b=line.findRev('\"');if (b==-1) { return result; }
}
result=line.mid(b+1);
for(i=0;i<result.length();i++) {
if (result[i]==CTRL_C) { result[i]='\n'; }
}
return result;
}
QString FilterEudoraAb::get(const QString& line,const QString& key) const
{
QString result;
QString fd="<"+key+":";
int b,e;
unsigned int i;
b=line.find(fd);if (b==-1) { return result; }
b+=fd.length();
e=line.find('>',b);if (e==-1) { return result; }
e-=1;
result=line.mid(b,e-b+1);
for(i=0;i<result.length();i++) {
if (result[i]==CTRL_C) { result[i]='\n'; }
}
return result;
}
int FilterEudoraAb::find(const QString& key) const
{
return keys.findIndex(key);
}
// vim: ts=2 sw=2 et
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 The Kythe 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 <utility>
#include "absl/strings/match.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "kythe/cxx/common/kythe_uri.h"
namespace kythe {
namespace {
constexpr char kHexDigits[] = "0123456789ABCDEF";
/// The URI scheme label for Kythe.
constexpr char kUriScheme[] = "kythe";
constexpr char kUriPrefix[] = "kythe:";
/// \brief Returns whether a byte should be escaped.
/// \param mode The escaping mode to use.
/// \param c The byte to examine.
bool should_escape(UriEscapeMode mode, char c) {
return !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' ||
c == '~' || (mode == UriEscapeMode::kEscapePaths && c == '/'));
}
/// \brief Returns the value of a hex digit.
/// \param digit The hex digit.
/// \return The value of the digit, or -1 if it was not a hex digit.
int value_for_hex_digit(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return 10 + (c - 'a');
} else if (c >= 'A' && c <= 'F') {
return 10 + (c - 'A');
}
return -1;
}
std::pair<absl::string_view, absl::string_view> Split(absl::string_view input,
char ch) {
return absl::StrSplit(input, absl::MaxSplits(ch, 1));
}
// Predicate used in CleanPath for skipping empty components
// and components consistening of a single '.'.
struct SkipEmptyDot {
bool operator()(absl::string_view sp) { return !(sp.empty() || sp == "."); }
};
// Deal with relative paths as well as '/' and '//'.
absl::string_view PathPrefix(absl::string_view path) {
int slash_count = 0;
for (char ch : path) {
if (ch == '/' && ++slash_count <= 2) continue;
break;
}
switch (slash_count) {
case 0:
return "";
case 2:
return "//";
default:
return "/";
}
}
// TODO(shahms): Use path_utils.h when it doesn't depend on LLVM.
std::string CleanPath(absl::string_view input) {
const bool is_absolute_path = absl::StartsWith(input, "/");
std::vector<absl::string_view> parts;
for (absl::string_view comp : absl::StrSplit(input, '/', SkipEmptyDot{})) {
if (comp == "..") {
if (!parts.empty() && parts.back() != "..") {
parts.pop_back();
continue;
}
if (is_absolute_path) continue;
}
parts.push_back(comp);
}
// Deal with leading '//' as well as '/'.
return absl::StrCat(PathPrefix(input), absl::StrJoin(parts, "/"));
}
} // namespace
std::string UriEscape(UriEscapeMode mode, absl::string_view uri) {
size_t num_escapes = 0;
for (char c : uri) {
if (should_escape(mode, c)) {
++num_escapes;
}
}
std::string result;
result.reserve(num_escapes * 2 + uri.size());
for (char c : uri) {
if (should_escape(mode, c)) {
result.push_back('%');
result.push_back(kHexDigits[(c >> 4) & 0xF]);
result.push_back(kHexDigits[c & 0xF]);
} else {
result.push_back(c);
}
}
return result;
}
/// \brief URI-unescapes a string.
/// \param string The string to unescape.
/// \return A pair of (success, error-or-unescaped-string).
std::pair<bool, std::string> UriUnescape(absl::string_view string) {
size_t num_escapes = 0;
for (size_t i = 0, s = string.size(); i < s; ++i) {
if (string[i] == '%') {
++num_escapes;
if (i + 3 > string.size()) {
return std::make_pair(false, "bad escape");
}
i += 2;
}
}
std::string result;
result.reserve(string.size() - num_escapes * 2);
for (size_t i = 0, s = string.size(); i < s; ++i) {
char c = string[i];
if (c != '%') {
result.push_back(c);
continue;
}
int high = value_for_hex_digit(string[++i]);
int low = value_for_hex_digit(string[++i]);
if (high < 0 || low < 0) {
return std::make_pair(false, "bad hex digit");
}
result.push_back((high << 4) | low);
}
return std::make_pair(true, result);
}
std::string URI::ToString() const {
std::string result = kUriPrefix;
if (vname_.signature().empty() && vname_.path().empty() &&
vname_.root().empty() && vname_.corpus().empty() &&
vname_.language().empty()) {
return result;
}
absl::string_view signature = vname_.signature();
absl::string_view path = vname_.path();
absl::string_view corpus = vname_.corpus();
absl::string_view language = vname_.language();
absl::string_view root = vname_.root();
if (!corpus.empty()) {
result.append("//");
result.append(UriEscape(UriEscapeMode::kEscapePaths, corpus));
}
if (!language.empty()) {
result.append("?lang=");
result.append(UriEscape(UriEscapeMode::kEscapeAll, language));
}
if (!path.empty()) {
result.append("?path=");
result.append(UriEscape(UriEscapeMode::kEscapePaths, CleanPath(path)));
}
if (!root.empty()) {
result.append("?root=");
result.append(UriEscape(UriEscapeMode::kEscapePaths, root));
}
if (!signature.empty()) {
result.push_back('#');
result.append(UriEscape(UriEscapeMode::kEscapeAll, signature));
}
return result;
}
/// \brief Separate out the scheme component of `uri` if one exists.
/// \return (scheme, tail) if there was a scheme; ("", uri) otherwise.
static std::pair<absl::string_view, absl::string_view> SplitScheme(
absl::string_view uri) {
for (size_t i = 0, s = uri.size(); i != s; ++i) {
char c = uri[i];
if (c == ':') {
return std::make_pair(uri.substr(0, i), uri.substr(i));
} else if ((i == 0 &&
((c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.')) ||
!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
break;
}
}
return std::make_pair(absl::string_view(), uri);
}
URI::URI(const kythe::proto::VName& from_vname) : vname_(from_vname) {}
bool URI::ParseString(absl::string_view input) {
auto head_fragment = Split(input, '#');
auto head = head_fragment.first, fragment = head_fragment.second;
auto scheme_head = SplitScheme(head);
auto scheme = scheme_head.first;
head = scheme_head.second;
if (scheme.empty()) {
if (absl::StartsWith(head, ":")) {
return false;
}
} else if (scheme != kUriScheme) {
return false;
} else if (!head.empty()) {
head.remove_prefix(1);
}
auto head_attrs = Split(head, '?');
head = head_attrs.first;
auto attrs = head_attrs.second;
std::string corpus;
if (!head.empty()) {
if (!absl::StartsWith(head, "//")) {
return false;
}
auto maybe_corpus = UriUnescape(head.substr(2));
if (!maybe_corpus.first) {
return false;
}
corpus = maybe_corpus.second;
}
auto maybe_sig = UriUnescape(fragment);
if (!maybe_sig.first) {
return false;
}
auto signature = maybe_sig.second;
while (!attrs.empty()) {
auto attr_rest = Split(attrs, '?');
auto attr = attr_rest.first;
attrs = attr_rest.second;
auto name_value = Split(attr, '=');
auto maybe_value = UriUnescape(name_value.second);
if (!maybe_value.first || maybe_value.second.empty()) {
return false;
}
if (name_value.first == "lang") {
vname_.set_language(maybe_value.second);
} else if (name_value.first == "root") {
vname_.set_root(maybe_value.second);
} else if (name_value.first == "path") {
vname_.set_path(CleanPath(maybe_value.second));
} else {
return false;
}
}
vname_.set_signature(signature);
vname_.set_corpus(corpus);
return true;
}
} // namespace kythe
<commit_msg>Fix lint warning (#3101)<commit_after>/*
* Copyright 2015 The Kythe 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 <utility>
#include "absl/strings/match.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "kythe/cxx/common/kythe_uri.h"
namespace kythe {
namespace {
constexpr char kHexDigits[] = "0123456789ABCDEF";
/// The URI scheme label for Kythe.
constexpr char kUriScheme[] = "kythe";
constexpr char kUriPrefix[] = "kythe:";
/// \brief Returns whether a byte should be escaped.
/// \param mode The escaping mode to use.
/// \param c The byte to examine.
bool should_escape(UriEscapeMode mode, char c) {
return !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' ||
c == '~' || (mode == UriEscapeMode::kEscapePaths && c == '/'));
}
/// \brief Returns the value of a hex digit.
/// \param digit The hex digit.
/// \return The value of the digit, or -1 if it was not a hex digit.
int value_for_hex_digit(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return 10 + (c - 'a');
} else if (c >= 'A' && c <= 'F') {
return 10 + (c - 'A');
}
return -1;
}
std::pair<absl::string_view, absl::string_view> Split(absl::string_view input,
char ch) {
return absl::StrSplit(input, absl::MaxSplits(ch, 1));
}
// Predicate used in CleanPath for skipping empty components
// and components consistening of a single '.'.
struct SkipEmptyDot {
bool operator()(absl::string_view sp) { return !(sp.empty() || sp == "."); }
};
// Deal with relative paths as well as '/' and '//'.
absl::string_view PathPrefix(absl::string_view path) {
int slash_count = 0;
for (char ch : path) {
if (ch == '/' && ++slash_count <= 2) continue;
break;
}
switch (slash_count) {
case 0:
return "";
case 2:
return "//";
default:
return "/";
}
}
// TODO(shahms): Use path_utils.h when it doesn't depend on LLVM.
std::string CleanPath(absl::string_view input) {
const bool is_absolute_path = absl::StartsWith(input, "/");
std::vector<absl::string_view> parts;
for (absl::string_view comp : absl::StrSplit(input, '/', SkipEmptyDot{})) {
if (comp == "..") {
if (!parts.empty() && parts.back() != "..") {
parts.pop_back();
continue;
}
if (is_absolute_path) continue;
}
parts.push_back(comp);
}
// Deal with leading '//' as well as '/'.
return absl::StrCat(PathPrefix(input), absl::StrJoin(parts, "/"));
}
} // namespace
std::string UriEscape(UriEscapeMode mode, absl::string_view uri) {
size_t num_escapes = 0;
for (char c : uri) {
if (should_escape(mode, c)) {
++num_escapes;
}
}
std::string result;
result.reserve(num_escapes * 2 + uri.size());
for (char c : uri) {
if (should_escape(mode, c)) {
result.push_back('%');
result.push_back(kHexDigits[(c >> 4) & 0xF]);
result.push_back(kHexDigits[c & 0xF]);
} else {
result.push_back(c);
}
}
return result;
}
/// \brief URI-unescapes a string.
/// \param string The string to unescape.
/// \return A pair of (success, error-or-unescaped-string).
std::pair<bool, std::string> UriUnescape(absl::string_view string) {
size_t num_escapes = 0;
for (size_t i = 0, s = string.size(); i < s; ++i) {
if (string[i] == '%') {
++num_escapes;
if (i + 3 > string.size()) {
return std::make_pair(false, "bad escape");
}
i += 2;
}
}
std::string result;
result.reserve(string.size() - num_escapes * 2);
for (size_t i = 0, s = string.size(); i < s; ++i) {
char c = string[i];
if (c != '%') {
result.push_back(c);
continue;
}
int high = value_for_hex_digit(string[++i]);
int low = value_for_hex_digit(string[++i]);
if (high < 0 || low < 0) {
return std::make_pair(false, "bad hex digit");
}
result.push_back((high << 4) | low);
}
return std::make_pair(true, result);
}
std::string URI::ToString() const {
std::string result = kUriPrefix;
if (vname_.signature().empty() && vname_.path().empty() &&
vname_.root().empty() && vname_.corpus().empty() &&
vname_.language().empty()) {
return result;
}
absl::string_view signature = vname_.signature();
absl::string_view path = vname_.path();
absl::string_view corpus = vname_.corpus();
absl::string_view language = vname_.language();
absl::string_view root = vname_.root();
if (!corpus.empty()) {
result.append("//");
result.append(UriEscape(UriEscapeMode::kEscapePaths, corpus));
}
if (!language.empty()) {
result.append("?lang=");
result.append(UriEscape(UriEscapeMode::kEscapeAll, language));
}
if (!path.empty()) {
result.append("?path=");
result.append(UriEscape(UriEscapeMode::kEscapePaths, CleanPath(path)));
}
if (!root.empty()) {
result.append("?root=");
result.append(UriEscape(UriEscapeMode::kEscapePaths, root));
}
if (!signature.empty()) {
result.push_back('#');
result.append(UriEscape(UriEscapeMode::kEscapeAll, signature));
}
return result;
}
/// \brief Separate out the scheme component of `uri` if one exists.
/// \return (scheme, tail) if there was a scheme; ("", uri) otherwise.
static std::pair<absl::string_view, absl::string_view> SplitScheme(
absl::string_view uri) {
for (size_t i = 0, s = uri.size(); i != s; ++i) {
char c = uri[i];
if (c == ':') {
return std::make_pair(uri.substr(0, i), uri.substr(i));
} else if ((i == 0 &&
((c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.')) ||
!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
break;
}
}
return std::make_pair(absl::string_view(), uri);
}
URI::URI(const kythe::proto::VName& from_vname) : vname_(from_vname) {}
bool URI::ParseString(absl::string_view uri) {
auto head_fragment = Split(uri, '#');
auto head = head_fragment.first, fragment = head_fragment.second;
auto scheme_head = SplitScheme(head);
auto scheme = scheme_head.first;
head = scheme_head.second;
if (scheme.empty()) {
if (absl::StartsWith(head, ":")) {
return false;
}
} else if (scheme != kUriScheme) {
return false;
} else if (!head.empty()) {
head.remove_prefix(1);
}
auto head_attrs = Split(head, '?');
head = head_attrs.first;
auto attrs = head_attrs.second;
std::string corpus;
if (!head.empty()) {
if (!absl::StartsWith(head, "//")) {
return false;
}
auto maybe_corpus = UriUnescape(head.substr(2));
if (!maybe_corpus.first) {
return false;
}
corpus = maybe_corpus.second;
}
auto maybe_sig = UriUnescape(fragment);
if (!maybe_sig.first) {
return false;
}
auto signature = maybe_sig.second;
while (!attrs.empty()) {
auto attr_rest = Split(attrs, '?');
auto attr = attr_rest.first;
attrs = attr_rest.second;
auto name_value = Split(attr, '=');
auto maybe_value = UriUnescape(name_value.second);
if (!maybe_value.first || maybe_value.second.empty()) {
return false;
}
if (name_value.first == "lang") {
vname_.set_language(maybe_value.second);
} else if (name_value.first == "root") {
vname_.set_root(maybe_value.second);
} else if (name_value.first == "path") {
vname_.set_path(CleanPath(maybe_value.second));
} else {
return false;
}
}
vname_.set_signature(signature);
vname_.set_corpus(corpus);
return true;
}
} // namespace kythe
<|endoftext|>
|
<commit_before>/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#ifndef LYASTELLARCOMP_HPP
#define LYASTELLARCOMP_HPP
#include "GeometricStellarComp.hpp"
#include "LyaSpectrum.hpp"
//////////////////////////////////////////////////////////////////////
/** The LyaStellarComp class is a subclass of the GeometricStellarComp class and represents a Lyα
emitting component that uses a built-in geometry in a Lyα simulation. The velocity spectrum of
the emission can be chosen to be either line emission at a specified velocity, or a flat
continuum spectrum over the entire velocity range. */
class LyaStellarComp : public GeometricStellarComp
{
Q_OBJECT
Q_CLASSINFO("Title", "a Lyα component with a built-in geometry")
Q_CLASSINFO("AllowedIf", "LyaMonteCarloSimulation")
Q_CLASSINFO("Property", "spectrum")
Q_CLASSINFO("Title", "the emission spectrum of the component")
//============= Construction - Setup - Destruction =============
public:
/** The default constructor. */
Q_INVOKABLE LyaStellarComp();
protected:
/** This function verifies the attribute values. */
void setupSelfBefore();
/** This function calculates the luminosity vector maintained by the GeometricStellarComp base
class using the emission spectrum provided as attribute. */
void setupSelfAfter();
//======== Setters & Getters for Discoverable Attributes =======
public:
/** Sets the Lyα emission spectrum for the stellar component. */
Q_INVOKABLE void setSpectrum(LyaSpectrum* value);
/** Returns the Lyα emission spectrum for the stellar component. */
Q_INVOKABLE LyaSpectrum* spectrum() const;
//======================== Data Members ========================
private:
LyaSpectrum* _spectrum;
};
//////////////////////////////////////////////////////////////////////
#endif // LYASTELLARCOMP_HPP
<commit_msg>Very minor changes in LyaStellarComp class<commit_after>/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#ifndef LYASTELLARCOMP_HPP
#define LYASTELLARCOMP_HPP
#include "GeometricStellarComp.hpp"
#include "LyaSpectrum.hpp"
//////////////////////////////////////////////////////////////////////
/** The LyaStellarComp class is a subclass of the GeometricStellarComp class and represents a
component that radiates the primary emission that can be used in a Lyα simulation. The geometry
(i.e. the spatial location of the sources) and the spectral distribution (the amount of
radiation emitted as a function of the velocity or wavelength) of the component can be set
independently. */
class LyaStellarComp : public GeometricStellarComp
{
Q_OBJECT
Q_CLASSINFO("Title", "a component with a built-in geometry (to be used in a Lyα simulation)")
Q_CLASSINFO("AllowedIf", "LyaMonteCarloSimulation")
Q_CLASSINFO("Property", "spectrum")
Q_CLASSINFO("Title", "the emission spectrum")
//============= Construction - Setup - Destruction =============
public:
/** The default constructor. */
Q_INVOKABLE LyaStellarComp();
protected:
/** This function verifies the attribute values. */
void setupSelfBefore();
/** This function calculates the luminosity vector maintained by the GeometricStellarComp base
class using the emission spectrum provided as attribute. */
void setupSelfAfter();
//======== Setters & Getters for Discoverable Attributes =======
public:
/** Sets the Lyα emission spectrum for the stellar component. */
Q_INVOKABLE void setSpectrum(LyaSpectrum* value);
/** Returns the Lyα emission spectrum for the stellar component. */
Q_INVOKABLE LyaSpectrum* spectrum() const;
//======================== Data Members ========================
private:
LyaSpectrum* _spectrum;
};
//////////////////////////////////////////////////////////////////////
#endif // LYASTELLARCOMP_HPP
<|endoftext|>
|
<commit_before>/**************************************************************************
* Copyright(c) 1998-2007, 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. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------------------------------------
// Event handler for ESD input
// Author: Andreas Morsch, CERN
//-------------------------------------------------------------------------
#include <TTree.h>
#include <TChain.h>
#include <TFile.h>
#include <TArchiveFile.h>
#include <TObjArray.h>
#include <TSystem.h>
#include <TString.h>
#include <TObjString.h>
#include <TProcessID.h>
#include "AliESDInputHandler.h"
#include "AliESDEvent.h"
#include "AliESD.h"
#include "AliRunTag.h"
#include "AliEventTag.h"
#include "AliLog.h"
ClassImp(AliESDInputHandler)
//______________________________________________________________________________
AliESDInputHandler::AliESDInputHandler() :
AliInputEventHandler(),
fEvent(0x0),
fBranches(""),
fBranchesOn(""),
fAnalysisType(0),
fUseTags(kFALSE),
fChainT(0),
fTreeT(0),
fRunTag(0)
{
// default constructor
}
//______________________________________________________________________________
AliESDInputHandler::~AliESDInputHandler()
{
// destructor
// delete fEvent;
}
//______________________________________________________________________________
AliESDInputHandler::AliESDInputHandler(const char* name, const char* title):
AliInputEventHandler(name, title), fEvent(0x0), fBranches(""), fBranchesOn(""), fAnalysisType(0),
fUseTags(kFALSE), fChainT(0), fTreeT(0), fRunTag(0)
{
// Constructor
}
Bool_t AliESDInputHandler::Init(TTree* tree, Option_t* opt)
{
// Initialisation necessary for each new tree
fAnalysisType = opt;
fTree = tree;
if (!fTree) return kFALSE;
// Get pointer to ESD event
SwitchOffBranches();
SwitchOnBranches();
if (fEvent) {
delete fEvent;
fEvent = 0;
}
fEvent = new AliESDEvent();
fEvent->ReadFromTree(fTree);
return kTRUE;
}
Bool_t AliESDInputHandler::BeginEvent(Long64_t /*entry*/)
{
// Copy from old to new format if necessary
AliESD* old = ((AliESDEvent*) fEvent)->GetAliESDOld();
if (old) {
((AliESDEvent*)fEvent)->CopyFromOldESD();
old->Reset();
}
return kTRUE;
}
Bool_t AliESDInputHandler::FinishEvent()
{
// Finish the event
if(fEvent)fEvent->Reset();
return kTRUE;
}
Bool_t AliESDInputHandler::Notify(const char* path)
{
// Notify a directory change
AliInfo(Form("Directory change %s \n", path));
//
if (!fUseTags) return (kTRUE);
Bool_t zip = kFALSE;
TString fileName(path);
if(fileName.Contains("#AliESDs.root")){
fileName.ReplaceAll("#AliESDs.root", "");
zip = kTRUE;
}
else if (fileName.Contains("AliESDs.root")){
fileName.ReplaceAll("AliESDs.root", "");
}
else if(fileName.Contains("#AliAOD.root")){
fileName.ReplaceAll("#AliAOD.root", "");
zip = kTRUE;
}
else if(fileName.Contains("AliAOD.root")){
fileName.ReplaceAll("AliAOD.root", "");
}
else if(fileName.Contains("#galice.root")){
// For running with galice and kinematics alone...
fileName.ReplaceAll("#galice.root", "");
zip = kTRUE;
}
else if(fileName.Contains("galice.root")){
// For running with galice and kinematics alone...
fileName.ReplaceAll("galice.root", "");
}
TString* pathName = new TString("./");
*pathName = fileName;
printf("AliESDInputHandler::Notify() Path: %s\n", pathName->Data());
if (fRunTag) {
fRunTag->Clear();
} else {
fRunTag = new AliRunTag();
}
delete fTreeT; fTreeT = 0;
if (fChainT) {
delete fChainT;
fChainT = 0;
}
if (!fChainT) {
fChainT = new TChain("T");
}
const char* tagPattern = "ESD.tag.root";
const char* name = 0x0;
TString tagFilename;
if (zip) {
TFile* file = TFile::Open(fileName.Data());
TArchiveFile* arch = file->GetArchive();
TObjArray* arr = arch->GetMembers();
TIter next(arr);
while ((file = (TFile*) next())) {
name = file->GetName();
if (strstr(name,tagPattern)) {
tagFilename = pathName->Data();
tagFilename += "#";
tagFilename += name;
fChainT->Add(tagFilename);
AliInfo(Form("Adding %s to tag chain \n", tagFilename.Data()));
}//pattern check
} // archive file loop
} else {
void * dirp = gSystem->OpenDirectory(pathName->Data());
while((name = gSystem->GetDirEntry(dirp))) {
if (strstr(name,tagPattern)) {
tagFilename = pathName->Data();
tagFilename += "/";
tagFilename += name;
fChainT->Add(tagFilename);
AliInfo(Form("Adding %s to tag chain \n", tagFilename.Data()));
}//pattern check
}//directory loop
}
fChainT->SetBranchAddress("AliTAG",&fRunTag);
fChainT->GetEntry(0);
return kTRUE;
}
void AliESDInputHandler::SwitchOffBranches() const {
//
// Switch of branches on user request
TObjArray * tokens = fBranches.Tokenize(" ");
Int_t ntok = tokens->GetEntries();
for (Int_t i = 0; i < ntok; i++) {
TString str = ((TObjString*) tokens->At(i))->GetString();
if (str.Length() == 0)
continue;
fTree->SetBranchStatus(Form("%s%s%s","*", str.Data(), "*"), 0);
AliInfo(Form("Branch %s switched off \n", str.Data()));
}
}
void AliESDInputHandler::SwitchOnBranches() const {
//
// Switch of branches on user request
TObjArray * tokens = fBranchesOn.Tokenize(" ");
Int_t ntok = tokens->GetEntries();
for (Int_t i = 0; i < ntok; i++) {
TString str = ((TObjString*) tokens->At(i))->GetString();
if (str.Length() == 0)
continue;
fTree->SetBranchStatus(Form("%s%s%s","*", str.Data(), "*"), 1);
AliInfo(Form("Branch %s switched on \n", str.Data()));
}
}
<commit_msg>In Notify, correct handling of the local case where the path is empty. (R. Arnaldi, AM)<commit_after>/**************************************************************************
* Copyright(c) 1998-2007, 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. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------------------------------------
// Event handler for ESD input
// Author: Andreas Morsch, CERN
//-------------------------------------------------------------------------
#include <TTree.h>
#include <TChain.h>
#include <TFile.h>
#include <TArchiveFile.h>
#include <TObjArray.h>
#include <TSystem.h>
#include <TString.h>
#include <TObjString.h>
#include <TProcessID.h>
#include "AliESDInputHandler.h"
#include "AliESDEvent.h"
#include "AliESD.h"
#include "AliRunTag.h"
#include "AliEventTag.h"
#include "AliLog.h"
ClassImp(AliESDInputHandler)
//______________________________________________________________________________
AliESDInputHandler::AliESDInputHandler() :
AliInputEventHandler(),
fEvent(0x0),
fBranches(""),
fBranchesOn(""),
fAnalysisType(0),
fUseTags(kFALSE),
fChainT(0),
fTreeT(0),
fRunTag(0)
{
// default constructor
}
//______________________________________________________________________________
AliESDInputHandler::~AliESDInputHandler()
{
// destructor
// delete fEvent;
}
//______________________________________________________________________________
AliESDInputHandler::AliESDInputHandler(const char* name, const char* title):
AliInputEventHandler(name, title), fEvent(0x0), fBranches(""), fBranchesOn(""), fAnalysisType(0),
fUseTags(kFALSE), fChainT(0), fTreeT(0), fRunTag(0)
{
// Constructor
}
Bool_t AliESDInputHandler::Init(TTree* tree, Option_t* opt)
{
// Initialisation necessary for each new tree
fAnalysisType = opt;
fTree = tree;
if (!fTree) return kFALSE;
// Get pointer to ESD event
SwitchOffBranches();
SwitchOnBranches();
if (fEvent) {
delete fEvent;
fEvent = 0;
}
fEvent = new AliESDEvent();
fEvent->ReadFromTree(fTree);
return kTRUE;
}
Bool_t AliESDInputHandler::BeginEvent(Long64_t /*entry*/)
{
// Copy from old to new format if necessary
AliESD* old = ((AliESDEvent*) fEvent)->GetAliESDOld();
if (old) {
((AliESDEvent*)fEvent)->CopyFromOldESD();
old->Reset();
}
return kTRUE;
}
Bool_t AliESDInputHandler::FinishEvent()
{
// Finish the event
if(fEvent)fEvent->Reset();
return kTRUE;
}
Bool_t AliESDInputHandler::Notify(const char* path)
{
// Notify a directory change
AliInfo(Form("Directory change %s \n", path));
//
if (!fUseTags) return (kTRUE);
Bool_t zip = kFALSE;
TString fileName(path);
if(fileName.Contains("#AliESDs.root")){
fileName.ReplaceAll("#AliESDs.root", "");
zip = kTRUE;
}
else if (fileName.Contains("AliESDs.root")){
fileName.ReplaceAll("AliESDs.root", "");
}
else if(fileName.Contains("#AliAOD.root")){
fileName.ReplaceAll("#AliAOD.root", "");
zip = kTRUE;
}
else if(fileName.Contains("AliAOD.root")){
fileName.ReplaceAll("AliAOD.root", "");
}
else if(fileName.Contains("#galice.root")){
// For running with galice and kinematics alone...
fileName.ReplaceAll("#galice.root", "");
zip = kTRUE;
}
else if(fileName.Contains("galice.root")){
// For running with galice and kinematics alone...
fileName.ReplaceAll("galice.root", "");
}
TString* pathName = new TString("./");
if (fileName.Length() != 0) {
*pathName = fileName;
}
printf("AliESDInputHandler::Notify() Path: %s\n", pathName->Data());
if (fRunTag) {
fRunTag->Clear();
} else {
fRunTag = new AliRunTag();
}
delete fTreeT; fTreeT = 0;
if (fChainT) {
delete fChainT;
fChainT = 0;
}
if (!fChainT) {
fChainT = new TChain("T");
}
const char* tagPattern = "ESD.tag.root";
const char* name = 0x0;
TString tagFilename;
if (zip) {
TFile* file = TFile::Open(fileName.Data());
TArchiveFile* arch = file->GetArchive();
TObjArray* arr = arch->GetMembers();
TIter next(arr);
while ((file = (TFile*) next())) {
name = file->GetName();
if (strstr(name,tagPattern)) {
tagFilename = pathName->Data();
tagFilename += "#";
tagFilename += name;
fChainT->Add(tagFilename);
AliInfo(Form("Adding %s to tag chain \n", tagFilename.Data()));
}//pattern check
} // archive file loop
} else {
void * dirp = gSystem->OpenDirectory(pathName->Data());
while((name = gSystem->GetDirEntry(dirp))) {
if (strstr(name,tagPattern)) {
tagFilename = pathName->Data();
tagFilename += "/";
tagFilename += name;
fChainT->Add(tagFilename);
AliInfo(Form("Adding %s to tag chain \n", tagFilename.Data()));
}//pattern check
}//directory loop
}
fChainT->SetBranchAddress("AliTAG",&fRunTag);
fChainT->GetEntry(0);
return kTRUE;
}
void AliESDInputHandler::SwitchOffBranches() const {
//
// Switch of branches on user request
TObjArray * tokens = fBranches.Tokenize(" ");
Int_t ntok = tokens->GetEntries();
for (Int_t i = 0; i < ntok; i++) {
TString str = ((TObjString*) tokens->At(i))->GetString();
if (str.Length() == 0)
continue;
fTree->SetBranchStatus(Form("%s%s%s","*", str.Data(), "*"), 0);
AliInfo(Form("Branch %s switched off \n", str.Data()));
}
}
void AliESDInputHandler::SwitchOnBranches() const {
//
// Switch of branches on user request
TObjArray * tokens = fBranchesOn.Tokenize(" ");
Int_t ntok = tokens->GetEntries();
for (Int_t i = 0; i < ntok; i++) {
TString str = ((TObjString*) tokens->At(i))->GetString();
if (str.Length() == 0)
continue;
fTree->SetBranchStatus(Form("%s%s%s","*", str.Data(), "*"), 1);
AliInfo(Form("Branch %s switched on \n", str.Data()));
}
}
<|endoftext|>
|
<commit_before>/** \file create_literary_remains_records.cc
* \author Dr. Johannes Ruscheinski
*
* A tool for creating literary remains MARC records from Beacon files.
*/
/*
Copyright (C) 2019-2020, Library of the University of Tübingen
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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unordered_map>
#include <unordered_set>
#include "FileUtil.h"
#include "MARC.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "TimeUtil.h"
#include "util.h"
namespace {
struct TitleRecordCounter {
unsigned total_count_;
unsigned religious_studies_count_;
public:
TitleRecordCounter(): total_count_(0), religious_studies_count_(0) { }
TitleRecordCounter(const TitleRecordCounter &other) = default;
TitleRecordCounter(const bool is_relevant_to_reigious_studies)
: total_count_(1), religious_studies_count_(is_relevant_to_reigious_studies ? 1 : 0) { }
inline bool exceedsReligiousStudiesThreshold() const
{ return 100.0 * static_cast<double>(religious_studies_count_) / static_cast<double>(total_count_) >= 10.0 /* percent */; }
};
// Counts the number of religious studies title records for authors.
void CopyMarcAndCollectRelgiousStudiesFrequencies(
MARC::Reader * const reader, MARC::Writer * const writer,
std::unordered_map<std::string, TitleRecordCounter> * const author_ppn_to_relstudies_title_counters)
{
while (auto record = reader->read()) {
const bool rel_tag_found(record.findTag("REL") != record.end());
for (const auto &author_name_and_author_ppn : record.getAllAuthorsAndPPNs()) {
auto author_ppn_and_counter(author_ppn_to_relstudies_title_counters->find(author_name_and_author_ppn.second));
if (author_ppn_and_counter == author_ppn_to_relstudies_title_counters->end())
(*author_ppn_to_relstudies_title_counters)[author_name_and_author_ppn.second] = TitleRecordCounter(rel_tag_found);
else {
++(author_ppn_and_counter->second.total_count_);
if (rel_tag_found)
++(author_ppn_and_counter->second.religious_studies_count_);
}
}
writer->write(record);
}
}
struct LiteraryRemainsInfo {
std::string author_name_;
std::string url_;
std::string source_name_;
std::string dates_;
public:
LiteraryRemainsInfo() = default;
LiteraryRemainsInfo(const LiteraryRemainsInfo &other) = default;
LiteraryRemainsInfo(const std::string &author_name, const std::string &url, const std::string &source_name, const std::string &dates)
: author_name_(author_name), url_(url), source_name_(source_name), dates_(dates) { }
LiteraryRemainsInfo &operator=(const LiteraryRemainsInfo &rhs) = default;
};
std::vector<std::pair<RegexMatcher *, std::string>> CompileMatchers() {
// Please note that the order in the following vector matters. The first successful match will be used.
const std::vector<std::pair<std::string, std::string>> patterns_and_replacements {
{ "v([0-9]+) ?- ?v([0-9]+)", "\\1 v. Chr. - \\2 v. Chr." },
{ "v([0-9]+)" , "\\1 v. Chr." },
};
std::vector<std::pair<RegexMatcher *, std::string>> compiled_patterns_and_replacements;
for (const auto &pattern_and_replacement : patterns_and_replacements)
compiled_patterns_and_replacements.push_back(
std::pair<RegexMatcher *, std::string>(RegexMatcher::RegexMatcherFactoryOrDie(pattern_and_replacement.first),
pattern_and_replacement.second));
return compiled_patterns_and_replacements;
}
const std::vector<std::pair<RegexMatcher *, std::string>> matchers_and_replacements(CompileMatchers());
std::string ReplaceNonStandardBCEDates(const std::string &dates) {
for (const auto &matcher_and_replacement : matchers_and_replacements) {
RegexMatcher * const matcher(matcher_and_replacement.first);
const std::string replaced_string(matcher->replaceWithBackreferences(dates, matcher_and_replacement.second));
if (replaced_string != dates)
return replaced_string;
}
return dates;
}
void LoadAuthorGNDNumbersAndTagAuthors(
MARC::Reader * const reader, MARC::Writer * const writer,
const std::unordered_map<std::string, TitleRecordCounter> &author_ppn_to_relstudies_titles_counters,
std::unordered_map<std::string, std::vector<LiteraryRemainsInfo>> * const gnd_numbers_to_literary_remains_infos_map,
std::unordered_map<std::string, std::string> * const gnd_numbers_to_ppns_map)
{
unsigned total_count(0), references_count(0), tagged_count(0);
while (auto record = reader->read()) {
++total_count;
auto beacon_field(record.findTag("BEA"));
if (beacon_field == record.end()) {
writer->write(record);
continue;
}
const auto _100_field(record.findTag("100"));
if (_100_field == record.end() or not _100_field->hasSubfield('a')) {
writer->write(record);
continue;
}
std::string gnd_number;
if (not MARC::GetGNDCode(record, &gnd_number)) {
writer->write(record);
continue;
}
(*gnd_numbers_to_ppns_map)[gnd_number] = record.getControlNumber();
const auto numeration(_100_field->getFirstSubfieldWithCode('b'));
const auto titles_and_other_words_associated_with_a_name(_100_field->getFirstSubfieldWithCode('c'));
const auto name_and_numeration(_100_field->getFirstSubfieldWithCode('a') + (numeration.empty() ? "" : " " + numeration));
const auto author_name(not titles_and_other_words_associated_with_a_name.empty()
? name_and_numeration + " (" + titles_and_other_words_associated_with_a_name + ")"
: name_and_numeration);
const auto dates(ReplaceNonStandardBCEDates(_100_field->getFirstSubfieldWithCode('d')));
std::vector<LiteraryRemainsInfo> literary_remains_infos;
while (beacon_field != record.end() and beacon_field->getTag() == "BEA") {
literary_remains_infos.emplace_back(author_name, beacon_field->getFirstSubfieldWithCode('u'),
beacon_field->getFirstSubfieldWithCode('a'), dates);
++beacon_field;
}
(*gnd_numbers_to_literary_remains_infos_map)[gnd_number] = literary_remains_infos;
references_count += literary_remains_infos.size();
if (author_ppn_to_relstudies_titles_counters.find(record.getControlNumber()) != author_ppn_to_relstudies_titles_counters.cend()) {
record.insertField("REL", { { 'a', "1" }, { 'o', FileUtil::GetBasename(::progname) } });
++tagged_count;
}
writer->write(record);
}
LOG_INFO("Loaded " + std::to_string(references_count) + " literary remains references from \"" + reader->getPath()
+ "\" which contained a total of " + std::to_string(total_count) + " records.");
LOG_INFO("Tagged " + std::to_string(tagged_count) + " authority records as relevant to religious studies.");
}
std::string NormaliseAuthorName(std::string author_name) {
const auto comma_pos(author_name.find(','));
if (comma_pos == std::string::npos)
return author_name;
std::string auxillary_info;
const auto open_paren_pos(author_name.find('('));
if (open_paren_pos != std::string::npos) {
if (comma_pos > open_paren_pos)
return author_name;
auxillary_info = " " + author_name.substr(open_paren_pos);
author_name.resize(open_paren_pos);
}
return StringUtil::TrimWhite(author_name.substr(comma_pos + 1)) + " " + StringUtil::TrimWhite(author_name.substr(0, comma_pos))
+ auxillary_info;
}
void AppendLiteraryRemainsRecords(
MARC::Writer * const writer,
const std::unordered_map<std::string, std::vector<LiteraryRemainsInfo>> &gnd_numbers_to_literary_remains_infos_map,
const std::unordered_map<std::string, std::string> &gnd_numbers_to_ppns_map,
const std::unordered_map<std::string, TitleRecordCounter> &author_ppn_to_relstudies_titles_counters)
{
unsigned creation_count(0);
for (const auto &gnd_numbers_and_literary_remains_infos : gnd_numbers_to_literary_remains_infos_map) {
MARC::Record new_record(MARC::Record::TypeOfRecord::MIXED_MATERIALS, MARC::Record::BibliographicLevel::COLLECTION,
"LR" + gnd_numbers_and_literary_remains_infos.first);
const std::string &author_name(gnd_numbers_and_literary_remains_infos.second.front().author_name_);
std::string dates(gnd_numbers_and_literary_remains_infos.second.front().dates_.empty()
? "" : " " + gnd_numbers_and_literary_remains_infos.second.front().dates_);
new_record.insertField("003", "PipeLineGenerated");
new_record.insertField("005", TimeUtil::GetCurrentDateAndTime("%Y%m%d%H%M%S") + ".0");
new_record.insertField("008", "190606s2019 xx ||||| 00| ||ger c");
if (gnd_numbers_and_literary_remains_infos.second.front().dates_.empty())
new_record.insertField("100", { { 'a', author_name }, { '0', "(DE-588)" + gnd_numbers_and_literary_remains_infos.first } });
else
new_record.insertField("100",
{ { 'a', author_name }, { '0', "(DE-588)" + gnd_numbers_and_literary_remains_infos.first },
{ 'd', gnd_numbers_and_literary_remains_infos.second.front().dates_ } });
new_record.insertField("245", { { 'a', "Nachlass von " + NormaliseAuthorName(author_name) + dates } });
for (const auto &literary_remains_info : gnd_numbers_and_literary_remains_infos.second)
new_record.insertField("856",
{ { 'u', literary_remains_info.url_ },
{ '3', "Nachlassdatenbank (" + literary_remains_info.source_name_ + ")" } });
// Do we have a religious studies author?
const auto gnd_number_and_author_ppn(gnd_numbers_to_ppns_map.find(gnd_numbers_and_literary_remains_infos.first));
if (unlikely(gnd_number_and_author_ppn == gnd_numbers_to_ppns_map.cend()))
LOG_ERROR("we should *always* find the GND number in gnd_numbers_to_ppns_map!");
const auto author_ppn_and_relstudies_titles_counter(
author_ppn_to_relstudies_titles_counters.find(gnd_number_and_author_ppn->second));
if (author_ppn_and_relstudies_titles_counter != author_ppn_to_relstudies_titles_counters.cend()
and author_ppn_and_relstudies_titles_counter->second.exceedsReligiousStudiesThreshold())
new_record.insertField("REL", { { 'a', "1" }, { 'o', FileUtil::GetBasename(::progname) } });
writer->write(new_record);
}
LOG_INFO("Appended a total of " + std::to_string(creation_count) + " record(s).");
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc != 5)
::Usage("marc_input marc_output authority_records_input authority_records_output");
auto title_reader(MARC::Reader::Factory(argv[1]));
auto title_writer(MARC::Writer::Factory(argv[2]));
std::unordered_map<std::string, TitleRecordCounter> author_ppn_to_relstudies_titles_counters;
CopyMarcAndCollectRelgiousStudiesFrequencies(title_reader.get(), title_writer.get(), &author_ppn_to_relstudies_titles_counters);
if (author_ppn_to_relstudies_titles_counters.empty())
LOG_ERROR("You must run this program on an input that contains REL records!");
auto authority_reader(MARC::Reader::Factory(argv[3]));
auto authority_writer(MARC::Writer::Factory(argv[4]));
std::unordered_map<std::string, std::vector<LiteraryRemainsInfo>> gnd_numbers_to_literary_remains_infos_map;
std::unordered_map<std::string, std::string> gnd_numbers_to_ppns_map;
LoadAuthorGNDNumbersAndTagAuthors(authority_reader.get(), authority_writer.get(), author_ppn_to_relstudies_titles_counters,
&gnd_numbers_to_literary_remains_infos_map, &gnd_numbers_to_ppns_map);
AppendLiteraryRemainsRecords(title_writer.get(), gnd_numbers_to_literary_remains_infos_map, gnd_numbers_to_ppns_map,
author_ppn_to_relstudies_titles_counters);
return EXIT_SUCCESS;
}
<commit_msg>create_literary_remains_records.cc: Add k10plus id (DE-627)<commit_after>/** \file create_literary_remains_records.cc
* \author Dr. Johannes Ruscheinski
*
* A tool for creating literary remains MARC records from Beacon files.
*/
/*
Copyright (C) 2019-2020, Library of the University of Tübingen
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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unordered_map>
#include <unordered_set>
#include "FileUtil.h"
#include "MARC.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "TimeUtil.h"
#include "util.h"
namespace {
struct TitleRecordCounter {
unsigned total_count_;
unsigned religious_studies_count_;
public:
TitleRecordCounter(): total_count_(0), religious_studies_count_(0) { }
TitleRecordCounter(const TitleRecordCounter &other) = default;
TitleRecordCounter(const bool is_relevant_to_reigious_studies)
: total_count_(1), religious_studies_count_(is_relevant_to_reigious_studies ? 1 : 0) { }
inline bool exceedsReligiousStudiesThreshold() const
{ return 100.0 * static_cast<double>(religious_studies_count_) / static_cast<double>(total_count_) >= 10.0 /* percent */; }
};
// Counts the number of religious studies title records for authors.
void CopyMarcAndCollectRelgiousStudiesFrequencies(
MARC::Reader * const reader, MARC::Writer * const writer,
std::unordered_map<std::string, TitleRecordCounter> * const author_ppn_to_relstudies_title_counters)
{
while (auto record = reader->read()) {
const bool rel_tag_found(record.findTag("REL") != record.end());
for (const auto &author_name_and_author_ppn : record.getAllAuthorsAndPPNs()) {
auto author_ppn_and_counter(author_ppn_to_relstudies_title_counters->find(author_name_and_author_ppn.second));
if (author_ppn_and_counter == author_ppn_to_relstudies_title_counters->end())
(*author_ppn_to_relstudies_title_counters)[author_name_and_author_ppn.second] = TitleRecordCounter(rel_tag_found);
else {
++(author_ppn_and_counter->second.total_count_);
if (rel_tag_found)
++(author_ppn_and_counter->second.religious_studies_count_);
}
}
writer->write(record);
}
}
struct LiteraryRemainsInfo {
std::string author_id_;
std::string author_name_;
std::string url_;
std::string source_name_;
std::string dates_;
public:
LiteraryRemainsInfo() = default;
LiteraryRemainsInfo(const LiteraryRemainsInfo &other) = default;
LiteraryRemainsInfo(const std::string &author_id, const std::string &author_name, const std::string &url, const std::string &source_name, const std::string &dates)
: author_id_(author_id), author_name_(author_name), url_(url), source_name_(source_name), dates_(dates) { }
LiteraryRemainsInfo &operator=(const LiteraryRemainsInfo &rhs) = default;
};
std::vector<std::pair<RegexMatcher *, std::string>> CompileMatchers() {
// Please note that the order in the following vector matters. The first successful match will be used.
const std::vector<std::pair<std::string, std::string>> patterns_and_replacements {
{ "v([0-9]+) ?- ?v([0-9]+)", "\\1 v. Chr. - \\2 v. Chr." },
{ "v([0-9]+)" , "\\1 v. Chr." },
};
std::vector<std::pair<RegexMatcher *, std::string>> compiled_patterns_and_replacements;
for (const auto &pattern_and_replacement : patterns_and_replacements)
compiled_patterns_and_replacements.push_back(
std::pair<RegexMatcher *, std::string>(RegexMatcher::RegexMatcherFactoryOrDie(pattern_and_replacement.first),
pattern_and_replacement.second));
return compiled_patterns_and_replacements;
}
const std::vector<std::pair<RegexMatcher *, std::string>> matchers_and_replacements(CompileMatchers());
std::string ReplaceNonStandardBCEDates(const std::string &dates) {
for (const auto &matcher_and_replacement : matchers_and_replacements) {
RegexMatcher * const matcher(matcher_and_replacement.first);
const std::string replaced_string(matcher->replaceWithBackreferences(dates, matcher_and_replacement.second));
if (replaced_string != dates)
return replaced_string;
}
return dates;
}
void LoadAuthorGNDNumbersAndTagAuthors(
MARC::Reader * const reader, MARC::Writer * const writer,
const std::unordered_map<std::string, TitleRecordCounter> &author_ppn_to_relstudies_titles_counters,
std::unordered_map<std::string, std::vector<LiteraryRemainsInfo>> * const gnd_numbers_to_literary_remains_infos_map,
std::unordered_map<std::string, std::string> * const gnd_numbers_to_ppns_map)
{
unsigned total_count(0), references_count(0), tagged_count(0);
while (auto record = reader->read()) {
++total_count;
auto beacon_field(record.findTag("BEA"));
if (beacon_field == record.end()) {
writer->write(record);
continue;
}
const auto _100_field(record.findTag("100"));
if (_100_field == record.end() or not _100_field->hasSubfield('a')) {
writer->write(record);
continue;
}
std::string gnd_number;
if (not MARC::GetGNDCode(record, &gnd_number)) {
writer->write(record);
continue;
}
(*gnd_numbers_to_ppns_map)[gnd_number] = record.getControlNumber();
const auto numeration(_100_field->getFirstSubfieldWithCode('b'));
const auto titles_and_other_words_associated_with_a_name(_100_field->getFirstSubfieldWithCode('c'));
const auto name_and_numeration(_100_field->getFirstSubfieldWithCode('a') + (numeration.empty() ? "" : " " + numeration));
const auto author_name(not titles_and_other_words_associated_with_a_name.empty()
? name_and_numeration + " (" + titles_and_other_words_associated_with_a_name + ")"
: name_and_numeration);
const auto dates(ReplaceNonStandardBCEDates(_100_field->getFirstSubfieldWithCode('d')));
std::vector<LiteraryRemainsInfo> literary_remains_infos;
while (beacon_field != record.end() and beacon_field->getTag() == "BEA") {
literary_remains_infos.emplace_back(record.getControlNumber(), author_name, beacon_field->getFirstSubfieldWithCode('u'),
beacon_field->getFirstSubfieldWithCode('a'), dates);
++beacon_field;
}
(*gnd_numbers_to_literary_remains_infos_map)[gnd_number] = literary_remains_infos;
references_count += literary_remains_infos.size();
if (author_ppn_to_relstudies_titles_counters.find(record.getControlNumber()) != author_ppn_to_relstudies_titles_counters.cend()) {
record.insertField("REL", { { 'a', "1" }, { 'o', FileUtil::GetBasename(::progname) } });
++tagged_count;
}
writer->write(record);
}
LOG_INFO("Loaded " + std::to_string(references_count) + " literary remains references from \"" + reader->getPath()
+ "\" which contained a total of " + std::to_string(total_count) + " records.");
LOG_INFO("Tagged " + std::to_string(tagged_count) + " authority records as relevant to religious studies.");
}
std::string NormaliseAuthorName(std::string author_name) {
const auto comma_pos(author_name.find(','));
if (comma_pos == std::string::npos)
return author_name;
std::string auxillary_info;
const auto open_paren_pos(author_name.find('('));
if (open_paren_pos != std::string::npos) {
if (comma_pos > open_paren_pos)
return author_name;
auxillary_info = " " + author_name.substr(open_paren_pos);
author_name.resize(open_paren_pos);
}
return StringUtil::TrimWhite(author_name.substr(comma_pos + 1)) + " " + StringUtil::TrimWhite(author_name.substr(0, comma_pos))
+ auxillary_info;
}
void AppendLiteraryRemainsRecords(
MARC::Writer * const writer,
const std::unordered_map<std::string, std::vector<LiteraryRemainsInfo>> &gnd_numbers_to_literary_remains_infos_map,
const std::unordered_map<std::string, std::string> &gnd_numbers_to_ppns_map,
const std::unordered_map<std::string, TitleRecordCounter> &author_ppn_to_relstudies_titles_counters)
{
unsigned creation_count(0);
for (const auto &gnd_numbers_and_literary_remains_infos : gnd_numbers_to_literary_remains_infos_map) {
MARC::Record new_record(MARC::Record::TypeOfRecord::MIXED_MATERIALS, MARC::Record::BibliographicLevel::COLLECTION,
"LR" + gnd_numbers_and_literary_remains_infos.first);
const std::string &author_name(gnd_numbers_and_literary_remains_infos.second.front().author_name_);
std::string dates(gnd_numbers_and_literary_remains_infos.second.front().dates_.empty()
? "" : " " + gnd_numbers_and_literary_remains_infos.second.front().dates_);
new_record.insertField("003", "PipeLineGenerated");
new_record.insertField("005", TimeUtil::GetCurrentDateAndTime("%Y%m%d%H%M%S") + ".0");
new_record.insertField("008", "190606s2019 xx ||||| 00| ||ger c");
if (gnd_numbers_and_literary_remains_infos.second.front().dates_.empty())
new_record.insertField("100", { { 'a', author_name }, { '0', "(DE-588)" + gnd_numbers_and_literary_remains_infos.first }, { '0', "(DE-627)" + gnd_numbers_and_literary_remains_infos.second.front().author_id_ } });
else
new_record.insertField("100",
{ { 'a', author_name }, { '0', "(DE-588)" + gnd_numbers_and_literary_remains_infos.first }, { '0', "(DE-627)" + gnd_numbers_and_literary_remains_infos.second.front().author_id_ },
{ 'd', gnd_numbers_and_literary_remains_infos.second.front().dates_ } });
new_record.insertField("245", { { 'a', "Nachlass von " + NormaliseAuthorName(author_name) + dates } });
for (const auto &literary_remains_info : gnd_numbers_and_literary_remains_infos.second)
new_record.insertField("856",
{ { 'u', literary_remains_info.url_ },
{ '3', "Nachlassdatenbank (" + literary_remains_info.source_name_ + ")" } });
// Do we have a religious studies author?
const auto gnd_number_and_author_ppn(gnd_numbers_to_ppns_map.find(gnd_numbers_and_literary_remains_infos.first));
if (unlikely(gnd_number_and_author_ppn == gnd_numbers_to_ppns_map.cend()))
LOG_ERROR("we should *always* find the GND number in gnd_numbers_to_ppns_map!");
const auto author_ppn_and_relstudies_titles_counter(
author_ppn_to_relstudies_titles_counters.find(gnd_number_and_author_ppn->second));
if (author_ppn_and_relstudies_titles_counter != author_ppn_to_relstudies_titles_counters.cend()
and author_ppn_and_relstudies_titles_counter->second.exceedsReligiousStudiesThreshold())
new_record.insertField("REL", { { 'a', "1" }, { 'o', FileUtil::GetBasename(::progname) } });
writer->write(new_record);
}
LOG_INFO("Appended a total of " + std::to_string(creation_count) + " record(s).");
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc != 5)
::Usage("marc_input marc_output authority_records_input authority_records_output");
auto title_reader(MARC::Reader::Factory(argv[1]));
auto title_writer(MARC::Writer::Factory(argv[2]));
std::unordered_map<std::string, TitleRecordCounter> author_ppn_to_relstudies_titles_counters;
CopyMarcAndCollectRelgiousStudiesFrequencies(title_reader.get(), title_writer.get(), &author_ppn_to_relstudies_titles_counters);
if (author_ppn_to_relstudies_titles_counters.empty())
LOG_ERROR("You must run this program on an input that contains REL records!");
auto authority_reader(MARC::Reader::Factory(argv[3]));
auto authority_writer(MARC::Writer::Factory(argv[4]));
std::unordered_map<std::string, std::vector<LiteraryRemainsInfo>> gnd_numbers_to_literary_remains_infos_map;
std::unordered_map<std::string, std::string> gnd_numbers_to_ppns_map;
LoadAuthorGNDNumbersAndTagAuthors(authority_reader.get(), authority_writer.get(), author_ppn_to_relstudies_titles_counters,
&gnd_numbers_to_literary_remains_infos_map, &gnd_numbers_to_ppns_map);
AppendLiteraryRemainsRecords(title_writer.get(), gnd_numbers_to_literary_remains_infos_map, gnd_numbers_to_ppns_map,
author_ppn_to_relstudies_titles_counters);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* 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.
*/
// CLASS HEADER
#include <dali/internal/event/actors/actor-parent.h>
// INTERNAL INCLUDES
#include <dali/internal/event/actors/actor-impl.h>
#include <dali/internal/event/common/scene-impl.h>
#include <dali/public-api/common/vector-wrapper.h>
// EXTERNAL INCLUDES
#include <algorithm>
namespace Dali
{
namespace Internal
{
namespace
{
/// Helper for emitting signals with multiple parameters
template<typename Signal, typename... Param>
void EmitSignal(Actor& actor, Signal& signal, Param... params)
{
if(!signal.Empty())
{
Dali::Actor handle(&actor);
signal.Emit(handle, params...);
}
}
} //anonymous namespace
ActorParentImpl::ActorParentImpl(Actor& owner)
: mOwner(owner),
mChildAddedSignal(),
mChildRemovedSignal(),
mChildOrderChangedSignal()
{
}
ActorParentImpl::~ActorParentImpl()
{
delete mChildren;
}
void ActorParentImpl::Add(Actor& child)
{
DALI_ASSERT_ALWAYS(&mOwner != &child && "Cannot add actor to itself");
DALI_ASSERT_ALWAYS(!child.IsRoot() && "Cannot add root actor");
if(!mChildren)
{
mChildren = new ActorContainer;
}
Actor* oldParent = child.GetParent();
// child might already be ours
if(&mOwner != oldParent)
{
// if we already have parent, unparent us first
if(oldParent)
{
oldParent->Remove(child); // This causes OnChildRemove callback & ChildRemoved signal
// Old parent may need to readjust to missing child
if(oldParent->RelayoutDependentOnChildren())
{
oldParent->RelayoutRequest();
}
}
// Guard against Add() during previous OnChildRemove callback
if(!child.GetParent())
{
// Do this first, since user callbacks from within SetParent() may need to remove child
mChildren->push_back(ActorPtr(&child));
// SetParent asserts that child can be added
child.SetParent(&mOwner);
// Notification for derived classes
mOwner.OnChildAdd(child);
EmitChildAddedSignal(child);
child.InheritLayoutDirectionRecursively(mOwner.GetLayoutDirection());
// Only put in a relayout request if there is a suitable dependency
if(mOwner.RelayoutDependentOnChildren())
{
mOwner.RelayoutRequest();
}
}
}
}
void ActorParentImpl::Remove(Actor& child)
{
if((&mOwner == &child) || (!mChildren))
{
// no children or removing itself
return;
}
ActorPtr removed;
// Find the child in mChildren, and unparent it
ActorIter end = mChildren->end();
for(ActorIter iter = mChildren->begin(); iter != end; ++iter)
{
ActorPtr actor = (*iter);
if(actor.Get() == &child)
{
// Keep handle for OnChildRemove notification
removed = actor;
// Do this first, since user callbacks from within SetParent() may need to add the child
mChildren->erase(iter);
DALI_ASSERT_DEBUG(actor->GetParent() == &mOwner);
actor->SetParent(nullptr);
break;
}
}
if(removed)
{
// Only put in a relayout request if there is a suitable dependency
if(mOwner.RelayoutDependentOnChildren())
{
mOwner.RelayoutRequest();
}
}
// Notification for derived classes
mOwner.OnChildRemove(child);
EmitChildRemovedSignal(child);
}
uint32_t ActorParentImpl::GetChildCount() const
{
return (nullptr != mChildren) ? static_cast<uint32_t>(mChildren->size()) : 0; // only 4,294,967,295 children per actor
}
ActorPtr ActorParentImpl::GetChildAt(uint32_t index) const
{
DALI_ASSERT_ALWAYS(index < GetChildCount());
return ((mChildren) ? (*mChildren)[index] : ActorPtr());
}
ActorPtr ActorParentImpl::FindChildByName(const std::string& actorName)
{
ActorPtr child = nullptr;
if(actorName == mOwner.GetName())
{
child = &mOwner;
}
else if(mChildren)
{
for(const auto& actor : *mChildren)
{
child = actor->FindChildByName(actorName);
if(child)
{
break;
}
}
}
return child;
}
ActorPtr ActorParentImpl::FindChildById(const uint32_t id)
{
ActorPtr child = nullptr;
if(id == mOwner.GetId())
{
child = &mOwner;
}
else if(mChildren)
{
for(const auto& actor : *mChildren)
{
child = actor->FindChildById(id);
if(child)
{
break;
}
}
}
return child;
}
void ActorParentImpl::UnparentChildren()
{
if(mChildren)
{
for(const auto& child : *mChildren)
{
child->SetParent(nullptr);
}
}
}
void ActorParentImpl::SetSiblingOrderOfChild(
Actor& child,
uint32_t order)
{
if(mChildren)
{
uint32_t currentOrder = GetSiblingOrderOfChild(child);
if(order != currentOrder)
{
if(order == 0)
{
LowerChildToBottom(child);
}
else if(order < mChildren->size() - 1)
{
if(order > currentOrder)
{
RaiseChildAbove(child, *((*mChildren)[order]));
}
else
{
LowerChildBelow(child, *((*mChildren)[order]));
}
}
else
{
RaiseChildToTop(child);
}
}
}
}
uint32_t ActorParentImpl::GetSiblingOrderOfChild(const Actor& child) const
{
uint32_t order = 0;
if(mChildren)
{
for(std::size_t i = 0; i < mChildren->size(); ++i)
{
if((*mChildren)[i] == &child)
{
order = static_cast<uint32_t>(i);
break;
}
}
}
return order;
}
void ActorParentImpl::RaiseChild(Actor& child)
{
bool changed = false;
if(mChildren && mChildren && mChildren->back() != &child) // If not already at end
{
for(std::size_t i = 0; i < mChildren->size(); ++i)
{
if((*mChildren)[i] == &child)
{
// Swap with next
ActorPtr next = (*mChildren)[i + 1];
(*mChildren)[i + 1] = &child;
(*mChildren)[i] = next;
changed = true;
break;
}
}
}
if(changed)
{
EmitOrderChangedAndRebuild(child);
}
}
void ActorParentImpl::LowerChild(Actor& child)
{
bool changed = false;
if(mChildren && mChildren->front() != &child) // If not already at beginning
{
for(std::size_t i = 1; i < mChildren->size(); ++i)
{
if((*mChildren)[i] == &child)
{
// Swap with previous
ActorPtr previous = (*mChildren)[i - 1];
(*mChildren)[i - 1] = &child;
(*mChildren)[i] = previous;
changed = true;
break;
}
}
}
if(changed)
{
EmitOrderChangedAndRebuild(child);
}
}
void ActorParentImpl::RaiseChildToTop(Actor& child)
{
bool changed = false;
if(mChildren && mChildren->back() != &child) // If not already at end
{
auto iter = std::find(mChildren->begin(), mChildren->end(), &child);
if(iter != mChildren->end())
{
mChildren->erase(iter);
mChildren->push_back(ActorPtr(&child));
changed = true;
}
}
if(changed)
{
EmitOrderChangedAndRebuild(child);
}
}
void ActorParentImpl::LowerChildToBottom(Actor& child)
{
bool changed = false;
if(mChildren && mChildren->front() != &child) // If not already at bottom,
{
ActorPtr childPtr(&child); // ensure actor remains referenced.
auto iter = std::find(mChildren->begin(), mChildren->end(), &child);
if(iter != mChildren->end())
{
mChildren->erase(iter);
mChildren->insert(mChildren->begin(), childPtr);
changed = true;
}
}
if(changed)
{
EmitOrderChangedAndRebuild(child);
}
}
void ActorParentImpl::RaiseChildAbove(Actor& child, Actor& target)
{
bool raised = false;
if(mChildren && mChildren->back() != &child && target.GetParent() == child.GetParent()) // If not already at top
{
ActorPtr childPtr(&child); // ensure actor actor remains referenced.
auto targetIter = std::find(mChildren->begin(), mChildren->end(), &target);
auto childIter = std::find(mChildren->begin(), mChildren->end(), &child);
if(childIter < targetIter)
{
mChildren->erase(childIter);
// Erasing early invalidates the targetIter. (Conversely, inserting first may also
// invalidate actorIter)
targetIter = std::find(mChildren->begin(), mChildren->end(), &target);
++targetIter;
mChildren->insert(targetIter, childPtr);
}
raised = true;
}
if(raised)
{
EmitOrderChangedAndRebuild(child);
}
}
void ActorParentImpl::LowerChildBelow(Actor& child, Actor& target)
{
bool lowered = false;
// If not already at bottom
if(mChildren && mChildren->front() != &child && target.GetParent() == child.GetParent())
{
ActorPtr childPtr(&child); // ensure actor actor remains referenced.
auto targetIter = std::find(mChildren->begin(), mChildren->end(), &target);
auto childIter = std::find(mChildren->begin(), mChildren->end(), &child);
if(childIter > targetIter)
{
mChildren->erase(childIter); // actor only invalidates iterators at or after actor point.
mChildren->insert(targetIter, childPtr);
}
lowered = true;
}
if(lowered)
{
EmitOrderChangedAndRebuild(child);
}
}
void ActorParentImpl::EmitChildAddedSignal(Actor& child)
{
EmitSignal(child, mChildAddedSignal);
}
void ActorParentImpl::EmitChildRemovedSignal(Actor& child)
{
EmitSignal(child, mChildRemovedSignal);
}
void ActorParentImpl::EmitOrderChangedAndRebuild(Actor& child)
{
EmitSignal(child, mChildOrderChangedSignal);
if(mOwner.OnScene())
{
mOwner.GetScene().RequestRebuildDepthTree();
}
}
} // namespace Internal
} // namespace Dali
<commit_msg>Fix Svace error in actor-parent-impl.cpp<commit_after>/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* 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.
*/
// CLASS HEADER
#include <dali/internal/event/actors/actor-parent.h>
// INTERNAL INCLUDES
#include <dali/internal/event/actors/actor-impl.h>
#include <dali/internal/event/common/scene-impl.h>
#include <dali/public-api/common/vector-wrapper.h>
// EXTERNAL INCLUDES
#include <algorithm>
namespace Dali
{
namespace Internal
{
namespace
{
/// Helper for emitting signals with multiple parameters
template<typename Signal, typename... Param>
void EmitSignal(Actor& actor, Signal& signal, Param... params)
{
if(!signal.Empty())
{
Dali::Actor handle(&actor);
signal.Emit(handle, params...);
}
}
} //anonymous namespace
ActorParentImpl::ActorParentImpl(Actor& owner)
: mOwner(owner),
mChildAddedSignal(),
mChildRemovedSignal(),
mChildOrderChangedSignal()
{
}
ActorParentImpl::~ActorParentImpl()
{
delete mChildren;
}
void ActorParentImpl::Add(Actor& child)
{
DALI_ASSERT_ALWAYS(&mOwner != &child && "Cannot add actor to itself");
DALI_ASSERT_ALWAYS(!child.IsRoot() && "Cannot add root actor");
if(!mChildren)
{
mChildren = new ActorContainer;
}
Actor* oldParent = child.GetParent();
// child might already be ours
if(&mOwner != oldParent)
{
// if we already have parent, unparent us first
if(oldParent)
{
oldParent->Remove(child); // This causes OnChildRemove callback & ChildRemoved signal
// Old parent may need to readjust to missing child
if(oldParent->RelayoutDependentOnChildren())
{
oldParent->RelayoutRequest();
}
}
// Guard against Add() during previous OnChildRemove callback
if(!child.GetParent())
{
// Do this first, since user callbacks from within SetParent() may need to remove child
mChildren->push_back(ActorPtr(&child));
// SetParent asserts that child can be added
child.SetParent(&mOwner);
// Notification for derived classes
mOwner.OnChildAdd(child);
EmitChildAddedSignal(child);
child.InheritLayoutDirectionRecursively(mOwner.GetLayoutDirection());
// Only put in a relayout request if there is a suitable dependency
if(mOwner.RelayoutDependentOnChildren())
{
mOwner.RelayoutRequest();
}
}
}
}
void ActorParentImpl::Remove(Actor& child)
{
if((&mOwner == &child) || (!mChildren))
{
// no children or removing itself
return;
}
ActorPtr removed;
// Find the child in mChildren, and unparent it
ActorIter end = mChildren->end();
for(ActorIter iter = mChildren->begin(); iter != end; ++iter)
{
ActorPtr actor = (*iter);
if(actor.Get() == &child)
{
// Keep handle for OnChildRemove notification
removed = actor;
// Do this first, since user callbacks from within SetParent() may need to add the child
mChildren->erase(iter);
DALI_ASSERT_DEBUG(actor->GetParent() == &mOwner);
actor->SetParent(nullptr);
break;
}
}
if(removed)
{
// Only put in a relayout request if there is a suitable dependency
if(mOwner.RelayoutDependentOnChildren())
{
mOwner.RelayoutRequest();
}
}
// Notification for derived classes
mOwner.OnChildRemove(child);
EmitChildRemovedSignal(child);
}
uint32_t ActorParentImpl::GetChildCount() const
{
return (nullptr != mChildren) ? static_cast<uint32_t>(mChildren->size()) : 0; // only 4,294,967,295 children per actor
}
ActorPtr ActorParentImpl::GetChildAt(uint32_t index) const
{
DALI_ASSERT_ALWAYS(index < GetChildCount());
return ((mChildren) ? (*mChildren)[index] : ActorPtr());
}
ActorPtr ActorParentImpl::FindChildByName(const std::string& actorName)
{
ActorPtr child = nullptr;
if(actorName == mOwner.GetName())
{
child = &mOwner;
}
else if(mChildren)
{
for(const auto& actor : *mChildren)
{
child = actor->FindChildByName(actorName);
if(child)
{
break;
}
}
}
return child;
}
ActorPtr ActorParentImpl::FindChildById(const uint32_t id)
{
ActorPtr child = nullptr;
if(id == mOwner.GetId())
{
child = &mOwner;
}
else if(mChildren)
{
for(const auto& actor : *mChildren)
{
child = actor->FindChildById(id);
if(child)
{
break;
}
}
}
return child;
}
void ActorParentImpl::UnparentChildren()
{
if(mChildren)
{
for(const auto& child : *mChildren)
{
child->SetParent(nullptr);
}
}
}
void ActorParentImpl::SetSiblingOrderOfChild(
Actor& child,
uint32_t order)
{
if(mChildren)
{
uint32_t currentOrder = GetSiblingOrderOfChild(child);
if(order != currentOrder)
{
if(order == 0)
{
LowerChildToBottom(child);
}
else if(order < mChildren->size() - 1)
{
if(order > currentOrder)
{
RaiseChildAbove(child, *((*mChildren)[order]));
}
else
{
LowerChildBelow(child, *((*mChildren)[order]));
}
}
else
{
RaiseChildToTop(child);
}
}
}
}
uint32_t ActorParentImpl::GetSiblingOrderOfChild(const Actor& child) const
{
uint32_t order = 0;
if(mChildren)
{
for(std::size_t i = 0; i < mChildren->size(); ++i)
{
if((*mChildren)[i] == &child)
{
order = static_cast<uint32_t>(i);
break;
}
}
}
return order;
}
void ActorParentImpl::RaiseChild(Actor& child)
{
bool changed = false;
if(mChildren && mChildren->back() != &child) // If not already at end
{
for(std::size_t i = 0; i < mChildren->size(); ++i)
{
if((*mChildren)[i] == &child)
{
// Swap with next
ActorPtr next = (*mChildren)[i + 1];
(*mChildren)[i + 1] = &child;
(*mChildren)[i] = next;
changed = true;
break;
}
}
}
if(changed)
{
EmitOrderChangedAndRebuild(child);
}
}
void ActorParentImpl::LowerChild(Actor& child)
{
bool changed = false;
if(mChildren && mChildren->front() != &child) // If not already at beginning
{
for(std::size_t i = 1; i < mChildren->size(); ++i)
{
if((*mChildren)[i] == &child)
{
// Swap with previous
ActorPtr previous = (*mChildren)[i - 1];
(*mChildren)[i - 1] = &child;
(*mChildren)[i] = previous;
changed = true;
break;
}
}
}
if(changed)
{
EmitOrderChangedAndRebuild(child);
}
}
void ActorParentImpl::RaiseChildToTop(Actor& child)
{
bool changed = false;
if(mChildren && mChildren->back() != &child) // If not already at end
{
auto iter = std::find(mChildren->begin(), mChildren->end(), &child);
if(iter != mChildren->end())
{
mChildren->erase(iter);
mChildren->push_back(ActorPtr(&child));
changed = true;
}
}
if(changed)
{
EmitOrderChangedAndRebuild(child);
}
}
void ActorParentImpl::LowerChildToBottom(Actor& child)
{
bool changed = false;
if(mChildren && mChildren->front() != &child) // If not already at bottom,
{
ActorPtr childPtr(&child); // ensure actor remains referenced.
auto iter = std::find(mChildren->begin(), mChildren->end(), &child);
if(iter != mChildren->end())
{
mChildren->erase(iter);
mChildren->insert(mChildren->begin(), childPtr);
changed = true;
}
}
if(changed)
{
EmitOrderChangedAndRebuild(child);
}
}
void ActorParentImpl::RaiseChildAbove(Actor& child, Actor& target)
{
bool raised = false;
if(mChildren && mChildren->back() != &child && target.GetParent() == child.GetParent()) // If not already at top
{
ActorPtr childPtr(&child); // ensure actor actor remains referenced.
auto targetIter = std::find(mChildren->begin(), mChildren->end(), &target);
auto childIter = std::find(mChildren->begin(), mChildren->end(), &child);
if(childIter < targetIter)
{
mChildren->erase(childIter);
// Erasing early invalidates the targetIter. (Conversely, inserting first may also
// invalidate actorIter)
targetIter = std::find(mChildren->begin(), mChildren->end(), &target);
++targetIter;
mChildren->insert(targetIter, childPtr);
}
raised = true;
}
if(raised)
{
EmitOrderChangedAndRebuild(child);
}
}
void ActorParentImpl::LowerChildBelow(Actor& child, Actor& target)
{
bool lowered = false;
// If not already at bottom
if(mChildren && mChildren->front() != &child && target.GetParent() == child.GetParent())
{
ActorPtr childPtr(&child); // ensure actor actor remains referenced.
auto targetIter = std::find(mChildren->begin(), mChildren->end(), &target);
auto childIter = std::find(mChildren->begin(), mChildren->end(), &child);
if(childIter > targetIter)
{
mChildren->erase(childIter); // actor only invalidates iterators at or after actor point.
mChildren->insert(targetIter, childPtr);
}
lowered = true;
}
if(lowered)
{
EmitOrderChangedAndRebuild(child);
}
}
void ActorParentImpl::EmitChildAddedSignal(Actor& child)
{
EmitSignal(child, mChildAddedSignal);
}
void ActorParentImpl::EmitChildRemovedSignal(Actor& child)
{
EmitSignal(child, mChildRemovedSignal);
}
void ActorParentImpl::EmitOrderChangedAndRebuild(Actor& child)
{
EmitSignal(child, mChildOrderChangedSignal);
if(mOwner.OnScene())
{
mOwner.GetScene().RequestRebuildDepthTree();
}
}
} // namespace Internal
} // namespace Dali
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2020 musikcube team
//
// 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 other 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 <stdafx.h>
#include "RemoteLibrarySettingsLayout.h"
#include <cursespp/App.h>
#include <cursespp/Colors.h>
#include <musikcore/library/LibraryFactory.h>
#include <musikcore/support/PreferenceKeys.h>
#include <app/overlay/SettingsOverlays.h>
#include <algorithm>
#include <vector>
using namespace musik;
using namespace musik::core;
using namespace musik::core::library;
using namespace musik::core::sdk;
using namespace musik::cube;
using namespace cursespp;
#define R(x) (x->GetX() + x->GetWidth())
static const std::string kArrowSymbol = "> ";
static inline int longestStringLength(const std::vector<std::string>&& keys) {
int max = 0;
for (auto& str: keys) {
size_t len = u8cols(_TSTR(str));
max = len > max ? len : max;
}
return max;
}
RemoteLibrarySettingsLayout::RemoteLibrarySettingsLayout()
: LayoutBase() {
this->prefs = Preferences::ForComponent(core::prefs::components::Settings);
this->SetFocusMode(FocusModeTerminating);
this->InitializeWindows();
}
RemoteLibrarySettingsLayout::~RemoteLibrarySettingsLayout() {
this->SavePreferences();
}
void RemoteLibrarySettingsLayout::OnLayout() {
const int labelWidth = longestStringLength({
"settings_library_type_remote_hostname",
"settings_library_type_remote_wss_port",
"settings_library_type_remote_http_port",
"settings_library_type_remote_password"
});
const int checkboxWidth = u8cols(_TSTR("settings_library_type_remote_use_tls")) + 4;
int const cx = this->GetWidth();
int const inputWidth = std::min((int) 32, (int) (cx - labelWidth - 1));
int y = 0;
this->hostLabel->MoveAndResize(0, y, labelWidth, 1);
this->hostInput->MoveAndResize(labelWidth + 1, y++, inputWidth, 1);
this->wssPortLabel->MoveAndResize(0, y, labelWidth, 1);
this->wssPortInput->MoveAndResize(labelWidth + 1, y, 5, 1);
this->wssTlsCheckbox->MoveAndResize(R(this->wssPortInput) + 1, y++, checkboxWidth, 1);
this->httpPortLabel->MoveAndResize(0, y, labelWidth, 1);
this->httpPortInput->MoveAndResize(labelWidth + 1, y, 5, 1);
this->httpTlsCheckbox->MoveAndResize(R(this->wssPortInput) + 1, y++, checkboxWidth, 1);
this->pwLabel->MoveAndResize(0, y, labelWidth, 1);
this->pwInput->MoveAndResize(labelWidth + 1, y++, inputWidth, 1);
this->transcoderCheckbox->MoveAndResize(
0, y,
u8cols(this->transcoderCheckbox->GetText()) + 4, 1);
this->transcoderFormatDropdown->MoveAndResize(
R(this->transcoderCheckbox) + 1, y,
u8cols(this->transcoderFormatDropdown->GetText()), 1);
this->transcoderBitrateDropdown->MoveAndResize(
R(this->transcoderFormatDropdown) + 1, y,
u8cols(this->transcoderBitrateDropdown->GetText()), 1);
}
void RemoteLibrarySettingsLayout::OnTlsCheckboxChanged(cursespp::Checkbox* cb, bool checked) {
if (checked) {
SettingsOverlays::CheckShowTlsWarningDialog();
}
}
void RemoteLibrarySettingsLayout::InitializeWindows() {
this->SetFrameVisible(false);
this->hostLabel = std::make_shared<TextLabel>();
this->hostLabel->SetText(_TSTR("settings_library_type_remote_hostname"), text::AlignRight);
this->hostInput = std::make_shared<TextInput>(TextInput::StyleLine);
this->wssPortLabel = std::make_shared<TextLabel>();
this->wssPortLabel->SetText(_TSTR("settings_library_type_remote_wss_port"), text::AlignRight);
this->wssPortInput = std::make_shared<TextInput>(TextInput::StyleLine);
this->wssTlsCheckbox = std::make_shared<Checkbox>();
this->wssTlsCheckbox->SetText(_TSTR("settings_library_type_remote_use_tls"));
this->httpPortLabel = std::make_shared<TextLabel>();
this->httpPortLabel->SetText(_TSTR("settings_library_type_remote_http_port"), text::AlignRight);
this->httpPortInput = std::make_shared<TextInput>(TextInput::StyleLine);
this->httpTlsCheckbox = std::make_shared<Checkbox>();
this->httpTlsCheckbox->SetText(_TSTR("settings_library_type_remote_use_tls"));
this->pwLabel = std::make_shared<TextLabel>();
this->pwLabel->SetText(_TSTR("settings_library_type_remote_password"), text::AlignRight);
this->pwInput = std::make_shared<TextInput>(TextInput::StyleLine);
this->pwInput->SetInputMode(IInput::InputPassword);
this->transcoderCheckbox = std::make_shared<Checkbox>();
this->transcoderCheckbox->SetText(_TSTR("settings_library_type_remote_library_transcoder_enable"));
this->transcoderFormatDropdown = std::make_shared<TextLabel>();
this->transcoderFormatDropdown->Activated.connect(this, &RemoteLibrarySettingsLayout::OnActivateTranscoderFormat);
this->transcoderBitrateDropdown = std::make_shared<TextLabel>();
this->transcoderBitrateDropdown->Activated.connect(this, &RemoteLibrarySettingsLayout::OnActivateTranscoderBitrate);
this->AddWindow(this->hostLabel);
this->AddWindow(this->hostInput);
this->AddWindow(this->hostLabel);
this->AddWindow(this->hostInput);
this->AddWindow(this->wssPortLabel);
this->AddWindow(this->wssPortInput);
this->AddWindow(this->wssTlsCheckbox);
this->AddWindow(this->httpPortLabel);
this->AddWindow(this->httpPortInput);
this->AddWindow(this->httpTlsCheckbox);
this->AddWindow(this->pwLabel);
this->AddWindow(this->pwInput);
this->AddWindow(this->transcoderCheckbox);
this->AddWindow(this->transcoderFormatDropdown);
this->AddWindow(this->transcoderBitrateDropdown);
int order = 0;
this->hostInput->SetFocusOrder(order++);
this->wssPortInput->SetFocusOrder(order++);
this->wssTlsCheckbox->SetFocusOrder(order++);
this->httpPortInput->SetFocusOrder(order++);
this->httpTlsCheckbox->SetFocusOrder(order++);
this->pwInput->SetFocusOrder(order++);
this->transcoderCheckbox->SetFocusOrder(order++);
this->transcoderFormatDropdown->SetFocusOrder(order++);
this->transcoderBitrateDropdown->SetFocusOrder(order++);
}
void RemoteLibrarySettingsLayout::LoadPreferences() {
this->wssTlsCheckbox->CheckChanged.disconnect(this);
this->httpTlsCheckbox->CheckChanged.disconnect(this);
auto host = prefs->GetString(core::prefs::keys::RemoteLibraryHostname, "127.0.0.1");
auto const wssPort = (short) prefs->GetInt(core::prefs::keys::RemoteLibraryWssPort, 7905);
auto const httpPort = (short) prefs->GetInt(core::prefs::keys::RemoteLibraryHttpPort, 7906);
auto const password = prefs->GetString(core::prefs::keys::RemoteLibraryPassword, "");
auto const wssTls = prefs->GetBool(core::prefs::keys::RemoteLibraryWssTls, false);
auto const httpTls = prefs->GetBool(core::prefs::keys::RemoteLibraryHttpTls, false);
this->hostInput->SetText(host);
this->wssPortInput->SetText(std::to_string(wssPort));
this->wssTlsCheckbox->SetChecked(wssTls);
this->httpPortInput->SetText(std::to_string(httpPort));
this->httpTlsCheckbox->SetChecked(httpTls);
this->pwInput->SetText(password);
this->transcoderCheckbox->SetChecked(prefs->GetBool(core::prefs::keys::RemoteLibraryTranscoderEnabled, false));
const std::string transcodeFormat = prefs->GetString(core::prefs::keys::RemoteLibraryTranscoderFormat, "ogg");
this->transcoderFormatDropdown->SetText(
kArrowSymbol +
u8fmt(_TSTR(
"settings_library_type_remote_library_transcoder_format"),
transcodeFormat.c_str()),
text::AlignRight);
const int transcodeBitrate = prefs->GetInt(core::prefs::keys::RemoteLibraryTranscoderBitrate, 192);
this->transcoderBitrateDropdown->SetText(
kArrowSymbol +
u8fmt(_TSTR(
"settings_library_type_remote_library_transcoder_bitrate"),
transcodeBitrate),
text::AlignRight);
this->wssTlsCheckbox->CheckChanged.connect(this, &RemoteLibrarySettingsLayout::OnTlsCheckboxChanged);
this->httpTlsCheckbox->CheckChanged.connect(this, &RemoteLibrarySettingsLayout::OnTlsCheckboxChanged);
}
void RemoteLibrarySettingsLayout::SyncPreferencesAndLayout() {
this->SavePreferences();
this->LoadPreferences();
this->Layout();
}
void RemoteLibrarySettingsLayout::SavePreferences() {
auto host = this->hostInput->GetText();
auto wssPort = std::stoi(this->wssPortInput->GetText());
auto httpPort = std::stoi(this->httpPortInput->GetText());
auto password = this->pwInput->GetText();
auto const wssTls = this->wssTlsCheckbox->IsChecked();
auto const httpTls = this->httpTlsCheckbox->IsChecked();
auto const transcoderEnabled = this->transcoderCheckbox->IsChecked();
if (wssPort > 65535 || wssPort < 0) { wssPort = 7905; }
if (httpPort > 65535 || httpPort < 0) { httpPort = 7905; }
prefs->SetString(core::prefs::keys::RemoteLibraryHostname, host.size() ? host.c_str() : "127.0.0.1");
prefs->SetInt(core::prefs::keys::RemoteLibraryWssPort, wssPort);
prefs->SetInt(core::prefs::keys::RemoteLibraryHttpPort, httpPort);
prefs->SetString(core::prefs::keys::RemoteLibraryPassword, password.c_str());
prefs->SetBool(core::prefs::keys::RemoteLibraryWssTls, wssTls);
prefs->SetBool(core::prefs::keys::RemoteLibraryHttpTls, httpTls);
prefs->SetBool(core::prefs::keys::RemoteLibraryTranscoderEnabled, transcoderEnabled);
/* note: transcoder format and bitrate settings are saved via SettingsOverlays calls */
auto library = LibraryFactory::Instance().DefaultRemoteLibrary();
auto remoteLibrary = std::dynamic_pointer_cast<RemoteLibrary>(library);
if (remoteLibrary) {
remoteLibrary->ReloadConnectionFromPreferences();
}
}
void RemoteLibrarySettingsLayout::OnActivateTranscoderFormat(cursespp::TextLabel* tl) {
SettingsOverlays::ShowTranscoderFormatOverlay([this]() {
this->SyncPreferencesAndLayout();
});
}
void RemoteLibrarySettingsLayout::OnActivateTranscoderBitrate(cursespp::TextLabel* tl) {
SettingsOverlays::ShowTranscoderBitrateOverlay([this]() {
this->SyncPreferencesAndLayout();
});
}
<commit_msg>Ensure we prime the RemoteLibrarySettingsLayout during construction.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2020 musikcube team
//
// 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 other 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 <stdafx.h>
#include "RemoteLibrarySettingsLayout.h"
#include <cursespp/App.h>
#include <cursespp/Colors.h>
#include <musikcore/library/LibraryFactory.h>
#include <musikcore/support/PreferenceKeys.h>
#include <app/overlay/SettingsOverlays.h>
#include <algorithm>
#include <vector>
using namespace musik;
using namespace musik::core;
using namespace musik::core::library;
using namespace musik::core::sdk;
using namespace musik::cube;
using namespace cursespp;
#define R(x) (x->GetX() + x->GetWidth())
static const std::string kArrowSymbol = "> ";
static inline int longestStringLength(const std::vector<std::string>&& keys) {
int max = 0;
for (auto& str: keys) {
size_t len = u8cols(_TSTR(str));
max = len > max ? len : max;
}
return max;
}
RemoteLibrarySettingsLayout::RemoteLibrarySettingsLayout()
: LayoutBase() {
this->prefs = Preferences::ForComponent(core::prefs::components::Settings);
this->SetFocusMode(FocusModeTerminating);
this->InitializeWindows();
this->LoadPreferences();
}
RemoteLibrarySettingsLayout::~RemoteLibrarySettingsLayout() {
this->SavePreferences();
}
void RemoteLibrarySettingsLayout::OnLayout() {
const int labelWidth = longestStringLength({
"settings_library_type_remote_hostname",
"settings_library_type_remote_wss_port",
"settings_library_type_remote_http_port",
"settings_library_type_remote_password"
});
const int checkboxWidth = u8cols(_TSTR("settings_library_type_remote_use_tls")) + 4;
int const cx = this->GetWidth();
int const inputWidth = std::min((int) 32, (int) (cx - labelWidth - 1));
int y = 0;
this->hostLabel->MoveAndResize(0, y, labelWidth, 1);
this->hostInput->MoveAndResize(labelWidth + 1, y++, inputWidth, 1);
this->wssPortLabel->MoveAndResize(0, y, labelWidth, 1);
this->wssPortInput->MoveAndResize(labelWidth + 1, y, 5, 1);
this->wssTlsCheckbox->MoveAndResize(R(this->wssPortInput) + 1, y++, checkboxWidth, 1);
this->httpPortLabel->MoveAndResize(0, y, labelWidth, 1);
this->httpPortInput->MoveAndResize(labelWidth + 1, y, 5, 1);
this->httpTlsCheckbox->MoveAndResize(R(this->wssPortInput) + 1, y++, checkboxWidth, 1);
this->pwLabel->MoveAndResize(0, y, labelWidth, 1);
this->pwInput->MoveAndResize(labelWidth + 1, y++, inputWidth, 1);
this->transcoderCheckbox->MoveAndResize(
0, y,
u8cols(this->transcoderCheckbox->GetText()) + 4, 1);
this->transcoderFormatDropdown->MoveAndResize(
R(this->transcoderCheckbox) + 1, y,
u8cols(this->transcoderFormatDropdown->GetText()), 1);
this->transcoderBitrateDropdown->MoveAndResize(
R(this->transcoderFormatDropdown) + 1, y,
u8cols(this->transcoderBitrateDropdown->GetText()), 1);
}
void RemoteLibrarySettingsLayout::OnTlsCheckboxChanged(cursespp::Checkbox* cb, bool checked) {
if (checked) {
SettingsOverlays::CheckShowTlsWarningDialog();
}
}
void RemoteLibrarySettingsLayout::InitializeWindows() {
this->SetFrameVisible(false);
this->hostLabel = std::make_shared<TextLabel>();
this->hostLabel->SetText(_TSTR("settings_library_type_remote_hostname"), text::AlignRight);
this->hostInput = std::make_shared<TextInput>(TextInput::StyleLine);
this->wssPortLabel = std::make_shared<TextLabel>();
this->wssPortLabel->SetText(_TSTR("settings_library_type_remote_wss_port"), text::AlignRight);
this->wssPortInput = std::make_shared<TextInput>(TextInput::StyleLine);
this->wssTlsCheckbox = std::make_shared<Checkbox>();
this->wssTlsCheckbox->SetText(_TSTR("settings_library_type_remote_use_tls"));
this->httpPortLabel = std::make_shared<TextLabel>();
this->httpPortLabel->SetText(_TSTR("settings_library_type_remote_http_port"), text::AlignRight);
this->httpPortInput = std::make_shared<TextInput>(TextInput::StyleLine);
this->httpTlsCheckbox = std::make_shared<Checkbox>();
this->httpTlsCheckbox->SetText(_TSTR("settings_library_type_remote_use_tls"));
this->pwLabel = std::make_shared<TextLabel>();
this->pwLabel->SetText(_TSTR("settings_library_type_remote_password"), text::AlignRight);
this->pwInput = std::make_shared<TextInput>(TextInput::StyleLine);
this->pwInput->SetInputMode(IInput::InputPassword);
this->transcoderCheckbox = std::make_shared<Checkbox>();
this->transcoderCheckbox->SetText(_TSTR("settings_library_type_remote_library_transcoder_enable"));
this->transcoderFormatDropdown = std::make_shared<TextLabel>();
this->transcoderFormatDropdown->Activated.connect(this, &RemoteLibrarySettingsLayout::OnActivateTranscoderFormat);
this->transcoderBitrateDropdown = std::make_shared<TextLabel>();
this->transcoderBitrateDropdown->Activated.connect(this, &RemoteLibrarySettingsLayout::OnActivateTranscoderBitrate);
this->AddWindow(this->hostLabel);
this->AddWindow(this->hostInput);
this->AddWindow(this->hostLabel);
this->AddWindow(this->hostInput);
this->AddWindow(this->wssPortLabel);
this->AddWindow(this->wssPortInput);
this->AddWindow(this->wssTlsCheckbox);
this->AddWindow(this->httpPortLabel);
this->AddWindow(this->httpPortInput);
this->AddWindow(this->httpTlsCheckbox);
this->AddWindow(this->pwLabel);
this->AddWindow(this->pwInput);
this->AddWindow(this->transcoderCheckbox);
this->AddWindow(this->transcoderFormatDropdown);
this->AddWindow(this->transcoderBitrateDropdown);
int order = 0;
this->hostInput->SetFocusOrder(order++);
this->wssPortInput->SetFocusOrder(order++);
this->wssTlsCheckbox->SetFocusOrder(order++);
this->httpPortInput->SetFocusOrder(order++);
this->httpTlsCheckbox->SetFocusOrder(order++);
this->pwInput->SetFocusOrder(order++);
this->transcoderCheckbox->SetFocusOrder(order++);
this->transcoderFormatDropdown->SetFocusOrder(order++);
this->transcoderBitrateDropdown->SetFocusOrder(order++);
}
void RemoteLibrarySettingsLayout::LoadPreferences() {
this->wssTlsCheckbox->CheckChanged.disconnect(this);
this->httpTlsCheckbox->CheckChanged.disconnect(this);
auto host = prefs->GetString(core::prefs::keys::RemoteLibraryHostname, "127.0.0.1");
auto const wssPort = (short) prefs->GetInt(core::prefs::keys::RemoteLibraryWssPort, 7905);
auto const httpPort = (short) prefs->GetInt(core::prefs::keys::RemoteLibraryHttpPort, 7906);
auto const password = prefs->GetString(core::prefs::keys::RemoteLibraryPassword, "");
auto const wssTls = prefs->GetBool(core::prefs::keys::RemoteLibraryWssTls, false);
auto const httpTls = prefs->GetBool(core::prefs::keys::RemoteLibraryHttpTls, false);
this->hostInput->SetText(host);
this->wssPortInput->SetText(std::to_string(wssPort));
this->wssTlsCheckbox->SetChecked(wssTls);
this->httpPortInput->SetText(std::to_string(httpPort));
this->httpTlsCheckbox->SetChecked(httpTls);
this->pwInput->SetText(password);
this->transcoderCheckbox->SetChecked(prefs->GetBool(core::prefs::keys::RemoteLibraryTranscoderEnabled, false));
const std::string transcodeFormat = prefs->GetString(core::prefs::keys::RemoteLibraryTranscoderFormat, "ogg");
this->transcoderFormatDropdown->SetText(
kArrowSymbol +
u8fmt(_TSTR(
"settings_library_type_remote_library_transcoder_format"),
transcodeFormat.c_str()),
text::AlignRight);
const int transcodeBitrate = prefs->GetInt(core::prefs::keys::RemoteLibraryTranscoderBitrate, 192);
this->transcoderBitrateDropdown->SetText(
kArrowSymbol +
u8fmt(_TSTR(
"settings_library_type_remote_library_transcoder_bitrate"),
transcodeBitrate),
text::AlignRight);
this->wssTlsCheckbox->CheckChanged.connect(this, &RemoteLibrarySettingsLayout::OnTlsCheckboxChanged);
this->httpTlsCheckbox->CheckChanged.connect(this, &RemoteLibrarySettingsLayout::OnTlsCheckboxChanged);
}
void RemoteLibrarySettingsLayout::SyncPreferencesAndLayout() {
this->SavePreferences();
this->LoadPreferences();
this->Layout();
}
void RemoteLibrarySettingsLayout::SavePreferences() {
auto host = this->hostInput->GetText();
auto wssPort = std::stoi(this->wssPortInput->GetText());
auto httpPort = std::stoi(this->httpPortInput->GetText());
auto password = this->pwInput->GetText();
auto const wssTls = this->wssTlsCheckbox->IsChecked();
auto const httpTls = this->httpTlsCheckbox->IsChecked();
auto const transcoderEnabled = this->transcoderCheckbox->IsChecked();
if (wssPort > 65535 || wssPort < 0) { wssPort = 7905; }
if (httpPort > 65535 || httpPort < 0) { httpPort = 7905; }
prefs->SetString(core::prefs::keys::RemoteLibraryHostname, host.size() ? host.c_str() : "127.0.0.1");
prefs->SetInt(core::prefs::keys::RemoteLibraryWssPort, wssPort);
prefs->SetInt(core::prefs::keys::RemoteLibraryHttpPort, httpPort);
prefs->SetString(core::prefs::keys::RemoteLibraryPassword, password.c_str());
prefs->SetBool(core::prefs::keys::RemoteLibraryWssTls, wssTls);
prefs->SetBool(core::prefs::keys::RemoteLibraryHttpTls, httpTls);
prefs->SetBool(core::prefs::keys::RemoteLibraryTranscoderEnabled, transcoderEnabled);
/* note: transcoder format and bitrate settings are saved via SettingsOverlays calls */
auto library = LibraryFactory::Instance().DefaultRemoteLibrary();
auto remoteLibrary = std::dynamic_pointer_cast<RemoteLibrary>(library);
if (remoteLibrary) {
remoteLibrary->ReloadConnectionFromPreferences();
}
}
void RemoteLibrarySettingsLayout::OnActivateTranscoderFormat(cursespp::TextLabel* tl) {
SettingsOverlays::ShowTranscoderFormatOverlay([this]() {
this->SyncPreferencesAndLayout();
});
}
void RemoteLibrarySettingsLayout::OnActivateTranscoderBitrate(cursespp::TextLabel* tl) {
SettingsOverlays::ShowTranscoderBitrateOverlay([this]() {
this->SyncPreferencesAndLayout();
});
}
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Torsten Rahn <[email protected]>"
//
#include "MarbleCrosshairsPlugin.h"
#include <QtCore/QDebug>
#include "GeoPainter.h"
#include "MarbleDirs.h"
#include "ViewportParams.h"
namespace Marble
{
QStringList MarbleCrosshairsPlugin::backendTypes() const
{
return QStringList( "crosshairs" );
}
QString MarbleCrosshairsPlugin::renderPolicy() const
{
return QString( "ALWAYS" );
}
QStringList MarbleCrosshairsPlugin::renderPosition() const
{
return QStringList( "FLOAT_ITEM" ); // although this is not a float item we choose the position of one
}
QString MarbleCrosshairsPlugin::name() const
{
return tr( "Crosshairs Plugin" );
}
QString MarbleCrosshairsPlugin::guiString() const
{
return tr( "Cross&hairs" );
}
QString MarbleCrosshairsPlugin::nameId() const
{
return QString( "crosshairs" );
}
QString MarbleCrosshairsPlugin::description() const
{
return tr( "A plugin that shows crosshairs." );
}
QIcon MarbleCrosshairsPlugin::icon () const
{
return QIcon();
}
void MarbleCrosshairsPlugin::initialize ()
{
}
bool MarbleCrosshairsPlugin::isInitialized () const
{
return true;
}
bool MarbleCrosshairsPlugin::render( GeoPainter *painter, ViewportParams *viewport,
const QString& renderPos,
GeoSceneLayer * layer )
{
int centerx = viewport->width() / 2;
int centery = viewport->height() / 2;
int halfsize = 5;
painter->save();
painter->setRenderHint( QPainter::Antialiasing, false );
painter->setPen( QColor( Qt::white ) );
painter->drawLine( centerx - halfsize, centery,
centerx + halfsize, centery );
painter->drawLine( centerx, centery - halfsize,
centerx, centery + halfsize );
painter->restore();
return true;
}
}
Q_EXPORT_PLUGIN2(MarbleCrosshairsPlugin, Marble::MarbleCrosshairsPlugin)
#include "MarbleCrosshairsPlugin.moc"
<commit_msg>i18n-string-freeze fix - Removed ToolTip string that got introduced accidently - Changed name string to some existing string. <commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Torsten Rahn <[email protected]>"
//
#include "MarbleCrosshairsPlugin.h"
#include <QtCore/QDebug>
#include "GeoPainter.h"
#include "MarbleDirs.h"
#include "ViewportParams.h"
namespace Marble
{
QStringList MarbleCrosshairsPlugin::backendTypes() const
{
return QStringList( "crosshairs" );
}
QString MarbleCrosshairsPlugin::renderPolicy() const
{
return QString( "ALWAYS" );
}
QStringList MarbleCrosshairsPlugin::renderPosition() const
{
return QStringList( "FLOAT_ITEM" ); // although this is not a float item we choose the position of one
}
QString MarbleCrosshairsPlugin::name() const
{
// FIXME (once we are out of string freeze):
return tr( "Cross&hairs" ).remove( QChar( '&' ) ); // return tr( "Crosshairs" );
}
QString MarbleCrosshairsPlugin::guiString() const
{
return tr( "Cross&hairs" );
}
QString MarbleCrosshairsPlugin::nameId() const
{
return QString( "crosshairs" );
}
QString MarbleCrosshairsPlugin::description() const
{
return QString( "" ); // tr( "A plugin that shows crosshairs." );
}
QIcon MarbleCrosshairsPlugin::icon () const
{
return QIcon();
}
void MarbleCrosshairsPlugin::initialize ()
{
}
bool MarbleCrosshairsPlugin::isInitialized () const
{
return true;
}
bool MarbleCrosshairsPlugin::render( GeoPainter *painter, ViewportParams *viewport,
const QString& renderPos,
GeoSceneLayer * layer )
{
int centerx = viewport->width() / 2;
int centery = viewport->height() / 2;
int halfsize = 5;
painter->save();
painter->setRenderHint( QPainter::Antialiasing, false );
painter->setPen( QColor( Qt::white ) );
painter->drawLine( centerx - halfsize, centery,
centerx + halfsize, centery );
painter->drawLine( centerx, centery - halfsize,
centerx, centery + halfsize );
painter->restore();
return true;
}
}
Q_EXPORT_PLUGIN2(MarbleCrosshairsPlugin, Marble::MarbleCrosshairsPlugin)
#include "MarbleCrosshairsPlugin.moc"
<|endoftext|>
|
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Chrono test program for rolling friction
//
// The global reference frame has Y up.
//
// =============================================================================
#include "chrono/ChConfig.h"
#include "chrono/utils/ChUtilsCreators.h"
#include "chrono/physics/ChSystemNSC.h"
#ifdef CHRONO_IRRLICHT
#include "chrono_irrlicht/ChIrrApp.h"
#endif
using namespace chrono;
// --------------------------------------------------------------------------
int main(int argc, char* argv[]) {
// ----------------
// Parameters
// ----------------
double radius = 0.5;
double density = 1000;
double mass = density * (4.0 / 3.0) * CH_C_PI * pow(radius, 3);
double inertia = (2.0 / 5.0) * mass * pow(radius, 2);
double initial_angspeed = 10;
double initial_linspeed = initial_angspeed * radius;
float sliding_friction = 0.1f;
float rolling_friction = 0.1f;
double time_step = 1e-3;
double tolerance = 0;
double contact_recovery_speed = 1e8;
double collision_envelope = .05 * radius;
// -----------------
// Create the system
// -----------------
ChSystemNSC system;
system.Set_G_acc(ChVector<>(0, -10, 0));
// Set solver settings
system.SetSolverType(ChSolver::Type::APGD);
system.SetSolverMaxIterations(100);
system.SetSolverTolerance(tolerance);
system.SetSolverForceTolerance(tolerance);
system.SetMaxPenetrationRecoverySpeed(contact_recovery_speed);
// ----------
// Add bodies
// ----------
// Shared contact material
auto material = chrono_types::make_shared<ChMaterialSurfaceNSC>();
material->SetFriction(sliding_friction);
material->SetRollingFriction(rolling_friction);
auto container = std::shared_ptr<ChBody>(system.NewBody());
system.Add(container);
container->SetPos(ChVector<>(0, 0, 0));
container->SetBodyFixed(true);
container->SetIdentifier(-1);
container->SetCollide(true);
container->GetCollisionModel()->SetEnvelope(collision_envelope);
container->GetCollisionModel()->ClearModel();
utils::AddBoxGeometry(container.get(), material, ChVector<>(20, .5, 20), ChVector<>(0, -.5, 0));
container->GetCollisionModel()->BuildModel();
container->AddAsset(chrono_types::make_shared<ChColorAsset>(ChColor(0.4f, 0.4f, 0.2f)));
auto ball = std::shared_ptr<ChBody>(system.NewBody());
ChVector<> pos = ChVector<>(0, radius, 0);
ChVector<> vel = ChVector<>(initial_linspeed, 0, 0);
ChVector<> wvel = ChVector<>(0, 0, -initial_angspeed);
ball->SetMass(mass);
ball->SetPos(pos);
ball->SetPos_dt(vel);
ball->SetWvel_par(wvel);
ball->SetInertiaXX(ChVector<>(inertia));
ball->SetCollide(true);
ball->GetCollisionModel()->SetEnvelope(collision_envelope);
ball->GetCollisionModel()->ClearModel();
utils::AddSphereGeometry(ball.get(), material, radius);
ball->GetCollisionModel()->BuildModel();
ball->AddAsset(chrono_types::make_shared<ChTexture>(GetChronoDataFile("bluwhite.png")));
system.AddBody(ball);
#ifdef CHRONO_IRRLICHT
// -------------------------------
// Create the visualization window
// -------------------------------
irrlicht::ChIrrApp application(&system, L"Rolling test", irr::core::dimension2d<irr::u32>(800, 600), false, true);
irrlicht::ChIrrWizard::add_typical_Logo(application.GetDevice());
irrlicht::ChIrrWizard::add_typical_Sky(application.GetDevice());
irrlicht::ChIrrWizard::add_typical_Lights(application.GetDevice());
irrlicht::ChIrrWizard::add_typical_Camera(application.GetDevice(), irr::core::vector3df(10, 10, -20));
application.AssetBindAll();
application.AssetUpdateAll();
#endif
// ---------------
// Simulate system
// ---------------
double time_end = 20.0;
double time_out = 2.5;
bool output = false;
while (system.GetChTime() < time_end) {
system.DoStepDynamics(time_step);
auto pos = ball->GetPos();
printf("T: %f Pos: %f %f %f\n", system.GetChTime(), pos.x(), pos.y(), pos.z());
// if (!output && system.GetChTime() >= time_out) {
// for (int i = 1; i <= 10; i++) {
// auto pos = system.Get_bodylist()->at(i)->GetPos();
// std::cout << pos.x() << std::endl;
// }
// output = true;
//}
#ifdef CHRONO_IRRLICHT
if (application.GetDevice()->run()) {
application.BeginScene(true, true, irr::video::SColor(255, 140, 161, 192));
application.DrawAll();
application.EndScene();
} else {
return 1;
}
#endif
}
return 0;
}
<commit_msg>Modify test program to demonstrate use of collision shapes with different contact materials<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Chrono test program for:
// - collision shapes with different material properties within same model
// - rolling friction
//
// The global reference frame has Y up.
//
// =============================================================================
#include "chrono/utils/ChUtilsCreators.h"
#include "chrono/physics/ChSystemNSC.h"
#include "chrono_irrlicht/ChIrrApp.h"
using namespace chrono;
// --------------------------------------------------------------------------
int main(int argc, char* argv[]) {
// ----------------
// Parameters
// ----------------
double radius = 0.5;
double density = 1000;
double mass = density * (4.0 / 3.0) * CH_C_PI * pow(radius, 3);
double inertia = (2.0 / 5.0) * mass * pow(radius, 2);
double initial_angspeed = 10;
double initial_linspeed = initial_angspeed * radius;
float sliding_friction = 0.1f;
float rolling_friction = 0.1f;
double time_step = 1e-3;
double tolerance = 0;
double contact_recovery_speed = 1e8;
double collision_envelope = 0.02 * radius;
// -----------------
// Create the system
// -----------------
ChSystemNSC system;
system.Set_G_acc(ChVector<>(0, -10, 0));
// Set solver settings
system.SetSolverType(ChSolver::Type::APGD);
system.SetSolverMaxIterations(100);
system.SetSolverTolerance(tolerance);
system.SetSolverForceTolerance(tolerance);
system.SetMaxPenetrationRecoverySpeed(contact_recovery_speed);
// ----------
// Add bodies
// ----------
auto container = std::shared_ptr<ChBody>(system.NewBody());
system.Add(container);
container->SetPos(ChVector<>(0, 0, 0));
container->SetBodyFixed(true);
container->SetIdentifier(-1);
container->SetCollide(true);
container->GetCollisionModel()->SetEnvelope(collision_envelope);
container->GetCollisionModel()->ClearModel();
for (int i = 0; i < 5; i++) {
auto material = chrono_types::make_shared<ChMaterialSurfaceNSC>();
material->SetFriction(0.15f * (i + 1));
material->SetRollingFriction(0.05f * (i + 1) / 5.0f);
utils::AddBoxGeometry(container.get(), material, ChVector<>(20, 0.5, 1.8 * radius),
ChVector<>(0, -0.5, i * 4.0 * radius));
}
container->GetCollisionModel()->BuildModel();
container->AddAsset(chrono_types::make_shared<ChColorAsset>(ChColor(0.4f, 0.4f, 0.2f)));
auto ball_material = chrono_types::make_shared<ChMaterialSurfaceNSC>();
ball_material->SetFriction(1.0);
ball_material->SetRollingFriction(1.0);
std::vector<std::shared_ptr<ChBody>> balls;
for (int i = 0; i < 5; i++) {
auto ball = std::shared_ptr<ChBody>(system.NewBody());
ball->SetMass(mass);
ball->SetPos(ChVector<>(-9, radius, 4.0 * i * radius));
ball->SetPos_dt(ChVector<>(initial_linspeed, 0, 0));
ball->SetWvel_par(ChVector<>(0, 0, -initial_angspeed));
ball->SetInertiaXX(ChVector<>(inertia));
ball->SetCollide(true);
ball->GetCollisionModel()->SetEnvelope(collision_envelope);
ball->GetCollisionModel()->ClearModel();
utils::AddSphereGeometry(ball.get(), ball_material, radius);
ball->GetCollisionModel()->BuildModel();
ball->AddAsset(chrono_types::make_shared<ChTexture>(GetChronoDataFile("bluwhite.png")));
system.AddBody(ball);
balls.push_back(ball);
}
// -------------------------------
// Create the visualization window
// -------------------------------
irrlicht::ChIrrApp application(&system, L"Rolling test", irr::core::dimension2d<irr::u32>(800, 600), false, true);
irrlicht::ChIrrWizard::add_typical_Logo(application.GetDevice());
irrlicht::ChIrrWizard::add_typical_Sky(application.GetDevice());
irrlicht::ChIrrWizard::add_typical_Lights(application.GetDevice());
irrlicht::ChIrrWizard::add_typical_Camera(application.GetDevice(), irr::core::vector3df(10, 10, -20));
application.AssetBindAll();
application.AssetUpdateAll();
// ---------------
// Simulate system
// ---------------
while (application.GetDevice()->run()) {
std::cout << "time: " << system.GetChTime();
for (auto ball : balls)
std::cout << " " << ball->GetPos().y();
std::cout << std::endl;
application.BeginScene();
application.DrawAll();
application.EndScene();
system.DoStepDynamics(time_step);
}
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef STAN__AGRAD__REV__OPERATORS__OPERATOR_UNARY_NEGATIVE_HPP
#define STAN__AGRAD__REV__OPERATORS__OPERATOR_UNARY_NEGATIVE_HPP
#include <stan/agrad/rev/var.hpp>
#include <stan/agrad/rev/internal/v_vari.hpp>
namespace stan {
namespace agrad {
namespace {
class neg_vari : public op_v_vari {
public:
neg_vari(vari* avi) :
op_v_vari(-(avi->val_), avi) {
}
void chain() {
avi_->adj_ -= adj_;
}
};
}
/**
* Unary negation operator for variables (C++).
*
* \f$\frac{d}{dx} -x = -1\f$.
*
* @param a Argument variable.
* @return Negation of variable.
*/
inline var operator-(const var& a) {
return var(new neg_vari(a.vi_));
}
}
}
#endif
<commit_msg>fixed operator_unary_negative so gradient returns NaN<commit_after>#ifndef STAN__AGRAD__REV__OPERATORS__OPERATOR_UNARY_NEGATIVE_HPP
#define STAN__AGRAD__REV__OPERATORS__OPERATOR_UNARY_NEGATIVE_HPP
#include <stan/agrad/rev/var.hpp>
#include <stan/agrad/rev/internal/v_vari.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
namespace stan {
namespace agrad {
namespace {
class neg_vari : public op_v_vari {
public:
neg_vari(vari* avi) :
op_v_vari(-(avi->val_), avi) {
}
void chain() {
if (unlikely(boost::math::isnan(avi_->val_)))
avi_->adj_ = std::numeric_limits<double>::quiet_NaN();
else
avi_->adj_ -= adj_;
}
};
}
/**
* Unary negation operator for variables (C++).
*
* \f$\frac{d}{dx} -x = -1\f$.
*
* @param a Argument variable.
* @return Negation of variable.
*/
inline var operator-(const var& a) {
return var(new neg_vari(a.vi_));
}
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2008-2009
*
* School of Computing, University of Utah,
* Salt Lake City, UT 84112, USA
*
* and the Gauss Group
* http://www.cs.utah.edu/formal_verification
*
* See LICENSE for licensing information
*/
#ifndef _AMPLE_SET_HPP
#define _AMPLE_SET_HPP
//#define CONSOLE_OUTPUT_THRESHOLD 200
#include <vector>
#include <set>
#include <iterator>
#include <memory>
#include <boost/optional.hpp>
#include "Trace.hpp"
#include "Matcher.hpp"
#include "State.hpp"
using std::vector;
using std::shared_ptr;
//using boost::optional;
struct AmpleSet {
public:
AmpleSet(State &s, const Matcher & m, const vector<shared_ptr<Transition>> & f):
matcher(m),
state(s),
funcs(f)
{}
vector<vector<shared_ptr<Transition> > > create();
private:
vector<vector<shared_ptr<Transition> > > ample_set;
const Matcher & matcher;
State & state;
const vector<shared_ptr<Transition>> & funcs;
bool genCollectiveAmple(int collective);
bool genWaitorTestAmple();
bool genReceiveAmple();
bool genTestIProbe();
bool genNonWildcardReceive();
vector<vector<shared_ptr<Transition> > > createAllMatchingSends(shared_ptr<Transition>);
bool genAllSends();
};
inline vector<vector<shared_ptr<Transition> > > createAmpleSet(State& s, const Matcher & m,
const vector<shared_ptr<Transition> > & f) {
return AmpleSet(s, m, f).create();
}
#endif
<commit_msg>Removed unused headers.<commit_after>/*
* Copyright (c) 2008-2009
*
* School of Computing, University of Utah,
* Salt Lake City, UT 84112, USA
*
* and the Gauss Group
* http://www.cs.utah.edu/formal_verification
*
* See LICENSE for licensing information
*/
#ifndef _AMPLE_SET_HPP
#define _AMPLE_SET_HPP
//#define CONSOLE_OUTPUT_THRESHOLD 200
#include <vector>
#include <set>
#include <iterator>
#include <memory>
#include "Trace.hpp"
#include "Matcher.hpp"
#include "State.hpp"
using std::vector;
using std::shared_ptr;
struct AmpleSet {
public:
AmpleSet(State &s, const Matcher & m, const vector<shared_ptr<Transition>> & f):
matcher(m),
state(s),
funcs(f)
{}
vector<vector<shared_ptr<Transition> > > create();
private:
vector<vector<shared_ptr<Transition> > > ample_set;
const Matcher & matcher;
State & state;
const vector<shared_ptr<Transition>> & funcs;
bool genCollectiveAmple(int collective);
bool genWaitorTestAmple();
bool genReceiveAmple();
bool genTestIProbe();
bool genNonWildcardReceive();
vector<vector<shared_ptr<Transition> > > createAllMatchingSends(shared_ptr<Transition>);
bool genAllSends();
};
inline vector<vector<shared_ptr<Transition> > > createAmpleSet(State& s, const Matcher & m,
const vector<shared_ptr<Transition> > & f) {
return AmpleSet(s, m, f).create();
}
#endif
<|endoftext|>
|
<commit_before>// -*- C++ -*-
/*!
* @file Spline.cpp
* @brief Cubic Hermite splines implementation with first derivative end
*conditions
* $Date$
*
* $Id$
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <iomanip>
#include <ostream>
#include "CHSpline/CHSpline.h"
namespace
{
const bool CONTROLLER_BRIDGE_DEBUG = false;
}
Spline::Spline()
{
t_.push_back(0.0);
t_.push_back(1.0);
p_.push_back(0.0);
p_.push_back(1.0);
v_.push_back(0.0);
v_.push_back(0.0);
}
Spline::Spline(double ti0, double ti1, double pi0, double pi1, double vi0,
double vi1)
{
t_.push_back(ti0);
t_.push_back(ti1);
p_.push_back(pi0);
p_.push_back(pi1);
v_.push_back(vi0);
v_.push_back(vi1);
}
Spline::~Spline()
{
}
bool Spline::initSpline(double ti0, double ti1, double pi0, double pi1,
double vi0, double vi1)
{
t_.clear();
p_.clear();
v_.clear();
t_.push_back(ti0);
t_.push_back(ti1);
p_.push_back(pi0);
p_.push_back(pi1);
v_.push_back(vi0);
v_.push_back(vi1);
return true;
}
bool Spline::initSpline(std::vector<double> ti, std::vector<double> pi,
std::vector<double> vi)
{
// check vector sizes
if ((ti.size() < 2) || (pi.size() < 2) || (vi.size() < 2))
{
std::cerr << "Spline initialisation: Error in vector sizes (too small)"
<< std::endl;
return false;
}
if (ti.size() != pi.size())
{
std::cerr << "Spline initialisation: Different vector sizes for knot time "
"and position" << std::endl;
return false;
}
if ((vi.size() != ti.size()) && (vi.size() != 2))
{
std::cerr << "Spline initialisation: Error in velocity vector size"
<< std::endl;
return false;
}
// t is sorted
for (std::vector<double>::size_type i = 1; i < ti.size(); i++)
{
if ((ti[i] - ti[i - 1]) < 0)
{
std::cerr << "Spline initialisation: Error t vector is not sorted"
<< std::endl;
return false;
}
}
t_.clear();
p_.clear();
v_.clear();
t_ = ti;
p_ = pi;
// if more than two knot and only boundaries conditions for velocities
// use Catmull-Rom Spline construction: V_i=0.5*(p_(i+1)-p_(i+1))
if ((vi.size() == 2) && (t_.size() != 2))
{
v_.push_back(vi[0]);
for (std::vector<double>::size_type i = 1; i < (t_.size() - 1); i++)
{
v_.push_back(0.5 * (((p_[i] - p_[i - 1]) * (t_[i + 1] - t_[i])) /
((t_[i] - t_[i - 1]) * (t_[i + 1] - t_[i - 1])) +
((p_[i + 1] - p_[i]) * (t_[i] - t_[i - 1])) /
((t_[i + 1] - t_[i]) * (t_[i + 1] - t_[i - 1]))));
}
v_.push_back(vi[1]);
}
else
{
v_ = vi;
}
return true;
}
bool Spline::initDerivativeCatmullRom()
{
if (t_.size() > 2)
{
double vFront = v_.front();
double vBack = v_.back();
v_.clear();
v_.push_back(vFront);
for (std::vector<double>::size_type i = 1; i < (t_.size() - 1); i++)
{
v_.push_back(0.5 * (((p_[i] - p_[i - 1]) * (t_[i + 1] - t_[i])) /
((t_[i] - t_[i - 1]) * (t_[i + 1] - t_[i - 1])) +
((p_[i + 1] - p_[i]) * (t_[i] - t_[i - 1])) /
((t_[i + 1] - t_[i]) * (t_[i + 1] - t_[i - 1]))));
}
v_.push_back(vBack);
return true;
}
return false;
}
bool Spline::initDerivativezero()
{
if (t_.size() > 2)
{
double vFront = v_.front();
double vBack = v_.back();
v_.clear();
v_.push_back(vFront);
for (std::vector<double>::size_type i = 1; i < (t_.size() - 1); i++)
{
v_.push_back(0.0);
}
v_.push_back(vBack);
return true;
}
return false;
}
bool Spline::initDerivatives(std::vector<double> vi)
{
if (vi.size() == t_.size())
{
v_ = vi;
return true;
}
return false;
}
bool Spline::addNode(double ti, double pi, double vi)
{
if ((t_.back()) < ti)
{
t_.push_back(ti);
p_.push_back(pi);
v_.push_back(vi);
return true;
}
else
{
return false;
}
}
double Spline::evalSpline(double te) const
{
if (te <= t_.front())
{
return p_.front();
}
if (te >= t_.back())
{
return p_.back();
}
// deal with more than two knot
std::vector<double>::const_iterator up;
up = std::upper_bound(t_.begin(), t_.end(), te);
int noSpline = up - t_.begin() - 1;
double tn = (te - t_[noSpline]) /
(t_[noSpline + 1] - t_[noSpline]); // normalized time
double h1 = 2 * tn * tn * tn - 3 * tn * tn + 1; // calculate basis function 1
double h2 = -2 * tn * tn * tn + 3 * tn * tn; // calculate basis function 2
double h3 = tn * tn * tn - 2 * tn * tn + tn; // calculate basis function 3
double h4 = tn * tn * tn - tn * tn; // calculate basis function 4
return h1 * p_[noSpline] + // multiply and sum all functions
h2 * p_[noSpline + 1] + // together to build the interpolated
h3 * v_[noSpline] *
(t_[noSpline + 1] - t_[noSpline]) + // point along the curve.
h4 * v_[noSpline + 1] * (t_[noSpline + 1] - t_[noSpline]);
}
bool Spline::evalVectorSpline(std::vector<double> t,
std::vector<double>& output) const
{
output.clear();
for (std::vector<double>::size_type i = 0; i < t.size(); i++)
{
output.push_back(evalSpline(t[i]));
}
return true;
}
std::vector<double> Spline::evalVectorSpline(std::vector<double> t) const
{
std::vector<double> output;
for (std::vector<double>::size_type i = 0; i < t.size(); i++)
{
output.push_back(evalSpline(t[i]));
}
return output;
}
<commit_msg>Use jrl-cmakemodules<commit_after>// -*- C++ -*-
/*!
* @file Spline.cpp
* @brief Cubic Hermite splines implementation with first derivative end
*conditions
* $Date$
*
* $Id$
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <iomanip>
#include <ostream>
#include "CHSpline/CHSpline.h"
namespace
{
const bool CONTROLLER_BRIDGE_DEBUG = false;
}
Spline::Spline()
{
t_.push_back(0.0);
t_.push_back(1.0);
p_.push_back(0.0);
p_.push_back(1.0);
v_.push_back(0.0);
v_.push_back(0.0);
}
Spline::Spline(double ti0, double ti1, double pi0, double pi1, double vi0,
double vi1)
{
t_.push_back(ti0);
t_.push_back(ti1);
p_.push_back(pi0);
p_.push_back(pi1);
v_.push_back(vi0);
v_.push_back(vi1);
}
Spline::~Spline()
{
}
bool Spline::initSpline(double ti0, double ti1, double pi0, double pi1,
double vi0, double vi1)
{
t_.clear();
p_.clear();
v_.clear();
t_.push_back(ti0);
t_.push_back(ti1);
p_.push_back(pi0);
p_.push_back(pi1);
v_.push_back(vi0);
v_.push_back(vi1);
return true;
}
bool Spline::initSpline(std::vector<double> ti, std::vector<double> pi,
std::vector<double> vi)
{
// check vector sizes
if ((ti.size() < 2) || (pi.size() < 2) || (vi.size() < 2))
{
std::cerr << "Spline initialisation: Error in vector sizes (too small)"
<< std::endl;
return false;
}
if (ti.size() != pi.size())
{
std::cerr << "Spline initialisation: Different vector sizes for knot time "
"and position" << std::endl;
return false;
}
if ((vi.size() != ti.size()) && (vi.size() != 2))
{
std::cerr << "Spline initialisation: Error in velocity vector size"
<< std::endl;
return false;
}
// t is sorted
for (std::vector<double>::size_type i = 1; i < ti.size(); i++)
{
if ((ti[i] - ti[i - 1]) < 0)
{
std::cerr << "Spline initialisation: Error t vector is not sorted"
<< std::endl;
return false;
}
}
t_.clear();
p_.clear();
v_.clear();
t_ = ti;
p_ = pi;
// if more than two knot and only boundaries conditions for velocities
// use Catmull-Rom Spline construction: V_i=0.5*(p_(i+1)-p_(i+1))
if ((vi.size() == 2) && (t_.size() != 2))
{
v_.push_back(vi[0]);
for (std::vector<double>::size_type i = 1; i < (t_.size() - 1); i++)
{
v_.push_back(0.5 * (((p_[i] - p_[i - 1]) * (t_[i + 1] - t_[i])) /
((t_[i] - t_[i - 1]) * (t_[i + 1] - t_[i - 1])) +
((p_[i + 1] - p_[i]) * (t_[i] - t_[i - 1])) /
((t_[i + 1] - t_[i]) * (t_[i + 1] - t_[i - 1]))));
}
v_.push_back(vi[1]);
}
else
{
v_ = vi;
}
return true;
}
bool Spline::initDerivativeCatmullRom()
{
if (t_.size() > 2)
{
double vFront = v_.front();
double vBack = v_.back();
v_.clear();
v_.push_back(vFront);
for (std::vector<double>::size_type i = 1; i < (t_.size() - 1); i++)
{
v_.push_back(0.5 * (((p_[i] - p_[i - 1]) * (t_[i + 1] - t_[i])) /
((t_[i] - t_[i - 1]) * (t_[i + 1] - t_[i - 1])) +
((p_[i + 1] - p_[i]) * (t_[i] - t_[i - 1])) /
((t_[i + 1] - t_[i]) * (t_[i + 1] - t_[i - 1]))));
}
v_.push_back(vBack);
return true;
}
return false;
}
bool Spline::initDerivativezero()
{
if (t_.size() > 2)
{
double vFront = v_.front();
double vBack = v_.back();
v_.clear();
v_.push_back(vFront);
for (std::vector<double>::size_type i = 1; i < (t_.size() - 1); i++)
{
v_.push_back(0.0);
}
v_.push_back(vBack);
return true;
}
return false;
}
bool Spline::initDerivatives(std::vector<double> vi)
{
if (vi.size() == t_.size())
{
v_ = vi;
return true;
}
return false;
}
bool Spline::addNode(double ti, double pi, double vi)
{
if ((t_.back()) < ti)
{
t_.push_back(ti);
p_.push_back(pi);
v_.push_back(vi);
return true;
}
else
{
return false;
}
}
double Spline::evalSpline(double te) const
{
if (te <= t_.front())
{
return p_.front();
}
if (te >= t_.back())
{
return p_.back();
}
// deal with more than two knot
std::vector<double>::const_iterator up;
up = std::upper_bound(t_.begin(), t_.end(), te);
std::vector<double>::size_type noSpline = up - t_.begin() - 1;
double tn = (te - t_[noSpline]) /
(t_[noSpline + 1] - t_[noSpline]); // normalized time
double h1 = 2 * tn * tn * tn - 3 * tn * tn + 1; // calculate basis function 1
double h2 = -2 * tn * tn * tn + 3 * tn * tn; // calculate basis function 2
double h3 = tn * tn * tn - 2 * tn * tn + tn; // calculate basis function 3
double h4 = tn * tn * tn - tn * tn; // calculate basis function 4
return h1 * p_[noSpline] + // multiply and sum all functions
h2 * p_[noSpline + 1] + // together to build the interpolated
h3 * v_[noSpline] *
(t_[noSpline + 1] - t_[noSpline]) + // point along the curve.
h4 * v_[noSpline + 1] * (t_[noSpline + 1] - t_[noSpline]);
}
bool Spline::evalVectorSpline(std::vector<double> t,
std::vector<double>& output) const
{
output.clear();
for (std::vector<double>::size_type i = 0; i < t.size(); i++)
{
output.push_back(evalSpline(t[i]));
}
return true;
}
std::vector<double> Spline::evalVectorSpline(std::vector<double> t) const
{
std::vector<double> output;
for (std::vector<double>::size_type i = 0; i < t.size(); i++)
{
output.push_back(evalSpline(t[i]));
}
return output;
}
<|endoftext|>
|
<commit_before>
#include "Globals.h"
#include "ChunkDef.h"
// It appears that failing to have this definition causes link errors as cChunkDef::Height is not
// defined. It also appears that we can have the initalizer in the declaration so it can be inlined
// if the declaration is in a class????
const int cChunkDef::Height;
<commit_msg>Fixed MSVC builds.<commit_after><|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2010 - 2014, Göteborg Bit Factory.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <utf8.h>
#include <Path.h>
#include <Directory.h>
#include <File.h>
#include <text.h>
#include <util.h>
#include <taskd.h>
#include <Database.h>
////////////////////////////////////////////////////////////////////////////////
Database::Database (Config* config)
: _config (config)
, _log (NULL)
{
}
////////////////////////////////////////////////////////////////////////////////
Database::~Database ()
{
}
////////////////////////////////////////////////////////////////////////////////
void Database::setLog (Log* l)
{
_log = l;
}
////////////////////////////////////////////////////////////////////////////////
// Authentication is when the org/user/key data exists/matches that on the
// server, in the absence of org/user account suspension.
//
// If authentication fails, fills in response code and status.
// Note: information regarding valid/invalid org/user is not revealed.
bool Database::authenticate (
const Msg& request,
Msg& response)
{
std::string org = request.get ("org");
std::string user = request.get ("user");
std::string key = request.get ("key");
// Verify existence of <root>/orgs/<org>
Directory org_dir (_config->get ("root") + "/orgs/" + org);
if (! org_dir.exists ())
{
if (_log)
_log->format ("INFO Auth failure: org '%s' unknown",
org.c_str ());
response.set ("code", 430);
response.set ("status", taskd_error (430));
return false;
}
// Verify non-existence of <root>/orgs/<org>/suspended
File org_suspended (_config->get ("root") + "/orgs/" + org + "/suspended");
if (org_suspended.exists ())
{
if (_log)
_log->format ("INFO Auth failure: org '%s' suspended",
org.c_str ());
response.set ("code", 431);
response.set ("status", taskd_error (431));
return false;
}
// Verify existence of <root>/orgs/<org>/users/<key>
Directory user_dir (_config->get ("root") + "/orgs/" + org + "/users/" + key);
if (! user_dir.exists ())
{
if (_log)
_log->format ("INFO Auth failure: org '%s' user '%s' unknown",
org.c_str (),
user.c_str ());
response.set ("code", 430);
response.set ("status", taskd_error (430));
return false;
}
// Verify non-existence of <root>/orgs/<org>/users/<key>/suspended
File user_suspended (_config->get ("root") + "/orgs/" + org + "/users/" + key + "/suspended");
if (user_suspended.exists ())
{
if (_log)
_log->format ("INFO Auth failure: org '%s' user '%s' suspended",
org.c_str (),
user.c_str ());
response.set ("code", 431);
response.set ("status", taskd_error (431));
return false;
}
// Match <user> against <root>/orgs/<org>/users/<key>/rc:<user>
Config user_rc (_config->get ("root") + "/orgs/" + org + "/users/" + key + "/config");
if (user_rc.get ("user") != user)
{
if (_log)
_log->format ("INFO Auth failure: org '%s' user '%s' bad key",
org.c_str (),
user.c_str ());
response.set ("code", 430);
response.set ("status", taskd_error (430));
return false;
}
// All checks succeed, user is authenticated.
return true;
}
////////////////////////////////////////////////////////////////////////////////
// if <root>/orgs/<org>/redirect exists, read it and send contents as a 301.
bool Database::redirect (const std::string& org, Msg& response)
{
File redirect (_config->get ("root"));
redirect += "orgs";
redirect += org;
redirect += "redirect";
if (redirect.exists ())
{
std::string server;
redirect.read (server);
response.set ("code", 301);
response.set ("info", trim (server, " \n"));
if (_log)
_log->format ("INFO Redirecting org '%s' to '%s'",
org.c_str (),
response.get ("info").c_str ());
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool Database::add_org (const std::string& org)
{
Directory new_org (_config->get ("root"));
new_org += "orgs";
new_org += org;
Directory groups (new_org);
groups += "groups";
Directory users (new_org);
users += "users";
return new_org.create (0700) &&
groups.create (0700) &&
users.create (0700);
}
////////////////////////////////////////////////////////////////////////////////
bool Database::add_group (
const std::string& org,
const std::string& group)
{
Directory new_group (_config->get ("root"));
new_group += "orgs";
new_group += org;
new_group += "groups";
new_group += group;
return new_group.create (0700);
}
////////////////////////////////////////////////////////////////////////////////
bool Database::add_user (
const std::string& org,
const std::string& user)
{
// Generate new KEY
std::string key = key_generate ();
Directory new_user (_config->get ("root"));
new_user += "orgs";
new_user += org;
new_user += "users";
new_user += key;
if (new_user.create (0700))
{
// Store USER in <new_user>/config
File conf_file (new_user._data + "/config");
conf_file.create (0600);
Config conf (conf_file._data);
conf.set ("user", user);
conf.save ();
// User will need this key.
std::cout << "New user key: " << key << "\n";
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool Database::remove_org (const std::string& org)
{
Directory org_dir (_config->get ("root"));
org_dir += "orgs";
org_dir += org;
// TODO Remove users?
// TODO Remove groups?
// TODO Revoke user group membership.
return org_dir.remove ();
}
////////////////////////////////////////////////////////////////////////////////
bool Database::remove_group (
const std::string& org,
const std::string& group)
{
Directory group_dir (_config->get ("root"));
group_dir += "orgs";
group_dir += org;
group_dir += "groups";
group_dir += group;
// TODO Revoke user group membership.
return group_dir.remove ();
}
////////////////////////////////////////////////////////////////////////////////
bool Database::remove_user (
const std::string& org,
const std::string& key)
{
Directory user_dir (_config->get ("root"));
user_dir += "orgs";
user_dir += org;
user_dir += "users";
user_dir += key;
// TODO Revoke group memberships.
return user_dir.remove ();
}
////////////////////////////////////////////////////////////////////////////////
bool Database::suspend (const Directory& node)
{
File semaphore (node._data + "/suspended");
return semaphore.create (0600);
}
////////////////////////////////////////////////////////////////////////////////
bool Database::resume (const Directory& node)
{
File semaphore (node._data + "/suspended");
return semaphore.remove ();
}
////////////////////////////////////////////////////////////////////////////////
std::string Database::key_generate ()
{
return uuid ();
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Ensure that the username is non-empty<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2010 - 2014, Göteborg Bit Factory.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <utf8.h>
#include <Path.h>
#include <Directory.h>
#include <File.h>
#include <text.h>
#include <util.h>
#include <taskd.h>
#include <Database.h>
////////////////////////////////////////////////////////////////////////////////
Database::Database (Config* config)
: _config (config)
, _log (NULL)
{
}
////////////////////////////////////////////////////////////////////////////////
Database::~Database ()
{
}
////////////////////////////////////////////////////////////////////////////////
void Database::setLog (Log* l)
{
_log = l;
}
////////////////////////////////////////////////////////////////////////////////
// Authentication is when the org/user/key data exists/matches that on the
// server, in the absence of org/user account suspension.
//
// If authentication fails, fills in response code and status.
// Note: information regarding valid/invalid org/user is not revealed.
bool Database::authenticate (
const Msg& request,
Msg& response)
{
std::string org = request.get ("org");
std::string user = request.get ("user");
std::string key = request.get ("key");
// Verify existence of <root>/orgs/<org>
Directory org_dir (_config->get ("root") + "/orgs/" + org);
if (! org_dir.exists ())
{
if (_log)
_log->format ("INFO Auth failure: org '%s' unknown",
org.c_str ());
response.set ("code", 430);
response.set ("status", taskd_error (430));
return false;
}
// Verify non-existence of <root>/orgs/<org>/suspended
File org_suspended (_config->get ("root") + "/orgs/" + org + "/suspended");
if (org_suspended.exists ())
{
if (_log)
_log->format ("INFO Auth failure: org '%s' suspended",
org.c_str ());
response.set ("code", 431);
response.set ("status", taskd_error (431));
return false;
}
// Verify existence of <root>/orgs/<org>/users/<key>
Directory user_dir (_config->get ("root") + "/orgs/" + org + "/users/" + key);
if (! user_dir.exists ())
{
if (_log)
_log->format ("INFO Auth failure: org '%s' user '%s' unknown",
org.c_str (),
user.c_str ());
response.set ("code", 430);
response.set ("status", taskd_error (430));
return false;
}
// Verify non-existence of <root>/orgs/<org>/users/<key>/suspended
File user_suspended (_config->get ("root") + "/orgs/" + org + "/users/" + key + "/suspended");
if (user_suspended.exists ())
{
if (_log)
_log->format ("INFO Auth failure: org '%s' user '%s' suspended",
org.c_str (),
user.c_str ());
response.set ("code", 431);
response.set ("status", taskd_error (431));
return false;
}
// Match <user> against <root>/orgs/<org>/users/<key>/rc:<user>
Config user_rc (_config->get ("root") + "/orgs/" + org + "/users/" + key + "/config");
if (!user.empty () && user_rc.get ("user") != user)
{
if (_log)
_log->format ("INFO Auth failure: org '%s' user '%s' bad key",
org.c_str (),
user.c_str ());
response.set ("code", 430);
response.set ("status", taskd_error (430));
return false;
}
// All checks succeed, user is authenticated.
return true;
}
////////////////////////////////////////////////////////////////////////////////
// if <root>/orgs/<org>/redirect exists, read it and send contents as a 301.
bool Database::redirect (const std::string& org, Msg& response)
{
File redirect (_config->get ("root"));
redirect += "orgs";
redirect += org;
redirect += "redirect";
if (redirect.exists ())
{
std::string server;
redirect.read (server);
response.set ("code", 301);
response.set ("info", trim (server, " \n"));
if (_log)
_log->format ("INFO Redirecting org '%s' to '%s'",
org.c_str (),
response.get ("info").c_str ());
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool Database::add_org (const std::string& org)
{
Directory new_org (_config->get ("root"));
new_org += "orgs";
new_org += org;
Directory groups (new_org);
groups += "groups";
Directory users (new_org);
users += "users";
return new_org.create (0700) &&
groups.create (0700) &&
users.create (0700);
}
////////////////////////////////////////////////////////////////////////////////
bool Database::add_group (
const std::string& org,
const std::string& group)
{
Directory new_group (_config->get ("root"));
new_group += "orgs";
new_group += org;
new_group += "groups";
new_group += group;
return new_group.create (0700);
}
////////////////////////////////////////////////////////////////////////////////
bool Database::add_user (
const std::string& org,
const std::string& user)
{
// Generate new KEY
std::string key = key_generate ();
Directory new_user (_config->get ("root"));
new_user += "orgs";
new_user += org;
new_user += "users";
new_user += key;
if (new_user.create (0700))
{
// Store USER in <new_user>/config
File conf_file (new_user._data + "/config");
conf_file.create (0600);
Config conf (conf_file._data);
conf.set ("user", user);
conf.save ();
// User will need this key.
std::cout << "New user key: " << key << "\n";
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
bool Database::remove_org (const std::string& org)
{
Directory org_dir (_config->get ("root"));
org_dir += "orgs";
org_dir += org;
// TODO Remove users?
// TODO Remove groups?
// TODO Revoke user group membership.
return org_dir.remove ();
}
////////////////////////////////////////////////////////////////////////////////
bool Database::remove_group (
const std::string& org,
const std::string& group)
{
Directory group_dir (_config->get ("root"));
group_dir += "orgs";
group_dir += org;
group_dir += "groups";
group_dir += group;
// TODO Revoke user group membership.
return group_dir.remove ();
}
////////////////////////////////////////////////////////////////////////////////
bool Database::remove_user (
const std::string& org,
const std::string& key)
{
Directory user_dir (_config->get ("root"));
user_dir += "orgs";
user_dir += org;
user_dir += "users";
user_dir += key;
// TODO Revoke group memberships.
return user_dir.remove ();
}
////////////////////////////////////////////////////////////////////////////////
bool Database::suspend (const Directory& node)
{
File semaphore (node._data + "/suspended");
return semaphore.create (0600);
}
////////////////////////////////////////////////////////////////////////////////
bool Database::resume (const Directory& node)
{
File semaphore (node._data + "/suspended");
return semaphore.remove ();
}
////////////////////////////////////////////////////////////////////////////////
std::string Database::key_generate ()
{
return uuid ();
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>#include <signal.h> // for signal, SIGINT
#include <thread>
#include <string>
#include <cstring>
#include <sys/stat.h>
#include <armadillo>
#include <zmq.h>
#include "zmq_packet.h"
#include <basedir.h>
#include <basedir_fs.h>
#include "lconf.h"
#include "util.h"
#include "artifact_filter.h"
bool s_interrupted = false;
std::vector <void *> g_socks;
static void s_signal_handler(int)
{
s_interrupted = true;
}
static void s_catch_signals(void)
{
struct sigaction action;
action.sa_handler = s_signal_handler;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
sigaction(SIGINT, &action, NULL);
sigaction(SIGQUIT, &action, NULL);
sigaction(SIGTERM, &action, NULL);
}
static void die(void *ctx, int status)
{
s_interrupted = true;
for (auto &sock : g_socks) {
zmq_close(sock);
}
zmq_ctx_destroy(ctx);
exit(status);
}
void trainer(void *ctx, size_t batch_size, ArtifactFilterDirect &af)
{
// for data
void *socket = zmq_socket(ctx, ZMQ_SUB);
zmq_connect(socket, "inproc://data");
zmq_setsockopt(socket, ZMQ_SUBSCRIBE, "", 0);
// for control input
void *controller = zmq_socket(ctx, ZMQ_SUB);
zmq_connect(controller, "inproc://controller");
zmq_setsockopt(controller, ZMQ_SUBSCRIBE, "", 0);
zmq_pollitem_t items [] = {
{ socket, 0, ZMQ_POLLIN, 0 },
{ controller, 0, ZMQ_POLLIN, 0}
};
mat X(af.order(), batch_size);
size_t idx = 0;
while (true) {
zmq_poll(items, 2, -1); // -1 means block
if (items[0].revents & ZMQ_POLLIN) {
zmq_msg_t header;
zmq_msg_init(&header);
zmq_msg_recv(&header, socket, 0);
zmq_neural_header *p = (zmq_neural_header *)zmq_msg_data(&header);
u64 nc = p->nc;
u64 ns = p->ns;
zmq_msg_t body;
zmq_msg_init(&body);
zmq_msg_recv(&body, socket, 0);
float *f = (float *)zmq_msg_data(&body);
if (idx+ns >= batch_size) {
X.resize(nc, idx+ns+1);
}
for (size_t i=0; i<nc; i++) {
for (size_t k=0; k<ns; k++) {
X(i, idx+k) = f[i*ns+k];
}
}
idx += ns;
if (idx >= batch_size) {
debug("af2: training on batch");
af.train(X);
X.set_size(nc, batch_size);
idx = 0;
}
zmq_msg_close(&header);
zmq_msg_close(&body);
}
if (items[1].revents & ZMQ_POLLIN) {
//controller.recv(&buf);
break;
}
}
}
void filter(void *ctx, std::string zout, ArtifactFilterDirect &af)
{
// for data in
void *socket_in = zmq_socket(ctx, ZMQ_SUB);
zmq_connect(socket_in, "inproc://data");
zmq_setsockopt(socket_in, ZMQ_SUBSCRIBE, "", 0);
// for data out
void *socket_out = zmq_socket(ctx, ZMQ_PUB);
zmq_connect(socket_out, zout.c_str());
// for control input
void *controller = zmq_socket(ctx, ZMQ_SUB);
zmq_connect(controller, "inproc://controller");
zmq_setsockopt(controller, ZMQ_SUBSCRIBE, "", 0);
zmq_pollitem_t items [] = {
{ socket_in, 0, ZMQ_POLLIN, 0 },
{ controller, 0, ZMQ_POLLIN, 0 }
};
while (true) {
zmq_poll(items, 2, -1); // -1 means block
if (items[0].revents & ZMQ_POLLIN) {
zmq_msg_t header;
zmq_msg_init(&header);
zmq_msg_recv(&header, socket_in, 0);
size_t nh = zmq_msg_size(&header);
zmq_neural_header *p = (zmq_neural_header *)zmq_msg_data(&header);
u64 nc = p->nc;
u64 ns = p->ns;
zmq_msg_t body;
zmq_msg_init(&body);
zmq_msg_recv(&body, socket_in, 0);
size_t nb = zmq_msg_size(&body);
float *f = (float *)zmq_msg_data(&body);
mat X(nc, ns);
for (size_t i=0; i<nc; i++) {
for (size_t j=0; j<ns; j++) {
X(i, j) = f[i*ns+j];
}
}
mat Y = af.filter(X);
for (size_t i=0; i<nc; i++) {
for (size_t j=0; j<ns; j++) {
f[i*ns+j] -= Y(i, j);
}
}
zmq_send(socket_out, p, nh, ZMQ_SNDMORE);
zmq_send(socket_out, f, nb, 0);
zmq_msg_close(&header);
zmq_msg_close(&body);
}
if (items[1].revents & ZMQ_POLLIN) {
//controller.recv(&buf);
break;
}
}
}
int main(int argc, char *argv[])
{
// af2 [batch_size_samps] [zmq_sub] [zmq_pub]
if (argc < 4) {
printf("\naf2 - artifact filter v2 (direct computation / batch update)\n");
printf("usage: af2 [batch_size_samps] [zmq_sub] [zmq_pub]\n\n");
return 1;
}
size_t batch_size = atoi(argv[1]);
std::string zin = argv[2];
std::string zout = argv[3];
debug("Batch Size: %zu samples", batch_size);
debug("ZMQ SUB: %s", zin.c_str());
debug("ZMQ PUB: %s", zout.c_str());
s_catch_signals();
xdgHandle xdg;
xdgInitHandle(&xdg);
char *confpath = xdgConfigFind("spk/spk.rc", &xdg);
char *tmp = confpath;
// confpath is "string1\0string2\0string3\0\0"
luaConf conf;
while (*tmp) {
conf.loadConf(tmp);
tmp += strlen(tmp) + 1;
}
if (confpath)
free(confpath);
xdgWipeHandle(&xdg);
std::string zq = "ipc:///tmp/query.zmq";
conf.getString("spk.query_socket", zq);
void *zcontext = zmq_ctx_new();
if (zcontext == NULL) {
error("zmq: could not create context");
return 1;
}
// we don't need 1024 sockets
if (zmq_ctx_set(zcontext, ZMQ_MAX_SOCKETS, 64) != 0) {
error("zmq: could not set max sockets");
die(zcontext, 1);
}
void *query_sock = zmq_socket(zcontext, ZMQ_REQ);
if (query_sock == NULL) {
error("zmq: could not create socket");
die(zcontext, 1);
}
g_socks.push_back(query_sock);
if (zmq_connect(query_sock, zq.c_str()) != 0) {
error("zmq: could not connect to socket");
die(zcontext, 1);
}
u64 nnc; // num neural channels
zmq_send(query_sock, "NNC", 3, 0);
if (zmq_recv(query_sock, &nnc, sizeof(u64), 0) == -1) {
error("zmq: could not recv from query sock");
die(zcontext, 1);
}
ArtifactFilterDirect af(nnc);
struct stat buf;
if (stat("af2.h5", &buf) == 0) { // ie file exists
printf("loading af2 weights\n");
af.loadWeights("af2.h5");
}
std::thread t1(trainer, zcontext, batch_size, std::ref(af));
std::thread t2(filter, zcontext, zout, std::ref(af));
// here is what will do:
// subscribe to messages from po8e
// publish them to the training thread (inproc)
// publish them to the filter thread (also inproc)
// the filter thread then publishes the result
// the controller socket handles killing threads
void *controller = zmq_socket(zcontext, ZMQ_PUB);
if (controller == NULL) {
error("zmq: could not create socket");
zmq_ctx_destroy(zcontext);
return 1;
}
if (zmq_bind(controller, "inproc://controller") != 0) {
error("zmq: could not bind to socket");
zmq_close(controller);
zmq_ctx_destroy(zcontext);
return 1;
}
// this socket subscribes to messages sent from the po8e
void *subscriber = zmq_socket(zcontext, ZMQ_XSUB);
if (subscriber == NULL) {
error("zmq: could not create socket");
die(zcontext, 1);
}
g_socks.push_back(subscriber);
if (zmq_connect(subscriber, zin.c_str()) != 0) {
error("zmq: could not connect to socket");
die(zcontext, 1);
}
// this socket publishes received message to local threads
void *publisher = zmq_socket(zcontext, ZMQ_XPUB);
if (publisher == NULL) {
error("zmq: could not create socket");
die(zcontext, 1);
}
g_socks.push_back(publisher);
if (zmq_bind(publisher, "inproc://data") != 0) {
error("zmq: could not bind to socket");
die(zcontext, 1);
}
// this hooks up the subscriber to the publisher
while (!s_interrupted) {
zmq_proxy(subscriber, publisher, NULL);
}
zmq_send(controller, "KILL", 4, 0);
t1.join();
t2.join();
af.saveWeights("af2.h5");
printf("\nsaving weights\n");
die(zcontext, 0);
}
<commit_msg>bugfix: was connect, needed bind<commit_after>#include <signal.h> // for signal, SIGINT
#include <thread>
#include <string>
#include <cstring>
#include <sys/stat.h>
#include <armadillo>
#include <zmq.h>
#include "zmq_packet.h"
#include <basedir.h>
#include <basedir_fs.h>
#include "lconf.h"
#include "util.h"
#include "artifact_filter.h"
bool s_interrupted = false;
std::vector <void *> g_socks;
static void s_signal_handler(int)
{
s_interrupted = true;
}
static void s_catch_signals(void)
{
struct sigaction action;
action.sa_handler = s_signal_handler;
action.sa_flags = 0;
sigemptyset(&action.sa_mask);
sigaction(SIGINT, &action, NULL);
sigaction(SIGQUIT, &action, NULL);
sigaction(SIGTERM, &action, NULL);
}
static void die(void *ctx, int status)
{
s_interrupted = true;
for (auto &sock : g_socks) {
zmq_close(sock);
}
zmq_ctx_destroy(ctx);
exit(status);
}
void trainer(void *ctx, size_t batch_size, ArtifactFilterDirect &af)
{
// for data
void *socket = zmq_socket(ctx, ZMQ_SUB);
g_socks.push_back(socket);
zmq_connect(socket, "inproc://data");
zmq_setsockopt(socket, ZMQ_SUBSCRIBE, "", 0);
// for control input
void *controller = zmq_socket(ctx, ZMQ_SUB);
g_socks.push_back(controller);
zmq_connect(controller, "inproc://controller");
zmq_setsockopt(controller, ZMQ_SUBSCRIBE, "", 0);
zmq_pollitem_t items [] = {
{ socket, 0, ZMQ_POLLIN, 0 },
{ controller, 0, ZMQ_POLLIN, 0}
};
mat X(af.order(), batch_size);
size_t idx = 0;
while (true) {
zmq_poll(items, 2, -1); // -1 means block
if (items[0].revents & ZMQ_POLLIN) {
zmq_msg_t header;
zmq_msg_init(&header);
zmq_msg_recv(&header, socket, 0);
zmq_neural_header *p = (zmq_neural_header *)zmq_msg_data(&header);
u64 nc = p->nc;
u64 ns = p->ns;
zmq_msg_t body;
zmq_msg_init(&body);
zmq_msg_recv(&body, socket, 0);
float *f = (float *)zmq_msg_data(&body);
if (idx+ns >= batch_size) {
X.resize(nc, idx+ns+1);
}
for (size_t i=0; i<nc; i++) {
for (size_t k=0; k<ns; k++) {
X(i, idx+k) = f[i*ns+k];
}
}
idx += ns;
if (idx >= batch_size) {
debug("af2: training on batch");
af.train(X);
X.set_size(nc, batch_size);
idx = 0;
}
zmq_msg_close(&header);
zmq_msg_close(&body);
}
if (items[1].revents & ZMQ_POLLIN) {
break;
}
}
}
void filter(void *ctx, std::string zout, ArtifactFilterDirect &af)
{
// for data in
void *socket_in = zmq_socket(ctx, ZMQ_SUB);
g_socks.push_back(socket_in);
zmq_connect(socket_in, "inproc://data");
zmq_setsockopt(socket_in, ZMQ_SUBSCRIBE, "", 0);
// for data out
void *socket_out = zmq_socket(ctx, ZMQ_PUB);
g_socks.push_back(socket_out);
zmq_bind(socket_out, zout.c_str());
// for control input
void *controller = zmq_socket(ctx, ZMQ_SUB);
g_socks.push_back(controller);
zmq_connect(controller, "inproc://controller");
zmq_setsockopt(controller, ZMQ_SUBSCRIBE, "", 0);
zmq_pollitem_t items [] = {
{ socket_in, 0, ZMQ_POLLIN, 0 },
{ controller, 0, ZMQ_POLLIN, 0 }
};
while (true) {
zmq_poll(items, 2, -1); // -1 means block
if (items[0].revents & ZMQ_POLLIN) {
zmq_msg_t header;
zmq_msg_init(&header);
zmq_msg_recv(&header, socket_in, 0);
size_t nh = zmq_msg_size(&header);
zmq_neural_header *p = (zmq_neural_header *)zmq_msg_data(&header);
u64 nc = p->nc;
u64 ns = p->ns;
zmq_msg_t body;
zmq_msg_init(&body);
zmq_msg_recv(&body, socket_in, 0);
size_t nb = zmq_msg_size(&body);
float *f = (float *)zmq_msg_data(&body);
mat X(nc, ns);
for (size_t i=0; i<nc; i++) {
for (size_t j=0; j<ns; j++) {
X(i, j) = f[i*ns+j];
}
}
mat Y = af.filter(X);
for (size_t i=0; i<nc; i++) {
for (size_t j=0; j<ns; j++) {
f[i*ns+j] -= Y(i, j);
}
}
zmq_send(socket_out, p, nh, ZMQ_SNDMORE);
zmq_send(socket_out, f, nb, 0);
zmq_msg_close(&header);
zmq_msg_close(&body);
}
if (items[1].revents & ZMQ_POLLIN) {
break;
}
}
}
int main(int argc, char *argv[])
{
// af2 [batch_size_samps] [zmq_sub] [zmq_pub]
if (argc < 4) {
printf("\naf2 - artifact filter v2 (direct computation / batch update)\n");
printf("usage: af2 [batch_size_samps] [zmq_sub] [zmq_pub]\n\n");
return 1;
}
size_t batch_size = atoi(argv[1]);
std::string zin = argv[2];
std::string zout = argv[3];
debug("Batch Size: %zu samples", batch_size);
debug("ZMQ SUB: %s", zin.c_str());
debug("ZMQ PUB: %s", zout.c_str());
s_catch_signals();
xdgHandle xdg;
xdgInitHandle(&xdg);
char *confpath = xdgConfigFind("spk/spk.rc", &xdg);
char *tmp = confpath;
// confpath is "string1\0string2\0string3\0\0"
luaConf conf;
while (*tmp) {
conf.loadConf(tmp);
tmp += strlen(tmp) + 1;
}
if (confpath)
free(confpath);
xdgWipeHandle(&xdg);
std::string zq = "ipc:///tmp/query.zmq";
conf.getString("spk.query_socket", zq);
void *zcontext = zmq_ctx_new();
if (zcontext == NULL) {
error("zmq: could not create context");
return 1;
}
// we don't need 1024 sockets
if (zmq_ctx_set(zcontext, ZMQ_MAX_SOCKETS, 64) != 0) {
error("zmq: could not set max sockets");
die(zcontext, 1);
}
void *query_sock = zmq_socket(zcontext, ZMQ_REQ);
if (query_sock == NULL) {
error("zmq: could not create socket");
die(zcontext, 1);
}
g_socks.push_back(query_sock);
if (zmq_connect(query_sock, zq.c_str()) != 0) {
error("zmq: could not connect to socket");
die(zcontext, 1);
}
u64 nnc; // num neural channels
zmq_send(query_sock, "NNC", 3, 0);
if (zmq_recv(query_sock, &nnc, sizeof(u64), 0) == -1) {
error("zmq: could not recv from query sock");
die(zcontext, 1);
}
ArtifactFilterDirect af(nnc);
struct stat buf;
if (stat("af2.h5", &buf) == 0) { // ie file exists
printf("loading af2 weights\n");
af.loadWeights("af2.h5");
}
std::thread t1(trainer, zcontext, batch_size, std::ref(af));
std::thread t2(filter, zcontext, zout, std::ref(af));
// here is what will do:
// subscribe to messages from po8e
// publish them to the training thread (inproc)
// publish them to the filter thread (also inproc)
// the filter thread then publishes the result
// the controller socket handles killing threads
void *controller = zmq_socket(zcontext, ZMQ_PUB);
if (controller == NULL) {
error("zmq: could not create socket");
die(zcontext, 1);
}
g_socks.push_back(controller);
if (zmq_bind(controller, "inproc://controller") != 0) {
error("zmq: could not bind to socket");
die(zcontext, 1);
}
// this socket subscribes to messages sent from the po8e
void *subscriber = zmq_socket(zcontext, ZMQ_XSUB);
if (subscriber == NULL) {
error("zmq: could not create socket");
die(zcontext, 1);
}
g_socks.push_back(subscriber);
if (zmq_connect(subscriber, zin.c_str()) != 0) {
error("zmq: could not connect to socket");
die(zcontext, 1);
}
// this socket publishes received message to local threads
void *publisher = zmq_socket(zcontext, ZMQ_XPUB);
if (publisher == NULL) {
error("zmq: could not create socket");
die(zcontext, 1);
}
g_socks.push_back(publisher);
if (zmq_bind(publisher, "inproc://data") != 0) {
error("zmq: could not bind to socket");
die(zcontext, 1);
}
// this hooks up the subscriber to the publisher
while (!s_interrupted) {
zmq_proxy(subscriber, publisher, NULL);
}
zmq_send(controller, "KILL", 4, 0);
t1.join();
t2.join();
af.saveWeights("af2.h5");
printf("\nsaving weights\n");
die(zcontext, 0);
}
<|endoftext|>
|
<commit_before>#include <cassert>
#include "FE_Field.h"
// ---------------------------------------------------------------------------
cigma::FE_Field::FE_Field()
{
dim = 0;
rank = 0;
fe = 0;
meshPart = 0;
dofHandler = 0;
}
cigma::FE_Field::~FE_Field()
{
}
// ---------------------------------------------------------------------------
void cigma::FE_Field::get_cell_dofs(int cellIndex, double *cellDofs)
{
assert(fe != 0);
assert(dofHandler != 0);
assert(meshPart != 0);
assert(0 <= cellIndex);
assert(cellIndex < (meshPart->nel));
const int ndofs = fe->cell->n_nodes();
const int valdim = n_rank();
int *n = &(meshPart->connect[ndofs * cellIndex]);
for (int i = 0; i < ndofs; i++)
{
for (int j = 0; j < valdim; j++)
{
cellDofs[valdim * i + j] = dofHandler->dofs[valdim * n[i] + j];
}
}
}
// ---------------------------------------------------------------------------
void cigma::FE_Field::eval(double *point, double *value)
{
assert(fe != 0);
assert(meshPart != 0);
// get reference cell object from fe
Cell *cell = fe->cell;
assert(cell != 0);
// find the cell which contains given point
int e;
bool found_cell = false;
found_cell = meshPart->find_cell(point, &e);
assert(found_cell);
// use dofs as weights on the shape function values
const int ndofs = cell->n_nodes();
int valdim = n_rank();
//double globalCellCoords[cell_nno * cell_nsd];
//meshPart->get_cell_coords(e, globalCellCoords);
//cell->interpolate(globalCellCoords, point, value, valdim);
double field_dofs[ndofs * valdim];
get_cell_dofs(e, field_dofs);
double uvw[3];
cell->xyz2uvw(point,uvw);
cell->interpolate(field_dofs, uvw, value, valdim);
}
void cigma::FE_Field::tabulate_element(int e, double *values)
{
assert(fe != 0);
assert(meshPart != 0);
Cell *cell = fe->cell;
assert(cell != 0);
// quadrature
QuadraturePoints *quadrature = fe->quadrature;
assert(quadrature != 0);
int nq = quadrature->n_points();
double *qpts = quadrature->qpts;
//double *qwts = quadrature->qwts;
// get shape function values at known quadrature points
//cell->shape(nq, qpts, fe->basis_tab);
// get shape function derivatives at known quadrature points
//cell->grad_shape(nq, qpts, fe->basis_jet);
// XXX: move this step out of tabulate()
// evaluate jacobian at known quadrature points and calculate jxw
//fe->update_jxw();
// tabulate the function values
int i,j;
const int valdim = n_rank();
const int ndofs = cell->n_nodes();
double dofs[ndofs * valdim];
get_cell_dofs(e, dofs);
for (int q = 0; q < nq; q++)
{
double *N = &(fe->basis_tab[ndofs*q]);
for (i = 0; i < valdim; i++)
{
double sum = 0.0;
for (j = 0; j < ndofs; j++)
{
sum += dofs[i + valdim*j] * N[j];
}
values[valdim*q + i] = sum;
}
}
}
// ---------------------------------------------------------------------------
<commit_msg>Removed commented out code from FE_Field::tabulate_element() * Parts were moved to FE::set_quadrature() * Parts were moved to FE::update_jxw()<commit_after>#include <cassert>
#include "FE_Field.h"
// ---------------------------------------------------------------------------
cigma::FE_Field::FE_Field()
{
dim = 0;
rank = 0;
fe = 0;
meshPart = 0;
dofHandler = 0;
}
cigma::FE_Field::~FE_Field()
{
}
// ---------------------------------------------------------------------------
void cigma::FE_Field::get_cell_dofs(int cellIndex, double *cellDofs)
{
assert(fe != 0);
assert(dofHandler != 0);
assert(meshPart != 0);
assert(0 <= cellIndex);
assert(cellIndex < (meshPart->nel));
const int ndofs = fe->cell->n_nodes();
const int valdim = n_rank();
int *n = &(meshPart->connect[ndofs * cellIndex]);
for (int i = 0; i < ndofs; i++)
{
for (int j = 0; j < valdim; j++)
{
cellDofs[valdim * i + j] = dofHandler->dofs[valdim * n[i] + j];
}
}
}
// ---------------------------------------------------------------------------
void cigma::FE_Field::eval(double *point, double *value)
{
assert(fe != 0);
assert(meshPart != 0);
// get reference cell object from fe
Cell *cell = fe->cell;
assert(cell != 0);
// find the cell which contains given point
int e;
bool found_cell = false;
found_cell = meshPart->find_cell(point, &e);
assert(found_cell);
// use dofs as weights on the shape function values
const int ndofs = cell->n_nodes();
int valdim = n_rank();
//double globalCellCoords[cell_nno * cell_nsd];
//meshPart->get_cell_coords(e, globalCellCoords);
//cell->interpolate(globalCellCoords, point, value, valdim);
double field_dofs[ndofs * valdim];
get_cell_dofs(e, field_dofs);
double uvw[3];
cell->xyz2uvw(point,uvw);
cell->interpolate(field_dofs, uvw, value, valdim);
}
void cigma::FE_Field::tabulate_element(int e, double *values)
{
assert(fe != 0);
assert(meshPart != 0);
Cell *cell = fe->cell;
assert(cell != 0);
QuadraturePoints *quadrature = fe->quadrature;
assert(quadrature != 0);
int nq = quadrature->n_points();
double *qpts = quadrature->qpts;
// tabulate the function values
int i,j;
const int valdim = n_rank();
const int ndofs = cell->n_nodes();
double dofs[ndofs * valdim]; // XXX
get_cell_dofs(e, dofs);
for (int q = 0; q < nq; q++)
{
double *N = &(fe->basis_tab[ndofs*q]);
for (i = 0; i < valdim; i++)
{
double sum = 0.0;
for (j = 0; j < ndofs; j++)
{
sum += dofs[i + valdim*j] * N[j];
}
values[valdim*q + i] = sum;
}
}
}
// ---------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/**
* This file is part of Slideshow.
* Copyright (C) 2008-2010 David Sveningsson <[email protected]>
*
* Slideshow 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.
*
* Slideshow 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 Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "Exceptions.h"
#include "Graphics.h"
#include "Kernel.h"
#include "OS.h"
#include "Log.h"
#include "Transition.h"
#include "path.h"
#include "gl.h"
#include <cstdlib>
#include <memory>
#include <portable/string.h>
/* hack to get opengl functions, does not seem to be used in header even when
* built with opengl support. */
#define ILUT_USE_OPENGL
#include <IL/il.h>
#include <IL/ilu.h>
#include <IL/ilut.h>
Graphics::Graphics(int width, int height, bool fullscreen):
_transition(NULL),
_width(width),
_height(height){
for ( unsigned int i = 0; i < 2; i++ ){
_texture[i] = 0;
}
Log::message(Log::Verbose, "Graphics: Using resoultion %dx%d\n", width, height);
imageloader_init();
gl_setup();
gl_set_matrices();
gl_init_textures();
}
Graphics::~Graphics(){
gl_cleanup_textures();
imageloader_cleanup();
if ( _transition && _transition->cleanup ){
_transition->cleanup();
}
free(_transition);
}
void Graphics::imageloader_init(){
ilInit();
ILuint devilError = ilGetError();
if (devilError != IL_NO_ERROR) {
throw exception("Devil Error (ilInit: %s)", iluErrorString(devilError));
}
iluInit();
ilutRenderer(ILUT_OPENGL);
}
void Graphics::imageloader_cleanup(){
}
void Graphics::gl_setup(){
glShadeModel( GL_FLAT );
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );
glClearColor(0, 0, 0, 1);
glColor4f(1, 1, 1, 1);
glDisable( GL_DEPTH_TEST );
glDisable( GL_LIGHTING );
glDisable(GL_ALPHA_TEST);
glEnable( GL_TEXTURE_2D );
glEnable(GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClear( GL_COLOR_BUFFER_BIT );
}
void Graphics::gl_set_matrices(){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 1, 0, 1, -1.0, 1.0);
glScalef(1, -1, 1);
glTranslated(0, -1, 0);
glEnable(GL_CULL_FACE);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void Graphics::gl_init_textures(){
glGenTextures(2, _texture);
for ( unsigned int i = 0; i < 2; i++ ){
glBindTexture(GL_TEXTURE_2D, _texture[i]);
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_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
}
void Graphics::gl_cleanup_textures(){
glDeleteTextures(2, _texture);
}
void Graphics::render(float state){
transition_context_t context;
context.texture[0] = _texture[0];
context.texture[1] = _texture[1];
context.state = state;
if ( _transition ){
_transition->render(&context);
}
}
#ifdef WIN32
/* convert to LPCTSTR, release memory with free */
static TCHAR* to_tchar(const char* src){
size_t len = 0;
TCHAR* buf = NULL;
if ( mbstowcs_s(&len, NULL, 0, src, _TRUNCATE) != 0 ){
return NULL;
}
buf = (TCHAR*)malloc(sizeof(TCHAR) * (len+1));
if ( mbstowcs_s(&len, buf, len+1, src, _TRUNCATE) != 0 ){
return NULL;
}
return buf;
}
/* convert from LPCTSTR, release memory with free */
static char* from_tchar(const TCHAR* src){
size_t len = 0;
char* buf = NULL;
if ( wcstombs_s(&len, NULL, 0, src, _TRUNCATE) != 0 ){
return NULL;
}
buf = (char*)malloc(sizeof(char) * (len+1));
if ( wcstombs_s(&len, buf, len+1, src, _TRUNCATE) != 0 ){
return NULL;
}
return buf;
}
#endif /* WIN32 */
void Graphics::load_image(const char* name){
swap_textures();
glBindTexture(GL_TEXTURE_2D, _texture[0]);
if ( name ){
#ifdef UNICODE
char* tmp = real_path(name);
std::auto_ptr<wchar_t> path(to_tchar(tmp));
free(tmp);
#else /* UNICODE */
std::auto_ptr<char> path(real_path(name));
#endif /* UNICODE */
ILuint devilID;
ilGenImages(1, &devilID);
ilBindImage(devilID);
ilLoadImage(path.get());
ILuint devilError = ilGetError();
if( devilError != IL_NO_ERROR ){
#ifdef UNICODE
const wchar_t* asdf = iluErrorString (devilError);
const char* error = from_tchar(asdf);
#else /* UNICODE */
const char* error = iluErrorString (devilError);
#endif /* UNICODE */
throw exception("Failed to load image '%s' (ilLoadImage: %s)", path.get(), error);
}
ilutGLTexImage(0);
} else {
static const unsigned char black[] = {
0, 0, 0
};
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, black);
}
}
void Graphics::swap_textures(){
unsigned int tmp = _texture[0];
_texture[0] = _texture[1];
_texture[1] = tmp;
}
void Graphics::set_transition(transition_module_t* module){
if ( _transition && _transition->cleanup ){
_transition->cleanup();
}
_transition = module;
if ( _transition && _transition->init ){
_transition->init();
}
}
<commit_msg>loading texture manually since ilut rescales to a POT texture, but I want a NPOT. NPOT texture support is a requirement for slideshow.<commit_after>/**
* This file is part of Slideshow.
* Copyright (C) 2008-2010 David Sveningsson <[email protected]>
*
* Slideshow 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.
*
* Slideshow 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 Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "Exceptions.h"
#include "Graphics.h"
#include "Kernel.h"
#include "OS.h"
#include "Log.h"
#include "Transition.h"
#include "path.h"
#include "gl.h"
#include <cstdlib>
#include <memory>
#include <portable/string.h>
/* hack to get opengl functions, does not seem to be used in header even when
* built with opengl support. */
#define ILUT_USE_OPENGL
#include <IL/il.h>
#include <IL/ilu.h>
#include <IL/ilut.h>
Graphics::Graphics(int width, int height, bool fullscreen):
_transition(NULL),
_width(width),
_height(height){
for ( unsigned int i = 0; i < 2; i++ ){
_texture[i] = 0;
}
Log::message(Log::Verbose, "Graphics: Using resoultion %dx%d\n", width, height);
imageloader_init();
gl_setup();
gl_set_matrices();
gl_init_textures();
}
Graphics::~Graphics(){
gl_cleanup_textures();
imageloader_cleanup();
if ( _transition && _transition->cleanup ){
_transition->cleanup();
}
free(_transition);
}
void Graphics::imageloader_init(){
ilInit();
ILuint devilError = ilGetError();
if (devilError != IL_NO_ERROR) {
throw exception("Devil Error (ilInit: %s)", iluErrorString(devilError));
}
iluInit();
ilutRenderer(ILUT_OPENGL);
}
void Graphics::imageloader_cleanup(){
}
void Graphics::gl_setup(){
glShadeModel( GL_FLAT );
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );
glClearColor(0, 0, 0, 1);
glColor4f(1, 1, 1, 1);
glDisable( GL_DEPTH_TEST );
glDisable( GL_LIGHTING );
glDisable(GL_ALPHA_TEST);
glEnable( GL_TEXTURE_2D );
glEnable(GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClear( GL_COLOR_BUFFER_BIT );
}
void Graphics::gl_set_matrices(){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 1, 0, 1, -1.0, 1.0);
glScalef(1, -1, 1);
glTranslated(0, -1, 0);
glEnable(GL_CULL_FACE);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void Graphics::gl_init_textures(){
glGenTextures(2, _texture);
for ( unsigned int i = 0; i < 2; i++ ){
glBindTexture(GL_TEXTURE_2D, _texture[i]);
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_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
}
void Graphics::gl_cleanup_textures(){
glDeleteTextures(2, _texture);
}
void Graphics::render(float state){
transition_context_t context;
context.texture[0] = _texture[0];
context.texture[1] = _texture[1];
context.state = state;
if ( _transition ){
_transition->render(&context);
}
}
#ifdef WIN32
/* convert to LPCTSTR, release memory with free */
static TCHAR* to_tchar(const char* src){
size_t len = 0;
TCHAR* buf = NULL;
if ( mbstowcs_s(&len, NULL, 0, src, _TRUNCATE) != 0 ){
return NULL;
}
buf = (TCHAR*)malloc(sizeof(TCHAR) * (len+1));
if ( mbstowcs_s(&len, buf, len+1, src, _TRUNCATE) != 0 ){
return NULL;
}
return buf;
}
/* convert from LPCTSTR, release memory with free */
static char* from_tchar(const TCHAR* src){
size_t len = 0;
char* buf = NULL;
if ( wcstombs_s(&len, NULL, 0, src, _TRUNCATE) != 0 ){
return NULL;
}
buf = (char*)malloc(sizeof(char) * (len+1));
if ( wcstombs_s(&len, buf, len+1, src, _TRUNCATE) != 0 ){
return NULL;
}
return buf;
}
#endif /* WIN32 */
void Graphics::load_image(const char* name){
swap_textures();
glBindTexture(GL_TEXTURE_2D, _texture[0]);
if ( name ){
#ifdef UNICODE
char* tmp = real_path(name);
std::auto_ptr<wchar_t> path(to_tchar(tmp));
free(tmp);
#else /* UNICODE */
std::auto_ptr<char> path(real_path(name));
#endif /* UNICODE */
ILuint devilID;
ilGenImages(1, &devilID);
ilBindImage(devilID);
ilLoadImage(path.get());
ILuint devilError = ilGetError();
if( devilError != IL_NO_ERROR ){
#ifdef UNICODE
const wchar_t* asdf = iluErrorString (devilError);
const char* error = from_tchar(asdf);
#else /* UNICODE */
const char* error = iluErrorString (devilError);
#endif /* UNICODE */
throw exception("Failed to load image '%s' (ilLoadImage: %s)", path.get(), error);
}
ILubyte* pixels = ilGetData();
int width = ilGetInteger(IL_IMAGE_WIDTH);
int height = ilGetInteger(IL_IMAGE_HEIGHT);
int format = ilGetInteger(IL_IMAGE_FORMAT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, format, GL_UNSIGNED_BYTE, pixels);
} else {
static const unsigned char black[] = {
0, 0, 0
};
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, black);
}
}
void Graphics::swap_textures(){
unsigned int tmp = _texture[0];
_texture[0] = _texture[1];
_texture[1] = tmp;
}
void Graphics::set_transition(transition_module_t* module){
if ( _transition && _transition->cleanup ){
_transition->cleanup();
}
_transition = module;
if ( _transition && _transition->init ){
_transition->init();
}
}
<|endoftext|>
|
<commit_before>#ifndef AST_HPP
#define AST_HPP
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <memory>
#include <numeric>
#include <typeinfo>
#include <rapidxml.hpp>
#include "error.hpp"
#include "token.hpp"
#include "util.hpp"
#include "operator.hpp"
typedef std::set<std::string> TypeList;
class ASTNode: public std::enable_shared_from_this<ASTNode> {
public:
typedef std::shared_ptr<ASTNode> Link;
typedef std::weak_ptr<ASTNode> WeakLink;
typedef std::vector<Link> Children;
protected:
WeakLink parent = WeakLink();
Children children {};
uint64 lineNumber = 0;
static void printIndent(uint level) {
for (uint i = 0; i < level; i++) print(" ");
}
public:
ASTNode(uint64 lineNumber = 0): lineNumber(lineNumber) {}
virtual ~ASTNode() {};
virtual void addChild(Link child) {
child->setParent(shared_from_this());
children.push_back(child);
}
Children getChildren() const {
return children;
}
Link at(int64 pos) const {
if (pos < 0) {
pos = children.size() + pos; // Negative indices count from the end of the vector
}
if (abs(pos) > children.size() || pos < 0) {
throw InternalError("Index out of array bounds", {METADATA_PAIRS, {"index", std::to_string(pos)}});
}
return children[pos];
}
void setParent(WeakLink newParent) {parent = newParent;}
WeakLink getParent() const {return parent;}
void inline setLineNumber(uint64 newLineNumber) {
lineNumber = newLineNumber;
}
uint64 inline getLineNumber() const {
return lineNumber;
}
virtual void printTree(uint level) const {
printIndent(level);
println("Base ASTNode");
for (auto& child : children) child->printTree(level + 1);
}
virtual bool operator==(const ASTNode& rhs) const {
if (typeid(*this) != typeid(rhs)) return false;
if (children.size() != rhs.getChildren().size()) return false;
for (uint64 i = 0; i < children.size(); i++) {
if (*(this->at(i)) != *(rhs.at(i))) return false;
}
return true;
}
virtual bool operator!=(const ASTNode& rhs) const {
return !operator==(rhs);
}
};
#define GET_SET_FOR(childIndex, nameOf, linkType) \
void set##nameOf(Node<linkType>::Link newNode) {children[childIndex] = newNode;}\
Node<linkType>::Link get##nameOf() const {\
return Node<linkType>::dynPtrCast(children[childIndex]);\
}
#define PRETTY_PRINT_FOR(childIndex, name) \
{\
printIndent(level + 1);\
println(#name":");\
children[childIndex]->printTree(level + 1);\
}
class NoMoreChildrenNode: public ASTNode {
public:
NoMoreChildrenNode(int childrenCount) {
children.resize(childrenCount, nullptr);
}
void addChild(Link child) {
UNUSED(child);
throw InternalError("Cannot add children to NoMoreChildrenNode", {METADATA_PAIRS});
}
bool inline notNull(uint childIndex) const {
return children[childIndex] != nullptr;
}
};
template<typename T, typename std::enable_if<std::is_base_of<ASTNode, T>::value>::type* = nullptr>
struct Node: public PtrUtil<T> {
typedef typename PtrUtil<T>::Link Link;
typedef typename PtrUtil<T>::WeakLink WeakLink;
static inline bool isSameType(ASTNode::Link node) {
return typeid(T) == typeid(*node);
}
static inline Link dynPtrCast(ASTNode::Link node) {
return std::dynamic_pointer_cast<T>(node);
}
};
class BlockNode: public ASTNode {
public:
void printTree(uint level) const {
printIndent(level);
println("Block Node");
for (auto& child : children) child->printTree(level + 1);
}
bool operator==(const ASTNode& rhs) const {
return ASTNode::operator==(rhs);
}
bool operator!=(const ASTNode& rhs) const {
return !operator==(rhs);
}
};
class ExpressionNode: public ASTNode {
private:
Token tok = Token(UNPROCESSED, 0);
public:
ExpressionNode() {}
ExpressionNode(Token token): tok(token) {
switch (tok.type) {
case IDENTIFIER:
case OPERATOR:
case L_INTEGER:
case L_FLOAT:
case L_STRING:
case L_BOOLEAN:
break;
default: throw InternalError("Trying to add unsupported token to ExpressionNode", {METADATA_PAIRS, {"token", token.toString()}});
}
}
std::shared_ptr<ExpressionNode> at(int64 pos) {
return std::dynamic_pointer_cast<ExpressionNode>(ASTNode::at(pos));
}
Token getToken() const {
return tok;
}
void printTree(uint level) const {
printIndent(level);
println("Expression Node:", tok);
for (auto& child : children) child->printTree(level + 1);
}
bool operator==(const ASTNode& rhs) const {
if (!ASTNode::operator==(rhs)) return false;
if (this->tok != dynamic_cast<const ExpressionNode&>(rhs).tok) return false;
return true;
}
bool operator!=(const ASTNode& rhs) const {
return !operator==(rhs);
}
};
class DeclarationNode: public ASTNode {
private:
std::string identifier;
TypeList typeList;
bool dynamic;
public:
DeclarationNode(std::string identifier, TypeList typeList):
identifier(identifier), typeList(typeList), dynamic(false) {}
DeclarationNode(std::string identifier):
identifier(identifier), typeList({}), dynamic(true) {}
std::string getIdentifier() const {
return identifier;
}
TypeList getTypeList() const {
return typeList;
}
bool isDynamic() const {
return dynamic;
}
bool hasInit() const {
return children.size() == 1;
}
Node<ExpressionNode>::Link getInit() const {
return Node<ExpressionNode>::dynPtrCast(children[0]);
}
void addChild(Link child) {
if (children.size() >= 1) throw InternalError("Trying to add more than one child to a DeclarationNode", {METADATA_PAIRS});
if (!Node<ExpressionNode>::dynPtrCast(child)) throw InternalError("DeclarationNode only supports ExpressionNode as its child", {METADATA_PAIRS});
ASTNode::addChild(child);
}
void printTree(uint level) const {
printIndent(level);
std::string collatedTypes = "";
if (dynamic) collatedTypes = "[dynamic]";
if (!dynamic && typeList.size() == 0) throw InternalError("No types in typed declaration", {METADATA_PAIRS});
if (typeList.size() == 1) {
collatedTypes = *typeList.begin();
}
if (typeList.size() >= 2) {
collatedTypes = std::accumulate(++typeList.begin(), typeList.end(), *typeList.begin(),
[](const std::string& prev, const std::string& current) {
return prev + ", " + current;
});
}
println("Declaration Node: " + identifier + " (valid types: " + collatedTypes + ")");
if (children.size() > 0) children[0]->printTree(level + 1);
}
bool operator==(const ASTNode& rhs) const {
if (!ASTNode::operator==(rhs)) return false;
auto decl = dynamic_cast<const DeclarationNode&>(rhs);
if (this->identifier != decl.identifier) return false;
if (this->typeList != decl.typeList) return false;
if (this->dynamic != decl.dynamic) return false;
return true;
}
bool operator!=(const ASTNode& rhs) const {
return !operator==(rhs);
}
};
class BranchNode: public NoMoreChildrenNode {
public:
BranchNode(): NoMoreChildrenNode(3) {}
GET_SET_FOR(0, Condition, ExpressionNode)
GET_SET_FOR(1, SuccessBlock, BlockNode)
GET_SET_FOR(2, FailiureBlock, ASTNode)
bool operator==(const ASTNode& rhs) const {
return ASTNode::operator==(rhs);
}
bool operator!=(const ASTNode& rhs) const {
return !operator==(rhs);
}
void printTree(uint level) const {
printIndent(level);
println("Branch Node:");
PRETTY_PRINT_FOR(0, Condition)
PRETTY_PRINT_FOR(1, Success)
if (notNull(2)) PRETTY_PRINT_FOR(2, Failiure)
}
};
class LoopNode: public NoMoreChildrenNode {
public:
LoopNode(): NoMoreChildrenNode(4) {}
GET_SET_FOR(0, Init, DeclarationNode)
GET_SET_FOR(1, Condition, ExpressionNode)
GET_SET_FOR(2, Update, ExpressionNode)
GET_SET_FOR(3, Code, BlockNode)
void printTree(uint level) const {
printIndent(level);
println("Loop Node");
if (notNull(0)) PRETTY_PRINT_FOR(0, Init)
if (notNull(1)) PRETTY_PRINT_FOR(1, Condition)
if (notNull(2)) PRETTY_PRINT_FOR(2, Update)
if (notNull(3)) PRETTY_PRINT_FOR(3, Code)
}
bool operator==(const ASTNode& rhs) const {
return ASTNode::operator==(rhs);
}
bool operator!=(const ASTNode& rhs) const {
return !operator==(rhs);
}
};
class AST {
private:
BlockNode root = BlockNode();
public:
bool operator==(const AST& rhs) const {
if (this->root != rhs.root) return false;
return true;
}
bool operator!=(const AST& rhs) const {
return !operator==(rhs);
}
void print() const {
root.printTree(0);
}
void setRoot(BlockNode rootNode) {
root = rootNode;
}
BlockNode getRoot() const {
return root;
}
Node<BlockNode>::Link getRootAsLink() const {
return Node<BlockNode>::make(root);
}
};
#undef PRETTY_PRINT_FOR
#undef GET_SET_FOR
#endif
<commit_msg>Made types in setters explicit<commit_after>#ifndef AST_HPP
#define AST_HPP
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <memory>
#include <numeric>
#include <typeinfo>
#include <rapidxml.hpp>
#include "error.hpp"
#include "token.hpp"
#include "util.hpp"
#include "operator.hpp"
typedef std::set<std::string> TypeList;
class ASTNode: public std::enable_shared_from_this<ASTNode> {
public:
typedef std::shared_ptr<ASTNode> Link;
typedef std::weak_ptr<ASTNode> WeakLink;
typedef std::vector<Link> Children;
protected:
WeakLink parent = WeakLink();
Children children {};
uint64 lineNumber = 0;
static void printIndent(uint level) {
for (uint i = 0; i < level; i++) print(" ");
}
public:
ASTNode(uint64 lineNumber = 0): lineNumber(lineNumber) {}
virtual ~ASTNode() {};
virtual void addChild(Link child) {
child->setParent(shared_from_this());
children.push_back(child);
}
Children getChildren() const {
return children;
}
Link at(int64 pos) const {
if (pos < 0) {
pos = children.size() + pos; // Negative indices count from the end of the vector
}
if (abs(pos) > children.size() || pos < 0) {
throw InternalError("Index out of array bounds", {METADATA_PAIRS, {"index", std::to_string(pos)}});
}
return children[pos];
}
void setParent(WeakLink newParent) {parent = newParent;}
WeakLink getParent() const {return parent;}
void inline setLineNumber(uint64 newLineNumber) {
lineNumber = newLineNumber;
}
uint64 inline getLineNumber() const {
return lineNumber;
}
virtual void printTree(uint level) const {
printIndent(level);
println("Base ASTNode");
for (auto& child : children) child->printTree(level + 1);
}
virtual bool operator==(const ASTNode& rhs) const {
if (typeid(*this) != typeid(rhs)) return false;
if (children.size() != rhs.getChildren().size()) return false;
for (uint64 i = 0; i < children.size(); i++) {
if (*(this->at(i)) != *(rhs.at(i))) return false;
}
return true;
}
virtual bool operator!=(const ASTNode& rhs) const {
return !operator==(rhs);
}
};
#define GET_FOR(childIndex, nameOf, linkType) \
Node<linkType>::Link get##nameOf() const {\
return Node<linkType>::dynPtrCast(children[childIndex]);\
}
#define SET_FOR(childIndex, nameOf, linkType) \
void set##nameOf(std::shared_ptr<linkType> newNode) {children[childIndex] = newNode;}
#define GET_SET_FOR(childIndex, nameOf, linkType) \
GET_FOR(childIndex, nameOf, linkType) \
SET_FOR(childIndex, nameOf, linkType)
#define PRETTY_PRINT_FOR(childIndex, name) \
{\
printIndent(level + 1);\
println(#name":");\
children[childIndex]->printTree(level + 1);\
}
class NoMoreChildrenNode: public ASTNode {
public:
NoMoreChildrenNode(int childrenCount) {
children.resize(childrenCount, nullptr);
}
void addChild(Link child) {
UNUSED(child);
throw InternalError("Cannot add children to NoMoreChildrenNode", {METADATA_PAIRS});
}
bool inline notNull(uint childIndex) const {
return children[childIndex] != nullptr;
}
};
template<typename T, typename std::enable_if<std::is_base_of<ASTNode, T>::value>::type* = nullptr>
struct Node: public PtrUtil<T> {
typedef typename PtrUtil<T>::Link Link;
typedef typename PtrUtil<T>::WeakLink WeakLink;
static inline bool isSameType(ASTNode::Link node) {
return typeid(T) == typeid(*node);
}
static inline Link dynPtrCast(ASTNode::Link node) {
return std::dynamic_pointer_cast<T>(node);
}
};
class BlockNode: public ASTNode {
public:
void printTree(uint level) const {
printIndent(level);
println("Block Node");
for (auto& child : children) child->printTree(level + 1);
}
bool operator==(const ASTNode& rhs) const {
return ASTNode::operator==(rhs);
}
bool operator!=(const ASTNode& rhs) const {
return !operator==(rhs);
}
};
class ExpressionNode: public ASTNode {
private:
Token tok = Token(UNPROCESSED, 0);
public:
ExpressionNode() {}
ExpressionNode(Token token): tok(token) {
switch (tok.type) {
case IDENTIFIER:
case OPERATOR:
case L_INTEGER:
case L_FLOAT:
case L_STRING:
case L_BOOLEAN:
break;
default: throw InternalError("Trying to add unsupported token to ExpressionNode", {METADATA_PAIRS, {"token", token.toString()}});
}
}
std::shared_ptr<ExpressionNode> at(int64 pos) {
return std::dynamic_pointer_cast<ExpressionNode>(ASTNode::at(pos));
}
Token getToken() const {
return tok;
}
void printTree(uint level) const {
printIndent(level);
println("Expression Node:", tok);
for (auto& child : children) child->printTree(level + 1);
}
bool operator==(const ASTNode& rhs) const {
if (!ASTNode::operator==(rhs)) return false;
if (this->tok != dynamic_cast<const ExpressionNode&>(rhs).tok) return false;
return true;
}
bool operator!=(const ASTNode& rhs) const {
return !operator==(rhs);
}
};
class DeclarationNode: public ASTNode {
private:
std::string identifier;
TypeList typeList;
bool dynamic;
public:
DeclarationNode(std::string identifier, TypeList typeList):
identifier(identifier), typeList(typeList), dynamic(false) {}
DeclarationNode(std::string identifier):
identifier(identifier), typeList({}), dynamic(true) {}
std::string getIdentifier() const {
return identifier;
}
TypeList getTypeList() const {
return typeList;
}
bool isDynamic() const {
return dynamic;
}
bool hasInit() const {
return children.size() == 1;
}
Node<ExpressionNode>::Link getInit() const {
return Node<ExpressionNode>::dynPtrCast(children[0]);
}
void addChild(Link child) {
if (children.size() >= 1) throw InternalError("Trying to add more than one child to a DeclarationNode", {METADATA_PAIRS});
if (!Node<ExpressionNode>::dynPtrCast(child)) throw InternalError("DeclarationNode only supports ExpressionNode as its child", {METADATA_PAIRS});
ASTNode::addChild(child);
}
void printTree(uint level) const {
printIndent(level);
std::string collatedTypes = "";
if (dynamic) collatedTypes = "[dynamic]";
if (!dynamic && typeList.size() == 0) throw InternalError("No types in typed declaration", {METADATA_PAIRS});
if (typeList.size() == 1) {
collatedTypes = *typeList.begin();
}
if (typeList.size() >= 2) {
collatedTypes = std::accumulate(++typeList.begin(), typeList.end(), *typeList.begin(),
[](const std::string& prev, const std::string& current) {
return prev + ", " + current;
});
}
println("Declaration Node: " + identifier + " (valid types: " + collatedTypes + ")");
if (children.size() > 0) children[0]->printTree(level + 1);
}
bool operator==(const ASTNode& rhs) const {
if (!ASTNode::operator==(rhs)) return false;
auto decl = dynamic_cast<const DeclarationNode&>(rhs);
if (this->identifier != decl.identifier) return false;
if (this->typeList != decl.typeList) return false;
if (this->dynamic != decl.dynamic) return false;
return true;
}
bool operator!=(const ASTNode& rhs) const {
return !operator==(rhs);
}
};
class BranchNode: public NoMoreChildrenNode {
public:
BranchNode(): NoMoreChildrenNode(3) {}
GET_SET_FOR(0, Condition, ExpressionNode)
GET_SET_FOR(1, SuccessBlock, BlockNode)
GET_FOR(2, FailiureBlock, ASTNode)
SET_FOR(2, FailiureBlock, BlockNode)
SET_FOR(2, FailiureBlock, BranchNode)
bool operator==(const ASTNode& rhs) const {
return ASTNode::operator==(rhs);
}
bool operator!=(const ASTNode& rhs) const {
return !operator==(rhs);
}
void printTree(uint level) const {
printIndent(level);
println("Branch Node:");
PRETTY_PRINT_FOR(0, Condition)
PRETTY_PRINT_FOR(1, Success)
if (notNull(2)) PRETTY_PRINT_FOR(2, Failiure)
}
};
class LoopNode: public NoMoreChildrenNode {
public:
LoopNode(): NoMoreChildrenNode(4) {}
GET_SET_FOR(0, Init, DeclarationNode)
GET_SET_FOR(1, Condition, ExpressionNode)
GET_SET_FOR(2, Update, ExpressionNode)
GET_SET_FOR(3, Code, BlockNode)
void printTree(uint level) const {
printIndent(level);
println("Loop Node");
if (notNull(0)) PRETTY_PRINT_FOR(0, Init)
if (notNull(1)) PRETTY_PRINT_FOR(1, Condition)
if (notNull(2)) PRETTY_PRINT_FOR(2, Update)
if (notNull(3)) PRETTY_PRINT_FOR(3, Code)
}
bool operator==(const ASTNode& rhs) const {
return ASTNode::operator==(rhs);
}
bool operator!=(const ASTNode& rhs) const {
return !operator==(rhs);
}
};
class AST {
private:
BlockNode root = BlockNode();
public:
bool operator==(const AST& rhs) const {
if (this->root != rhs.root) return false;
return true;
}
bool operator!=(const AST& rhs) const {
return !operator==(rhs);
}
void print() const {
root.printTree(0);
}
void setRoot(BlockNode rootNode) {
root = rootNode;
}
BlockNode getRoot() const {
return root;
}
Node<BlockNode>::Link getRootAsLink() const {
return Node<BlockNode>::make(root);
}
};
#undef PRETTY_PRINT_FOR
#undef GET_FOR
#undef SET_FOR
#undef GET_SET_FOR
#endif
<|endoftext|>
|
<commit_before>#include <cstring>
#include "alloc.h"
#include "cons.h"
namespace mclisp
{
const ConsCell* kT = nullptr;
const ConsCell* kNil = nullptr;
//static constexpr char* kPname = "PNAME";
static ConsCell* MakeAssociationList(const std::string& name)
{
// TODO
ConsCell* c = Alloc::Allocate();
return c;
}
const ConsCell* MakeCons(const ConsCell* car, const ConsCell* cdr)
{
ConsCell* c = Alloc::Allocate();
c->car_ = const_cast<ConsCell*>(car);
c->cdr_ = const_cast<ConsCell*>(cdr);
return c;
}
const ConsCell* MakeSymbol(const std::string& name)
{
ConsCell* c = Alloc::Allocate();
c->car_ = const_cast<ConsCell*>(Alloc::AtomMagic());
c->cdr_ = MakeAssociationList(name);
return c;
}
const std::string SymbolName(const ConsCell* symbol)
{
// TODO
return "NIL";
}
} // namespace mclisp
<commit_msg>Implement MakeAssociationList and MakePnameList.<commit_after>#include <cassert>
#include <cstddef>
#include <cstring>
#include "alloc.h"
#include "cons.h"
namespace
{
using namespace mclisp;
const std::string kPname = "PNAME";
void SetCons(ConsCell** c, const char* s)
{
strncpy(reinterpret_cast<char *>(c), s, sizeof c);
}
std::string Slurp(ConsCell** c, const std::string& s)
{
SetCons(c, s.c_str());
return s.length() > sizeof c ? s.substr(sizeof c, std::string::npos) : "";
}
ConsCell* MakePnameList(const std::string& name)
{
ConsCell *head, *prev, *curr, *data;
std::string rest(name);
for (head = prev = curr = Alloc::Allocate();
rest.length() > 0;
curr = Alloc::Allocate())
{
data = Alloc::Allocate();
rest = Slurp(&data->car_, rest);
rest = Slurp(&data->cdr_, rest);
prev->cdr_ = curr;
curr->car_ = data;
prev = curr;
}
curr->cdr_ = const_cast<ConsCell*>(kNil);
return head;
}
ConsCell* MakeAssociationList(const std::string& name)
{
ConsCell* pname = Alloc::Allocate();
ConsCell* link = Alloc::Allocate();
SetCons(&pname->car_, kPname.c_str());
pname->cdr_ = link;
link->car_ = MakePnameList(name);
link->cdr_ = const_cast<ConsCell*>(kNil);
return pname;
}
} // namespace
namespace mclisp
{
const ConsCell* kT = nullptr;
const ConsCell* kNil = nullptr;
const ConsCell* MakeCons(const ConsCell* car, const ConsCell* cdr)
{
ConsCell* c = Alloc::Allocate();
c->car_ = const_cast<ConsCell*>(car);
c->cdr_ = const_cast<ConsCell*>(cdr);
return c;
}
const ConsCell* MakeSymbol(const std::string& name)
{
assert(name.length());
ConsCell* c = Alloc::Allocate();
c->car_ = const_cast<ConsCell*>(Alloc::AtomMagic());
c->cdr_ = MakeAssociationList(name);
return c;
}
const std::string SymbolName(const ConsCell* symbol)
{
// TODO
return "NIL";
}
} // namespace mclisp
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2014 Steven Hickson
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Labeling.h"
using namespace std;
using namespace pcl;
using namespace cv;
inline void MakeCloudDense(PointCloud<PointXYZRGBA> &cloud) {
PointCloud<PointXYZRGBA>::iterator p = cloud.begin();
cloud.is_dense = true;
for(int j = 0; j < cloud.height; j++) {
for(int i = 0; i < cloud.width; i++) {
if(_isnan(p->z)) {
p->x = float(((float)i - KINECT_CX_D) * KINECT_FX_D);
p->y = float(((float)j - KINECT_CY_D) * KINECT_FY_D);
p->z = 0;
}
//p->a = 255;
++p;
}
}
}
inline void MakeCloudDense(PointCloud<PointNormal>::Ptr &cloud) {
PointCloud<PointNormal>::iterator p = cloud->begin();
cloud->is_dense = true;
for(int j = 0; j < cloud->height; j++) {
for(int i = 0; i < cloud->width; i++) {
if(_isnan(p->z)) {
p->x = float(((float)i - KINECT_CX_D) * KINECT_FX_D);
p->y = float(((float)j - KINECT_CY_D) * KINECT_FY_D);
p->z = 0;
p->normal_x = p->normal_y = p->normal_z = 0;
}
//p->a = 255;
++p;
}
}
}
class SimpleSegmentViewer
{
public:
SimpleSegmentViewer () : viewer("Original Viewer"),
label(new pcl::PointCloud<pcl::PointXYZI>), segment(new pcl::PointCloud<pcl::PointXYZRGBA>), sharedCloud(new pcl::PointCloud<pcl::PointXYZRGBA>), normals (new pcl::PointCloud<pcl::PointNormal>), update(false) { c = new Classifier(""); };
void cloud_cb_ (const boost::shared_ptr<const PointCloud<PointXYZRGBA> > &cloud)
{
if(!cloud->empty()) {
normalMutex.lock();
double begin = pcl::getTime();
copyPointCloud(*cloud,*sharedCloud);
EstimateNormals(sharedCloud,normals);
MakeCloudDense(*sharedCloud);
//MakeCloudDense(normals);
stseg.AddSlice(*sharedCloud,0.5f,900,500,0.8f,900,500,label,segment);
//SegmentNormals(*sharedCloud,normals,0.5f,50,50,label,segment);
label->clear();
double end = pcl::getTime();
update = true;
normalMutex.unlock();
}
}
void cloud_cb2_ (const boost::shared_ptr<const PointCloud<PointXYZRGBA> > &cloud)
{
if(!cloud->empty()) {
normalMutex.lock();
double begin = pcl::getTime();
copyPointCloud(*cloud,*sharedCloud);
c->TestCloud(*cloud);
c->CreateAugmentedCloud(sharedCloud);
double end = pcl::getTime();
cout << "Time: " << end << endl;
update = true;
Mat tmp;
GetMatFromCloud(*sharedCloud,tmp);
imshow("Results",tmp);
waitKey(1);
normalMutex.unlock();
}
}
void run ()
{
// create a new grabber for OpenNI devices
pcl::Grabber* my_interface = new pcl::Microsoft2Grabber();
// make callback function from member function
boost::function<void (const boost::shared_ptr<const PointCloud<PointXYZRGBA> >&)> f =
boost::bind (&SimpleSegmentViewer::cloud_cb2_, this, _1);
my_interface->registerCallback (f);
//viewer.setBackgroundColor(0.0, 0.0, 0.5);
c->InitializeTesting();
my_interface->start ();
bool finished = false;
while (!viewer.wasStopped())
{
normalMutex.lock();
if(update) {
//viewer.removePointCloud("cloud");
viewer.removePointCloud("original");
viewer.addPointCloud(segment,"original");
//viewer.addPointCloudNormals<pcl::PointXYZRGBA,pcl::PointNormal>(sharedCloud, normals);
update = false;
sharedCloud->clear();
segment->clear();
//normals->clear();
}
viewer.spinOnce();
normalMutex.unlock();
}
my_interface->stop ();
}
boost::shared_ptr<PointCloud<PointXYZI> > label;
boost::shared_ptr<pcl::PointCloud<pcl::PointXYZRGBA> > segment, sharedCloud;
boost::shared_ptr<pcl::PointCloud<pcl::PointNormal> > normals;
pcl::visualization::PCLVisualizer viewer;
bool update;
boost::mutex normalMutex;
Segment3D stseg;
Classifier *c;
};
int main (int argc, char** argv) {
try {
int run = atoi(argv[2]);
if(run == 0) {
Classifier c(argv[1]);
c.build_vocab();
} else if(run == 1) {
Classifier c(argv[1]);
c.Annotate();
} else if(run == 2)
BuildDataset(string(argv[1]));
else if(run == 3)
BuildRFClassifier(string(argv[1]));
else {
SimpleSegmentViewer v;
v.run();
}
} catch (pcl::PCLException e) {
cout << e.detailedMessage() << endl;
} catch (std::exception &e) {
cout << e.what() << endl;
}
cin.get();
return 0;
}<commit_msg>removed pcl visualizer<commit_after>/*
Copyright (C) 2014 Steven Hickson
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Labeling.h"
using namespace std;
using namespace pcl;
using namespace cv;
inline void MakeCloudDense(PointCloud<PointXYZRGBA> &cloud) {
PointCloud<PointXYZRGBA>::iterator p = cloud.begin();
cloud.is_dense = true;
for(int j = 0; j < cloud.height; j++) {
for(int i = 0; i < cloud.width; i++) {
if(_isnan(p->z)) {
p->x = float(((float)i - KINECT_CX_D) * KINECT_FX_D);
p->y = float(((float)j - KINECT_CY_D) * KINECT_FY_D);
p->z = 0;
}
//p->a = 255;
++p;
}
}
}
inline void MakeCloudDense(PointCloud<PointNormal>::Ptr &cloud) {
PointCloud<PointNormal>::iterator p = cloud->begin();
cloud->is_dense = true;
for(int j = 0; j < cloud->height; j++) {
for(int i = 0; i < cloud->width; i++) {
if(_isnan(p->z)) {
p->x = float(((float)i - KINECT_CX_D) * KINECT_FX_D);
p->y = float(((float)j - KINECT_CY_D) * KINECT_FY_D);
p->z = 0;
p->normal_x = p->normal_y = p->normal_z = 0;
}
//p->a = 255;
++p;
}
}
}
class SimpleSegmentViewer
{
public:
SimpleSegmentViewer () :
label(new pcl::PointCloud<pcl::PointXYZI>), segment(new pcl::PointCloud<pcl::PointXYZRGBA>), sharedCloud(new pcl::PointCloud<pcl::PointXYZRGBA>), normals (new pcl::PointCloud<pcl::PointNormal>), update(false) { c = new Classifier(""); };
void cloud_cb_ (const boost::shared_ptr<const PointCloud<PointXYZRGBA> > &cloud)
{
if(!cloud->empty()) {
normalMutex.lock();
double begin = pcl::getTime();
copyPointCloud(*cloud,*sharedCloud);
EstimateNormals(sharedCloud,normals);
MakeCloudDense(*sharedCloud);
//MakeCloudDense(normals);
stseg.AddSlice(*sharedCloud,0.5f,900,500,0.8f,900,500,label,segment);
//SegmentNormals(*sharedCloud,normals,0.5f,50,50,label,segment);
label->clear();
double end = pcl::getTime();
update = true;
normalMutex.unlock();
}
}
void cloud_cb2_ (const boost::shared_ptr<const PointCloud<PointXYZRGBA> > &cloud)
{
if(!cloud->empty()) {
normalMutex.lock();
double begin = pcl::getTime();
copyPointCloud(*cloud,*sharedCloud);
c->TestCloud(*cloud);
c->CreateAugmentedCloud(sharedCloud);
double end = pcl::getTime();
cout << "Time: " << end << endl;
update = true;
Mat tmp;
GetMatFromCloud(*sharedCloud,tmp);
imshow("Results",tmp);
waitKey(1);
normalMutex.unlock();
}
}
void run ()
{
// create a new grabber for OpenNI devices
pcl::Grabber* my_interface = new pcl::Microsoft2Grabber();
// make callback function from member function
boost::function<void (const boost::shared_ptr<const PointCloud<PointXYZRGBA> >&)> f =
boost::bind (&SimpleSegmentViewer::cloud_cb2_, this, _1);
my_interface->registerCallback (f);
//viewer.setBackgroundColor(0.0, 0.0, 0.5);
c->InitializeTesting();
my_interface->start ();
bool finished = false;
while(1);
//while (!viewer.wasStopped())
//{
// normalMutex.lock();
// if(update) {
// //viewer.removePointCloud("cloud");
// viewer.removePointCloud("original");
// viewer.addPointCloud(segment,"original");
// //viewer.addPointCloudNormals<pcl::PointXYZRGBA,pcl::PointNormal>(sharedCloud, normals);
// update = false;
// sharedCloud->clear();
// segment->clear();
// //normals->clear();
// }
// viewer.spinOnce();
// normalMutex.unlock();
//}
my_interface->stop ();
}
boost::shared_ptr<PointCloud<PointXYZI> > label;
boost::shared_ptr<pcl::PointCloud<pcl::PointXYZRGBA> > segment, sharedCloud;
boost::shared_ptr<pcl::PointCloud<pcl::PointNormal> > normals;
//pcl::visualization::PCLVisualizer viewer;
bool update;
boost::mutex normalMutex;
Segment3D stseg;
Classifier *c;
};
int main (int argc, char** argv) {
try {
int run = atoi(argv[2]);
if(run == 0) {
Classifier c(argv[1]);
c.build_vocab();
} else if(run == 1) {
Classifier c(argv[1]);
c.Annotate();
} else if(run == 2)
BuildDataset(string(argv[1]));
else if(run == 3)
BuildRFClassifier(string(argv[1]));
else {
SimpleSegmentViewer v;
v.run();
}
} catch (pcl::PCLException e) {
cout << e.detailedMessage() << endl;
} catch (std::exception &e) {
cout << e.what() << endl;
}
cin.get();
return 0;
}<|endoftext|>
|
<commit_before>#include "ghost/config.h"
#include "ghost/types.h"
#include "ghost/densemat.h"
#include "ghost/util.h"
#include "ghost/dot_avx_gen.h"
#include "ghost/dot_plain_gen.h"
#include "ghost/machine.h"
#include "ghost/dot.h"
#include <map>
using namespace std;
static bool operator<(const ghost_dot_parameters_t &a, const ghost_dot_parameters_t &b)
{
return (ghost_hash(a.dt,a.blocksz,ghost_hash(a.impl,a.storage,0)) < ghost_hash(b.dt,b.blocksz,ghost_hash(b.impl,b.storage,0)));
}
static map<ghost_dot_parameters_t, ghost_dot_kernel_t> ghost_dot_kernels;
ghost_error_t ghost_dot(void *res, ghost_densemat_t *vec1, ghost_densemat_t *vec2)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH|GHOST_FUNCTYPE_COMMUNICATION);
GHOST_CALL_RETURN(ghost_localdot(res,vec1,vec2));
#ifdef GHOST_HAVE_MPI
if (vec1->context) {
GHOST_INSTR_START("reduce")
ghost_mpi_op_t sumOp;
ghost_mpi_datatype_t mpiDt;
ghost_mpi_op_sum(&sumOp,vec1->traits.datatype);
ghost_mpi_datatype(&mpiDt,vec1->traits.datatype);
int v;
if (vec1->context) {
for (v=0; v<MIN(vec1->traits.ncols,vec2->traits.ncols); v++) {
MPI_CALL_RETURN(MPI_Allreduce(MPI_IN_PLACE, (char *)res+vec1->elSize*v, 1, mpiDt, sumOp, vec1->context->mpicomm));
}
}
GHOST_INSTR_STOP("reduce")
}
#endif
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH|GHOST_FUNCTYPE_COMMUNICATION);
return GHOST_SUCCESS;
}
ghost_error_t ghost_localdot(void *res, ghost_densemat_t *vec1, ghost_densemat_t *vec2)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);
ghost_error_t ret = GHOST_SUCCESS;
if (ghost_dot_kernels.empty()) {
#include "dot_avx.def"
#include "dot_plain.def"
}
memset(res,0,vec1->traits.ncols*vec2->elSize);
ghost_dot_parameters_t p;
p.dt = vec1->traits.datatype;
p.alignment = GHOST_ALIGNED;
ghost_dot_kernel_t kernel = NULL;
#ifdef GHOST_HAVE_MIC
p.impl = GHOST_IMPLEMENTATION_MIC;
#elif defined(GHOST_HAVE_AVX)
p.impl = GHOST_IMPLEMENTATION_AVX;
#elif defined(GHOST_HAVE_SSE)
p.impl = GHOST_IMPLEMENTATION_SSE;
#elif defined(GHOST_HAVE_CUDA)
ghost_type type;
ghost_type_get(&type);
if (type == GHOST_TYPE_CUDA) {
p.impl = GHOST_IMPLEMENTATION_CUDA;
}
#else
p.impl = GHOST_IMPLEMENTATION_PLAIN;
#endif
if (vec1->traits.flags & GHOST_DENSEMAT_SCATTERED || vec2->traits.flags & GHOST_DENSEMAT_SCATTERED ||
p.impl == GHOST_IMPLEMENTATION_CUDA) {
PERFWARNING_LOG("Fallback to vanilla dot implementation");
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return vec1->localdot_vanilla(vec1,res,vec2);
}
p.storage = vec1->traits.storage;
p.blocksz = vec1->traits.ncols;
int al = ghost_machine_alignment();
if (IS_ALIGNED(vec1->val,al) && IS_ALIGNED(vec2->val,al) && !((vec1->stride*vec1->elSize) % al) && !((vec2->stride*vec2->elSize) % al)) {
p.alignment = GHOST_ALIGNED;
} else {
p.alignment = GHOST_UNALIGNED;
}
kernel = ghost_dot_kernels[p];
if (!kernel) {
PERFWARNING_LOG("Try unaligned version");
p.alignment = GHOST_UNALIGNED;
kernel = ghost_dot_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try plain version");
p.impl = GHOST_IMPLEMENTATION_PLAIN;
kernel = ghost_dot_kernels[p];
}
if (kernel) {
ret = kernel(res,vec1,vec2);
} else {
PERFWARNING_LOG("Calling fallback dot");
ret = vec1->localdot_vanilla(vec1,res,vec2);
}
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return ret;
}
<commit_msg>missing include<commit_after>#include "ghost/config.h"
#include "ghost/types.h"
#include "ghost/densemat.h"
#include "ghost/util.h"
#include "ghost/dot_avx_gen.h"
#include "ghost/dot_plain_gen.h"
#include "ghost/machine.h"
#include "ghost/dot.h"
#include "ghost/timing.h"
#include <map>
using namespace std;
static bool operator<(const ghost_dot_parameters_t &a, const ghost_dot_parameters_t &b)
{
return (ghost_hash(a.dt,a.blocksz,ghost_hash(a.impl,a.storage,0)) < ghost_hash(b.dt,b.blocksz,ghost_hash(b.impl,b.storage,0)));
}
static map<ghost_dot_parameters_t, ghost_dot_kernel_t> ghost_dot_kernels;
ghost_error_t ghost_dot(void *res, ghost_densemat_t *vec1, ghost_densemat_t *vec2)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH|GHOST_FUNCTYPE_COMMUNICATION);
GHOST_CALL_RETURN(ghost_localdot(res,vec1,vec2));
#ifdef GHOST_HAVE_MPI
if (vec1->context) {
GHOST_INSTR_START("reduce")
ghost_mpi_op_t sumOp;
ghost_mpi_datatype_t mpiDt;
ghost_mpi_op_sum(&sumOp,vec1->traits.datatype);
ghost_mpi_datatype(&mpiDt,vec1->traits.datatype);
int v;
if (vec1->context) {
for (v=0; v<MIN(vec1->traits.ncols,vec2->traits.ncols); v++) {
MPI_CALL_RETURN(MPI_Allreduce(MPI_IN_PLACE, (char *)res+vec1->elSize*v, 1, mpiDt, sumOp, vec1->context->mpicomm));
}
}
GHOST_INSTR_STOP("reduce")
}
#endif
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH|GHOST_FUNCTYPE_COMMUNICATION);
return GHOST_SUCCESS;
}
ghost_error_t ghost_localdot(void *res, ghost_densemat_t *vec1, ghost_densemat_t *vec2)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);
ghost_error_t ret = GHOST_SUCCESS;
if (ghost_dot_kernels.empty()) {
#include "dot_avx.def"
#include "dot_plain.def"
}
memset(res,0,vec1->traits.ncols*vec2->elSize);
ghost_dot_parameters_t p;
p.dt = vec1->traits.datatype;
p.alignment = GHOST_ALIGNED;
ghost_dot_kernel_t kernel = NULL;
#ifdef GHOST_HAVE_MIC
p.impl = GHOST_IMPLEMENTATION_MIC;
#elif defined(GHOST_HAVE_AVX)
p.impl = GHOST_IMPLEMENTATION_AVX;
#elif defined(GHOST_HAVE_SSE)
p.impl = GHOST_IMPLEMENTATION_SSE;
#elif defined(GHOST_HAVE_CUDA)
ghost_type type;
ghost_type_get(&type);
if (type == GHOST_TYPE_CUDA) {
p.impl = GHOST_IMPLEMENTATION_CUDA;
}
#else
p.impl = GHOST_IMPLEMENTATION_PLAIN;
#endif
if (vec1->traits.flags & GHOST_DENSEMAT_SCATTERED || vec2->traits.flags & GHOST_DENSEMAT_SCATTERED ||
p.impl == GHOST_IMPLEMENTATION_CUDA) {
PERFWARNING_LOG("Fallback to vanilla dot implementation");
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return vec1->localdot_vanilla(vec1,res,vec2);
}
p.storage = vec1->traits.storage;
p.blocksz = vec1->traits.ncols;
int al = ghost_machine_alignment();
if (IS_ALIGNED(vec1->val,al) && IS_ALIGNED(vec2->val,al) && !((vec1->stride*vec1->elSize) % al) && !((vec2->stride*vec2->elSize) % al)) {
p.alignment = GHOST_ALIGNED;
} else {
p.alignment = GHOST_UNALIGNED;
}
kernel = ghost_dot_kernels[p];
if (!kernel) {
PERFWARNING_LOG("Try unaligned version");
p.alignment = GHOST_UNALIGNED;
kernel = ghost_dot_kernels[p];
}
if (!kernel) {
PERFWARNING_LOG("Try plain version");
p.impl = GHOST_IMPLEMENTATION_PLAIN;
kernel = ghost_dot_kernels[p];
}
if (kernel) {
ret = kernel(res,vec1,vec2);
} else {
PERFWARNING_LOG("Calling fallback dot");
ret = vec1->localdot_vanilla(vec1,res,vec2);
}
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return ret;
}
<|endoftext|>
|
<commit_before>#include "MPEditor.h"
MPEditor::MPEditor(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID)
: BWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr)
{
AddShortcut('q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED));
AddShortcut('n', B_COMMAND_KEY, new BMessage(MENU_NEW_THT));
AddShortcut('e', B_COMMAND_KEY, new BMessage(MENU_EDT_THT));
AddShortcut('s', B_COMMAND_KEY, new BMessage(MENU_SAV_THT));
AddShortcut('r', B_COMMAND_KEY, new BMessage(MENU_PRV_THT));
AddShortcut('p', B_COMMAND_KEY, new BMessage(MENU_PUB_THT));
AddShortcut('k', B_COMMAND_KEY, new BMessage(MENU_KEY_THT));
// initialize controls
BRect r = Bounds();
r.bottom = r.bottom - 50;
editorTextView = new BTextView(r, NULL, r, B_FOLLOW_ALL, B_WILL_DRAW | B_NAVIGABLE);
backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
AddChild(backView);
// gui layout builder
backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));
backView->AddChild(BGridLayoutBuilder()
.Add(new EditorMenu(), 0, 0)
.Add(new BScrollView("scroll_editor", editorTextView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 1)
.SetInsets(0, 0, 0, 0)
);
currentideaID = ideaID; // pass current idea id selected to editor window for use
if(currentideaID != -1) // if id has a real value
{
sqlObject = new SqlObject(ideaStatement, "7");
sqlObject->PrepareSql("select ideatext from ideatable where ideaid = ?");
sqlObject->BindValue(1, currentideaID);
sqlObject->StepSql();
editorTextView->SetText(sqlObject->ReturnText(0));
sqlObject->FinalizeSql();
sqlObject->CloseSql();
}
}
void MPEditor::MessageReceived(BMessage* msg)
{
BRect r(Bounds());
//FILE *fp = NULL;
BString tmpPath;
switch(msg->what)
{
case MENU_NEW_THT: // open another untitled editor window
tmpEditor = new MPEditor(BMessage(SHOW_LAUNCHER), BMessenger(this), "MasterPiece Editor - untitled", -1);
tmpEditor->Show();
break;
case MENU_EDT_THT: // edit current idea name for editing
xPos = (r.right - r.left) / 2; // find xpos for window
yPos = (r.bottom - r.top) / 2; // find ypos for window
editIdeaName = new EditIdeaName(BMessage(UPDATE_TITLE), BMessenger(this), xPos, yPos, currentideaID);
editIdeaName->Show(); // show edit idea name window
break;
case MENU_SAV_THT: // save current idea progress
if(currentideaID == -1) // if its untitled insert new thought, then show saveidea to apply a name...
{
sqlObject = new SqlObject(ideaStatement, "8");
sqlObject->PrepareSql("insert into ideatable (ideaname, ideatext, ismp) values('untitled', ?, 0)");
sqlObject->BindValue(1, editorTextView->Text());
sqlObject->StepSql();
xPos = (r.right - r.left) / 2; // find xpos for window
yPos = (r.bottom - r.top) / 2; // find ypos for window
saveIdea = new SaveIdea(BMessage(UPDATE_TITLE), BMessenger(this), xPos, yPos, sqlObject->ReturnLastInsertRowID());
currentideaID = sqlObject->ReturnLastInsertRowID();
sqlObject->FinalizeSql();
sqlObject->CloseSql();
saveIdea->Show(); // show save window to name the untitled thought
}
else // already exists, just update ideatext and save new information
{
sqlObject = new SqlObject(ideaStatement, "9");
sqlObject->PrepareSql("update ideatable set ideatext = ? where ideaid = ?");
sqlObject->BindValue(1, editorTextView->Text());
sqlObject->BindValue(2, currentideaID);
sqlObject->StepSql();
sqlObject->FinalizeSql();
sqlObject->CloseSql();
}
break;
case MENU_PRV_THT: // preview thought in html in webpositive
// LOOK AT DOCUTILS CORE.PY FOR CALLING PYTHON COMMANDS.
// LOOK AT http://docs.python.org/faq/extending.html FOR REFERENCE TO CALLING FUNCTIONS FROM SOURCE...
// POSSIBLY PUT ALL THOUGHTS INTO A STRING. THEN CALL THE PYTHON CMD ON THEM, THEN OUTPUT THEM TO A FILE...
/*
PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *pArgs;
pName = PyString_FromString("docutils.core");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "publish_string");
if(PyCallable_Check(pFunc))
{
BString outString;
pArgs = PyTuple_New(3);
PyTuple_SetItem(pArgs, 0, PyString_FromString("*bolder*"));
PyTuple_SetItem(pArgs, 1, PyString_FromString(outString));
PyTuple_SetItem(pArgs, 2, PyString_FromString("xhtml"));
pValue = PyObject_CallObject(pFunc, pArgs);
}
else
{
PyErr_Print();
}
Py_DECREF(pModule);
Py_DECREF(pName);
//PyFinalize();
*/
/*
publish_string(source, source_path=None, destination_path=None,
reader=None, reader_name='standalone',
parser=None, parser_name='restructuredtext',
writer=None, writer_name='pseudoxml',
settings=None, settings_spec=None,
settings_overrides=None, config_section=None,
enable_exit_status=None): */
// publish_string(stringVar, destVar, writer_name='xhtml');
// runs python code and creates tmp.html. webpositive won't open it though but that's another issue
// determine current app directory and then make the string this way
//if(!(fp = fopen("./converters/rst2html.py", "r"))) printf("Error");
//PyObject* glb, loc;
//PyObject** args;
//loc = PyDict_New();
//glb = PyDict_New();
//PyDict_SetItemString(glb, "__builtins__", PyEval_GetBuiltins());
//Py_Initialize();
//PyRun_File(fp,
//PyEval_EvalCodeEx(fp, glb, loc
//PyRun_SimpleFileFlags(fp, "rst2html.py", "tmp.tht", "tmp.html");
//PyRun_SimpleString("./converters/rst2html.py tmp.tht tmp.html");
//Py_Finalize();
tmpPath = "/boot/apps/WebPositive/WebPositive file://";
tmpPath += GetAppDirPath();
tmpPath += "/tmp.html &";
system(tmpPath);
break;
case MENU_PUB_THT: // publish thought by opening publish window
printf("save data, open publish to window, export to python and save as name in publish window");
break;
case MENU_HLP_THT: // open help topic window
printf("open help topic window");
break;
case MENU_KEY_THT: // open keyboard reference window
xPos = (r.right - r.left) / 2; // find xpos for window
yPos = (r.bottom - r.top) / 2; // find ypos for window
helperWindow = new HelperWindows(BRect(xPos, yPos, xPos + 240, yPos + 190), "Keyboard Shortcuts");
helperWindow->AddText(BRect(10, 10, 200, 25), "1", "Close the Window :: ALT + q");
helperWindow->AddText(BRect(10, 35, 200, 50), "2", "New Thought :: ALT + n");
helperWindow->AddText(BRect(10, 60, 200, 75), "3", "Edit Thought Name :: ALT + e");
helperWindow->AddText(BRect(10, 85, 200, 100), "4", "Save Progress :: ALT + s");
helperWindow->AddText(BRect(10, 110, 200, 125), "5", "Preview Thought :: ALT + r");
helperWindow->AddText(BRect(10, 135, 200, 150), "6", "Publish Thought :: ALT + p");
helperWindow->AddText(BRect(10, 160, 230, 175), "7", "View Keyboard Shortcuts :: ALT + k");
helperWindow->Show();
printf("open keyboard reference window");
break;
case MENU_MRK_THT: // open markup reference window
printf("open markup reference window");
break;
case MENU_ABT_THT: // open about window
printf("open about window");
break;
case UPDATE_TITLE: // update title with the name from the saveidea window
if(msg->FindString("updatetitle", &updateTitle) == B_OK) // updated title exists in variable
{
tmpString = "Masterpiece Editor - ";
tmpString += updateTitle;
this->SetTitle(tmpString);
}
else //
{
eAlert = new ErrorAlert("3.1 Editor Error: Message not found."); // message variable not found
eAlert->Launch();
}
break;
default:
{
BWindow::MessageReceived(msg);
break;
}
}
}
bool MPEditor::QuitRequested(void)
{
// on quit, show launcher by sending message
launcherMessage.MakeEmpty();
launcherMessage.AddInt64("showLauncher", 1);
launcherMessenger.SendMessage(&launcherMessage);
return true;
}
<commit_msg>trying to figure out either system or python call stuff<commit_after>#include "MPEditor.h"
MPEditor::MPEditor(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID)
: BWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr)
{
AddShortcut('q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED));
AddShortcut('n', B_COMMAND_KEY, new BMessage(MENU_NEW_THT));
AddShortcut('e', B_COMMAND_KEY, new BMessage(MENU_EDT_THT));
AddShortcut('s', B_COMMAND_KEY, new BMessage(MENU_SAV_THT));
AddShortcut('r', B_COMMAND_KEY, new BMessage(MENU_PRV_THT));
AddShortcut('p', B_COMMAND_KEY, new BMessage(MENU_PUB_THT));
AddShortcut('k', B_COMMAND_KEY, new BMessage(MENU_KEY_THT));
// initialize controls
BRect r = Bounds();
r.bottom = r.bottom - 50;
editorTextView = new BTextView(r, NULL, r, B_FOLLOW_ALL, B_WILL_DRAW | B_NAVIGABLE);
backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
AddChild(backView);
// gui layout builder
backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));
backView->AddChild(BGridLayoutBuilder()
.Add(new EditorMenu(), 0, 0)
.Add(new BScrollView("scroll_editor", editorTextView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 1)
.SetInsets(0, 0, 0, 0)
);
currentideaID = ideaID; // pass current idea id selected to editor window for use
if(currentideaID != -1) // if id has a real value
{
sqlObject = new SqlObject(ideaStatement, "7");
sqlObject->PrepareSql("select ideatext from ideatable where ideaid = ?");
sqlObject->BindValue(1, currentideaID);
sqlObject->StepSql();
editorTextView->SetText(sqlObject->ReturnText(0));
sqlObject->FinalizeSql();
sqlObject->CloseSql();
}
}
void MPEditor::MessageReceived(BMessage* msg)
{
BRect r(Bounds());
//FILE *fp = NULL;
BString tmpPath;
switch(msg->what)
{
case MENU_NEW_THT: // open another untitled editor window
tmpEditor = new MPEditor(BMessage(SHOW_LAUNCHER), BMessenger(this), "MasterPiece Editor - untitled", -1);
tmpEditor->Show();
break;
case MENU_EDT_THT: // edit current idea name for editing
xPos = (r.right - r.left) / 2; // find xpos for window
yPos = (r.bottom - r.top) / 2; // find ypos for window
editIdeaName = new EditIdeaName(BMessage(UPDATE_TITLE), BMessenger(this), xPos, yPos, currentideaID);
editIdeaName->Show(); // show edit idea name window
break;
case MENU_SAV_THT: // save current idea progress
if(currentideaID == -1) // if its untitled insert new thought, then show saveidea to apply a name...
{
sqlObject = new SqlObject(ideaStatement, "8");
sqlObject->PrepareSql("insert into ideatable (ideaname, ideatext, ismp) values('untitled', ?, 0)");
sqlObject->BindValue(1, editorTextView->Text());
sqlObject->StepSql();
xPos = (r.right - r.left) / 2; // find xpos for window
yPos = (r.bottom - r.top) / 2; // find ypos for window
saveIdea = new SaveIdea(BMessage(UPDATE_TITLE), BMessenger(this), xPos, yPos, sqlObject->ReturnLastInsertRowID());
currentideaID = sqlObject->ReturnLastInsertRowID();
sqlObject->FinalizeSql();
sqlObject->CloseSql();
saveIdea->Show(); // show save window to name the untitled thought
}
else // already exists, just update ideatext and save new information
{
sqlObject = new SqlObject(ideaStatement, "9");
sqlObject->PrepareSql("update ideatable set ideatext = ? where ideaid = ?");
sqlObject->BindValue(1, editorTextView->Text());
sqlObject->BindValue(2, currentideaID);
sqlObject->StepSql();
sqlObject->FinalizeSql();
sqlObject->CloseSql();
}
break;
case MENU_PRV_THT: // preview thought in html in webpositive
// LOOK AT DOCUTILS CORE.PY FOR CALLING PYTHON COMMANDS.
// LOOK AT http://docs.python.org/faq/extending.html FOR REFERENCE TO CALLING FUNCTIONS FROM SOURCE...
// POSSIBLY PUT ALL THOUGHTS INTO A STRING. THEN CALL THE PYTHON CMD ON THEM, THEN OUTPUT THEM TO A FILE...
/*
PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *pArgs;
pName = PyString_FromString("docutils.core");
pModule = PyImport_Import(pName);
pDict = PyModule_GetDict(pModule);
pFunc = PyDict_GetItemString(pDict, "publish_string");
if(PyCallable_Check(pFunc))
{
BString outString;
pArgs = PyTuple_New(3);
PyTuple_SetItem(pArgs, 0, PyString_FromString("*bolder*"));
PyTuple_SetItem(pArgs, 1, PyString_FromString(outString));
PyTuple_SetItem(pArgs, 2, PyString_FromString("xhtml"));
pValue = PyObject_CallObject(pFunc, pArgs);
}
else
{
PyErr_Print();
}
Py_DECREF(pModule);
Py_DECREF(pName);
//PyFinalize();
*/
/*
publish_string(source, source_path=None, destination_path=None,
reader=None, reader_name='standalone',
parser=None, parser_name='restructuredtext',
writer=None, writer_name='pseudoxml',
settings=None, settings_spec=None,
settings_overrides=None, config_section=None,
enable_exit_status=None): */
// publish_string(stringVar, destVar, writer_name='xhtml');
// runs python code and creates tmp.html. webpositive won't open it though but that's another issue
// determine current app directory and then make the string this way
//if(!(fp = fopen("./converters/rst2html.py", "r"))) printf("Error");
//PyObject* glb, loc;
//PyObject** args;
//loc = PyDict_New();
//glb = PyDict_New();
//PyDict_SetItemString(glb, "__builtins__", PyEval_GetBuiltins());
//Py_Initialize();
//PyRun_File(fp,
//PyEval_EvalCodeEx(fp, glb, loc
//PyRun_SimpleFileFlags(fp, "rst2html.py", "tmp.tht", "tmp.html");
//PyRun_SimpleString("./converters/rst2html.py tmp.tht tmp.html");
//Py_Finalize();
system("python /boot/common/bin/rst2html.py tmp.tht tmp.html");
tmpPath = "/boot/apps/WebPositive/WebPositive file://";
tmpPath += GetAppDirPath();
tmpPath += "/tmp.html &";
system(tmpPath);
break;
case MENU_PUB_THT: // publish thought by opening publish window
printf("save data, open publish to window, export to python and save as name in publish window");
break;
case MENU_HLP_THT: // open help topic window
printf("open help topic window");
break;
case MENU_KEY_THT: // open keyboard reference window
xPos = (r.right - r.left) / 2; // find xpos for window
yPos = (r.bottom - r.top) / 2; // find ypos for window
helperWindow = new HelperWindows(BRect(xPos, yPos, xPos + 240, yPos + 190), "Keyboard Shortcuts");
helperWindow->AddText(BRect(10, 10, 200, 25), "1", "Close the Window :: ALT + q");
helperWindow->AddText(BRect(10, 35, 200, 50), "2", "New Thought :: ALT + n");
helperWindow->AddText(BRect(10, 60, 200, 75), "3", "Edit Thought Name :: ALT + e");
helperWindow->AddText(BRect(10, 85, 200, 100), "4", "Save Progress :: ALT + s");
helperWindow->AddText(BRect(10, 110, 200, 125), "5", "Preview Thought :: ALT + r");
helperWindow->AddText(BRect(10, 135, 200, 150), "6", "Publish Thought :: ALT + p");
helperWindow->AddText(BRect(10, 160, 230, 175), "7", "View Keyboard Shortcuts :: ALT + k");
helperWindow->Show();
printf("open keyboard reference window");
break;
case MENU_MRK_THT: // open markup reference window
printf("open markup reference window");
break;
case MENU_ABT_THT: // open about window
printf("open about window");
break;
case UPDATE_TITLE: // update title with the name from the saveidea window
if(msg->FindString("updatetitle", &updateTitle) == B_OK) // updated title exists in variable
{
tmpString = "Masterpiece Editor - ";
tmpString += updateTitle;
this->SetTitle(tmpString);
}
else //
{
eAlert = new ErrorAlert("3.1 Editor Error: Message not found."); // message variable not found
eAlert->Launch();
}
break;
default:
{
BWindow::MessageReceived(msg);
break;
}
}
}
bool MPEditor::QuitRequested(void)
{
// on quit, show launcher by sending message
launcherMessage.MakeEmpty();
launcherMessage.AddInt64("showLauncher", 1);
launcherMessenger.SendMessage(&launcherMessage);
return true;
}
<|endoftext|>
|
<commit_before>#include "MbedComm.h"
#include <math.h>
MbedComm::MbedComm(void)
{
}
MbedComm::MbedComm(string iIpAddress, int iUDPPort,bool iEnabled)
{
this->ipAddress=iIpAddress;
this->UDPPort=iUDPPort;
this->enabled=iEnabled;
this->sequence = 1;
this->bufferedFrame=NULL;
this->fragmentsSent=0;
this->universoFragment=0;
}
MbedComm::~MbedComm(void)
{
}
void MbedComm::setIPAddress(string iIpAddress)
{
this->ipAddress=iIpAddress;
}
void MbedComm::setUDPPort(int iUDPPort)
{
this->UDPPort=iUDPPort;
}
void MbedComm::setTransmitState(bool newState)
{
this->enabled=newState;
}
bool MbedComm::isEnabled()
{
return this->enabled;
}
int hex2int(string s)
{
stringstream ss(s);
int i;
ss >> hex >> i;
return i;
}
//this function sends the whole frame and puts the thread to sleep while waiting to send the next fragment.
//it SHOULD not be used, unless working just with one device.
void MbedComm::transmitFrame(DTFrame* frameToTransmit)
{
vector<DTPixel*>* pixels = frameToTransmit->getPixels();
vector <DTPixel*>::size_type i = pixels->size();
int cantPixelsInt = i;
int cantP = cantPixelsInt / 170;
int resto = cantPixelsInt % 170;
//float cantPixels = (float) i;
//float cantP = cantPixels/170.0f;
////
//int cantPackets = (int)(cantP + 0.5f);
int cantPackets = cantP + (resto>0);
short universo = 0;
for (int j=1; j<=cantPackets; j++)
{
if (j>1)
usleep(1000);
artnet_dmx_t packet;
// now build packet
memcpy(&packet.id, "Art-Net", 8);
packet.opCodeHi = 0x00;
packet.opCode = 0x50;
packet.verH = 0;
packet.ver = 14;
packet.sequence = this->sequence;
packet.physical = 0;
packet.universeHi = short_get_low_byte(universo);
packet.universe= short_get_high_byte(universo);
// set length
short length = 0;
if (j<cantPackets){
length = 170; // se transmiten 170 pixels
}
else{
length = cantPixelsInt - ((cantPackets - 1) * 170);
}
length= length * 3; // son 3 bytes por luz
packet.lengthHi = short_get_high_byte(length);
packet.length = short_get_low_byte(length);
//busco posicion en el vector de pixeles a partir de la cual voy a mandar pixeles
int pos = (j * 170) - 170;
vector<DTPixel*>::iterator it = pixels->begin();
for (int cp = 0; cp<(length-2); cp+=3)
{
packet.data[cp] = it[pos]->getR();
packet.data[cp+1] = it[pos]->getG();
packet.data[cp+2] = it[pos]->getB();
pos++;
}
universo ++;
int sent = udpConnection.Send((const char*)&packet, length+18);
}
this->sequence++;
}
bool MbedComm::sendFrameFragment(){
if (this->bufferedFrame!=NULL){
vector<DTPixel*>* pixels = bufferedFrame->getPixels();
//DTPixel* ppp = pixels->operator[](0);
//cout << ppp->getR() << endl;
vector <DTPixel*>::size_type i = pixels->size();
int cantPixelsInt = i;
int cantP = cantPixelsInt / 170;
int resto = cantPixelsInt % 170;
int cantPackets = cantP;
if (resto!=0){
cantPackets++;
}
//catPackets is the total amount of fragments to be sent
// in this->fragmentsSent we store the amount of fragments actualli sent at the time being.
//short universo = 0;
//universo should start at 0
artnet_dmx_t packet;
// now build packet
memcpy(&packet.id, "Art-Net", 8);
packet.opCodeHi = 0x00;
packet.opCode = 0x50;
packet.verH = 0;
packet.ver = 14;
packet.sequence = this->sequence;
packet.physical = 0;
packet.universeHi = short_get_low_byte(this->universoFragment); // TODO: Why is this inverted... and works?
packet.universe= short_get_high_byte(this->universoFragment);
// set length
short length = 0;
if ((this->fragmentsSent+1)<cantPackets){
length = 170; // se transmiten 170 pixels
}
else{
length = cantPixelsInt - ((cantPackets - 1) * 170); ///////////////////////////////// TODO: revisar
}
length= length * 3; // son 3 bytes por luz
packet.lengthHi = short_get_high_byte(length);
packet.length = short_get_low_byte(length);
//busco posicion en el vector de pixeles a partir de la cual voy a mandar pixeles
int pos = (this->fragmentsSent * 170);
vector<DTPixel*>::iterator it = pixels->begin();
for (int cp = 0; cp<(length-2); cp+=3)
{
// original order!! FIXXX uncomment for OCTOBARS
//int rNew= it[pos]->getR();
//int gNew= it[pos]->getG();
//int bNew= it[pos]->getB();
int rNew= pixels->operator[](pos)->getR();
int gNew= pixels->operator[](pos)->getG();
int bNew= pixels->operator[](pos)->getB();
if(rNew>255)
rNew=255;
if(gNew>255)
gNew=255;
if(bNew>255)
bNew=255;
//for Bondibar
packet.data[cp] = bNew;
packet.data[cp+1] = rNew;
packet.data[cp+2] = gNew;
/*
// for octobar
packet.data[cp] = rNew;
packet.data[cp+1] = gNew;
packet.data[cp+2] = bNew;
*/
pos++;
}
this->universoFragment++;
int sent = udpConnection.Send((const char*)&packet, length+18);
//cout << "r" << endl;
this->sequence++;
this->fragmentsSent++;
if (this->fragmentsSent==cantPackets){
//cout << "all sent" << endl;
//we've sent the whole frame
this->fragmentsSent=0;
this->universoFragment=0;
return false;
}
else{
//we still have fragments to process
return true;
}
}
return false;
}
void MbedComm::storeFrame(DTFrame* newFrame){
this->bufferedFrame=newFrame;
}
void MbedComm::clenUpBufferedFrame(){
if(bufferedFrame!=NULL){
delete this->bufferedFrame;
this->bufferedFrame=NULL;
}
}
void MbedComm::setupSender()
{
udpConnection.Create();
const char * ip = this->ipAddress.c_str();
udpConnection.Connect(ip,this->UDPPort);
udpConnection.SetNonBlocking(true);
}<commit_msg>Now we send pixels in RGB order so the devices reorder them depending on the LED stripe model<commit_after>#include "MbedComm.h"
#include <math.h>
MbedComm::MbedComm(void)
{
}
MbedComm::MbedComm(string iIpAddress, int iUDPPort,bool iEnabled)
{
this->ipAddress=iIpAddress;
this->UDPPort=iUDPPort;
this->enabled=iEnabled;
this->sequence = 1;
this->bufferedFrame=NULL;
this->fragmentsSent=0;
this->universoFragment=0;
}
MbedComm::~MbedComm(void)
{
}
void MbedComm::setIPAddress(string iIpAddress)
{
this->ipAddress=iIpAddress;
}
void MbedComm::setUDPPort(int iUDPPort)
{
this->UDPPort=iUDPPort;
}
void MbedComm::setTransmitState(bool newState)
{
this->enabled=newState;
}
bool MbedComm::isEnabled()
{
return this->enabled;
}
int hex2int(string s)
{
stringstream ss(s);
int i;
ss >> hex >> i;
return i;
}
//this function sends the whole frame and puts the thread to sleep while waiting to send the next fragment.
//it SHOULD not be used, unless working just with one device.
void MbedComm::transmitFrame(DTFrame* frameToTransmit)
{
vector<DTPixel*>* pixels = frameToTransmit->getPixels();
vector <DTPixel*>::size_type i = pixels->size();
int cantPixelsInt = i;
int cantP = cantPixelsInt / 170;
int resto = cantPixelsInt % 170;
//float cantPixels = (float) i;
//float cantP = cantPixels/170.0f;
////
//int cantPackets = (int)(cantP + 0.5f);
int cantPackets = cantP + (resto>0);
short universo = 0;
for (int j=1; j<=cantPackets; j++)
{
if (j>1)
usleep(1000);
artnet_dmx_t packet;
// now build packet
memcpy(&packet.id, "Art-Net", 8);
packet.opCodeHi = 0x00;
packet.opCode = 0x50;
packet.verH = 0;
packet.ver = 14;
packet.sequence = this->sequence;
packet.physical = 0;
packet.universeHi = short_get_low_byte(universo);
packet.universe= short_get_high_byte(universo);
// set length
short length = 0;
if (j<cantPackets){
length = 170; // se transmiten 170 pixels
}
else{
length = cantPixelsInt - ((cantPackets - 1) * 170);
}
length= length * 3; // son 3 bytes por luz
packet.lengthHi = short_get_high_byte(length);
packet.length = short_get_low_byte(length);
//busco posicion en el vector de pixeles a partir de la cual voy a mandar pixeles
int pos = (j * 170) - 170;
vector<DTPixel*>::iterator it = pixels->begin();
for (int cp = 0; cp<(length-2); cp+=3)
{
packet.data[cp] = it[pos]->getR();
packet.data[cp+1] = it[pos]->getG();
packet.data[cp+2] = it[pos]->getB();
pos++;
}
universo ++;
int sent = udpConnection.Send((const char*)&packet, length+18);
}
this->sequence++;
}
bool MbedComm::sendFrameFragment(){
if (this->bufferedFrame!=NULL){
vector<DTPixel*>* pixels = bufferedFrame->getPixels();
//DTPixel* ppp = pixels->operator[](0);
//cout << ppp->getR() << endl;
vector <DTPixel*>::size_type i = pixels->size();
int cantPixelsInt = i;
int cantP = cantPixelsInt / 170;
int resto = cantPixelsInt % 170;
int cantPackets = cantP;
if (resto!=0){
cantPackets++;
}
//catPackets is the total amount of fragments to be sent
// in this->fragmentsSent we store the amount of fragments actualli sent at the time being.
//short universo = 0;
//universo should start at 0
artnet_dmx_t packet;
// now build packet
memcpy(&packet.id, "Art-Net", 8);
packet.opCodeHi = 0x00;
packet.opCode = 0x50;
packet.verH = 0;
packet.ver = 14;
packet.sequence = this->sequence;
packet.physical = 0;
packet.universeHi = short_get_low_byte(this->universoFragment); // TODO: Why is this inverted... and works?
packet.universe= short_get_high_byte(this->universoFragment);
// set length
short length = 0;
if ((this->fragmentsSent+1)<cantPackets){
length = 170; // se transmiten 170 pixels
}
else{
length = cantPixelsInt - ((cantPackets - 1) * 170); ///////////////////////////////// TODO: revisar
}
length= length * 3; // son 3 bytes por luz
packet.lengthHi = short_get_high_byte(length);
packet.length = short_get_low_byte(length);
//busco posicion en el vector de pixeles a partir de la cual voy a mandar pixeles
int pos = (this->fragmentsSent * 170);
vector<DTPixel*>::iterator it = pixels->begin();
for (int cp = 0; cp<(length-2); cp+=3)
{
// original order!! FIXXX uncomment for OCTOBARS
//int rNew= it[pos]->getR();
//int gNew= it[pos]->getG();
//int bNew= it[pos]->getB();
int rNew= pixels->operator[](pos)->getR();
int gNew= pixels->operator[](pos)->getG();
int bNew= pixels->operator[](pos)->getB();
if(rNew>255)
rNew=255;
if(gNew>255)
gNew=255;
if(bNew>255)
bNew=255;
//for Bondibar
packet.data[cp] = rNew;
packet.data[cp+1] = gNew;
packet.data[cp+2] = bNew;
/*
// for octobar
packet.data[cp] = rNew;
packet.data[cp+1] = gNew;
packet.data[cp+2] = bNew;
*/
pos++;
}
this->universoFragment++;
int sent = udpConnection.Send((const char*)&packet, length+18);
//cout << "r" << endl;
this->sequence++;
this->fragmentsSent++;
if (this->fragmentsSent==cantPackets){
//cout << "all sent" << endl;
//we've sent the whole frame
this->fragmentsSent=0;
this->universoFragment=0;
return false;
}
else{
//we still have fragments to process
return true;
}
}
return false;
}
void MbedComm::storeFrame(DTFrame* newFrame){
this->bufferedFrame=newFrame;
}
void MbedComm::clenUpBufferedFrame(){
if(bufferedFrame!=NULL){
delete this->bufferedFrame;
this->bufferedFrame=NULL;
}
}
void MbedComm::setupSender()
{
udpConnection.Create();
const char * ip = this->ipAddress.c_str();
udpConnection.Connect(ip,this->UDPPort);
udpConnection.SetNonBlocking(true);
}
<|endoftext|>
|
<commit_before>#pragma once
#include <iostream>
#include <ctime>
#include <map>
#include <stack>
#include <algorithm>
#include <mutex>
#include <thread>
#define ROOT_ID 0
class Profiler {
public:
typedef std::string Key;
class KeyMap {
public:
typedef std::map<Key, std::map< std::size_t, int> >::iterator iter;
void clear() {
_map.clear();
}
bool exists(Key k) {
if (_map.count(k))
return true;
return false;
}
bool exists(Key k, std::size_t tid) {
if (_map.count(k))
if (_map[k].count(tid)) return true;
return false;
}
iter begin() {
return _map.begin();
}
iter end() {
return _map.end();
}
int & operator[](Key k) {
std::hash<std::thread::id> hasher;
std::size_t tid = hasher(std::this_thread::get_id());
return _map[k][tid];
}
int & get(Key k, std::size_t thread_id) {
return _map[k][thread_id];
}
private:
std::map<Key, std::map< std::size_t, int> > _map;
};
enum SortingMode {
TOTAL_ELAPSED,
AVERAGE_ELAPSED,
COUNT,
};
class Stats {
public:
Stats() {}
Stats(Key k, timespec s, int p, std::size_t tid) : key(k),
start(s),
parent(p),
count(1),
thread_id(tid) {}
struct timespec start, finish;
Key key;
double total;
long count;
int parent;
std::size_t thread_id;
double seconds_elapsed() {
double elapsed;
elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
return elapsed;
}
};
Profiler(const Key & key) : _key(key) {
std::unique_lock<std::mutex> lock(profile_mutex());
timespec starting_time = Profiler::get_time();
std::hash<std::thread::id> hasher;
std::size_t tid = hasher(std::this_thread::get_id());
if (!Profiler::keymap().exists("__root__")) {
Profiler::stats().push_back(Stats("__root__", starting_time, -1, tid));
Profiler::keymap()["__root__"] = 0;
}
if (keymap().exists(key, tid)) {
int id = keymap().get(_key, tid);
Profiler::stats()[id].count++;
Profiler::stats()[id].start = starting_time;
Profiler::hierarchy()[tid].push(id);
//assert should have the same parent
}
else {
int id = Profiler::stats().size();
keymap().get(_key,tid) = id;
int parent = 0;
if (hierarchy()[tid].size() > 0) parent = Profiler::hierarchy()[tid].top();
Profiler::stats().push_back(Stats(key,
starting_time,
parent,
tid));
Profiler::hierarchy()[tid].push(id);
}
}
~Profiler() {
std::unique_lock<std::mutex> lock(profile_mutex());
//TODO refactor
std::hash<std::thread::id> hasher;
std::size_t tid = hasher(std::this_thread::get_id());
timespec end_time = Profiler::get_time();
Stats & s = Profiler::stats()[keymap()[_key]];
s.finish = end_time;
s.total += s.seconds_elapsed();
Profiler::hierarchy()[tid].pop();
Profiler::stats()[ROOT_ID].finish = end_time;
Profiler::stats()[ROOT_ID].total = Profiler::stats()[ROOT_ID].seconds_elapsed();
}
static std::vector<Stats> getStatsSorted(SortingMode mode) {
std::vector<Stats> sorted = Profiler::stats();
switch(mode) {
case TOTAL_ELAPSED: {
struct {
bool operator()(const Stats & a, const Stats & b) {
return a.total < b.total;
}
} comp;
std::sort(sorted.begin(), sorted.end(), comp);
break;
}
case AVERAGE_ELAPSED: {
struct {
bool operator()(const Stats & a, const Stats & b) {
return a.total/a.count < b.total/b.count;
}
} comp;
std::sort(sorted.begin(), sorted.end(), comp);
break;
}
case COUNT:
struct {
bool operator()(const Stats & a, const Stats & b) {
return a.count < b.count;
}
} comp;
std::sort(sorted.begin(), sorted.end(), comp);
break;
};
return sorted;
}
static timespec get_time() {
struct timespec time;
clock_gettime(CLOCK_MONOTONIC, &time);
return time;
}
static std::vector<Stats> getFusedStats() {
std::map<Key, Stats> key_stats;
std::map<int,int> oldnewmapping;
std::vector<int> old_idx;
//accumulate times per key
int idx = 0;
for (auto s : stats()) {
Key key = s.key;
if (!key_stats.count(key)) {
key_stats[key] = s;
old_idx.push_back(idx);
}
else {
key_stats[key].count += s.count;
key_stats[key].total += s.seconds_elapsed();
}
idx++;
}
int count = 0;
for (auto idx : old_idx) {
oldnewmapping[idx] = count;
count++;
}
std::vector<Stats> fstats;
for (auto s : key_stats) {
Stats fs = s.second;
if (fs.parent >= 0)
fs.parent = oldnewmapping[fs.parent];
fstats.push_back(fs);
}
return fstats;
}
static void clear() {
//TODO refactor
std::hash<std::thread::id> hasher;
std::size_t tid = hasher(std::this_thread::get_id());
std::unique_lock<std::mutex> lock(profile_mutex());
stats().clear();
keymap().clear();
hierarchy()[tid].pop();
}
static std::map<int, Key> getInverseMap() {
std::map<int, Key> idToKey;
for (auto k : keymap()) {
for (auto t : k.second)
idToKey[t.second] = k.first;
}
return idToKey;
}
private:
Key _key;
static std::mutex & profile_mutex() { static std::mutex m; return m; }
static std::map<std::size_t, std::stack<int> > & hierarchy() {
static std::map<std::size_t, std::stack<int> > h; return h; }
static std::vector<Stats> & stats() { static std::vector<Stats> s; return s; }
static KeyMap & keymap() { static KeyMap k; return k; }
class ConsolePrinter {
public:
ConsolePrinter() {
_colWidth = 20;
}
struct Node {
Node(Profiler::Stats s) : name(s.key), stats(s) {}
Profiler::Key name;
Profiler::Stats stats;
std::vector<Node*> children;
};
void printcol(std::string n) {
if (n.length() > _colWidth) {
n[_colWidth-1] = '\0';
}
int spaces = _colWidth - n.length();
std::cout << n;
for(int i = 0; i < spaces; i++) std::cout << " ";
std::cout << "|";
}
void printTitle(std::string title) {
int spaces_left = _colWidth - title.size();
for(int i = 0; i < spaces_left/2; i++) std::cout << " ";
std::cout << title;
for(int i = 0; i < spaces_left/2 + spaces_left%2; i++) std::cout << " ";
std::cout << "|";
}
void printTopLine() {
for (int j = 0; j < 3; j++) {
for (int i = 0; i < _colWidth; i++)
std::cout << "=";
std::cout << "|";
}
}
void printBottomLine() {
for (int i = 0; i < _colWidth*3 + 3; i++)
std::cout << "=";
}
void print(Node *node, int level, float total_time) {
printcol(node->name);
char col[100];
sprintf(col, "%f sec.", node->stats.total);
printcol(std::string(col));
sprintf(col, "%03d %% of total", int((node->stats.total/total_time) * 100));
printcol(std::string(col));
std::cout << std::endl;
for (auto child : node->children)
print(child, level+1, total_time);
}
void print() {
std::vector<Profiler::Stats> fstats = Profiler::getFusedStats();
std::vector<Node> hierarchy;
for (int i = 0; i < fstats.size(); i++) {
hierarchy.push_back(Node(fstats[i]));
}
for (int i = 0; i < hierarchy.size(); i++) {
Profiler::Stats s = hierarchy[i].stats;
if (s.parent >= 0) {
hierarchy[s.parent].children.push_back(&hierarchy[i]);
}
}
printTitle("Key");
printTitle("Time");
printTitle("Percentage");
std::cout << std::endl;
printTopLine();
std::cout << std::endl;
print(&hierarchy[0], 0, fstats[0].total);
printBottomLine();
std::cout << std::endl;
}
private:
int _colWidth;
};
public:
static void print() {
ConsolePrinter printer;
printer.print();
}
};
<commit_msg>Fixes stack hierarchy for multi-threading<commit_after>#pragma once
#include <iostream>
#include <ctime>
#include <map>
#include <stack>
#include <algorithm>
#include <mutex>
#include <thread>
#define ROOT_ID 0
class Profiler {
public:
typedef std::string Key;
class KeyMap {
public:
typedef std::map<Key, std::map< std::size_t, int> >::iterator iter;
void clear() {
_map.clear();
}
bool exists(Key k) {
if (_map.count(k))
return true;
return false;
}
bool exists(Key k, std::size_t tid) {
if (_map.count(k))
if (_map[k].count(tid)) return true;
return false;
}
iter begin() {
return _map.begin();
}
iter end() {
return _map.end();
}
int & operator[](Key k) {
std::hash<std::thread::id> hasher;
std::size_t tid = hasher(std::this_thread::get_id());
return _map[k][tid];
}
int & get(Key k, std::size_t thread_id) {
return _map[k][thread_id];
}
private:
std::map<Key, std::map< std::size_t, int> > _map;
};
enum SortingMode {
TOTAL_ELAPSED,
AVERAGE_ELAPSED,
COUNT,
};
class Stats {
public:
Stats() {}
Stats(Key k, timespec s, int p, std::size_t tid) : key(k),
start(s),
parent(p),
count(1),
thread_id(tid) {}
struct timespec start, finish;
Key key;
double total;
long count;
int parent;
std::size_t thread_id;
double seconds_elapsed() {
double elapsed;
elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
return elapsed;
}
};
Profiler(const Key & key) : _key(key) {
std::unique_lock<std::mutex> lock(profile_mutex());
timespec starting_time = Profiler::get_time();
std::hash<std::thread::id> hasher;
std::size_t tid = hasher(std::this_thread::get_id());
if (!Profiler::keymap().exists("__root__")) {
Profiler::stats().push_back(Stats("__root__", starting_time, -1, tid));
Profiler::keymap()["__root__"] = 0;
}
if (keymap().exists(key, tid)) {
int id = keymap().get(_key, tid);
Profiler::stats()[id].count++;
Profiler::stats()[id].start = starting_time;
Profiler::hierarchy()[tid].push(id);
//assert should have the same parent
}
else {
int id = Profiler::stats().size();
keymap().get(_key,tid) = id;
int parent = 0;
if (hierarchy()[tid].size() > 0) parent = Profiler::hierarchy()[tid].top();
Profiler::stats().push_back(Stats(key,
starting_time,
parent,
tid));
Profiler::hierarchy()[tid].push(id);
}
}
~Profiler() {
std::unique_lock<std::mutex> lock(profile_mutex());
//TODO refactor
std::hash<std::thread::id> hasher;
std::size_t tid = hasher(std::this_thread::get_id());
timespec end_time = Profiler::get_time();
Stats & s = Profiler::stats()[keymap()[_key]];
s.finish = end_time;
s.total += s.seconds_elapsed();
Profiler::hierarchy()[tid].pop();
Profiler::stats()[ROOT_ID].finish = end_time;
Profiler::stats()[ROOT_ID].total = Profiler::stats()[ROOT_ID].seconds_elapsed();
}
static std::vector<Stats> getStatsSorted(SortingMode mode) {
std::vector<Stats> sorted = Profiler::stats();
switch(mode) {
case TOTAL_ELAPSED: {
struct {
bool operator()(const Stats & a, const Stats & b) {
return a.total < b.total;
}
} comp;
std::sort(sorted.begin(), sorted.end(), comp);
break;
}
case AVERAGE_ELAPSED: {
struct {
bool operator()(const Stats & a, const Stats & b) {
return a.total/a.count < b.total/b.count;
}
} comp;
std::sort(sorted.begin(), sorted.end(), comp);
break;
}
case COUNT:
struct {
bool operator()(const Stats & a, const Stats & b) {
return a.count < b.count;
}
} comp;
std::sort(sorted.begin(), sorted.end(), comp);
break;
};
return sorted;
}
static timespec get_time() {
struct timespec time;
clock_gettime(CLOCK_MONOTONIC, &time);
return time;
}
static std::vector<Stats> getFusedStats() {
std::map<Key, Stats> key_stats;
std::map<int,int> oldnewmapping;
std::map<Key, int> old_idx;
//accumulate times per key
int idx = 0;
for (auto s : stats()) {
Key key = s.key;
if (!key_stats.count(key)) {
key_stats[key] = s;
old_idx[key] = idx;
}
else {
key_stats[key].count += s.count;
key_stats[key].total += s.seconds_elapsed();
}
idx++;
}
int count = 0;
for (auto idx : old_idx) {
oldnewmapping[idx.second] = count;
count++;
}
std::vector<Stats> fstats;
for (auto s : key_stats) {
Stats fs = s.second;
if (fs.parent >= 0)
fs.parent = oldnewmapping[fs.parent];
fstats.push_back(fs);
}
return fstats;
}
static void clear() {
//TODO refactor
std::hash<std::thread::id> hasher;
std::size_t tid = hasher(std::this_thread::get_id());
std::unique_lock<std::mutex> lock(profile_mutex());
stats().clear();
keymap().clear();
}
static std::map<int, Key> getInverseMap() {
std::map<int, Key> idToKey;
for (auto k : keymap()) {
for (auto t : k.second)
idToKey[t.second] = k.first;
}
return idToKey;
}
private:
Key _key;
static std::mutex & profile_mutex() { static std::mutex m; return m; }
static std::map<std::size_t, std::stack<int> > & hierarchy() {
static std::map<std::size_t, std::stack<int> > h; return h; }
static std::vector<Stats> & stats() { static std::vector<Stats> s; return s; }
static KeyMap & keymap() { static KeyMap k; return k; }
class ConsolePrinter {
public:
ConsolePrinter() {
_colWidth = 20;
}
struct Node {
Node(Profiler::Stats s) : name(s.key), stats(s) {}
Profiler::Key name;
Profiler::Stats stats;
std::vector<Node*> children;
};
void printcol(std::string n) {
if (n.length() > _colWidth) {
n[_colWidth-1] = '\0';
}
int spaces = _colWidth - n.length();
std::cout << n;
for(int i = 0; i < spaces; i++) std::cout << " ";
std::cout << "|";
}
void printTitle(std::string title) {
int spaces_left = _colWidth - title.size();
for(int i = 0; i < spaces_left/2; i++) std::cout << " ";
std::cout << title;
for(int i = 0; i < spaces_left/2 + spaces_left%2; i++) std::cout << " ";
std::cout << "|";
}
void printTopLine() {
for (int j = 0; j < 4; j++) {
for (int i = 0; i < _colWidth; i++)
std::cout << "=";
std::cout << "|";
}
}
void printBottomLine() {
for (int i = 0; i < _colWidth*4 + 4; i++)
std::cout << "=";
}
void print(Node *node, int level, float total_time) {
printcol(node->name);
char col[100];
sprintf(col, "%d (%03.3f sec.)", node->stats.count,
node->stats.total/node->stats.count);
printcol(std::string(col));
sprintf(col, "%03.3f sec.", node->stats.total);
printcol(std::string(col));
sprintf(col, "%03d %% of total", int((node->stats.total/total_time) * 100));
printcol(std::string(col));
std::cout << std::endl;
for (auto child : node->children)
print(child, level+1, total_time);
}
void print() {
std::vector<Profiler::Stats> fstats = Profiler::getFusedStats();
std::vector<Node> hierarchy;
for (int i = 0; i < fstats.size(); i++) {
hierarchy.push_back(Node(fstats[i]));
}
for (int i = 0; i < hierarchy.size(); i++) {
Profiler::Stats s = hierarchy[i].stats;
if (s.parent >= 0) {
hierarchy[s.parent].children.push_back(&hierarchy[i]);
}
}
printTitle("Key");
printTitle("Num (Time)");
printTitle("Total Time");
printTitle("Total %");
std::cout << std::endl;
printTopLine();
std::cout << std::endl;
print(&hierarchy[0], 0, fstats[0].total);
printBottomLine();
std::cout << std::endl;
}
private:
int _colWidth;
};
public:
static void print() {
ConsolePrinter printer;
printer.print();
}
};
<|endoftext|>
|
<commit_before>// -*- mode:c++; indent-tabs-mode:nil; -*-
/*
Copyright (c) 2014, Anders Ronnbrant, [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 "Recorder.h"
#include <cassert>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <string>
#include <type_traits>
#include <unordered_map>
#include "zmqutils.h"
void Error(char const* msg) { std::fprintf(stderr, "%s\n", msg); }
// Create a item from name, value and time paramters.
// ---------------------------------------------------------------------------
// Specialization for char const*
Recorder::Item
createItem(Recorder::Item const& clone,
int64_t const time,
char const* value) {
Recorder::Item item;
std::memcpy(&item, &clone, sizeof(item));
item.time = time;
item.type = Recorder::Item::Type::STR;
strncpy(&item.data.s[0], &value[0], sizeof(item.data.s));
return std::move(item);
}
template<typename T> Recorder::Item
createItem(Recorder::Item const& clone,
int64_t const time,
T const value) {
Recorder::Item item;
std::memcpy(&item, &clone, sizeof(item));
item.time = time;
if (std::is_same<char, T>::value) {
item.type = Recorder::Item::Type::CHAR;
item.data.c = value;
} else if (std::is_integral<T>::value) {
if (std::is_signed<T>::value) {
item.type = Recorder::Item::Type::INT;
item.data.i = value;
} else if (std::is_unsigned<T>::value) {
item.type = Recorder::Item::Type::UINT;
item.data.u = value;
} else {
static_assert(
std::is_signed<T>::value || std::is_unsigned<T>::value,
"Unknown signedness for integral type");
}
} else if (std::is_floating_point<T>::value) {
item.type = Recorder::Item::Type::FLOAT;
item.data.d = value;
} else {
static_assert(
std::is_integral<T>::value || std::is_floating_point<T>::value,
"Value type must be char, integral or floating point");
}
return item;
}
// ---------------------------------------------------------------------------
template Recorder&
Recorder::record<char const*>(std::string const& key, char const* value);
template Recorder&
Recorder::record<char>(std::string const& key, char value);
template Recorder&
Recorder::record<int32_t>(std::string const& key, int32_t value);
template Recorder&
Recorder::record<int64_t>(std::string const& key, int64_t value);
template Recorder&
Recorder::record<uint32_t>(std::string const& key, uint32_t value);
template Recorder&
Recorder::record<uint64_t>(std::string const& key, uint64_t value);
template Recorder&
Recorder::record<double>(std::string const& key, double value);
Recorder::Item::Item()
: type(Type::INIT), time(-1) {
}
std::string&&
Recorder::Item::toString() const {
char buffer[128];
std::string name(this->name);
std::string unit(this->unit);
unit = "[" + unit + "]";
snprintf(buffer, sizeof(buffer), "%ld %10s = ", this->time, name.c_str());
switch (this->type) {
case Type::CHAR:
sprintf(buffer, "%c", data.c);
break;
case Type::INT:
sprintf(buffer, "%ld", data.i);
break;
case Type::UINT:
sprintf(buffer, "%lu", data.u);
break;
case Type::FLOAT:
sprintf(buffer, "%f", data.d);
break;
case Type::STR:
{
std::string str(data.s, sizeof(data.s));
sprintf(buffer, "%s", str.c_str());
}
break;
default:
break;
}
snprintf(buffer, 2+sizeof(this->unit), "%s\n", unit.c_str());
return std::move(std::string(buffer));
}
Recorder::Item::Item(std::string const& n, std::string const& u)
: Item() {
if (n.length() > sizeof(name)) {
Error("Maximum size of parameter name 8 chars");
std::exit(1);
} else if (u.length() > sizeof(unit)) {
Error("Maximum size of parameter unit 8 chars");
std::exit(1);
}
std::strncpy(name, n.c_str(), sizeof(name));
std::strncpy(unit, u.c_str(), sizeof(unit));
}
Recorder::Recorder(uint64_t id, std::string const address)
: _send_buffer_index(0)
, _identifier(id)
, _socket_address(address)
{
_storage.reserve(256);
bool error = false;
if (Recorder::socket_context == nullptr) {
Error("Recorder: setContext() must be called before instantiation");
error = true;
}
if (_socket_address.empty()) {
Error("Recorder: Socket address empty, setAddress() must be called");
Error(" before first instantiation or provide local address");
Error(" using ctor Recorder(uint64_t, std::string)");
error = true;
}
if (error) {
std::exit(1);
}
constexpr int linger = 3000;
_socket.reset(new zmq::socket_t(*Recorder::socket_context, ZMQ_PUSH));
_socket->setsockopt(ZMQ_LINGER, &linger, sizeof(linger));
zmqutils::connect(_socket.get(), _socket_address);
}
Recorder::Recorder(uint64_t id)
: Recorder(id, Recorder::socket_address) {
}
Recorder::~Recorder() {
flushSendBuffer();
if (_socket) {
_socket->close();
}
}
Recorder&
Recorder::setup(std::string const& key, std::string const& unit) {
auto it = _storage.find(key);
if (it == _storage.end()) {
Item item(key, unit);
_storage.emplace(key, item);
} else {
// Ignore already setup parameters
}
return (*this);
}
template<typename T>
Recorder& Recorder::record(std::string const& key, T const value) {
auto const time = std::time(nullptr);
auto it = _storage.find(key);
if (it == _storage.end()) {
assert(0 && "Must use setup() prior to record()");
} else if (it->second.type == Item::Type::INIT) {
auto const item = createItem(it->second, time, value);
_storage[key] = item;
send(item);
} else if (memcmp(&value, &(it->second.data), sizeof(value)) != 0) {
auto const item = createItem(it->second, time, value);
it->second.time = time;
send(it->second);
_storage[key] = item;
send(item);
} else {
// Ignore unchanged value
}
return (*this);
}
void
Recorder::send(Item const& item) {
_send_buffer[_send_buffer_index++] = item;
if (_send_buffer_index == _send_buffer.max_size()) {
flushSendBuffer();
}
}
void
Recorder::flushSendBuffer() {
constexpr auto item_size = sizeof(decltype(_send_buffer)::value_type);
if (_send_buffer_index > 0) {
_socket->send(_send_buffer.data(), _send_buffer_index * item_size);
_send_buffer_index = 0;
}
}
void
Recorder::setContext(zmq::context_t* ctx) {
socket_context = ctx;
}
void
Recorder::setAddress(std::string addr) {
socket_address = addr;
}
zmq::context_t* Recorder::socket_context = nullptr;
std::string Recorder::socket_address = "";
<commit_msg>Using std::move as return is not necessary<commit_after>// -*- mode:c++; indent-tabs-mode:nil; -*-
/*
Copyright (c) 2014, Anders Ronnbrant, [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 "Recorder.h"
#include <cassert>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <string>
#include <type_traits>
#include <unordered_map>
#include "zmqutils.h"
void Error(char const* msg) { std::fprintf(stderr, "%s\n", msg); }
// Create a item from name, value and time paramters.
// ---------------------------------------------------------------------------
// Specialization for char const*
Recorder::Item
createItem(Recorder::Item const& clone,
int64_t const time,
char const* value) {
Recorder::Item item;
std::memcpy(&item, &clone, sizeof(item));
item.time = time;
item.type = Recorder::Item::Type::STR;
strncpy(&item.data.s[0], &value[0], sizeof(item.data.s));
return item;
}
template<typename T> Recorder::Item
createItem(Recorder::Item const& clone,
int64_t const time,
T const value) {
Recorder::Item item;
std::memcpy(&item, &clone, sizeof(item));
item.time = time;
if (std::is_same<char, T>::value) {
item.type = Recorder::Item::Type::CHAR;
item.data.c = value;
} else if (std::is_integral<T>::value) {
if (std::is_signed<T>::value) {
item.type = Recorder::Item::Type::INT;
item.data.i = value;
} else if (std::is_unsigned<T>::value) {
item.type = Recorder::Item::Type::UINT;
item.data.u = value;
} else {
static_assert(
std::is_signed<T>::value || std::is_unsigned<T>::value,
"Unknown signedness for integral type");
}
} else if (std::is_floating_point<T>::value) {
item.type = Recorder::Item::Type::FLOAT;
item.data.d = value;
} else {
static_assert(
std::is_integral<T>::value || std::is_floating_point<T>::value,
"Value type must be char, integral or floating point");
}
return item;
}
// ---------------------------------------------------------------------------
template Recorder&
Recorder::record<char const*>(std::string const& key, char const* value);
template Recorder&
Recorder::record<char>(std::string const& key, char value);
template Recorder&
Recorder::record<int32_t>(std::string const& key, int32_t value);
template Recorder&
Recorder::record<int64_t>(std::string const& key, int64_t value);
template Recorder&
Recorder::record<uint32_t>(std::string const& key, uint32_t value);
template Recorder&
Recorder::record<uint64_t>(std::string const& key, uint64_t value);
template Recorder&
Recorder::record<double>(std::string const& key, double value);
Recorder::Item::Item()
: type(Type::INIT), time(-1) {
}
std::string&&
Recorder::Item::toString() const {
char buffer[128];
std::string name(this->name);
std::string unit(this->unit);
unit = "[" + unit + "]";
snprintf(buffer, sizeof(buffer), "%ld %10s = ", this->time, name.c_str());
switch (this->type) {
case Type::CHAR:
sprintf(buffer, "%c", data.c);
break;
case Type::INT:
sprintf(buffer, "%ld", data.i);
break;
case Type::UINT:
sprintf(buffer, "%lu", data.u);
break;
case Type::FLOAT:
sprintf(buffer, "%f", data.d);
break;
case Type::STR:
{
std::string str(data.s, sizeof(data.s));
sprintf(buffer, "%s", str.c_str());
}
break;
default:
break;
}
snprintf(buffer, 2+sizeof(this->unit), "%s\n", unit.c_str());
return std::move(std::string(buffer));
}
Recorder::Item::Item(std::string const& n, std::string const& u)
: Item() {
if (n.length() > sizeof(name)) {
Error("Maximum size of parameter name 8 chars");
std::exit(1);
} else if (u.length() > sizeof(unit)) {
Error("Maximum size of parameter unit 8 chars");
std::exit(1);
}
std::strncpy(name, n.c_str(), sizeof(name));
std::strncpy(unit, u.c_str(), sizeof(unit));
}
Recorder::Recorder(uint64_t id, std::string const address)
: _send_buffer_index(0)
, _identifier(id)
, _socket_address(address)
{
_storage.reserve(256);
bool error = false;
if (Recorder::socket_context == nullptr) {
Error("Recorder: setContext() must be called before instantiation");
error = true;
}
if (_socket_address.empty()) {
Error("Recorder: Socket address empty, setAddress() must be called");
Error(" before first instantiation or provide local address");
Error(" using ctor Recorder(uint64_t, std::string)");
error = true;
}
if (error) {
std::exit(1);
}
constexpr int linger = 3000;
_socket.reset(new zmq::socket_t(*Recorder::socket_context, ZMQ_PUSH));
_socket->setsockopt(ZMQ_LINGER, &linger, sizeof(linger));
zmqutils::connect(_socket.get(), _socket_address);
}
Recorder::Recorder(uint64_t id)
: Recorder(id, Recorder::socket_address) {
}
Recorder::~Recorder() {
flushSendBuffer();
if (_socket) {
_socket->close();
}
}
Recorder&
Recorder::setup(std::string const& key, std::string const& unit) {
auto it = _storage.find(key);
if (it == _storage.end()) {
Item item(key, unit);
_storage.emplace(key, item);
} else {
// Ignore already setup parameters
}
return (*this);
}
template<typename T>
Recorder& Recorder::record(std::string const& key, T const value) {
auto const time = std::time(nullptr);
auto it = _storage.find(key);
if (it == _storage.end()) {
assert(0 && "Must use setup() prior to record()");
} else if (it->second.type == Item::Type::INIT) {
auto const item = createItem(it->second, time, value);
_storage[key] = item;
send(item);
} else if (memcmp(&value, &(it->second.data), sizeof(value)) != 0) {
auto const item = createItem(it->second, time, value);
it->second.time = time;
send(it->second);
_storage[key] = item;
send(item);
} else {
// Ignore unchanged value
}
return (*this);
}
void
Recorder::send(Item const& item) {
_send_buffer[_send_buffer_index++] = item;
if (_send_buffer_index == _send_buffer.max_size()) {
flushSendBuffer();
}
}
void
Recorder::flushSendBuffer() {
constexpr auto item_size = sizeof(decltype(_send_buffer)::value_type);
if (_send_buffer_index > 0) {
_socket->send(_send_buffer.data(), _send_buffer_index * item_size);
_send_buffer_index = 0;
}
}
void
Recorder::setContext(zmq::context_t* ctx) {
socket_context = ctx;
}
void
Recorder::setAddress(std::string addr) {
socket_address = addr;
}
zmq::context_t* Recorder::socket_context = nullptr;
std::string Recorder::socket_address = "";
<|endoftext|>
|
<commit_before>// Reselect.cpp
// Copyright (c) 2010, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "Reselect.h"
#include "interface/PropertyString.h"
#include "interface/PropertyInt.h"
static bool GetSketches(std::list<int>& sketches )
{
// check for at least one sketch selected
const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
{
HeeksObj* object = *It;
if(object->GetType() == SketchType)
{
sketches.push_back(object->m_id);
}
}
if(sketches.size() == 0)return false;
return true;
}
void ReselectSketches::Run()
{
std::list<int> sketches;
heeksCAD->PickObjects(_("Select Sketches"), MARKING_FILTER_SKETCH);
if(GetSketches( sketches ))
{
m_sketches->clear();
*m_sketches = sketches;
}
else
{
wxMessageBox(_("Select cancelled. No sketches were selected!"));
}
// get back to the operation's properties
heeksCAD->ClearMarkedList();
heeksCAD->Mark(m_object);
}
static bool GetSolids(std::list<int>& solids )
{
// check for at least one sketch selected
const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
{
HeeksObj* object = *It;
if(object->GetType() == SolidType || object->GetType() == StlSolidType)
{
solids.push_back(object->m_id);
}
}
if(solids.size() == 0)return false;
return true;
}
void ReselectSolids::Run()
{
std::list<int> solids;
heeksCAD->PickObjects(_("Select Solids"), MARKING_FILTER_SOLID | MARKING_FILTER_STL_SOLID);
if(GetSolids( solids ))
{
m_solids->clear();
*m_solids = solids;
}
else
{
wxMessageBox(_("Select cancelled. No solids were selected!"));
}
// get back to the operation's properties
heeksCAD->ClearMarkedList();
heeksCAD->Mark(m_object);
}
wxString GetIntListString(const std::list<int> &list)
{
wxString str;
int i = 0;
for(std::list<int>::const_iterator It = list.begin(); It != list.end(); It++, i++)
{
if(i > 0)str.Append(_T(" "));
if(i > 8)
{
str.Append(_T("..."));
break;
}
str.Append(wxString::Format(_T("%d"), *It));
}
return str;
}
void AddSolidsProperties(std::list<Property *> *list, std::list<int> &solids)
{
if(solids.size() == 0)list->push_back(new PropertyString(_("solids"), _("None"), NULL));
else if(solids.size() == 1)list->push_back(new PropertyInt(_("solid id"), solids.front(), NULL));
else list->push_back(new PropertyString(_("solids"), GetIntListString(solids), NULL));
}
void AddSketchesProperties(std::list<Property *> *list, std::list<int> &sketches)
{
if(sketches.size() == 0)list->push_back(new PropertyString(_("sketches"), _("None"), NULL));
else if(sketches.size() == 1)list->push_back(new PropertyInt(_("sketch id"), sketches.front(), NULL));
else list->push_back(new PropertyString(_("sketches"), GetIntListString(sketches), NULL));
}
<commit_msg>ReselectSketches wasn't working correctly.<commit_after>// Reselect.cpp
// Copyright (c) 2010, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "Reselect.h"
#include "interface/PropertyString.h"
#include "interface/PropertyInt.h"
#include "interface/ObjList.h"
static bool GetSketches(std::list<int>& sketches )
{
// check for at least one sketch selected
const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
{
HeeksObj* object = *It;
if(object->GetType() == SketchType)
{
sketches.push_back(object->m_id);
}
}
if(sketches.size() == 0)return false;
return true;
}
void ReselectSketches::Run()
{
std::list<int> sketches;
heeksCAD->PickObjects(_("Select Sketches"), MARKING_FILTER_SKETCH);
if(GetSketches( sketches ))
{
heeksCAD->CreateUndoPoint();
m_sketches->clear();
*m_sketches = sketches;
((ObjList*)m_object)->Clear();
m_object->ReloadPointers();
heeksCAD->Changed();
}
else
{
wxMessageBox(_("Select cancelled. No sketches were selected!"));
}
// get back to the operation's properties
heeksCAD->ClearMarkedList();
heeksCAD->Mark(m_object);
}
static bool GetSolids(std::list<int>& solids )
{
// check for at least one sketch selected
const std::list<HeeksObj*>& list = heeksCAD->GetMarkedList();
for(std::list<HeeksObj*>::const_iterator It = list.begin(); It != list.end(); It++)
{
HeeksObj* object = *It;
if(object->GetType() == SolidType || object->GetType() == StlSolidType)
{
solids.push_back(object->m_id);
}
}
if(solids.size() == 0)return false;
return true;
}
void ReselectSolids::Run()
{
std::list<int> solids;
heeksCAD->PickObjects(_("Select Solids"), MARKING_FILTER_SOLID | MARKING_FILTER_STL_SOLID);
if(GetSolids( solids ))
{
m_solids->clear();
*m_solids = solids;
}
else
{
wxMessageBox(_("Select cancelled. No solids were selected!"));
}
// get back to the operation's properties
heeksCAD->ClearMarkedList();
heeksCAD->Mark(m_object);
}
wxString GetIntListString(const std::list<int> &list)
{
wxString str;
int i = 0;
for(std::list<int>::const_iterator It = list.begin(); It != list.end(); It++, i++)
{
if(i > 0)str.Append(_T(" "));
if(i > 8)
{
str.Append(_T("..."));
break;
}
str.Append(wxString::Format(_T("%d"), *It));
}
return str;
}
void AddSolidsProperties(std::list<Property *> *list, std::list<int> &solids)
{
if(solids.size() == 0)list->push_back(new PropertyString(_("solids"), _("None"), NULL));
else if(solids.size() == 1)list->push_back(new PropertyInt(_("solid id"), solids.front(), NULL));
else list->push_back(new PropertyString(_("solids"), GetIntListString(solids), NULL));
}
void AddSketchesProperties(std::list<Property *> *list, std::list<int> &sketches)
{
if(sketches.size() == 0)list->push_back(new PropertyString(_("sketches"), _("None"), NULL));
else if(sketches.size() == 1)list->push_back(new PropertyInt(_("sketch id"), sketches.front(), NULL));
else list->push_back(new PropertyString(_("sketches"), GetIntListString(sketches), NULL));
}
<|endoftext|>
|
<commit_before>// Sh: A GPU metaprogramming language.
//
// Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory
// Project administrator: Michael D. McCool
// Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa,
// Michael D. McCool
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must
// not claim that you wrote the original software. If you use this
// software in a product, an acknowledgment in the product documentation
// would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <cassert>
#include "ShSyntax.hpp"
#include "ShEnvironment.hpp"
#include "ShTokenizer.hpp"
#include "ShToken.hpp"
#include "ShProgram.hpp"
#include "ShBackend.hpp"
#include "ShOptimizer.hpp"
namespace SH {
ShProgram shBeginShader(const std::string& target)
{
assert(!ShEnvironment::insideShader);
ShEnvironment::shader = new ShProgramNode(target);
ShEnvironment::insideShader = true;
return ShEnvironment::shader;
}
void shEndShader()
{
assert(ShEnvironment::insideShader);
ShEnvironment::shader->ctrlGraph = new ShCtrlGraph(ShEnvironment::shader->tokenizer.blockList());
ShOptimizer optimizer(ShEnvironment::shader->ctrlGraph);
optimizer.optimize(ShEnvironment::optimizationLevel);
ShEnvironment::shader->collectVariables();
ShEnvironment::insideShader = false;
if (!ShEnvironment::shader->target().empty()) {
shCompile(ShEnvironment::shader);
}
ShEnvironment::shader = 0;
}
void shCompile(ShProgram& prg)
{
if (!ShEnvironment::backend) return;
prg->compile(ShEnvironment::backend);
}
void shCompile(ShProgram& prg, const std::string& target)
{
if (!ShEnvironment::backend) return;
prg->compile(target, ShEnvironment::backend);
}
void shCompileShader(ShProgram& shader)
{
shCompile(shader);
}
void shCompileShader(const std::string& target, ShProgram& shader)
{
shCompile(shader, target);
}
void shBind(ShProgram& prg)
{
if (!ShEnvironment::backend) return;
prg->code(ShEnvironment::backend)->bind();
}
void shBind(ShProgram& prg, const std::string& target)
{
if (!ShEnvironment::backend) return;
prg->code(target, ShEnvironment::backend)->bind();
}
void shBindShader(ShProgram& shader)
{
shBind(shader);
}
void shBindShader(const std::string& target, ShProgram& shader)
{
shBind(shader, target);
}
bool shSetBackend(const std::string& name)
{
ShBackendPtr backend = SH::ShBackend::lookup(name);
if (!backend) return false;
SH::ShEnvironment::backend = backend;
return true;
}
void shIf(bool)
{
ShPointer<ShToken> token = new ShToken(SH_TOKEN_IF);
token->arguments.push_back(ShEnvironment::shader->tokenizer.getArgument());
ShEnvironment::shader->tokenizer.popArgQueue();
ShEnvironment::shader->tokenizer.blockList()->addBlock(token);
}
void shEndIf()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDIF));
}
void shElse()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ELSE));
}
void shWhile(bool)
{
ShPointer<ShToken> token = new ShToken(SH_TOKEN_WHILE);
token->arguments.push_back(ShEnvironment::shader->tokenizer.getArgument());
ShEnvironment::shader->tokenizer.popArgQueue();
ShEnvironment::shader->tokenizer.blockList()->addBlock(token);
}
void shEndWhile()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDWHILE));
}
void shDo()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_DO));
}
void shUntil(bool)
{
ShPointer<ShToken> token = new ShToken(SH_TOKEN_UNTIL);
token->arguments.push_back(ShEnvironment::shader->tokenizer.getArgument());
ShEnvironment::shader->tokenizer.popArgQueue();
ShEnvironment::shader->tokenizer.blockList()->addBlock(token);
}
void shFor(bool)
{
ShPointer<ShToken> token = new ShToken(SH_TOKEN_FOR);
for (int i = 0; i < 3; i++) {
token->arguments.push_back(ShEnvironment::shader->tokenizer.getArgument());
}
ShEnvironment::shader->tokenizer.popArgQueue();
ShEnvironment::shader->tokenizer.blockList()->addBlock(token);
}
void shEndFor()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDFOR));
}
void ShBreak()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_BREAK));
}
void ShContinue()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_CONTINUE));
}
}
<commit_msg>Fix issue105 (rename ShInit to shInit)<commit_after>// Sh: A GPU metaprogramming language.
//
// Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory
// Project administrator: Michael D. McCool
// Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa,
// Michael D. McCool
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must
// not claim that you wrote the original software. If you use this
// software in a product, an acknowledgment in the product documentation
// would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <cassert>
#include "ShSyntax.hpp"
#include "ShEnvironment.hpp"
#include "ShTokenizer.hpp"
#include "ShToken.hpp"
#include "ShProgram.hpp"
#include "ShBackend.hpp"
#include "ShOptimizer.hpp"
namespace SH {
ShProgram shBeginShader(const std::string& target)
{
assert(!ShEnvironment::insideShader);
ShEnvironment::shader = new ShProgramNode(target);
ShEnvironment::insideShader = true;
return ShEnvironment::shader;
}
void shEndShader()
{
assert(ShEnvironment::insideShader);
ShEnvironment::shader->ctrlGraph = new ShCtrlGraph(ShEnvironment::shader->tokenizer.blockList());
ShOptimizer optimizer(ShEnvironment::shader->ctrlGraph);
optimizer.optimize(ShEnvironment::optimizationLevel);
ShEnvironment::shader->collectVariables();
ShEnvironment::insideShader = false;
if (!ShEnvironment::shader->target().empty()) {
shCompile(ShEnvironment::shader);
}
ShEnvironment::shader = 0;
}
void shCompile(ShProgram& prg)
{
if (!ShEnvironment::backend) return;
prg->compile(ShEnvironment::backend);
}
void shCompile(ShProgram& prg, const std::string& target)
{
if (!ShEnvironment::backend) return;
prg->compile(target, ShEnvironment::backend);
}
void shCompileShader(ShProgram& shader)
{
shCompile(shader);
}
void shCompileShader(const std::string& target, ShProgram& shader)
{
shCompile(shader, target);
}
void shBind(ShProgram& prg)
{
if (!ShEnvironment::backend) return;
prg->code(ShEnvironment::backend)->bind();
}
void shBind(ShProgram& prg, const std::string& target)
{
if (!ShEnvironment::backend) return;
prg->code(target, ShEnvironment::backend)->bind();
}
void shBindShader(ShProgram& shader)
{
shBind(shader);
}
void shBindShader(const std::string& target, ShProgram& shader)
{
shBind(shader, target);
}
bool shSetBackend(const std::string& name)
{
ShBackendPtr backend = SH::ShBackend::lookup(name);
if (!backend) return false;
SH::ShEnvironment::backend = backend;
return true;
}
void shInit()
{
#ifdef WIN32
static SH::ShPointer<ShArb::ArbBackend> instance = new ShArb::ArbBackend();
#endif /* WIN32 */
}
void shIf(bool)
{
ShPointer<ShToken> token = new ShToken(SH_TOKEN_IF);
token->arguments.push_back(ShEnvironment::shader->tokenizer.getArgument());
ShEnvironment::shader->tokenizer.popArgQueue();
ShEnvironment::shader->tokenizer.blockList()->addBlock(token);
}
void shEndIf()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDIF));
}
void shElse()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ELSE));
}
void shWhile(bool)
{
ShPointer<ShToken> token = new ShToken(SH_TOKEN_WHILE);
token->arguments.push_back(ShEnvironment::shader->tokenizer.getArgument());
ShEnvironment::shader->tokenizer.popArgQueue();
ShEnvironment::shader->tokenizer.blockList()->addBlock(token);
}
void shEndWhile()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDWHILE));
}
void shDo()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_DO));
}
void shUntil(bool)
{
ShPointer<ShToken> token = new ShToken(SH_TOKEN_UNTIL);
token->arguments.push_back(ShEnvironment::shader->tokenizer.getArgument());
ShEnvironment::shader->tokenizer.popArgQueue();
ShEnvironment::shader->tokenizer.blockList()->addBlock(token);
}
void shFor(bool)
{
ShPointer<ShToken> token = new ShToken(SH_TOKEN_FOR);
for (int i = 0; i < 3; i++) {
token->arguments.push_back(ShEnvironment::shader->tokenizer.getArgument());
}
ShEnvironment::shader->tokenizer.popArgQueue();
ShEnvironment::shader->tokenizer.blockList()->addBlock(token);
}
void shEndFor()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_ENDFOR));
}
void ShBreak()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_BREAK));
}
void ShContinue()
{
ShEnvironment::shader->tokenizer.blockList()->addBlock(new ShToken(SH_TOKEN_CONTINUE));
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2014 Ableton AG, Berlin
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.
*/
// clang-format off
#pragma once
#if defined(__clang__)
#if __has_warning("-Wdouble-promotion")
#define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_DOUBLE_PROMOTION \
_Pragma("clang diagnostic ignored \"-Wdouble-promotion\"")
#else
#define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_DOUBLE_PROMOTION
#endif
#if __has_warning("-Wreserved-id-macro")
#define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_RESERVED_ID_MACRO \
_Pragma("clang diagnostic ignored \"-Wreserved-id-macro\"")
#else
#define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_RESERVED_ID_MACRO
#endif
#if __has_warning("-Wunused-local-typedef")
#define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_UNUSED_LOCAL_TYPEDEF \
_Pragma("clang diagnostic ignored \"-Wunused-local-typedef\"")
#else
#define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_UNUSED_LOCAL_TYPEDEF
#endif
#define SUPPRESS_WARNINGS \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wconditional-uninitialized\"") \
_Pragma("clang diagnostic ignored \"-Wconversion\"") \
_Pragma("clang diagnostic ignored \"-Wcovered-switch-default\"") \
_Pragma("clang diagnostic ignored \"-Wdeprecated\"") \
_Pragma("clang diagnostic ignored \"-Wdisabled-macro-expansion\"") \
_Pragma("clang diagnostic ignored \"-Wdocumentation-unknown-command\"") \
_Pragma("clang diagnostic ignored \"-Wdocumentation\"") \
_Pragma("clang diagnostic ignored \"-Wexit-time-destructors\"") \
_Pragma("clang diagnostic ignored \"-Wextra-semi\"") \
_Pragma("clang diagnostic ignored \"-Wfloat-equal\"") \
_Pragma("clang diagnostic ignored \"-Wglobal-constructors\"") \
_Pragma("clang diagnostic ignored \"-Wheader-hygiene\"") \
_Pragma("clang diagnostic ignored \"-Wmissing-noreturn\"") \
_Pragma("clang diagnostic ignored \"-Wmissing-prototypes\"") \
_Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \
_Pragma("clang diagnostic ignored \"-Wpadded\"") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
_Pragma("clang diagnostic ignored \"-Wshift-sign-overflow\"") \
_Pragma("clang diagnostic ignored \"-Wshorten-64-to-32\"") \
_Pragma("clang diagnostic ignored \"-Wsign-compare\"") \
_Pragma("clang diagnostic ignored \"-Wsign-conversion\"") \
_Pragma("clang diagnostic ignored \"-Wswitch-enum\"") \
_Pragma("clang diagnostic ignored \"-Wundef\"") \
_Pragma("clang diagnostic ignored \"-Wundefined-reinterpret-cast\"") \
_Pragma("clang diagnostic ignored \"-Wunreachable-code\"") \
_Pragma("clang diagnostic ignored \"-Wunused-parameter\"") \
_Pragma("clang diagnostic ignored \"-Wused-but-marked-unused\"") \
_Pragma("clang diagnostic ignored \"-Wweak-vtables\"") \
ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_DOUBLE_PROMOTION \
ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_RESERVED_ID_MACRO \
ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_UNUSED_LOCAL_TYPEDEF
#define RESTORE_WARNINGS \
_Pragma("clang diagnostic pop")
#elif defined(_MSC_VER)
#if _MSC_VER < 1900
#define ABL_PRAGMA_DISABLE_MSVC_1900_WARNINGS
#else
/**
* C4459: declaration of 'parameter' hides global declaration
*/
#define ABL_PRAGMA_DISABLE_MSVC_1900_WARNINGS \
__pragma(warning(disable: 4459))
#endif
/**
* C4100: 'identifier' : unreferenced formal parameter
* C4127: conditional expression is constant
* C4191: 'type cast' : unsafe conversion from 'function pointer type' to 'function pointer type'
* Calling this function through the result pointer may cause your program to fail
* C4242: 'identifier' : conversion from 'type1' to 'type2', possible loss of data
* C4244: 'conversion' conversion from 'type1' to 'type2', possible loss of data
* C4251: 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2'
* C4365: 'action' : conversion from 'type_1' to 'type_2', signed/unsigned mismatch
* C4388: signed/unsigned mismatch
* C4459: declaration of 'identifier' hides global declaration
* C4555: expression has no effect; expected expression with side-effect
* C4619: #pragma warning : there is no warning number 'number'
* C4628: digraphs not supported with -Ze. Character sequence 'digraph' not interpreted as alternate token for 'char'
* C4640: 'instance' : construction of local static object is not thread-safe
* C4668: 'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives'
* C4714: function 'function' marked as __forceinline not inlined
* C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning)
* C4826: Conversion from 'type1 ' to 'type_2' is sign-extended. This may cause unexpected runtime behavior.
*/
#define SUPPRESS_WARNINGS \
__pragma(warning(push)) \
__pragma(warning(disable: 4100)) \
__pragma(warning(disable: 4127)) \
__pragma(warning(disable: 4191)) \
__pragma(warning(disable: 4242)) \
__pragma(warning(disable: 4244)) \
__pragma(warning(disable: 4251)) \
__pragma(warning(disable: 4267)) \
__pragma(warning(disable: 4365)) \
__pragma(warning(disable: 4388)) \
__pragma(warning(disable: 4510)) \
__pragma(warning(disable: 4555)) \
__pragma(warning(disable: 4610)) \
__pragma(warning(disable: 4619)) \
__pragma(warning(disable: 4628)) \
__pragma(warning(disable: 4640)) \
__pragma(warning(disable: 4668)) \
__pragma(warning(disable: 4714)) \
__pragma(warning(disable: 4800)) \
__pragma(warning(disable: 4826)) \
ABL_PRAGMA_DISABLE_MSVC_1900_WARNINGS
#define RESTORE_WARNINGS \
__pragma(warning(pop))
#elif defined(__GNUC__)
#define SUPPRESS_WARNINGS _Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") \
_Pragma("GCC diagnostic ignored \"-Wsign-compare\"")
#define RESTORE_WARNINGS _Pragma("GCC diagnostic pop")
#else
#define SUPPRESS_WARNINGS
#define RESTORE_WARNINGS
#endif
<commit_msg>Disable C5031 warning for VS2015<commit_after>/*
Copyright (c) 2014 Ableton AG, Berlin
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.
*/
// clang-format off
#pragma once
#if defined(__clang__)
#if __has_warning("-Wdouble-promotion")
#define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_DOUBLE_PROMOTION \
_Pragma("clang diagnostic ignored \"-Wdouble-promotion\"")
#else
#define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_DOUBLE_PROMOTION
#endif
#if __has_warning("-Wreserved-id-macro")
#define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_RESERVED_ID_MACRO \
_Pragma("clang diagnostic ignored \"-Wreserved-id-macro\"")
#else
#define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_RESERVED_ID_MACRO
#endif
#if __has_warning("-Wunused-local-typedef")
#define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_UNUSED_LOCAL_TYPEDEF \
_Pragma("clang diagnostic ignored \"-Wunused-local-typedef\"")
#else
#define ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_UNUSED_LOCAL_TYPEDEF
#endif
#define SUPPRESS_WARNINGS \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wconditional-uninitialized\"") \
_Pragma("clang diagnostic ignored \"-Wconversion\"") \
_Pragma("clang diagnostic ignored \"-Wcovered-switch-default\"") \
_Pragma("clang diagnostic ignored \"-Wdeprecated\"") \
_Pragma("clang diagnostic ignored \"-Wdisabled-macro-expansion\"") \
_Pragma("clang diagnostic ignored \"-Wdocumentation-unknown-command\"") \
_Pragma("clang diagnostic ignored \"-Wdocumentation\"") \
_Pragma("clang diagnostic ignored \"-Wexit-time-destructors\"") \
_Pragma("clang diagnostic ignored \"-Wextra-semi\"") \
_Pragma("clang diagnostic ignored \"-Wfloat-equal\"") \
_Pragma("clang diagnostic ignored \"-Wglobal-constructors\"") \
_Pragma("clang diagnostic ignored \"-Wheader-hygiene\"") \
_Pragma("clang diagnostic ignored \"-Wmissing-noreturn\"") \
_Pragma("clang diagnostic ignored \"-Wmissing-prototypes\"") \
_Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \
_Pragma("clang diagnostic ignored \"-Wpadded\"") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
_Pragma("clang diagnostic ignored \"-Wshift-sign-overflow\"") \
_Pragma("clang diagnostic ignored \"-Wshorten-64-to-32\"") \
_Pragma("clang diagnostic ignored \"-Wsign-compare\"") \
_Pragma("clang diagnostic ignored \"-Wsign-conversion\"") \
_Pragma("clang diagnostic ignored \"-Wswitch-enum\"") \
_Pragma("clang diagnostic ignored \"-Wundef\"") \
_Pragma("clang diagnostic ignored \"-Wundefined-reinterpret-cast\"") \
_Pragma("clang diagnostic ignored \"-Wunreachable-code\"") \
_Pragma("clang diagnostic ignored \"-Wunused-parameter\"") \
_Pragma("clang diagnostic ignored \"-Wused-but-marked-unused\"") \
_Pragma("clang diagnostic ignored \"-Wweak-vtables\"") \
ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_DOUBLE_PROMOTION \
ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_RESERVED_ID_MACRO \
ABL_PRAGMA_CLANG_DIAGNOSTIC_IGNORED_UNUSED_LOCAL_TYPEDEF
#define RESTORE_WARNINGS \
_Pragma("clang diagnostic pop")
#elif defined(_MSC_VER)
#if _MSC_VER < 1900
#define ABL_PRAGMA_DISABLE_MSVC_1900_WARNINGS
#else
/**
* C4459: declaration of 'parameter' hides global declaration
* C5031: #pragma warning(pop): likely mismatch, popping warning state pushed in different file (compiling source file <file>)
*/
#define ABL_PRAGMA_DISABLE_MSVC_1900_WARNINGS \
__pragma(warning(disable: 4459)) \
__pragma(warning(disable: 5031))
#endif
/**
* C4100: 'identifier' : unreferenced formal parameter
* C4127: conditional expression is constant
* C4191: 'type cast' : unsafe conversion from 'function pointer type' to 'function pointer type'
* Calling this function through the result pointer may cause your program to fail
* C4242: 'identifier' : conversion from 'type1' to 'type2', possible loss of data
* C4244: 'conversion' conversion from 'type1' to 'type2', possible loss of data
* C4251: 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2'
* C4365: 'action' : conversion from 'type_1' to 'type_2', signed/unsigned mismatch
* C4388: signed/unsigned mismatch
* C4459: declaration of 'identifier' hides global declaration
* C4555: expression has no effect; expected expression with side-effect
* C4619: #pragma warning : there is no warning number 'number'
* C4628: digraphs not supported with -Ze. Character sequence 'digraph' not interpreted as alternate token for 'char'
* C4640: 'instance' : construction of local static object is not thread-safe
* C4668: 'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives'
* C4714: function 'function' marked as __forceinline not inlined
* C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning)
* C4826: Conversion from 'type1 ' to 'type_2' is sign-extended. This may cause unexpected runtime behavior.
*/
#define SUPPRESS_WARNINGS \
__pragma(warning(push)) \
__pragma(warning(disable: 4100)) \
__pragma(warning(disable: 4127)) \
__pragma(warning(disable: 4191)) \
__pragma(warning(disable: 4242)) \
__pragma(warning(disable: 4244)) \
__pragma(warning(disable: 4251)) \
__pragma(warning(disable: 4267)) \
__pragma(warning(disable: 4365)) \
__pragma(warning(disable: 4388)) \
__pragma(warning(disable: 4510)) \
__pragma(warning(disable: 4555)) \
__pragma(warning(disable: 4610)) \
__pragma(warning(disable: 4619)) \
__pragma(warning(disable: 4628)) \
__pragma(warning(disable: 4640)) \
__pragma(warning(disable: 4668)) \
__pragma(warning(disable: 4714)) \
__pragma(warning(disable: 4800)) \
__pragma(warning(disable: 4826)) \
ABL_PRAGMA_DISABLE_MSVC_1900_WARNINGS
#define RESTORE_WARNINGS \
__pragma(warning(pop))
#elif defined(__GNUC__)
#define SUPPRESS_WARNINGS _Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") \
_Pragma("GCC diagnostic ignored \"-Wsign-compare\"")
#define RESTORE_WARNINGS _Pragma("GCC diagnostic pop")
#else
#define SUPPRESS_WARNINGS
#define RESTORE_WARNINGS
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015-2018 dubalu.com LLC. All rights reserved.
*
* 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 "xapiand.h"
#include "allocator.h"
#ifdef XAPIAND_TRACKED_MEM
#include <atomic> // for std::atomic_llong
#include <cassert> // for assert
#include <cstdlib> // for std::malloc, std::free
#include <functional> // for std::hash
#include <mutex> // for std::mutex
#include <new> // for std::nothrow_t, std::new_handler
#include <thread> // for std::this_thread
#include <unordered_map> // for std::unordered_map
#include <utility> // for std::make_pair
#if defined(_MSC_VER) || (defined(__GNUC__) && __GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || (defined(__llvm__) && !defined(_LIBCPP_VERSION))
# define HAS_THREAD_LOCAL
#elif defined(__clang__)
# if __has_feature(cxx_thread_local)
# define HAS_THREAD_LOCAL
# endif
#endif
#if defined(__FreeBSD__) && (__FreeBSD__ < 11) //Bug in freeBSD lower that 11v. Use of thread_local produces linking error
# undef HAS_THREAD_LOCAL
#endif
namespace allocator {
// allocate/deallocate using ::malloc/::free
void* allocate(std::size_t size) noexcept {
if (size == 0) {
size = 1;
}
void* p;
while ((p = std::malloc(size)) == 0) {
// If malloc fails and there is a new_handler, call it to try free up memory.
std::new_handler nh = std::get_new_handler();
if (nh) {
nh();
} else {
break;
}
}
return p;
}
void deallocate(void* p) noexcept {
if (p) {
std::free(p);
}
}
// VanillaAllocator
void* VanillaAllocator::allocate(std::size_t size) noexcept {
void* p = ::allocator::allocate(size + sizeof(std::size_t));
if (!p) return nullptr;
// fprintf(stderr, "[allocated %zu bytes]\n", size);
return p;
}
void VanillaAllocator::deallocate(void* p) noexcept {
if (p) {
::allocator::deallocate(p);
// fprintf(stderr, "[freed]\n");
}
}
// TrackedAllocator
std::atomic_llong& _total_allocated() noexcept {
static std::atomic_llong t_allocated;
return t_allocated;
}
#ifdef HAS_THREAD_LOCAL
static long long& _local_allocated() noexcept {
thread_local static long long l_allocated;
return l_allocated;
}
long long local_allocated() noexcept {
return _local_allocated();
}
#else
static std::mutex tracked_mutex;
static std::unordered_map<
std::thread::id,
long long,
std::hash<std::thread::id>,
std::equal_to<std::thread::id>,
allocator<std::pair<const std::thread::id, long long>, VanillaAllocator>
> tracked_sizes;
static long long& __local_allocated() noexcept {
const auto id = std::this_thread::get_id();
auto it = tracked_sizes.find(id);
if (it != tracked_sizes.end()) return it->second;
auto& l_allocated = tracked_sizes.emplace(id, 0).first->second;
return l_allocated;
}
static long long& _local_allocated() noexcept {
std::lock_guard<std::mutex> lock(tracked_mutex);
return __local_allocated();
}
long long local_allocated() noexcept {
std::lock_guard<std::mutex> lock(tracked_mutex);
std::size_t l_allocated = __local_allocated();
return l_allocated;
}
#endif
long long total_allocated() noexcept {
return _total_allocated();
}
void* TrackedAllocator::allocate(std::size_t size) noexcept {
void* p = ::allocator::allocate(size + sizeof(std::size_t));
if (!p) return nullptr;
auto& t_allocated = _total_allocated();
auto& l_allocated = _local_allocated();
t_allocated += size;
l_allocated += size;
*static_cast<std::size_t*>(p) = size;
// fprintf(stderr, "[allocated %zu bytes, %lld [%lld] are now allocated]\n", size, l_allocated, t_allocated.load());
return static_cast<char*>(p) + sizeof(std::size_t);
}
void TrackedAllocator::deallocate(void* p) noexcept {
if (p) {
p = static_cast<char*>(p) - sizeof(std::size_t);
std::size_t size = *static_cast<std::size_t*>(p);
auto& t_allocated = _total_allocated();
auto& l_allocated = _local_allocated();
t_allocated -= size;
l_allocated -= size;
::allocator::deallocate(p);
// fprintf(stderr, "[freed %zu bytes, %lld [%lld] remain allocated]\n", size, l_allocated, t_allocated.load());
}
}
}
// Operators overload for tracking
void* operator new(std::size_t size) noexcept(false) {
void* p = allocator::TrackedAllocator::allocate(size);
if (!p) {
static const std::bad_alloc nomem;
throw nomem;
}
return p;
}
void* operator new(std::size_t size, const std::nothrow_t&) noexcept {
return allocator::TrackedAllocator::allocate(size);
}
void* operator new[](std::size_t size) noexcept(false) {
void* p = allocator::TrackedAllocator::allocate(size);
if (!p) {
static const std::bad_alloc nomem;
throw nomem;
}
return p;
}
void* operator new[](std::size_t size, const std::nothrow_t&) noexcept {
return allocator::TrackedAllocator::allocate(size);
}
void operator delete(void* p) noexcept {
return allocator::TrackedAllocator::deallocate(p);
}
void operator delete[](void* p) noexcept {
return allocator::TrackedAllocator::deallocate(p);
}
#else /* XAPIAND_TRACKED_MEM */
namespace allocator {
long long total_allocated() noexcept {
return 0;
}
long long local_allocated() noexcept {
return 0;
}
}
#endif
<commit_msg>Allocator: Pointer arithmetic using size_t<commit_after>/*
* Copyright (C) 2015-2018 dubalu.com LLC. All rights reserved.
*
* 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 "xapiand.h"
#include "allocator.h"
#ifdef XAPIAND_TRACKED_MEM
#include <atomic> // for std::atomic_llong
#include <cassert> // for assert
#include <cstdlib> // for std::malloc, std::free
#include <functional> // for std::hash
#include <mutex> // for std::mutex
#include <new> // for std::nothrow_t, std::new_handler
#include <thread> // for std::this_thread
#include <unordered_map> // for std::unordered_map
#include <utility> // for std::make_pair
#if defined(_MSC_VER) || (defined(__GNUC__) && __GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || (defined(__llvm__) && !defined(_LIBCPP_VERSION))
# define HAS_THREAD_LOCAL
#elif defined(__clang__)
# if __has_feature(cxx_thread_local)
# define HAS_THREAD_LOCAL
# endif
#endif
#if defined(__FreeBSD__) && (__FreeBSD__ < 11) //Bug in freeBSD lower that 11v. Use of thread_local produces linking error
# undef HAS_THREAD_LOCAL
#endif
namespace allocator {
// allocate/deallocate using ::malloc/::free
void* allocate(std::size_t size) noexcept {
if (size == 0) {
size = 1;
}
void* p;
while ((p = std::malloc(size)) == 0) {
// If malloc fails and there is a new_handler, call it to try free up memory.
std::new_handler nh = std::get_new_handler();
if (nh) {
nh();
} else {
break;
}
}
return p;
}
void deallocate(void* p) noexcept {
if (p) {
std::free(p);
}
}
// VanillaAllocator
void* VanillaAllocator::allocate(std::size_t size) noexcept {
void* p = ::allocator::allocate(size + sizeof(std::size_t));
if (!p) return nullptr;
// fprintf(stderr, "[allocated %zu bytes]\n", size);
return p;
}
void VanillaAllocator::deallocate(void* p) noexcept {
if (p) {
::allocator::deallocate(p);
// fprintf(stderr, "[freed]\n");
}
}
// TrackedAllocator
std::atomic_llong& _total_allocated() noexcept {
static std::atomic_llong t_allocated;
return t_allocated;
}
#ifdef HAS_THREAD_LOCAL
static long long& _local_allocated() noexcept {
thread_local static long long l_allocated;
return l_allocated;
}
long long local_allocated() noexcept {
return _local_allocated();
}
#else
static std::mutex tracked_mutex;
static std::unordered_map<
std::thread::id,
long long,
std::hash<std::thread::id>,
std::equal_to<std::thread::id>,
allocator<std::pair<const std::thread::id, long long>, VanillaAllocator>
> tracked_sizes;
static long long& __local_allocated() noexcept {
const auto id = std::this_thread::get_id();
auto it = tracked_sizes.find(id);
if (it != tracked_sizes.end()) return it->second;
auto& l_allocated = tracked_sizes.emplace(id, 0).first->second;
return l_allocated;
}
static long long& _local_allocated() noexcept {
std::lock_guard<std::mutex> lock(tracked_mutex);
return __local_allocated();
}
long long local_allocated() noexcept {
std::lock_guard<std::mutex> lock(tracked_mutex);
std::size_t l_allocated = __local_allocated();
return l_allocated;
}
#endif
long long total_allocated() noexcept {
return _total_allocated();
}
void* TrackedAllocator::allocate(std::size_t size) noexcept {
void* p = ::allocator::allocate(size + sizeof(std::size_t));
if (!p) return nullptr;
auto& t_allocated = _total_allocated();
auto& l_allocated = _local_allocated();
t_allocated += size;
l_allocated += size;
*static_cast<std::size_t*>(p) = size;
p = static_cast<std::size_t*>(p) + 1;
// fprintf(stderr, "[allocated %zu bytes, %lld [%lld] are now allocated]\n", size, l_allocated, t_allocated.load());
return p;
}
void TrackedAllocator::deallocate(void* p) noexcept {
if (p) {
p = static_cast<std::size_t*>(p) - 1;
std::size_t size = *static_cast<std::size_t*>(p);
auto& t_allocated = _total_allocated();
auto& l_allocated = _local_allocated();
t_allocated -= size;
l_allocated -= size;
::allocator::deallocate(p);
// fprintf(stderr, "[freed %zu bytes, %lld [%lld] remain allocated]\n", size, l_allocated, t_allocated.load());
}
}
}
// Operators overload for tracking
void* operator new(std::size_t size) noexcept(false) {
void* p = allocator::TrackedAllocator::allocate(size);
if (!p) {
static const std::bad_alloc nomem;
throw nomem;
}
return p;
}
void* operator new(std::size_t size, const std::nothrow_t&) noexcept {
return allocator::TrackedAllocator::allocate(size);
}
void* operator new[](std::size_t size) noexcept(false) {
void* p = allocator::TrackedAllocator::allocate(size);
if (!p) {
static const std::bad_alloc nomem;
throw nomem;
}
return p;
}
void* operator new[](std::size_t size, const std::nothrow_t&) noexcept {
return allocator::TrackedAllocator::allocate(size);
}
void operator delete(void* p) noexcept {
return allocator::TrackedAllocator::deallocate(p);
}
void operator delete[](void* p) noexcept {
return allocator::TrackedAllocator::deallocate(p);
}
#else /* XAPIAND_TRACKED_MEM */
namespace allocator {
long long total_allocated() noexcept {
return 0;
}
long long local_allocated() noexcept {
return 0;
}
}
#endif
<|endoftext|>
|
<commit_before>///
/// @file help.cpp
///
/// Copyright (C) 2016 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
namespace {
const string helpMenu(
"Usage: primecount x [OPTION]...\n"
"Count the primes below x <= 10^31 using fast implementations of the\n"
"combinatorial prime counting function.\n"
"\n"
"Options:\n"
"\n"
" -d, --deleglise_rivat Count primes using Deleglise-Rivat algorithm\n"
" --legendre Count primes using Legendre's formula\n"
" --lehmer Count primes using Lehmer's formula\n"
" -l, --lmo Count primes using Lagarias-Miller-Odlyzko\n"
" -m, --meissel Count primes using Meissel's formula\n"
" --Li Approximate pi(x) using the logarithmic integral\n"
" --Li_inverse Approximate the nth prime using Li^-1(x)\n"
" -n, --nthprime Calculate the nth prime\n"
" -p, --primesieve Count primes using the sieve of Eratosthenes\n"
" -s[N], --status[=N] Show computation progress 1%, 2%, 3%, ...\n"
" [N] digits after decimal point e.g. N=1, 99.9%\n"
" --test Run various correctness tests and exit\n"
" --time Print the time elapsed in seconds\n"
" -t<N>, --threads=<N> Set the number of threads, 1 <= N <= CPU cores\n"
" -v, --version Print version and license information\n"
" -h, --help Print this help menu\n"
"\n"
"Advanced Deleglise-Rivat options:\n"
"\n"
" -a<N>, --alpha=<N> Tuning factor, 1 <= alpha <= x^(1/6)\n"
" --P2 Only compute the 2nd partial sieve function\n"
" --S1 Only compute the ordinary leaves\n"
" --S2_trivial Only compute the trivial special leaves\n"
" --S2_easy Only compute the easy special leaves\n"
" --S2_hard Only compute the hard special leaves\n"
"\n"
"Examples:\n"
"\n"
" primecount 1e13\n"
" primecount 1e13 --nthprime --threads=4"
);
const string versionInfo(
"primecount " PRIMECOUNT_VERSION ", <https://github.com/kimwalisch/primecount>\n"
"Copyright (C) 2016 Kim Walisch\n"
"BSD 2-Clause License <http://opensource.org/licenses/BSD-2-Clause>"
);
} // end namespace
namespace primecount {
void help()
{
cout << helpMenu << endl;
exit(1);
}
void version()
{
cout << versionInfo << endl;
exit(1);
}
} // namespace
<commit_msg>Update copyright year<commit_after>///
/// @file help.cpp
///
/// Copyright (C) 2016 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount.hpp>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
namespace {
const string helpMenu(
"Usage: primecount x [OPTION]...\n"
"Count the primes below x <= 10^31 using fast implementations of the\n"
"combinatorial prime counting function.\n"
"\n"
"Options:\n"
"\n"
" -d, --deleglise_rivat Count primes using Deleglise-Rivat algorithm\n"
" --legendre Count primes using Legendre's formula\n"
" --lehmer Count primes using Lehmer's formula\n"
" -l, --lmo Count primes using Lagarias-Miller-Odlyzko\n"
" -m, --meissel Count primes using Meissel's formula\n"
" --Li Approximate pi(x) using the logarithmic integral\n"
" --Li_inverse Approximate the nth prime using Li^-1(x)\n"
" -n, --nthprime Calculate the nth prime\n"
" -p, --primesieve Count primes using the sieve of Eratosthenes\n"
" -s[N], --status[=N] Show computation progress 1%, 2%, 3%, ...\n"
" [N] digits after decimal point e.g. N=1, 99.9%\n"
" --test Run various correctness tests and exit\n"
" --time Print the time elapsed in seconds\n"
" -t<N>, --threads=<N> Set the number of threads, 1 <= N <= CPU cores\n"
" -v, --version Print version and license information\n"
" -h, --help Print this help menu\n"
"\n"
"Advanced Deleglise-Rivat options:\n"
"\n"
" -a<N>, --alpha=<N> Tuning factor, 1 <= alpha <= x^(1/6)\n"
" --P2 Only compute the 2nd partial sieve function\n"
" --S1 Only compute the ordinary leaves\n"
" --S2_trivial Only compute the trivial special leaves\n"
" --S2_easy Only compute the easy special leaves\n"
" --S2_hard Only compute the hard special leaves\n"
"\n"
"Examples:\n"
"\n"
" primecount 1e13\n"
" primecount 1e13 --nthprime --threads=4"
);
const string versionInfo(
"primecount " PRIMECOUNT_VERSION ", <https://github.com/kimwalisch/primecount>\n"
"Copyright (C) 2013 - 2017 Kim Walisch\n"
"BSD 2-Clause License <http://opensource.org/licenses/BSD-2-Clause>"
);
} // end namespace
namespace primecount {
void help()
{
cout << helpMenu << endl;
exit(1);
}
void version()
{
cout << versionInfo << endl;
exit(1);
}
} // namespace
<|endoftext|>
|
<commit_before>// builds all boost.asio SSL source as a separate compilation unit
#include <boost/version.hpp>
#if BOOST_VERSION >= 104610
#include <boost/asio/ssl/impl/src.hpp>
#endif
<commit_msg>fix openssl build for shared libraries on non msvc-compilers<commit_after>// builds all boost.asio SSL source as a separate compilation unit
#include <boost/version.hpp>
#ifndef BOOST_ASIO_SOURCE
#define BOOST_ASIO_SOURCE
#endif
#include "libtorrent/config.hpp"
#define TORRENT_HAS_ASIO_DECL x ## BOOST_ASIO_DECL
// only define BOOST_ASIO_DECL if it hasn't already been defined
// or if it has been defined to an empty string
#if TORRENT_HAS_ASIO_DECL == x
#define BOOST_ASIO_DECL BOOST_SYMBOL_EXPORT
#endif
#if BOOST_VERSION >= 104610
#include <boost/asio/ssl/impl/src.hpp>
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright 2007-2017 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 "balancer.hxx"
#include "address_list.hxx"
#include "net/SocketAddress.hxx"
#include "net/FailureManager.hxx"
#include "bulldog.hxx"
#include <string>
#include <assert.h>
static bool
check_failure(FailureManager &failure_manager, Expiry now,
const SocketAddress address, bool allow_fade)
{
enum failure_status status = failure_manager.Get(now, address);
if (status == FAILURE_FADE && allow_fade)
status = FAILURE_OK;
return status == FAILURE_OK;
}
gcc_pure
static bool
check_bulldog(const SocketAddress address, bool allow_fade)
{
return bulldog_check(address) &&
(allow_fade || !bulldog_is_fading(address));
}
static bool
CheckAddress(FailureManager &failure_manager, Expiry now,
const SocketAddress address, bool allow_fade)
{
return check_failure(failure_manager, now, address, allow_fade) &&
check_bulldog(address, allow_fade);
}
static SocketAddress
next_failover_address(FailureManager &failure_manager, Expiry now,
const AddressList &list)
{
assert(list.GetSize() > 0);
for (auto i : list)
if (CheckAddress(failure_manager, now, i, true))
return i;
/* none available - return first node as last resort */
return list[0];
}
const SocketAddress &
Balancer::Item::NextAddress(const AddressList &addresses)
{
assert(addresses.GetSize() >= 2);
assert(next < addresses.GetSize());
const SocketAddress &address = addresses[next];
++next;
if (next >= addresses.GetSize())
next = 0;
return address;
}
const SocketAddress &
Balancer::Item::NextAddressChecked(FailureManager &_failure_manager,
const Expiry now,
const AddressList &addresses,
bool allow_fade)
{
const auto &first = NextAddress(addresses);
const SocketAddress *ret = &first;
do {
if (CheckAddress(_failure_manager, now, *ret, allow_fade))
return *ret;
ret = &NextAddress(addresses);
} while (ret != &first);
/* all addresses failed: */
return first;
}
static const SocketAddress &
next_sticky_address_checked(FailureManager &failure_manager, const Expiry now,
const AddressList &al, sticky_hash_t sticky_hash)
{
assert(al.GetSize() >= 2);
unsigned i = sticky_hash % al.GetSize();
bool allow_fade = true;
const SocketAddress &first = al[i];
const SocketAddress *ret = &first;
do {
if (CheckAddress(failure_manager, now, *ret, allow_fade))
return *ret;
/* only the first iteration is allowed to override
FAILURE_FADE */
allow_fade = false;
++i;
if (i >= al.GetSize())
i = 0;
ret = &al[i];
} while (ret != &first);
/* all addresses failed: */
return first;
}
SocketAddress
Balancer::Get(const Expiry now,
const AddressList &list, sticky_hash_t sticky_hash) noexcept
{
if (list.IsSingle())
return list[0];
switch (list.sticky_mode) {
case StickyMode::NONE:
break;
case StickyMode::FAILOVER:
return next_failover_address(failure_manager, now, list);
case StickyMode::SOURCE_IP:
case StickyMode::HOST:
case StickyMode::XHOST:
case StickyMode::SESSION_MODULO:
case StickyMode::COOKIE:
case StickyMode::JVM_ROUTE:
if (sticky_hash != 0)
return next_sticky_address_checked(failure_manager, now, list,
sticky_hash);
break;
}
std::string key = list.GetKey();
auto *item = cache.Get(key);
if (item == nullptr)
/* create a new cache item */
item = &cache.Put(std::move(key), Item());
return item->NextAddressChecked(failure_manager, now, list,
list.sticky_mode == StickyMode::NONE);
}
<commit_msg>balancer: use FailureManager::Check()<commit_after>/*
* Copyright 2007-2017 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 "balancer.hxx"
#include "address_list.hxx"
#include "net/SocketAddress.hxx"
#include "net/FailureManager.hxx"
#include "bulldog.hxx"
#include <string>
#include <assert.h>
gcc_pure
static bool
check_bulldog(const SocketAddress address, bool allow_fade)
{
return bulldog_check(address) &&
(allow_fade || !bulldog_is_fading(address));
}
static bool
CheckAddress(FailureManager &failure_manager, Expiry now,
const SocketAddress address, bool allow_fade)
{
return failure_manager.Check(now, address, allow_fade) &&
check_bulldog(address, allow_fade);
}
static SocketAddress
next_failover_address(FailureManager &failure_manager, Expiry now,
const AddressList &list)
{
assert(list.GetSize() > 0);
for (auto i : list)
if (CheckAddress(failure_manager, now, i, true))
return i;
/* none available - return first node as last resort */
return list[0];
}
const SocketAddress &
Balancer::Item::NextAddress(const AddressList &addresses)
{
assert(addresses.GetSize() >= 2);
assert(next < addresses.GetSize());
const SocketAddress &address = addresses[next];
++next;
if (next >= addresses.GetSize())
next = 0;
return address;
}
const SocketAddress &
Balancer::Item::NextAddressChecked(FailureManager &_failure_manager,
const Expiry now,
const AddressList &addresses,
bool allow_fade)
{
const auto &first = NextAddress(addresses);
const SocketAddress *ret = &first;
do {
if (CheckAddress(_failure_manager, now, *ret, allow_fade))
return *ret;
ret = &NextAddress(addresses);
} while (ret != &first);
/* all addresses failed: */
return first;
}
static const SocketAddress &
next_sticky_address_checked(FailureManager &failure_manager, const Expiry now,
const AddressList &al, sticky_hash_t sticky_hash)
{
assert(al.GetSize() >= 2);
unsigned i = sticky_hash % al.GetSize();
bool allow_fade = true;
const SocketAddress &first = al[i];
const SocketAddress *ret = &first;
do {
if (CheckAddress(failure_manager, now, *ret, allow_fade))
return *ret;
/* only the first iteration is allowed to override
FAILURE_FADE */
allow_fade = false;
++i;
if (i >= al.GetSize())
i = 0;
ret = &al[i];
} while (ret != &first);
/* all addresses failed: */
return first;
}
SocketAddress
Balancer::Get(const Expiry now,
const AddressList &list, sticky_hash_t sticky_hash) noexcept
{
if (list.IsSingle())
return list[0];
switch (list.sticky_mode) {
case StickyMode::NONE:
break;
case StickyMode::FAILOVER:
return next_failover_address(failure_manager, now, list);
case StickyMode::SOURCE_IP:
case StickyMode::HOST:
case StickyMode::XHOST:
case StickyMode::SESSION_MODULO:
case StickyMode::COOKIE:
case StickyMode::JVM_ROUTE:
if (sticky_hash != 0)
return next_sticky_address_checked(failure_manager, now, list,
sticky_hash);
break;
}
std::string key = list.GetKey();
auto *item = cache.Get(key);
if (item == nullptr)
/* create a new cache item */
item = &cache.Put(std::move(key), Item());
return item->NextAddressChecked(failure_manager, now, list,
list.sticky_mode == StickyMode::NONE);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdio.h>
#include <ctype.h>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>
using namespace std;
void parse(char x[], vector<string> &v){
//cout << "parse executes" << endl;
char* tmp;
tmp = strtok(x, " ");
while(tmp != NULL){
v.push_back(tmp);
//cout << "*" << tmp << "*" << endl;
tmp = strtok(NULL, " ");
}
}
bool run(char str[]){
char* pch;
bool sucs;
bool found = true;
string connector;
string strz = str;
vector<string> cmd;
pch = strtok(str, ";");
if(pch==NULL){
return true;
}
else if(pch != strz){
connector = ";";
}
else if(pch == strz){
pch = strtok(str, "&&");
if(pch == NULL){
return true;
}
if(pch != strz){
connector = "&&";
}
}
else if(pch == strz){
pch = strtok(str, "||");
if(pch == NULL){
return true;
}
if(pch != strz){
connector = "||";
}
}
while(pch != NULL){
//cout << "execvp executes" << endl;
int pid = fork();
if(pid == 0){
parse(pch, cmd);
char* argc[cmd.size() + 1];
for(int i = 0 ; i < cmd.size(); i++ ){
argc[i] = new char[cmd.at(i).size()];
strcpy(argc[i], cmd.at(i).c_str());
}
argc[cmd.size()] = NULL;
if(-1 == execvp(argc[0], argc)){
perror("execvp");
return false;
}
}
else{
wait(NULL);
cmd.clear();
pch = strtok(NULL, connector.c_str());
}
}
return true;
}
int main(){
bool goon = true;
while(goon){
string input;
cout << "$ ";
getline(cin, input);
char str[input.size()+1];
strcpy(str, input.c_str());
goon = run(str);
}
return 0;
}
<commit_msg>Updated hw0.cpp: added the exit command<commit_after>#include <iostream>
#include <stdio.h>
#include <ctype.h>
#include <cstring>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>
using namespace std;
void parse(char x[], vector<string> &v){
//cout << "parse executes" << endl;
char* tmp;
tmp = strtok(x, " ");
while(tmp != NULL){
v.push_back(tmp);
//cout << "*" << tmp << "*" << endl;
tmp = strtok(NULL, " ");
}
}
bool isExit(char x[]){
string tmp = x;
string ext = "exit";
int e = tmp.find('e');
int t = tmp.find('t', e);
if(e == -1 || t == -1){
return false;
}
int k = 0;
for(int i = e; i < t + 1; i++){
if(tmp.at(i) != ext.at(k)){
return false;
}
k++;
}
return true;
}
bool run(char str[]){
char* pch;
bool sucs;
bool found = true;
string ext = "exit";
string connector;
string strz = str;
vector<string> cmd;
pch = strtok(str, ";");
if(pch==NULL){
return true;
}
else if(pch != strz){
connector = ";";
}
else if(pch == strz){
pch = strtok(str, "&&");
if(pch == NULL){
return true;
}
if(pch != strz){
connector = "&&";
}
}
else if(pch == strz){
pch = strtok(str, "||");
if(pch == NULL){
return true;
}
if(pch != strz){
connector = "||";
}
}
if(pch != NULL && isExit(pch)){
exit(0);
}
while(pch != NULL){
//cout << "execvp executes" << endl;
int pid = fork();
if(pid == 0){
parse(pch, cmd);
char* argc[cmd.size() + 1];
for(int i = 0 ; i < cmd.size(); i++ ){
argc[i] = new char[cmd.at(i).size()];
strcpy(argc[i], cmd.at(i).c_str());
}
argc[cmd.size()] = NULL;
if(-1 == execvp(argc[0], argc)){
perror("execvp");
return false;
}
}
else{
wait(NULL);
cmd.clear();
pch = strtok(NULL, connector.c_str());
if(pch != NULL && isExit(pch)){
exit(0);
}
}
}
return true;
}
int main(){
bool goon = true;
while(goon){
string input;
cout << "$ ";
getline(cin, input);
char str[input.size()+1];
strcpy(str, input.c_str());
goon = run(str);
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
void printdir(const int argc, char** &args, const bool &l, const bool &a, const bool &R) {
if(l) {
//l stuff here
} else {
//non l stuff
}
//recursion stuff here?
void getFlags(const int argc, char** &args, bool &l, bool &a, bool &R) {
for(size_t i = 0; i < argc; i++) {
if(args[i][0] == '-') {
for(int j = 0; args[i][j]; j++) {
switch(args[i][j]) {
case 'l': //may not need ''
l = true;
break;
case 'a':
a = true;
break;
case 'R':
R = true;
break;
default:
break;
}
}
}
}
}
int main(int argc, char** argv) {
if(argc < 2) {
cout << "need ore argc" << endl;
exit(1);
}
//loop through argv, update flags
//loop through argv, ignoring -'s, do stat to see if file or directory exists
//if directory, do print direcoty stuff with flag option things
//if file do file print stuff with flag option things
bool el = 0;
bool ay = 0;
bool ar = 0;
struct stat s;
if(-1 == stat(argv[1], &s)) {
perror("error with stat");
cout << "could not find file or directory" << endl;
exit(1);
}
if(S_IFDIR & s.st_mode) { //it's a directory
//do directory print stuff here
//see dir_code.cpp file
} else { //it's a file
//regardless of flags, cout the name of the file
cout << argv[1] << endl;
if(argv[1][0] == '-') {
cout << "it's a dash" << endl;
}
}
return 0;
}
<commit_msg>ls and ls -a seem to work<commit_after>#include <iostream>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
using namespace std;
void printdir( char* dir, const bool &l, const bool &a, const bool &R) {
if(l) {
//l stuff here
} else {
//non l stuff
DIR *dirp;
if(NULL == (dirp = opendir(dir))) {
perror("error with oepndir(). ");
exit(1);
}
struct dirent *filespecs;
errno = 0;
while(NULL != (filespecs = readdir(dirp))) {
if(filespecs->d_name[0] == '.') {
if(a) {
cout << filespecs->d_name << ' ';
}
} else cout << filespecs->d_name << ' ';
}
if(errno != 0) {
perror("error with readdir()");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp)) {
perror("error with closedir()");
exit(1);
}
}
//recursion stuff here?
}
void getFlags(const int argc, char** &args, bool &l, bool &a, bool &R, bool &specified) {
for(size_t i = 1; i < argc; i++) {
if(args[i][0] == '-') {
for(int j = 0; args[i][j]; j++) {
switch(args[i][j]) {
case 'l': //may not need ''
l = true;
break;
case 'a':
a = true;
break;
case 'R':
R = true;
break;
default:
break;
}
}
} else if(args[i][0] > ' ') { //32 is ascii for space character
specified = 1; //for ls with no file or dir specified
}
}
}
int main(int argc, char** argv) {
if(argc < 1) {
cout << "need ore argc" << endl;
exit(1);
}
//loop through argv, update flags
//loop through argv, ignoring -'s, do stat to see if file or directory exists
//if directory, do print direcoty stuff with flag option things
//if file do file print stuff with flag option things
bool el = 0;
bool ay = 0;
bool ar = 0;
bool specified = 0; //tells us if a (file or dir) is specified
char dot[] = ".";
getFlags(argc, argv, el, ay, ar, specified);
struct stat s;
if(specified) {
for(size_t i = 1; i < argc; i++) {
if(argv[i][0] != '-') {
if(-1 == stat(argv[i], &s)) {
perror("error with stat");
cout << "could not find file or directory" << endl;
exit(1);
}
if(S_IFDIR & s.st_mode) { //it's a directory
//do directory print stuff here
//see dir_code.cpp file
printdir(argv[i], el, ay, ar);
} else { //it's a file
//
cout << argv[i] << endl;
}
}
}
} else {
printdir(dot, el, ay, ar);
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <QNetworkInterface>
#include <QTime>
#include <memory>
#include "ice.h"
#include "iceflowcontrol.h"
ICE::ICE():
portPair(22000),
connectionNominated_(false),
nominatingConnection_(false),
stun_(),
stun_entry_rtp_(new ICEInfo),
stun_entry_rtcp_(new ICEInfo)
{
QObject::connect(&stun_, SIGNAL(addressReceived(QHostAddress)), this, SLOT(createSTUNCandidate(QHostAddress)));
stun_.wantAddress("stun.l.google.com");
}
ICE::~ICE()
{
}
// TODO lue speksi uudelleen tämä osalta
/* @param type - 0 for relayed, 126 for host (always 126 TODO is it really?)
* @param local - local preference for selecting candidates (ie.
* @param component - */
int ICE::calculatePriority(int type, int local, int component)
{
// TODO speksin mukaan local pitää olal 0xffff ipv4-only hosteille
// TODO explain these coefficients
return (16777216 * type) + (256 * local) + component;
}
QString ICE::generateFoundation()
{
const QString possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
const int randomStringLength = 15;
QString randomString;
for (int i = 0; i < randomStringLength; ++i)
{
int index = qrand() % possibleCharacters.length();
QChar nextChar = possibleCharacters.at(index);
randomString.append(nextChar);
}
return randomString;
}
QList<ICEInfo *> ICE::generateICECandidates()
{
QList<ICEInfo *> candidates;
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
foreach (const QHostAddress& address, QNetworkInterface::allAddresses())
{
if (address.protocol() == QAbstractSocket::IPv4Protocol &&
(address.toString().startsWith("10.") ||
address.toString().startsWith("192.") ||
address.toString().startsWith("172.") ||
address == QHostAddress(QHostAddress::LocalHost)))
{
ICEInfo *entry_rtp = new ICEInfo;
ICEInfo *entry_rtcp = new ICEInfo;
entry_rtp->address = address.toString();
entry_rtcp->address = address.toString();
entry_rtp->port = portPair++;
entry_rtcp->port = portPair++;
// for each RTP/RTCP pair foundation is the same
const QString foundation = generateFoundation();
entry_rtp->foundation = foundation;
entry_rtcp->foundation = foundation;
entry_rtp->transport = "UDP";
entry_rtcp->transport = "UDP";
entry_rtp->component = RTP;
entry_rtcp->component = RTCP;
entry_rtp->priority = calculatePriority(126, 1, RTP);
entry_rtcp->priority = calculatePriority(126, 1, RTCP);
entry_rtp->type = "host";
entry_rtcp->type = "host";
candidates.push_back(entry_rtp);
candidates.push_back(entry_rtcp);
}
}
// add previously created STUN candidates too
candidates.push_back(stun_entry_rtp_);
candidates.push_back(stun_entry_rtcp_);
return candidates;
}
void ICE::createSTUNCandidate(QHostAddress address)
{
qDebug() << "Creating STUN candidate...";
stun_entry_rtp_->address = address.toString();
stun_entry_rtcp_->address = address.toString();
stun_entry_rtp_->port = portPair++;
stun_entry_rtcp_->port = portPair++;
// for each RTP/RTCP pair foundation is the same
const QString foundation = generateFoundation();
stun_entry_rtp_->foundation = foundation;
stun_entry_rtcp_->foundation = foundation;
stun_entry_rtp_->transport = "UDP";
stun_entry_rtcp_->transport = "UDP";
stun_entry_rtp_->component = RTP;
stun_entry_rtcp_->component = RTCP;
stun_entry_rtp_->priority = calculatePriority(126, 0, RTP);
stun_entry_rtcp_->priority = calculatePriority(126, 0, RTCP);
stun_entry_rtp_->type = "srflx";
stun_entry_rtcp_->type = "srflx";
}
void ICE::printCandidate(ICEInfo *candidate)
{
qDebug() << candidate->foundation << " " << candidate->priority << ": "
<< candidate->address << ":" << candidate->port;
}
// TODO sort them by priority/type/whatever first and make sure ports match!!!
QList<ICEPair *> *ICE::makeCandiatePairs(QList<ICEInfo *>& local, QList<ICEInfo *>& remote)
{
QList<ICEPair *> *pairs = new QList<ICEPair *>;
// create pairs
for (int i = 0; i < qMin(local.size(), remote.size()); ++i)
{
ICEPair *pair = new ICEPair;
pair->local = local[i];
pair->remote = remote[i];
pair->priority = qMin(local[i]->priority, remote[i]->priority);
pair->state = PAIR_FROZEN;
pairs->push_back(pair);
}
return pairs;
}
// callee (flow controller)
//
// this function spawns a control thread and exist right away so the 200 OK
// response can be set as fast as possible and the remote can start respoding to our requests
//
// Thread spawned by startNomination() must keep track of which candidates failed and which succeeded
void ICE::startNomination(QList<ICEInfo *>& local, QList<ICEInfo *>& remote, uint32_t sessionID)
{
connectionNominated_ = false;
callee_mtx.lock();
// this memory is release by FlowController
QList<ICEPair *> *pairs = makeCandiatePairs(local, remote);
FlowController *callee = new FlowController;
QObject::connect(callee, &FlowController::ready, this, &ICE::handleCalleeEndOfNomination, Qt::DirectConnection);
callee->setCandidates(pairs);
callee->setSessionID(sessionID);
callee->start();
}
// caller (flow controllee [TODO does that expression make sense?])
//
// respondToNominations() spawns a control thread that starts testing all candidates
// It doesn't do any external book keeping as it's responsible for only responding to STUN requets
// When it has gone through all candidate pairs it exits
void ICE::respondToNominations(QList<ICEInfo *>& local, QList<ICEInfo *>& remote, uint32_t sessionID)
{
// this memory is released by FlowControllee
QList<ICEPair *> *pairs = makeCandiatePairs(local, remote);
caller_mtx.lock();
FlowControllee *caller = new FlowControllee;
QObject::connect(caller, &FlowControllee::ready, this, &ICE::handleCallerEndOfNomination, Qt::DirectConnection);
caller->setCandidates(pairs);
caller->setSessionID(sessionID);
caller->start();
}
bool ICE::callerConnectionNominated()
{
while (!caller_mtx.try_lock_for(std::chrono::milliseconds(200)))
;
return connectionNominated_;
}
bool ICE::calleeConnectionNominated()
{
while (!callee_mtx.try_lock_for(std::chrono::milliseconds(200)))
;
return connectionNominated_;
}
void ICE::handleEndOfNomination(struct ICEPair *candidateRTP, struct ICEPair *candidateRTCP, uint32_t sessionID)
{
connectionNominated_ = (candidateRTP != nullptr && candidateRTCP != nullptr);
if (connectionNominated_)
{
nominated_[sessionID] = std::make_pair<ICEPair *, ICEPair *>((ICEPair *)candidateRTP, (ICEPair *)candidateRTCP);
}
}
void ICE::handleCallerEndOfNomination(struct ICEPair *candidateRTP, struct ICEPair *candidateRTCP, uint32_t sessionID)
{
this->handleEndOfNomination(candidateRTP, candidateRTCP, sessionID);
caller_mtx.unlock();
}
void ICE::handleCalleeEndOfNomination(struct ICEPair *candidateRTP, struct ICEPair *candidateRTCP, uint32_t sessionID)
{
this->handleEndOfNomination(candidateRTP, candidateRTCP, sessionID);
callee_mtx.unlock();
}
std::pair<ICEPair *, ICEPair *> ICE::getNominated(uint32_t sessionID)
{
if (nominated_.contains(sessionID))
{
return nominated_[sessionID];
}
else
{
return std::make_pair<ICEPair *, ICEPair *>(nullptr, nullptr);
}
}
<commit_msg>Unlock caller/callee nomination mutexes after nomination has finished<commit_after>#include <QNetworkInterface>
#include <QTime>
#include <memory>
#include "ice.h"
#include "iceflowcontrol.h"
ICE::ICE():
portPair(22000),
connectionNominated_(false),
nominatingConnection_(false),
stun_(),
stun_entry_rtp_(new ICEInfo),
stun_entry_rtcp_(new ICEInfo)
{
QObject::connect(&stun_, SIGNAL(addressReceived(QHostAddress)), this, SLOT(createSTUNCandidate(QHostAddress)));
stun_.wantAddress("stun.l.google.com");
}
ICE::~ICE()
{
}
// TODO lue speksi uudelleen tämä osalta
/* @param type - 0 for relayed, 126 for host (always 126 TODO is it really?)
* @param local - local preference for selecting candidates (ie.
* @param component - */
int ICE::calculatePriority(int type, int local, int component)
{
// TODO speksin mukaan local pitää olal 0xffff ipv4-only hosteille
// TODO explain these coefficients
return (16777216 * type) + (256 * local) + component;
}
QString ICE::generateFoundation()
{
const QString possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
const int randomStringLength = 15;
QString randomString;
for (int i = 0; i < randomStringLength; ++i)
{
int index = qrand() % possibleCharacters.length();
QChar nextChar = possibleCharacters.at(index);
randomString.append(nextChar);
}
return randomString;
}
QList<ICEInfo *> ICE::generateICECandidates()
{
QList<ICEInfo *> candidates;
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
foreach (const QHostAddress& address, QNetworkInterface::allAddresses())
{
if (address.protocol() == QAbstractSocket::IPv4Protocol &&
(address.toString().startsWith("10.") ||
address.toString().startsWith("192.") ||
address.toString().startsWith("172.") ||
address == QHostAddress(QHostAddress::LocalHost)))
{
ICEInfo *entry_rtp = new ICEInfo;
ICEInfo *entry_rtcp = new ICEInfo;
entry_rtp->address = address.toString();
entry_rtcp->address = address.toString();
entry_rtp->port = portPair++;
entry_rtcp->port = portPair++;
// for each RTP/RTCP pair foundation is the same
const QString foundation = generateFoundation();
entry_rtp->foundation = foundation;
entry_rtcp->foundation = foundation;
entry_rtp->transport = "UDP";
entry_rtcp->transport = "UDP";
entry_rtp->component = RTP;
entry_rtcp->component = RTCP;
entry_rtp->priority = calculatePriority(126, 1, RTP);
entry_rtcp->priority = calculatePriority(126, 1, RTCP);
entry_rtp->type = "host";
entry_rtcp->type = "host";
candidates.push_back(entry_rtp);
candidates.push_back(entry_rtcp);
}
}
// add previously created STUN candidates too
candidates.push_back(stun_entry_rtp_);
candidates.push_back(stun_entry_rtcp_);
return candidates;
}
void ICE::createSTUNCandidate(QHostAddress address)
{
qDebug() << "Creating STUN candidate...";
stun_entry_rtp_->address = address.toString();
stun_entry_rtcp_->address = address.toString();
stun_entry_rtp_->port = portPair++;
stun_entry_rtcp_->port = portPair++;
// for each RTP/RTCP pair foundation is the same
const QString foundation = generateFoundation();
stun_entry_rtp_->foundation = foundation;
stun_entry_rtcp_->foundation = foundation;
stun_entry_rtp_->transport = "UDP";
stun_entry_rtcp_->transport = "UDP";
stun_entry_rtp_->component = RTP;
stun_entry_rtcp_->component = RTCP;
stun_entry_rtp_->priority = calculatePriority(126, 0, RTP);
stun_entry_rtcp_->priority = calculatePriority(126, 0, RTCP);
stun_entry_rtp_->type = "srflx";
stun_entry_rtcp_->type = "srflx";
}
void ICE::printCandidate(ICEInfo *candidate)
{
qDebug() << candidate->foundation << " " << candidate->priority << ": "
<< candidate->address << ":" << candidate->port;
}
// TODO sort them by priority/type/whatever first and make sure ports match!!!
QList<ICEPair *> *ICE::makeCandiatePairs(QList<ICEInfo *>& local, QList<ICEInfo *>& remote)
{
QList<ICEPair *> *pairs = new QList<ICEPair *>;
// create pairs
for (int i = 0; i < qMin(local.size(), remote.size()); ++i)
{
ICEPair *pair = new ICEPair;
pair->local = local[i];
pair->remote = remote[i];
pair->priority = qMin(local[i]->priority, remote[i]->priority);
pair->state = PAIR_FROZEN;
pairs->push_back(pair);
}
return pairs;
}
// callee (flow controller)
//
// this function spawns a control thread and exist right away so the 200 OK
// response can be set as fast as possible and the remote can start respoding to our requests
//
// Thread spawned by startNomination() must keep track of which candidates failed and which succeeded
void ICE::startNomination(QList<ICEInfo *>& local, QList<ICEInfo *>& remote, uint32_t sessionID)
{
connectionNominated_ = false;
callee_mtx.lock();
// this memory is release by FlowController
QList<ICEPair *> *pairs = makeCandiatePairs(local, remote);
FlowController *callee = new FlowController;
QObject::connect(callee, &FlowController::ready, this, &ICE::handleCalleeEndOfNomination, Qt::DirectConnection);
callee->setCandidates(pairs);
callee->setSessionID(sessionID);
callee->start();
}
// caller (flow controllee [TODO does that expression make sense?])
//
// respondToNominations() spawns a control thread that starts testing all candidates
// It doesn't do any external book keeping as it's responsible for only responding to STUN requets
// When it has gone through all candidate pairs it exits
void ICE::respondToNominations(QList<ICEInfo *>& local, QList<ICEInfo *>& remote, uint32_t sessionID)
{
// this memory is released by FlowControllee
QList<ICEPair *> *pairs = makeCandiatePairs(local, remote);
caller_mtx.lock();
FlowControllee *caller = new FlowControllee;
QObject::connect(caller, &FlowControllee::ready, this, &ICE::handleCallerEndOfNomination, Qt::DirectConnection);
caller->setCandidates(pairs);
caller->setSessionID(sessionID);
caller->start();
}
bool ICE::callerConnectionNominated()
{
while (!caller_mtx.try_lock_for(std::chrono::milliseconds(200)))
;
caller_mtx.unlock();
return connectionNominated_;
}
bool ICE::calleeConnectionNominated()
{
while (!callee_mtx.try_lock_for(std::chrono::milliseconds(200)))
;
callee_mtx.unlock();
return connectionNominated_;
}
void ICE::handleEndOfNomination(struct ICEPair *candidateRTP, struct ICEPair *candidateRTCP, uint32_t sessionID)
{
connectionNominated_ = (candidateRTP != nullptr && candidateRTCP != nullptr);
if (connectionNominated_)
{
nominated_[sessionID] = std::make_pair<ICEPair *, ICEPair *>((ICEPair *)candidateRTP, (ICEPair *)candidateRTCP);
}
}
void ICE::handleCallerEndOfNomination(struct ICEPair *candidateRTP, struct ICEPair *candidateRTCP, uint32_t sessionID)
{
this->handleEndOfNomination(candidateRTP, candidateRTCP, sessionID);
caller_mtx.unlock();
}
void ICE::handleCalleeEndOfNomination(struct ICEPair *candidateRTP, struct ICEPair *candidateRTCP, uint32_t sessionID)
{
this->handleEndOfNomination(candidateRTP, candidateRTCP, sessionID);
callee_mtx.unlock();
}
std::pair<ICEPair *, ICEPair *> ICE::getNominated(uint32_t sessionID)
{
if (nominated_.contains(sessionID))
{
return nominated_[sessionID];
}
else
{
return std::make_pair<ICEPair *, ICEPair *>(nullptr, nullptr);
}
}
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <tf/transform_broadcaster.h>
#include <boost/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <sys/time.h>
#include "imu/bool_msg.h"
#include "Comm.h"
#include <sensor_msgs/Imu.h>
inline float deg_to_rad(float deg) {
// 180度リミッター(Z軸のみ)
return deg/180.0f*M_PI;
}
// 角度ごとにURGのデータを送信するためのサービス
// 要求があったときに,URGのデータを別のトピックに送信するだけ
class IMU {
private :
ros::Publisher imu_pub_;
ros::ServiceServer reset_service_;
ros::ServiceServer carivrate_service_;
float geta;
CComm usb;
float gyro_unit;
float acc_unit;
float init_angle;
std::string port_name;
int baudrate;
ros::Rate loop_rate;
int revice_digit_;
public:
bool resetCallback(imu::bool_msg::Request &req,
imu::bool_msg::Response &res)
{
char command[2] = {0};
sprintf(command, "0");
usb.Send(command, strlen(command)); //送信
sleep(1);
std::cout << "Gyro 0 Reset" << std::endl;
return true;
}
bool caribrateCallback(imu::bool_msg::Request &req,
imu::bool_msg::Response &res)
{
char command[2] = {0};
std::cout << "Calibration" << std::endl;
sprintf(command, "a");
usb.Send(command, strlen(command));
std::cout << "Caribrate start ";
for(int i=0; i<8; ++i) {
std::cout << ". ";
sleep(1);
}
std::cout << "finish." << std::endl;
return true;
}
IMU(ros::NodeHandle node) :
imu_pub_(node.advertise<sensor_msgs::Imu>("imu", 1000)),
reset_service_(node.advertiseService("imu_reset", &IMU::resetCallback, this)),
carivrate_service_(node.advertiseService("imu_caribrate", &IMU::caribrateCallback, this)),
geta(0), gyro_unit(0.00836181640625), acc_unit(0.8), init_angle(0.0),
port_name("/dev/ttyUSB0"), baudrate(115200), loop_rate(1000), revice_digit_(1)
{
// パラメータが定義されている場合は読み込んで上書き
ros::NodeHandle private_nh_("~");
std::string read_string;
if(private_nh_.getParam("port_name", read_string))
port_name = read_string;
float read_float;
if(ros::param::get("gyro_unit", read_float))
gyro_unit = read_float;
if(ros::param::get("acc_unit", read_float))
acc_unit = read_float;
int read_int;
if(ros::param::get("baud_rate", read_int))
baudrate = read_float;
if(ros::param::get("init_angle", read_float))
init_angle = read_float;
if(ros::param::get("revice_digit", read_int))
revice_digit_ = read_int;
}
bool init() {
char command[2] = {0};
char command2[101] = {0};
//シリアルポートオープン
char* s = new char[port_name.length()+1];
strcpy(s, port_name.c_str());
if (!usb.Open((char*)s, baudrate)) {
std::cerr << "open error" << std::endl;
delete [] s;
return false;
}
delete [] s;
std::cout << "device open success" << std::endl;
sleep(1);
//コンフィギュレーション キャリブレーション
// if(m_calibration == true){
std::cout << "Calibration" << std::endl;
sprintf(command, "a");
usb.Send(command, strlen(command));
std::cout << "send = " << command << std::endl;
for(int i=0; i<8; ++i) {
printf(". ");
sleep(1);
}
// }
//コンフィギュレーション リセット
// if(m_reset == true){
sprintf(command, "0");
usb.Send(command, strlen(command)); //送信
std::cout << "send = " << command << std::endl;
sleep(1);
std::cout << "Gyro 0 Reset" << std::endl;
// }
geta = 0;
usb.Recv(command2, 100); //空読み バッファクリアが効かない?
usb.ClearRecvBuf(); //バッファクリア
return true;
}
void run() {
while (ros::ok()) {
char command[2] = {0};
char command2[50] = {0};
char temp[6];
const float temp_unit = 0.00565;
float tempdata;
//コマンド送信
//oコマンドでジャイロ3軸、加速度3軸、温度が出力される
sprintf(command, "o");
usb.Send(command, strlen(command)); //送信
usleep(30000);
//結果受信
usb.Recv(command2, 50); //受信
std::cout << "recv = " << command2 << std::endl;
geometry_msgs::Twist output_data;
//ジャイロ読み込み
memmove(temp,command2,4);
output_data.angular.x = ((short)strtol(temp, NULL, 16)) * gyro_unit;
memmove(temp,command2+4,4);
output_data.angular.y = ((short)strtol(temp, NULL, 16)) * gyro_unit;
memmove(temp,command2+8,4);
output_data.angular.z = ((short)strtol(temp, NULL, 16)) * gyro_unit * revice_digit_;
//加速度読み込み
memmove(temp,command2+12,4);
output_data.linear.x = ((short)strtol(temp, NULL, 16)) * acc_unit;
memmove(temp,command2+16,4);
output_data.linear.y = ((short)strtol(temp, NULL, 16)) * acc_unit;
memmove(temp,command2+20,4);
output_data.linear.z = init_angle + ((short)strtol(temp, NULL, 16)) * acc_unit ;
// 180度リミッター(Z軸のみ)
while (output_data.angular.z < -180)
output_data.angular.z += 180;
while (output_data.angular.z > 180)
output_data.angular.z -= 180;
//温度読み込み
memmove(temp,command2+24,4);
tempdata = ((short)strtol(temp, NULL, 16)) * temp_unit + 25.0;
// 出力データの表示
std::cout << "ang_x = " << output_data.angular.x
<< "ang_y = " << output_data.angular.y
<< "ang_z = " << output_data.angular.z
<< "ang_z_orig = " << output_data.angular.z << std::endl;
std::cout << "acc_x = " << output_data.linear.x
<< "acc_y = " << output_data.linear.y
<< "acc_z = " << output_data.linear.z << std::endl;
std::cout << "temp = " << tempdata << std::endl;
output_data.angular.x = deg_to_rad(output_data.angular.x);
output_data.angular.y = deg_to_rad(output_data.angular.y);
output_data.angular.z = deg_to_rad(output_data.angular.z);
sensor_msgs::Imu output_data_imu;
tf::quaternionTFToMsg(tf::Quaternion(
output_data.angular.x,
output_data.angular.y,
output_data.angular.z
),
output_data_imu.orientation
);
output_data_imu.angular_velocity.x = output_data.angular.x;
output_data_imu.angular_velocity.y = output_data.angular.y;
output_data_imu.angular_velocity.z = output_data.angular.z;
output_data_imu.linear_acceleration.x = output_data.linear.x;
output_data_imu.linear_acceleration.y = output_data.linear.y;
output_data_imu.linear_acceleration.z = output_data.linear.z;
imu_pub_.publish(output_data_imu);
ros::spinOnce();
loop_rate.sleep();
}
}
};
int main(int argc, char * argv[])
{
ros::init(argc, argv, "imu");
ros::NodeHandle node;
IMU imu(node);
if(!imu.init()) return 1;
imu.run();
return 0;
}
<commit_msg>Add a timestamp to the topic for the publisher<commit_after>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <tf/transform_broadcaster.h>
#include <boost/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <sys/time.h>
#include "imu/bool_msg.h"
#include "Comm.h"
#include <sensor_msgs/Imu.h>
inline float deg_to_rad(float deg) {
// 180度リミッター(Z軸のみ)
return deg/180.0f*M_PI;
}
// 角度ごとにURGのデータを送信するためのサービス
// 要求があったときに,URGのデータを別のトピックに送信するだけ
class IMU {
private :
ros::Publisher imu_pub_;
ros::ServiceServer reset_service_;
ros::ServiceServer carivrate_service_;
float geta;
CComm usb;
float gyro_unit;
float acc_unit;
float init_angle;
std::string port_name;
int baudrate;
ros::Rate loop_rate;
int revice_digit_;
public:
bool resetCallback(imu::bool_msg::Request &req,
imu::bool_msg::Response &res)
{
char command[2] = {0};
sprintf(command, "0");
usb.Send(command, strlen(command)); //送信
sleep(1);
std::cout << "Gyro 0 Reset" << std::endl;
return true;
}
bool caribrateCallback(imu::bool_msg::Request &req,
imu::bool_msg::Response &res)
{
char command[2] = {0};
std::cout << "Calibration" << std::endl;
sprintf(command, "a");
usb.Send(command, strlen(command));
std::cout << "Caribrate start ";
for(int i=0; i<8; ++i) {
std::cout << ". ";
sleep(1);
}
std::cout << "finish." << std::endl;
return true;
}
IMU(ros::NodeHandle node) :
imu_pub_(node.advertise<sensor_msgs::Imu>("imu", 1000)),
reset_service_(node.advertiseService("imu_reset", &IMU::resetCallback, this)),
carivrate_service_(node.advertiseService("imu_caribrate", &IMU::caribrateCallback, this)),
geta(0), gyro_unit(0.00836181640625), acc_unit(0.8), init_angle(0.0),
port_name("/dev/ttyUSB0"), baudrate(115200), loop_rate(1000), revice_digit_(1)
{
// パラメータが定義されている場合は読み込んで上書き
ros::NodeHandle private_nh_("~");
std::string read_string;
if(private_nh_.getParam("port_name", read_string))
port_name = read_string;
float read_float;
if(ros::param::get("gyro_unit", read_float))
gyro_unit = read_float;
if(ros::param::get("acc_unit", read_float))
acc_unit = read_float;
int read_int;
if(ros::param::get("baud_rate", read_int))
baudrate = read_float;
if(ros::param::get("init_angle", read_float))
init_angle = read_float;
if(ros::param::get("revice_digit", read_int))
revice_digit_ = read_int;
}
bool init() {
char command[2] = {0};
char command2[101] = {0};
//シリアルポートオープン
char* s = new char[port_name.length()+1];
strcpy(s, port_name.c_str());
if (!usb.Open((char*)s, baudrate)) {
std::cerr << "open error" << std::endl;
delete [] s;
return false;
}
delete [] s;
std::cout << "device open success" << std::endl;
sleep(1);
//コンフィギュレーション キャリブレーション
// if(m_calibration == true){
std::cout << "Calibration" << std::endl;
sprintf(command, "a");
usb.Send(command, strlen(command));
std::cout << "send = " << command << std::endl;
for(int i=0; i<8; ++i) {
printf(". ");
sleep(1);
}
// }
//コンフィギュレーション リセット
// if(m_reset == true){
sprintf(command, "0");
usb.Send(command, strlen(command)); //送信
std::cout << "send = " << command << std::endl;
sleep(1);
std::cout << "Gyro 0 Reset" << std::endl;
// }
geta = 0;
usb.Recv(command2, 100); //空読み バッファクリアが効かない?
usb.ClearRecvBuf(); //バッファクリア
return true;
}
void run() {
while (ros::ok()) {
char command[2] = {0};
char command2[50] = {0};
char temp[6];
const float temp_unit = 0.00565;
float tempdata;
//コマンド送信
//oコマンドでジャイロ3軸、加速度3軸、温度が出力される
sprintf(command, "o");
usb.Send(command, strlen(command)); //送信
usleep(30000);
//結果受信
usb.Recv(command2, 50); //受信
std::cout << "recv = " << command2 << std::endl;
geometry_msgs::Twist output_data;
//ジャイロ読み込み
memmove(temp,command2,4);
output_data.angular.x = ((short)strtol(temp, NULL, 16)) * gyro_unit;
memmove(temp,command2+4,4);
output_data.angular.y = ((short)strtol(temp, NULL, 16)) * gyro_unit;
memmove(temp,command2+8,4);
output_data.angular.z = ((short)strtol(temp, NULL, 16)) * gyro_unit * revice_digit_;
//加速度読み込み
memmove(temp,command2+12,4);
output_data.linear.x = ((short)strtol(temp, NULL, 16)) * acc_unit;
memmove(temp,command2+16,4);
output_data.linear.y = ((short)strtol(temp, NULL, 16)) * acc_unit;
memmove(temp,command2+20,4);
output_data.linear.z = init_angle + ((short)strtol(temp, NULL, 16)) * acc_unit ;
// 180度リミッター(Z軸のみ)
while (output_data.angular.z < -180)
output_data.angular.z += 180;
while (output_data.angular.z > 180)
output_data.angular.z -= 180;
//温度読み込み
memmove(temp,command2+24,4);
tempdata = ((short)strtol(temp, NULL, 16)) * temp_unit + 25.0;
// 出力データの表示
std::cout << "ang_x = " << output_data.angular.x
<< "ang_y = " << output_data.angular.y
<< "ang_z = " << output_data.angular.z
<< "ang_z_orig = " << output_data.angular.z << std::endl;
std::cout << "acc_x = " << output_data.linear.x
<< "acc_y = " << output_data.linear.y
<< "acc_z = " << output_data.linear.z << std::endl;
std::cout << "temp = " << tempdata << std::endl;
output_data.angular.x = deg_to_rad(output_data.angular.x);
output_data.angular.y = deg_to_rad(output_data.angular.y);
output_data.angular.z = deg_to_rad(output_data.angular.z);
sensor_msgs::Imu output_data_imu;
output_data_imu.header.stamp = ros::Time::now();
tf::quaternionTFToMsg(tf::Quaternion(
output_data.angular.x,
output_data.angular.y,
output_data.angular.z
),
output_data_imu.orientation
);
output_data_imu.angular_velocity.x = output_data.angular.x;
output_data_imu.angular_velocity.y = output_data.angular.y;
output_data_imu.angular_velocity.z = output_data.angular.z;
output_data_imu.linear_acceleration.x = output_data.linear.x;
output_data_imu.linear_acceleration.y = output_data.linear.y;
output_data_imu.linear_acceleration.z = output_data.linear.z;
imu_pub_.publish(output_data_imu);
ros::spinOnce();
loop_rate.sleep();
}
}
};
int main(int argc, char * argv[])
{
ros::init(argc, argv, "imu");
ros::NodeHandle node;
IMU imu(node);
if(!imu.init()) return 1;
imu.run();
return 0;
}
<|endoftext|>
|
<commit_before>/* Copyright 2019 The TensorFlow 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 "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h"
#include <memory>
#include "mlir/IR/Module.h" // from @llvm-project
#include "mlir/Pass/PassManager.h" // from @llvm-project
#include "mlir/Transforms/Passes.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
namespace mlir {
namespace {
// Add logger to bridge passmanager.
void EnableLogging(PassManager *pm) {
// Print the whole module after each pass, which requires disabling
// multi-threading as well.
pm->getContext()->disableMultithreading();
pm->enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>(
/*print_module_scope=*/true));
pm->enableTiming(std::make_unique<tensorflow::BridgeTimingConfig>());
}
} // namespace
namespace TFTPU {
namespace {
void AddGraphExportLoweringPasses(OpPassManager &pm) {
pm.addNestedPass<FuncOp>(CreateFunctionalToExecutorDialectConversionPass());
pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass());
pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateToIslandPass());
pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass());
pm.addNestedPass<FuncOp>(TFDevice::CreateParallelExecuteToIslandsPass());
pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass());
pm.addNestedPass<FuncOp>(TFDevice::CreateLaunchToDeviceAttributePass());
pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass());
}
tensorflow::Status RunTPUBridge(
ModuleOp module, bool enable_logging,
llvm::function_ref<void(OpPassManager &pm)> pipeline_builder) {
PassManager bridge(module.getContext());
if (enable_logging) EnableLogging(&bridge);
// Populate a passmanager with the list of passes that implement the bridge.
pipeline_builder(bridge);
// Add set of passes to lower back to graph (from tf_executor).
AddGraphExportLoweringPasses(bridge);
// Run the bridge on the module, in case of failure, the `diag_handler`
// converts MLIR errors emitted to the MLIRContext into a tensorflow::Status.
mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
LogicalResult result = bridge.run(module);
(void)result;
return diag_handler.ConsumeStatus();
}
} // namespace
void CreateTPUBridgePipeline(OpPassManager &pm) {
pm.addNestedPass<FuncOp>(tf_executor::CreateTFExecutorGraphPruningPass());
// It is assumed at this stage there are no V1 control flow ops as Graph
// functionalization is ran before import. Ops can be lifted out of
// tf_executor dialect islands/graphs.
pm.addNestedPass<FuncOp>(CreateExecutorDialectToFunctionalConversionPass());
// Run shape inference so that tf_executor/tf_device ops created later will
// likely to inherit more concrete types.
pm.addPass(TF::CreateTFShapeInferencePass());
OpPassManager &func_pm = pm.nest<FuncOp>();
func_pm.addPass(CreateTPUClusterFormationPass());
// Place DecomposeResourceOpsPass before TFExecutorConstantSinking pass
// because DecomposeResourceOpsPass uses pattern rewriter which hoists
// changed constants out of tf_device.Launch.
func_pm.addPass(TFDevice::CreateDecomposeResourceOpsPass());
func_pm.addPass(CreateTPUHostComputationExpansionPass());
pm.addPass(CreateTPUExtractHeadTailOutsideCompilationPass());
// Run another shape inference pass because resource decomposition might have
// created new partial types.
pm.addPass(TF::CreateTFShapeInferencePass());
pm.addNestedPass<FuncOp>(tf_executor::CreateTFExecutorConstantSinkingPass());
pm.addPass(TFDevice::CreateResourceOpLiftingPass());
pm.addPass(TF::CreateResourceDeviceInferencePass());
pm.addPass(TFDevice::CreateClusterOutliningPass());
pm.addPass(CreateTPUDynamicPaddingMapperPass());
pm.addPass(CreateTPUShardingIdentificationPass());
pm.addPass(TFDevice::CreateAnnotateParameterReplicationPass());
pm.addPass(CreateTPURewritePass());
pm.addPass(createSymbolDCEPass());
pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateInvariantOpHoistingPass());
pm.addNestedPass<FuncOp>(CreateTPUDynamicLayoutPass());
pm.addNestedPass<FuncOp>(CreateTPUMergeVariablesWithExecutePass());
pm.addPass(CreateTPUVariableReformattingPass());
}
void CreateTPUBridgePipelineV1(OpPassManager &pm) {
// For V1 compatibility, we process a module where the graph does not have
// feeds and fetched. We extract first the TPU computation in a submodule,
// where it'll be in a function with args and returned values, much more like
// a TF v2 module. We can then run the usual pipeline on this nested module.
// Afterward we inline back in the parent module and delete the nested one.
pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandCoarseningPass());
pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandOutliningPass());
OpPassManager &nested_module = pm.nest<ModuleOp>();
CreateTPUBridgePipeline(nested_module);
pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandInliningPass());
}
tensorflow::Status TPUBridge(ModuleOp module, bool enable_logging) {
return RunTPUBridge(module, enable_logging, CreateTPUBridgePipeline);
}
tensorflow::Status TPUBridgeV1Compat(ModuleOp module, bool enable_logging) {
return RunTPUBridge(module, enable_logging, CreateTPUBridgePipelineV1);
}
} // namespace TFTPU
namespace TF {
tensorflow::Status RunBridgeWithStandardPipeline(ModuleOp module,
bool enable_logging,
bool enable_inliner) {
PassManager bridge(module.getContext());
if (enable_logging) EnableLogging(&bridge);
StandardPipelineOptions pipeline_options;
pipeline_options.enable_inliner.setValue(enable_inliner);
CreateTFStandardPipeline(bridge, pipeline_options);
mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
LogicalResult result = bridge.run(module);
(void)result;
return diag_handler.ConsumeStatus();
}
} // namespace TF
} // namespace mlir
<commit_msg>Add shape inference pass to the beginning of the TPUBridgeV1Compat pipeline.<commit_after>/* Copyright 2019 The TensorFlow 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 "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h"
#include <memory>
#include "mlir/IR/Module.h" // from @llvm-project
#include "mlir/Pass/PassManager.h" // from @llvm-project
#include "mlir/Transforms/Passes.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/bridge_logger.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
namespace mlir {
namespace {
// Add logger to bridge passmanager.
void EnableLogging(PassManager *pm) {
// Print the whole module after each pass, which requires disabling
// multi-threading as well.
pm->getContext()->disableMultithreading();
pm->enableIRPrinting(std::make_unique<tensorflow::BridgeLoggerConfig>(
/*print_module_scope=*/true));
pm->enableTiming(std::make_unique<tensorflow::BridgeTimingConfig>());
}
} // namespace
namespace TFTPU {
namespace {
void AddGraphExportLoweringPasses(OpPassManager &pm) {
pm.addNestedPass<FuncOp>(CreateFunctionalToExecutorDialectConversionPass());
pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass());
pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateToIslandPass());
pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass());
pm.addNestedPass<FuncOp>(TFDevice::CreateParallelExecuteToIslandsPass());
pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass());
pm.addNestedPass<FuncOp>(TFDevice::CreateLaunchToDeviceAttributePass());
pm.addNestedPass<FuncOp>(CreateBreakUpIslandsPass());
}
tensorflow::Status RunTPUBridge(
ModuleOp module, bool enable_logging,
llvm::function_ref<void(OpPassManager &pm)> pipeline_builder) {
PassManager bridge(module.getContext());
if (enable_logging) EnableLogging(&bridge);
// Populate a passmanager with the list of passes that implement the bridge.
pipeline_builder(bridge);
// Add set of passes to lower back to graph (from tf_executor).
AddGraphExportLoweringPasses(bridge);
// Run the bridge on the module, in case of failure, the `diag_handler`
// converts MLIR errors emitted to the MLIRContext into a tensorflow::Status.
mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
LogicalResult result = bridge.run(module);
(void)result;
return diag_handler.ConsumeStatus();
}
} // namespace
void CreateTPUBridgePipeline(OpPassManager &pm) {
pm.addNestedPass<FuncOp>(tf_executor::CreateTFExecutorGraphPruningPass());
// It is assumed at this stage there are no V1 control flow ops as Graph
// functionalization is ran before import. Ops can be lifted out of
// tf_executor dialect islands/graphs.
pm.addNestedPass<FuncOp>(CreateExecutorDialectToFunctionalConversionPass());
// Run shape inference so that tf_executor/tf_device ops created later will
// likely to inherit more concrete types.
pm.addPass(TF::CreateTFShapeInferencePass());
OpPassManager &func_pm = pm.nest<FuncOp>();
func_pm.addPass(CreateTPUClusterFormationPass());
// Place DecomposeResourceOpsPass before TFExecutorConstantSinking pass
// because DecomposeResourceOpsPass uses pattern rewriter which hoists
// changed constants out of tf_device.Launch.
func_pm.addPass(TFDevice::CreateDecomposeResourceOpsPass());
func_pm.addPass(CreateTPUHostComputationExpansionPass());
pm.addPass(CreateTPUExtractHeadTailOutsideCompilationPass());
// Run another shape inference pass because resource decomposition might have
// created new partial types.
pm.addPass(TF::CreateTFShapeInferencePass());
pm.addNestedPass<FuncOp>(tf_executor::CreateTFExecutorConstantSinkingPass());
pm.addPass(TFDevice::CreateResourceOpLiftingPass());
pm.addPass(TF::CreateResourceDeviceInferencePass());
pm.addPass(TFDevice::CreateClusterOutliningPass());
pm.addPass(CreateTPUDynamicPaddingMapperPass());
pm.addPass(CreateTPUShardingIdentificationPass());
pm.addPass(TFDevice::CreateAnnotateParameterReplicationPass());
pm.addPass(CreateTPURewritePass());
pm.addPass(createSymbolDCEPass());
pm.addNestedPass<FuncOp>(TFDevice::CreateReplicateInvariantOpHoistingPass());
pm.addNestedPass<FuncOp>(CreateTPUDynamicLayoutPass());
pm.addNestedPass<FuncOp>(CreateTPUMergeVariablesWithExecutePass());
pm.addPass(CreateTPUVariableReformattingPass());
}
void CreateTPUBridgePipelineV1(OpPassManager &pm) {
pm.addPass(TF::CreateTFShapeInferencePass());
// For V1 compatibility, we process a module where the graph does not have
// feeds and fetched. We extract first the TPU computation in a submodule,
// where it'll be in a function with args and returned values, much more like
// a TF v2 module. We can then run the usual pipeline on this nested module.
// Afterward we inline back in the parent module and delete the nested one.
pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandCoarseningPass());
pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandOutliningPass());
OpPassManager &nested_module = pm.nest<ModuleOp>();
CreateTPUBridgePipeline(nested_module);
pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandInliningPass());
}
tensorflow::Status TPUBridge(ModuleOp module, bool enable_logging) {
return RunTPUBridge(module, enable_logging, CreateTPUBridgePipeline);
}
tensorflow::Status TPUBridgeV1Compat(ModuleOp module, bool enable_logging) {
return RunTPUBridge(module, enable_logging, CreateTPUBridgePipelineV1);
}
} // namespace TFTPU
namespace TF {
tensorflow::Status RunBridgeWithStandardPipeline(ModuleOp module,
bool enable_logging,
bool enable_inliner) {
PassManager bridge(module.getContext());
if (enable_logging) EnableLogging(&bridge);
StandardPipelineOptions pipeline_options;
pipeline_options.enable_inliner.setValue(enable_inliner);
CreateTFStandardPipeline(bridge, pipeline_options);
mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());
LogicalResult result = bridge.run(module);
(void)result;
return diag_handler.ConsumeStatus();
}
} // namespace TF
} // namespace mlir
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)
struct ircaddr
{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
loop
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
loop
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
Sleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
loop
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
// Make this thread recognisable as the IRC seeding thread
RenameThread("bitcoin-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
// Don't connect to IRC if we won't use IPv4 connections.
if (IsLimited(NET_IPV4))
return;
// ... or if we won't make outbound connections and won't accept inbound ones.
if (mapArgs.count("-connect") && fNoListen)
return;
// ... or if IRC is not enabled.
if (!GetBoolArg("-irc", true))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
int nNameRetry = 0;
while (!fShutdown)
{
CService addrConnect("188.122.74.140", 6667); // eu.undernet.org
CService addrIRC("irc.rizon.net", 6667, true);
if (addrIRC.IsValid())
addrConnect = addrIRC;
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
{
printf("IRC connect failed\n");
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
// Don't use our IP as our nick if we're not listening
// or if it keeps failing because the nick is already in use.
if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%"PRI64u"", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
nNameRetry++;
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
nNameRetry = 0;
Sleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
// Don't use our IP as our nick if we're not listening
if (!fNoListen && addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #BottleCapsTEST2\r");
Send(hSocket, "WHO #BottleCapsTEST2\r");
} else {
// randomly join #BottleCaps00-#BottleCaps05
// int channel_number = GetRandInt(5);
// Channel number is always 0 for initial release
int channel_number = 0;
Send(hSocket, strprintf("JOIN #BottleCaps%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #BottleCaps%02d\r", channel_number).c_str());
}
int64 nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :[email protected] JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
if (addrman.Add(addr, addrConnect, 51 * 60))
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif
<commit_msg>updated irc hosts<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "net.h"
#include "strlcpy.h"
#include "base58.h"
using namespace std;
using namespace boost;
int nGotIRCAddresses = 0;
void ThreadIRCSeed2(void* parg);
#pragma pack(push, 1)
struct ircaddr
{
struct in_addr ip;
short port;
};
#pragma pack(pop)
string EncodeAddress(const CService& addr)
{
struct ircaddr tmp;
if (addr.GetInAddr(&tmp.ip))
{
tmp.port = htons(addr.GetPort());
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
return string("u") + EncodeBase58Check(vch);
}
return "";
}
bool DecodeAddress(string str, CService& addr)
{
vector<unsigned char> vch;
if (!DecodeBase58Check(str.substr(1), vch))
return false;
struct ircaddr tmp;
if (vch.size() != sizeof(tmp))
return false;
memcpy(&tmp, &vch[0], sizeof(tmp));
addr = CService(tmp.ip, ntohs(tmp.port));
return true;
}
static bool Send(SOCKET hSocket, const char* pszSend)
{
if (strstr(pszSend, "PONG") != pszSend)
printf("IRC SENDING: %s\n", pszSend);
const char* psz = pszSend;
const char* pszEnd = psz + strlen(psz);
while (psz < pszEnd)
{
int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
if (ret < 0)
return false;
psz += ret;
}
return true;
}
bool RecvLineIRC(SOCKET hSocket, string& strLine)
{
loop
{
bool fRet = RecvLine(hSocket, strLine);
if (fRet)
{
if (fShutdown)
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() >= 1 && vWords[0] == "PING")
{
strLine[1] = 'O';
strLine += '\r';
Send(hSocket, strLine.c_str());
continue;
}
}
return fRet;
}
}
int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
{
loop
{
string strLine;
strLine.reserve(10000);
if (!RecvLineIRC(hSocket, strLine))
return 0;
printf("IRC %s\n", strLine.c_str());
if (psz1 && strLine.find(psz1) != string::npos)
return 1;
if (psz2 && strLine.find(psz2) != string::npos)
return 2;
if (psz3 && strLine.find(psz3) != string::npos)
return 3;
if (psz4 && strLine.find(psz4) != string::npos)
return 4;
}
}
bool Wait(int nSeconds)
{
if (fShutdown)
return false;
printf("IRC waiting %d seconds to reconnect\n", nSeconds);
for (int i = 0; i < nSeconds; i++)
{
if (fShutdown)
return false;
Sleep(1000);
}
return true;
}
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
{
strRet.clear();
loop
{
string strLine;
if (!RecvLineIRC(hSocket, strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
if (vWords[1] == psz1)
{
printf("IRC %s\n", strLine.c_str());
strRet = strLine;
return true;
}
}
}
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
{
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
string strLine;
if (!RecvCodeLine(hSocket, "302", strLine))
return false;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 4)
return false;
string str = vWords[3];
if (str.rfind("@") == string::npos)
return false;
string strHost = str.substr(str.rfind("@")+1);
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
// but in case another IRC is ever used this should work.
printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
CNetAddr addr(strHost, true);
if (!addr.IsValid())
return false;
ipRet = addr;
return true;
}
void ThreadIRCSeed(void* parg)
{
// Make this thread recognisable as the IRC seeding thread
RenameThread("bitcoin-ircseed");
try
{
ThreadIRCSeed2(parg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ThreadIRCSeed()");
} catch (...) {
PrintExceptionContinue(NULL, "ThreadIRCSeed()");
}
printf("ThreadIRCSeed exited\n");
}
void ThreadIRCSeed2(void* parg)
{
// Don't connect to IRC if we won't use IPv4 connections.
if (IsLimited(NET_IPV4))
return;
// ... or if we won't make outbound connections and won't accept inbound ones.
if (mapArgs.count("-connect") && fNoListen)
return;
// ... or if IRC is not enabled.
if (!GetBoolArg("-irc", true))
return;
printf("ThreadIRCSeed started\n");
int nErrorWait = 10;
int nRetryWait = 10;
int nNameRetry = 0;
while (!fShutdown)
{
CService addrConnect("irc.lfnet.org", 6667);
CService addrIRC("pelican.heliacal.net", 6667, true);
if (addrIRC.IsValid())
addrConnect = addrIRC;
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
{
printf("IRC connect failed\n");
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
CService addrLocal;
string strMyName;
// Don't use our IP as our nick if we're not listening
// or if it keeps failing because the nick is already in use.
if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
if (strMyName == "")
strMyName = strprintf("x%"PRI64u"", GetRand(1000000000));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
if (nRet != 1)
{
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (nRet == 2)
{
printf("IRC name already in use\n");
nNameRetry++;
Wait(10);
continue;
}
nErrorWait = nErrorWait * 11 / 10;
if (Wait(nErrorWait += 60))
continue;
else
return;
}
nNameRetry = 0;
Sleep(500);
// Get our external IP from the IRC server and re-nick before joining the channel
CNetAddr addrFromIRC;
if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
{
printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
// Don't use our IP as our nick if we're not listening
if (!fNoListen && addrFromIRC.IsRoutable())
{
// IRC lets you to re-nick
AddLocal(addrFromIRC, LOCAL_IRC);
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
}
}
if (fTestNet) {
Send(hSocket, "JOIN #BottleCapsTEST2\r");
Send(hSocket, "WHO #BottleCapsTEST2\r");
} else {
// randomly join #BottleCaps00-#BottleCaps05
// int channel_number = GetRandInt(5);
// Channel number is always 0 for initial release
int channel_number = 0;
Send(hSocket, strprintf("JOIN #BottleCaps%02d\r", channel_number).c_str());
Send(hSocket, strprintf("WHO #BottleCaps%02d\r", channel_number).c_str());
}
int64 nStart = GetTime();
string strLine;
strLine.reserve(10000);
while (!fShutdown && RecvLineIRC(hSocket, strLine))
{
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
continue;
vector<string> vWords;
ParseString(strLine, ' ', vWords);
if (vWords.size() < 2)
continue;
char pszName[10000];
pszName[0] = '\0';
if (vWords[1] == "352" && vWords.size() >= 8)
{
// index 7 is limited to 16 characters
// could get full length name at index 10, but would be different from join messages
strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
printf("IRC got who\n");
}
if (vWords[1] == "JOIN" && vWords[0].size() > 1)
{
// :[email protected] JOIN :#channelname
strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
if (strchr(pszName, '!'))
*strchr(pszName, '!') = '\0';
printf("IRC got join\n");
}
if (pszName[0] == 'u')
{
CAddress addr;
if (DecodeAddress(pszName, addr))
{
addr.nTime = GetAdjustedTime();
if (addrman.Add(addr, addrConnect, 51 * 60))
printf("IRC got new address: %s\n", addr.ToString().c_str());
nGotIRCAddresses++;
}
else
{
printf("IRC decode failed\n");
}
}
}
closesocket(hSocket);
hSocket = INVALID_SOCKET;
if (GetTime() - nStart > 20 * 60)
{
nErrorWait /= 3;
nRetryWait /= 3;
}
nRetryWait = nRetryWait * 11 / 10;
if (!Wait(nRetryWait += 60))
return;
}
}
#ifdef TEST
int main(int argc, char *argv[])
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
{
printf("Error at WSAStartup()\n");
return false;
}
ThreadIRCSeed(NULL);
WSACleanup();
return 0;
}
#endif
<|endoftext|>
|
<commit_before>/*
* api.cpp
*
* Created on: 2016年12月16日
* Author: zhuqian
*/
#include "api.h"
#include "transform.h"
#include "paramset.h"
//transform相关参数
constexpr int MaxTransforms = 2;
constexpr int StartTransformBits = 1 << 0; //0x01
constexpr int EndTransformBits = 1 << 1; //0x10
constexpr int AllTransformsBits = (1 << MaxTransforms) - 1; //0x11
//transform集合
struct TransformSet {
private:
Transform _t[MaxTransforms];
public:
Transform& operator[](int i) {
Assert(i >= 0 && i < MaxTransforms);
return _t[i];
}
const Transform& operator[](int i) const {
Assert(i >= 0 && i < MaxTransforms);
return _t[i];
}
//判断是否包含不同的transform
bool IsAnimated() const {
for (int i = 0; i < MaxTransforms - 1; ++i) {
if (_t[i] != _t[i + 1]) {
return true;
}
}
return false;
}
//返回transformSet的逆
friend TransformSet Inverse(const TransformSet& ts) {
TransformSet invSet;
for (int i = 0; i < MaxTransforms; ++i) {
invSet._t[i] = Inverse(ts._t[i]);
}
return invSet;
}
};
//渲染参数
struct RenderOptions {
Float transformStartTime = 0;
Float transformEndTime = 1;
//过滤器名字 默认 box
std::string FilterName = "box";
ParamSet FilterParams;
//Film的名字
std::string FilmName = "image";
ParamSet FilmParams;
//采样器的名字
std::string SamplerName = "random";
ParamSet SamplerParams;
//加速结构的名字
std::string AcceleratorName = "normal";
ParamSet AcceleratorParams;
//积分器的名字
std::string IntegratorName = "normal";
ParamSet IntegratorParams;
//相机的名字
std::string CameraName = "pinhole";
ParamSet CameraParams;
//光源
std::vector<std::shared_ptr<Light>> lights;
//图元
std::vector<std::shared_ptr<Primitive>> primitives;
};
<commit_msg>copy some boring value from PBRT_V3<commit_after>/*
* api.cpp
*
* Created on: 2016年12月16日
* Author: zhuqian
*/
#include "api.h"
#include "transform.h"
#include "paramset.h"
//transform相关参数
constexpr int MaxTransforms = 2;
constexpr int StartTransformBits = 1 << 0; //0x01
constexpr int EndTransformBits = 1 << 1; //0x10
constexpr int AllTransformsBits = (1 << MaxTransforms) - 1; //0x11
//transform集合
struct TransformSet {
private:
Transform _t[MaxTransforms];
public:
Transform& operator[](int i) {
Assert(i >= 0 && i < MaxTransforms);
return _t[i];
}
const Transform& operator[](int i) const {
Assert(i >= 0 && i < MaxTransforms);
return _t[i];
}
//判断是否包含不同的transform
bool IsAnimated() const {
for (int i = 0; i < MaxTransforms - 1; ++i) {
if (_t[i] != _t[i + 1]) {
return true;
}
}
return false;
}
//返回transformSet的逆
friend TransformSet Inverse(const TransformSet& ts) {
TransformSet invSet;
for (int i = 0; i < MaxTransforms; ++i) {
invSet._t[i] = Inverse(ts._t[i]);
}
return invSet;
}
};
//渲染参数
struct RenderOptions {
Float transformStartTime = 0;
Float transformEndTime = 1;
//过滤器名字 默认 box
std::string FilterName = "box";
ParamSet FilterParams;
//Film的名字
std::string FilmName = "image";
ParamSet FilmParams;
//采样器的名字
std::string SamplerName = "random";
ParamSet SamplerParams;
//加速结构的名字
std::string AcceleratorName = "normal";
ParamSet AcceleratorParams;
//积分器的名字
std::string IntegratorName = "normal";
ParamSet IntegratorParams;
//相机的名字
std::string CameraName = "pinhole";
ParamSet CameraParams;
//光源
std::vector<std::shared_ptr<Light>> lights;
//图元
std::vector<std::shared_ptr<Primitive>> primitives;
};
struct GraphicsState{
};
//系统的三个状态
enum class APIState {
Uninitialized, OptionsBlock, WorldBlock
};
static APIState currentApiState = APIState::Uninitialized; //当前状态
static TransformSet curTransform;//当前的TransformSet
static uint32_t activeTransformBits = AllTransformsBits; //当前的TransformSet Bit
static std::map<std::string, TransformSet> namedCoordinateSystems; //保存坐标系的map
static std::unique_ptr<RenderOptions> renderOptions; //当前渲染参数
static GraphicsState graphicsState;//当前图形状态
static std::vector<GraphicsState> pushedGraphicsStates;
static std::vector<TransformSet> pushedTransforms;
static std::vector<uint32_t> pushedActiveTransformBits;
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015-2019 Dubalu LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <ostream> // for std::ostream
#include <type_traits> // for std::enable_if_t
#include <utility> // for std::forward, std::move
#include "fmt/format.h" // for fmt::formatter
template <typename F, std::enable_if_t<std::is_invocable<F&>::value, int> = 0>
auto eval(F&& invocable) {
return invocable();
}
template <typename Val, std::enable_if_t<not std::is_invocable<Val&>::value, int> = 0>
auto eval(Val&& val) {
return std::forward<Val>(val);
}
template <typename L>
class lazy_eval {
const L& lambda;
public:
using type = decltype(std::declval<L>()());
lazy_eval(const L& lambda) : lambda(lambda) {}
lazy_eval(lazy_eval&& other) : lambda(std::move(other.lambda)) { }
lazy_eval& operator=(lazy_eval&& other) {
lambda = std::move(other.lambda);
}
lazy_eval(const lazy_eval&) = delete;
lazy_eval& operator=(const lazy_eval&) = delete;
type operator()() const { return lambda(); }
explicit operator type() const { return lambda(); }
friend std::ostream& operator<<(std::ostream& os, const lazy_eval<L>& obj) {
return os << obj();
}
};
template <typename L>
struct fmt::formatter<lazy_eval<L>> : fmt::formatter<typename lazy_eval<L>::type> {
auto format(const lazy_eval<L>& val, format_context& ctx) {
return fmt::formatter<typename lazy_eval<L>::type>::format(val(), ctx);
}
};
template <typename L>
auto
make_lazy_eval(L&& lambda) {
return lazy_eval<L>{std::forward<L>(lambda)};
}
#define LAZY(Expr) make_lazy_eval([&]() { return eval(Expr); })
<commit_msg>Lazy: Indented with tabs<commit_after>/*
* Copyright (c) 2015-2019 Dubalu LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <ostream> // for std::ostream
#include <type_traits> // for std::enable_if_t
#include <utility> // for std::forward, std::move
#include "fmt/format.h" // for fmt::formatter
template <typename F, std::enable_if_t<std::is_invocable<F&>::value, int> = 0>
auto eval(F&& invocable) {
return invocable();
}
template <typename Val, std::enable_if_t<not std::is_invocable<Val&>::value, int> = 0>
auto eval(Val&& val) {
return std::forward<Val>(val);
}
template <typename L>
class lazy_eval {
const L& lambda;
public:
using type = decltype(std::declval<L>()());
lazy_eval(const L& lambda) : lambda(lambda) {}
lazy_eval(lazy_eval&& other) : lambda(std::move(other.lambda)) { }
lazy_eval& operator=(lazy_eval&& other) {
lambda = std::move(other.lambda);
}
lazy_eval(const lazy_eval&) = delete;
lazy_eval& operator=(const lazy_eval&) = delete;
type operator()() const { return lambda(); }
explicit operator type() const { return lambda(); }
friend std::ostream& operator<<(std::ostream& os, const lazy_eval<L>& obj) {
return os << obj();
}
};
template <typename L>
struct fmt::formatter<lazy_eval<L>> : fmt::formatter<typename lazy_eval<L>::type> {
auto format(const lazy_eval<L>& val, format_context& ctx) {
return fmt::formatter<typename lazy_eval<L>::type>::format(val(), ctx);
}
};
template <typename L>
auto
make_lazy_eval(L&& lambda) {
return lazy_eval<L>{std::forward<L>(lambda)};
}
#define LAZY(Expr) make_lazy_eval([&]() { return eval(Expr); })
<|endoftext|>
|
<commit_before>#include <cstring>
#include <iostream>
#include <iomanip>
#include <vector>
#include <utility>
#include <sstream>
#include "smf.hpp"
#include "parseutils.hpp"
namespace MgCore
{
uint32_t SmfReader::readVarLen()
{
uint8_t c = MgCore::read_type<uint8_t>(*m_smf);
uint32_t value = c & 0x7F;
if (c & 0x80) {
do {
c = MgCore::read_type<uint8_t>(*m_smf);
value = (value << 7) + (c & 0x7F);
} while (c & 0x80);
}
return value;
}
void SmfReader::readMidiEvent(SmfEventInfo &event)
{
MidiEvent midiEvent;
midiEvent.info = event;
midiEvent.message = event.status & 0xF0;
midiEvent.channel = event.status & 0xF;
midiEvent.data1 = MgCore::read_type<uint8_t>(*m_smf);
midiEvent.data2 = MgCore::read_type<uint8_t>(*m_smf);
std::cout << "Channel " << +midiEvent.channel << std::endl;
m_currentTrack->midiEvents.push_back(midiEvent);
}
void SmfReader::readMetaEvent(SmfEventInfo &event)
{
event.type = static_cast<MidiMetaEvent>(MgCore::read_type<uint8_t>(*m_smf));
uint32_t length = readVarLen();
switch(event.type)
{
case meta_SequenceNumber:
{
auto sequenceNumber = MgCore::read_type<uint16_t>(*m_smf);
std::cout << "Sequence Number: " << " " << std::hex << sequenceNumber << std::endl;
break;
}
case meta_Text:
case meta_Copyright:
case meta_InstrumentName:
case meta_Lyrics:
case meta_Marker:
case meta_CuePoint:
// The midi spec says the following text events exist and act the same as meta_Text.
case meta_TextReserved1:
case meta_TextReserved2:
case meta_TextReserved3:
case meta_TextReserved4:
case meta_TextReserved5:
case meta_TextReserved6:
case meta_TextReserved7:
case meta_TextReserved8:
{
auto textData = std::make_unique<char[]>(length+1);
textData[length] = '\0';
MgCore::read_type<char>(*m_smf, textData.get(), length);
TextEvent text {event, textData.get()};
break;
}
case meta_TrackName:
{
auto textData = std::make_unique<char[]>(length+1);
textData[length] = '\0';
MgCore::read_type<char>(*m_smf, textData.get(), length);
m_currentTrack->name = std::string(textData.get());
break;
}
case meta_MIDIChannelPrefix: {
auto midiChannel = MgCore::read_type<uint8_t>(*m_smf);
std::cout << "Midi Channel " << midiChannel << std::hex << std::endl;
break;
}
case meta_EndOfTrack:
{
std::cout << "End of Track " << std::endl;
break;
}
case meta_Tempo:
{
uint32_t bpmChange = read_type<uint32_t>(*m_smf, 3);
std::cout << "Tempo Change " << 60000000.0 / bpmChange << "BPM" << std::endl;
TempoEvent tempo {event, bpmChange};
m_currentTrack->tempo.push_back(tempo);
break;
}
case meta_SMPTEOffset:
case meta_TimeSignature: // TODO - Implement this...
case meta_KeySignature: // Not very useful for us
case meta_XMFPatchType: // probably not used
case meta_SequencerSpecific:
{
m_smf->seekg(length, std::ios::cur);
break;
}
default:
{
m_smf->seekg(length, std::ios::cur);
break;
}
}
}
void SmfReader::readSysExEvent(SmfEventInfo &event)
{
auto length = readVarLen();
std::cout << "sysex event " << m_smf->tellg() << std::endl;
m_smf->seekg(length, std::ios::cur);
}
void SmfReader::readFile()
{
int fileEnd = m_smf->tellg();
m_smf->seekg(0, std::ios::beg);
int fileBeg = m_smf->tellg();
int chunkStart = fileBeg;
int pos = 0;
SmfChunkInfo chunk;
MgCore::read_type<char>(*m_smf, chunk.chunkType, 4);
chunk.length = MgCore::read_type<uint32_t>(*m_smf);
if (strcmp(chunk.chunkType, "MThd") == 0) {
m_header.info = chunk;
m_header.format = MgCore::read_type<uint16_t>(*m_smf);
m_header.trackNum = MgCore::read_type<uint16_t>(*m_smf);
m_header.division = MgCore::read_type<int16_t>(*m_smf);
// seek to the end of the chunk
// 8 is the length of the type plus length fields
pos = chunkStart + (8 + chunk.length);
m_smf->seekg(pos);
if (m_header.format == smfType0 && m_header.trackNum != 1) {
throw std::runtime_error("Not a valid type 0 midi.");
}
} else {
throw std::runtime_error("Not a Standard MIDI file.");
}
if ((m_header.division & 0x8000) != 0) {
throw std::runtime_error("SMPTE division not supported");
}
for (int i = 0; i < m_header.trackNum; i++) {
MgCore::read_type<char>(*m_smf, chunk.chunkType, 4);
chunk.length = MgCore::read_type<uint32_t>(*m_smf);
m_pulseTime = 0;
double runningTimeSec = 0.0;
TempoEvent* currentTempoEvent;
// seek to the end of the chunk
// 8 is the length of the type plus length fields
chunkStart = pos;
pos = chunkStart + (8 + chunk.length);
if (strcmp(chunk.chunkType, "MTrk") == 0) {
uint8_t prevStatus;
auto track = std::make_unique<SmfTrack>();
m_currentTrack = track.get();
m_tracks.push_back(std::move(track));
while (m_smf->tellg() < pos)
{
SmfEventInfo event;
event.deltaPulses = readVarLen();
m_pulseTime += event.deltaPulses;
event.pulseTime = m_pulseTime;
auto status = MgCore::peek_type<uint8_t>(*m_smf);
if (status == status_MetaEvent) {
event.status = MgCore::read_type<uint8_t>(*m_smf);
readMetaEvent(event);
} else if (status == status_SysexEvent || status == status_SysexEvent2) {
event.status = MgCore::read_type<uint8_t>(*m_smf);
readSysExEvent(event);
} else {
if ((status & 0xF0) >= 0x80) {
event.status = MgCore::read_type<uint8_t>(*m_smf);
} else {
event.status = prevStatus;
}
readMidiEvent(event);
prevStatus = event.status;
}
currentTempoEvent = getLastTempoIdViaPulses(m_pulseTime);
if (currentTempoEvent != nullptr) {
runningTimeSec += event.deltaPulses * ((currentTempoEvent->qnLength / m_header.division) / 1000000.0);
}
}
std::cout << m_currentTrack->midiEvents.size() << std::endl;
m_currentTrack->seconds = static_cast<float>(runningTimeSec);
} else {
std::cout << "Supported track chunk not found." << std::endl;
}
m_smf->seekg(pos);
}
if (pos == fileEnd) {
std::cout << "End of MIDI reached." << std::endl;
} else {
std::cout << "Warning: Reached end of last track chunk, there is possibly data located outside of a track." << std::endl;
}
}
SmfReader::SmfReader(std::string filename)
{
m_smf = std::make_unique<std::ifstream>(filename, std::ios_base::ate | std::ios_base::binary);
// TODO - find cleaner way of implementing default the 120 BPM
// m_currentTempo = 500000; // default 120 BPM
if (*m_smf) {
readFile();
m_smf->close();
} else {
throw std::runtime_error("Failed to load MIDI file.");
}
}
TempoEvent* SmfReader::getLastTempoIdViaPulses(uint32_t pulseTime)
{
auto tempoTrack = *m_tracks[0];
auto tempos = tempoTrack.tempo;
if (tempos.size() == 0) {
std::cout << "Error too early no tempo changes" << std::endl;
return nullptr;
}
for (auto &tempo : tempos) {
if (pulseTime <= tempo.info.pulseTime) {
return &tempo;
}
}
return nullptr;
}
//TempoEvent SmfReader::getTempoViaId(int id)
//{
// tempoTrack = m_tracks[0]
// return tempoTrack->tempo[id]
//}
std::vector<SmfTrack*> SmfReader::getTracks()
{
std::vector<SmfTrack*> tracks;
for (auto &track : m_tracks) {
tracks.push_back(track.get());
}
return tracks;
}
}
<commit_msg>Fix slight bug in how current tempo event is found.<commit_after>#include <cstring>
#include <iostream>
#include <iomanip>
#include <vector>
#include <utility>
#include <sstream>
#include "smf.hpp"
#include "parseutils.hpp"
namespace MgCore
{
uint32_t SmfReader::readVarLen()
{
uint8_t c = MgCore::read_type<uint8_t>(*m_smf);
uint32_t value = c & 0x7F;
if (c & 0x80) {
do {
c = MgCore::read_type<uint8_t>(*m_smf);
value = (value << 7) + (c & 0x7F);
} while (c & 0x80);
}
return value;
}
void SmfReader::readMidiEvent(SmfEventInfo &event)
{
MidiEvent midiEvent;
midiEvent.info = event;
midiEvent.message = event.status & 0xF0;
midiEvent.channel = event.status & 0xF;
midiEvent.data1 = MgCore::read_type<uint8_t>(*m_smf);
midiEvent.data2 = MgCore::read_type<uint8_t>(*m_smf);
std::cout << "Channel " << +midiEvent.channel << std::endl;
m_currentTrack->midiEvents.push_back(midiEvent);
}
void SmfReader::readMetaEvent(SmfEventInfo &event)
{
event.type = static_cast<MidiMetaEvent>(MgCore::read_type<uint8_t>(*m_smf));
uint32_t length = readVarLen();
switch(event.type)
{
case meta_SequenceNumber:
{
auto sequenceNumber = MgCore::read_type<uint16_t>(*m_smf);
std::cout << "Sequence Number: " << " " << std::hex << sequenceNumber << std::endl;
break;
}
case meta_Text:
case meta_Copyright:
case meta_InstrumentName:
case meta_Lyrics:
case meta_Marker:
case meta_CuePoint:
// The midi spec says the following text events exist and act the same as meta_Text.
case meta_TextReserved1:
case meta_TextReserved2:
case meta_TextReserved3:
case meta_TextReserved4:
case meta_TextReserved5:
case meta_TextReserved6:
case meta_TextReserved7:
case meta_TextReserved8:
{
auto textData = std::make_unique<char[]>(length+1);
textData[length] = '\0';
MgCore::read_type<char>(*m_smf, textData.get(), length);
TextEvent text {event, textData.get()};
break;
}
case meta_TrackName:
{
auto textData = std::make_unique<char[]>(length+1);
textData[length] = '\0';
MgCore::read_type<char>(*m_smf, textData.get(), length);
m_currentTrack->name = std::string(textData.get());
break;
}
case meta_MIDIChannelPrefix: {
auto midiChannel = MgCore::read_type<uint8_t>(*m_smf);
std::cout << "Midi Channel " << midiChannel << std::hex << std::endl;
break;
}
case meta_EndOfTrack:
{
std::cout << "End of Track " << std::endl;
break;
}
case meta_Tempo:
{
uint32_t bpmChange = read_type<uint32_t>(*m_smf, 3);
std::cout << "Tempo Change " << 60000000.0 / bpmChange << "BPM" << std::endl;
TempoEvent tempo {event, bpmChange};
m_currentTrack->tempo.push_back(tempo);
break;
}
case meta_SMPTEOffset:
case meta_TimeSignature: // TODO - Implement this...
case meta_KeySignature: // Not very useful for us
case meta_XMFPatchType: // probably not used
case meta_SequencerSpecific:
{
m_smf->seekg(length, std::ios::cur);
break;
}
default:
{
m_smf->seekg(length, std::ios::cur);
break;
}
}
}
void SmfReader::readSysExEvent(SmfEventInfo &event)
{
auto length = readVarLen();
std::cout << "sysex event " << m_smf->tellg() << std::endl;
m_smf->seekg(length, std::ios::cur);
}
void SmfReader::readFile()
{
int fileEnd = m_smf->tellg();
m_smf->seekg(0, std::ios::beg);
int fileBeg = m_smf->tellg();
int chunkStart = fileBeg;
int pos = 0;
SmfChunkInfo chunk;
MgCore::read_type<char>(*m_smf, chunk.chunkType, 4);
chunk.length = MgCore::read_type<uint32_t>(*m_smf);
if (strcmp(chunk.chunkType, "MThd") == 0) {
m_header.info = chunk;
m_header.format = MgCore::read_type<uint16_t>(*m_smf);
m_header.trackNum = MgCore::read_type<uint16_t>(*m_smf);
m_header.division = MgCore::read_type<int16_t>(*m_smf);
// seek to the end of the chunk
// 8 is the length of the type plus length fields
pos = chunkStart + (8 + chunk.length);
m_smf->seekg(pos);
if (m_header.format == smfType0 && m_header.trackNum != 1) {
throw std::runtime_error("Not a valid type 0 midi.");
}
} else {
throw std::runtime_error("Not a Standard MIDI file.");
}
if ((m_header.division & 0x8000) != 0) {
throw std::runtime_error("SMPTE division not supported");
}
for (int i = 0; i < m_header.trackNum; i++) {
MgCore::read_type<char>(*m_smf, chunk.chunkType, 4);
chunk.length = MgCore::read_type<uint32_t>(*m_smf);
m_pulseTime = 0;
double runningTimeSec = 0.0;
TempoEvent* currentTempoEvent;
// seek to the end of the chunk
// 8 is the length of the type plus length fields
chunkStart = pos;
pos = chunkStart + (8 + chunk.length);
if (strcmp(chunk.chunkType, "MTrk") == 0) {
uint8_t prevStatus;
auto track = std::make_unique<SmfTrack>();
m_currentTrack = track.get();
m_tracks.push_back(std::move(track));
while (m_smf->tellg() < pos)
{
SmfEventInfo event;
event.deltaPulses = readVarLen();
m_pulseTime += event.deltaPulses;
event.pulseTime = m_pulseTime;
auto status = MgCore::peek_type<uint8_t>(*m_smf);
if (status == status_MetaEvent) {
event.status = MgCore::read_type<uint8_t>(*m_smf);
readMetaEvent(event);
} else if (status == status_SysexEvent || status == status_SysexEvent2) {
event.status = MgCore::read_type<uint8_t>(*m_smf);
readSysExEvent(event);
} else {
if ((status & 0xF0) >= 0x80) {
event.status = MgCore::read_type<uint8_t>(*m_smf);
} else {
event.status = prevStatus;
}
readMidiEvent(event);
prevStatus = event.status;
}
currentTempoEvent = getLastTempoIdViaPulses(m_pulseTime);
if (currentTempoEvent != nullptr) {
runningTimeSec += event.deltaPulses * ((currentTempoEvent->qnLength / m_header.division) / 1000000.0);
}
}
std::cout << m_currentTrack->midiEvents.size() << std::endl;
m_currentTrack->seconds = static_cast<float>(runningTimeSec);
} else {
std::cout << "Supported track chunk not found." << std::endl;
}
m_smf->seekg(pos);
}
if (pos == fileEnd) {
std::cout << "End of MIDI reached." << std::endl;
} else {
std::cout << "Warning: Reached end of last track chunk, there is possibly data located outside of a track." << std::endl;
}
}
SmfReader::SmfReader(std::string filename)
{
m_smf = std::make_unique<std::ifstream>(filename, std::ios_base::ate | std::ios_base::binary);
// TODO - find cleaner way of implementing default the 120 BPM
// m_currentTempo = 500000; // default 120 BPM
if (*m_smf) {
readFile();
m_smf->close();
} else {
throw std::runtime_error("Failed to load MIDI file.");
}
}
TempoEvent* SmfReader::getLastTempoIdViaPulses(uint32_t pulseTime)
{
auto tempoTrack = *m_tracks[0];
auto tempos = tempoTrack.tempo;
if (tempos.size() == 0) {
std::cout << "Error too early no tempo changes" << std::endl;
return nullptr;
}
for (auto &tempo : tempos) {
if (pulseTime >= tempo.info.pulseTime) {
return &tempo;
}
}
return nullptr;
}
//TempoEvent SmfReader::getTempoViaId(int id)
//{
// tempoTrack = m_tracks[0]
// return tempoTrack->tempo[id]
//}
std::vector<SmfTrack*> SmfReader::getTracks()
{
std::vector<SmfTrack*> tracks;
for (auto &track : m_tracks) {
tracks.push_back(track.get());
}
return tracks;
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include"ork/ork.hpp"
#define ORK_STL_INC_FILE <fstream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <iostream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <mutex>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <sstream>
#include"ork/core/stl_include.inl"
#include"ork/memory.hpp"
namespace ork {
const ork::string debug_trace(ORK("debug_trace"));
const ork::string output_data(ORK("output_data"));
const ork::string&to_string(const log_channel val) {
switch(val) {
case log_channel::debug_trace:
return debug_trace;
case log_channel::output_data:
return output_data;
};
ORK_UNREACHABLE
}
log_channel string2log_channel(const ork::string&str) {
if(str == output_data) {
return log_channel::output_data;
}
if(str == output_data) {
return log_channel::output_data;
}
ORK_THROW(ORK("Invalid log_channel: ") << str);
}
const ork::string trace(ORK("trace"));
const ork::string debug(ORK("debug"));
const ork::string info(ORK("info"));
const ork::string warning(ORK("warning"));
const ork::string error(ORK("error"));
const ork::string fatal(ORK("fatal"));
const ork::string&to_string(const severity_level val) {
switch(val) {
case severity_level::trace:
return trace;
case severity_level::debug:
return debug;
case severity_level::info:
return info;
case severity_level::warning:
return warning;
case severity_level::error:
return error;
case severity_level::fatal:
return fatal;
};
ORK_UNREACHABLE
}
severity_level string2severity_level(const ork::string&str) {
if(str == trace) {
return severity_level::trace;
}
if(str == debug) {
return severity_level::debug;
}
if(str == info) {
return severity_level::info;
}
if(str == warning) {
return severity_level::warning;
}
if(str == error) {
return severity_level::error;
}
if(str == fatal) {
return severity_level::fatal;
}
ORK_THROW(ORK("Invalid severity_level: ") << str);
}
//This is little more than a synchronous wrapper around an o_stream
class log_stream {
public:
using stream_ptr = std::shared_ptr<o_stream>;
private:
stream_ptr _stream;
std::mutex _mutex;
public:
explicit log_stream(stream_ptr stream_) : _stream{stream_}, _mutex{} {}
~log_stream() {
flush();
}
ORK_NON_COPYABLE(log_stream)
public:
void log(const string&message) {
std::lock_guard<std::mutex>lock(_mutex);
*_stream << message;
}
void flush() {
_stream->flush();
}
};
class log_sink {
public:
using stream_ptr = std::shared_ptr<log_stream>;
private:
std::vector<stream_ptr>_streams = {};
bool _auto_flush = true;
public:
log_sink() {}
log_sink(const bool auto_flush) : _auto_flush{auto_flush} {}
public:
void insert(const stream_ptr&ptr) {
_streams.push_back(ptr);
}
void log(const string&message) {
for(auto&stream : _streams) {
stream->log(message);
if(_auto_flush) {
stream->flush();
}
}
}
void set_auto_flush(const bool auto_flush) {
_auto_flush = auto_flush;
}
void flush() {
for(auto&stream : _streams) {
stream->flush();
}
}
};
std::shared_ptr<log_stream>open_file_log_stream(const file::path&file_name) {
if(!file::ensure_directory(file_name)) {
ORK_THROW(ORK("Could not create directory : ") << file_name.ORK_GEN_STR())
}
of_stream* p_stream = new of_stream();
p_stream->open(file_name);//std::ios::app | std::ios::ate
if(p_stream->fail()) {
ORK_THROW(ORK("Error opening log : ") << file_name)
}
//p_stream->rdbuf()->pubsetbuf(0, 0);//Less performance, more likely to catch error messages
return std::shared_ptr<log_stream>(new log_stream(log_stream::stream_ptr(p_stream)));
}
//This is where our logging system falls short of a generic filter system; try to hide it somewhat in one place
class log_multiplexer {
private:
std::array<log_sink, severity_levels.size()>_severity_sinks = {};
log_sink _data_sink = {};
public:
log_multiplexer(const file::path&root_directory){
auto lout = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CLOG, singleton_deleter<o_stream>()}}};
auto lerr = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CERR, singleton_deleter<o_stream>()}}};
auto flog = open_file_log_stream(root_directory / ORK("trace.log"));
auto fdata = open_file_log_stream(root_directory / ORK("output.log"));
for(const auto sv : severity_levels) {
auto sink = _severity_sinks[static_cast<size_t>(sv)];
if(sv < severity_level::error) {
sink.insert(lout);
sink.set_auto_flush(true);
}
else {
sink.insert(lerr);
}
sink.insert(flog);
}
_data_sink.insert(lout);
_data_sink.insert(fdata);
}
public:
void log(const log_channel channel, const severity_level severity, const o_string_stream&stream) {
const string message = stream.str();
switch(channel) {
case log_channel::debug_trace:
log_severity(severity, message);
break;
case log_channel::output_data:
_data_sink.log(stream.str());
break;
default:
ORK_UNREACHABLE
};
}
void flush_all() {
for(auto&sink : _severity_sinks) {
sink.flush();
}
_data_sink.flush();
}
private:
void log_severity(const severity_level severity, const string&message) {
const bool do_it = ORK_DEBUG || severity > severity_level::debug;
if(do_it || true) {//To avoid constant conditional expression
_severity_sinks[static_cast<size_t>(severity)].log(message);
}
}
};
struct log_scope::impl {
public:
std::shared_ptr<log_multiplexer>multiplexer;
log_channel channel;
severity_level severity;
o_string_stream stream;
public:
impl(std::shared_ptr<log_multiplexer>&mp, const log_channel lc, const severity_level sv)
: multiplexer{mp}
, channel{lc}
, severity{sv}
, stream{}
{}
~impl() {
multiplexer->log(channel, severity, stream);
}
ORK_MOVE_ONLY(impl)
};
log_scope::log_scope(std::unique_ptr<impl>&&ptr) : _pimpl{ std::move(ptr) } {}
log_scope::~log_scope() {}
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << val;\
return *this;\
}
LOG_STREAM_OPERATOR(bool)
LOG_STREAM_OPERATOR(short)
LOG_STREAM_OPERATOR(unsigned short)
LOG_STREAM_OPERATOR(int)
LOG_STREAM_OPERATOR(unsigned)
LOG_STREAM_OPERATOR(long)
LOG_STREAM_OPERATOR(unsigned long)
LOG_STREAM_OPERATOR(long long)
LOG_STREAM_OPERATOR(unsigned long long)
LOG_STREAM_OPERATOR(float)
LOG_STREAM_OPERATOR(double)
LOG_STREAM_OPERATOR(long double)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_BYTE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(char)
LOG_STREAM_OPERATOR(char*)
LOG_STREAM_OPERATOR(bstring&)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_WIDE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(wchar_t)
LOG_STREAM_OPERATOR(wchar_t*)
LOG_STREAM_OPERATOR(wstring&)
log_scope& log_scope::operator<< (const void* val) {
_pimpl->stream << val;
return *this;
}
log_scope& log_scope::operator<< (const std::streambuf* sb) {
_pimpl->stream << sb;
return *this;
}
log_scope& log_scope::operator<< (std::ostream& (*pf)(std::ostream&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios& (*pf)(std::ios&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios_base& (*pf)(std::ios_base&)) {
_pimpl->stream << pf;
return *this;
}
const string&to_formatted_string(const severity_level sv) {
static const std::array<const string, severity_levels.size()>strings = {{
ORK("TRACE")
, ORK("DEBUG")
, ORK("INFO ")
, ORK("WARN ")
, ORK("ERROR")
, ORK("FATAL")
}};
return strings[static_cast<size_t>(sv)];
}
struct logger::impl {
public:
file::path root_directory;
std::shared_ptr<log_multiplexer>multiplexer;
public:
impl(const file::path&directory)
: root_directory(directory)
, multiplexer{new log_multiplexer(directory)}
{}
void flush_all() {
multiplexer->flush_all();
}
};
logger::logger(const file::path&log_directory) : _pimpl(new impl(log_directory)) {}
logger::~logger() {}
const file::path& logger::root_directory() {
return _pimpl->root_directory;
}
log_scope logger::get_log_scope(
const string&file_
, const string&line_
, const string&function_
, const log_channel channel
, const severity_level severity)
{
const file::path fullpath(file_);
string file(fullpath.filename().ORK_GEN_STR());
file.resize(28, ORK(' '));
string line(line_);
line.resize(4, ORK(' '));
string function(function_);
function.resize(40, ORK(' '));
std::unique_ptr<log_scope::impl> ls_impl(new log_scope::impl(_pimpl->multiplexer, channel, severity));
log_scope scope(std::move(ls_impl));
//Output formatted context first
scope << ORK("[") << to_formatted_string(severity) << ORK("]:") << file << ORK("(") << line << ORK("):") << function << ORK("-- ");
//Finally, return the stream to the client
return std::move(scope);
}
void logger::flush_all() {
_pimpl->flush_all();
}
logger*_g_log = nullptr;
int make_global_log(const string&directory) {
static logger log(directory);
_g_log = &log;
return 0;
}
logger& get_global_log() {
return *_g_log;
}
}//namespace ork
<commit_msg>Eliminated warning from constant conditional<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include"ork/ork.hpp"
#define ORK_STL_INC_FILE <fstream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <iostream>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <mutex>
#include"ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <sstream>
#include"ork/core/stl_include.inl"
#include"ork/memory.hpp"
namespace ork {
const ork::string debug_trace(ORK("debug_trace"));
const ork::string output_data(ORK("output_data"));
const ork::string&to_string(const log_channel val) {
switch(val) {
case log_channel::debug_trace:
return debug_trace;
case log_channel::output_data:
return output_data;
};
ORK_UNREACHABLE
}
log_channel string2log_channel(const ork::string&str) {
if(str == output_data) {
return log_channel::output_data;
}
if(str == output_data) {
return log_channel::output_data;
}
ORK_THROW(ORK("Invalid log_channel: ") << str);
}
const ork::string trace(ORK("trace"));
const ork::string debug(ORK("debug"));
const ork::string info(ORK("info"));
const ork::string warning(ORK("warning"));
const ork::string error(ORK("error"));
const ork::string fatal(ORK("fatal"));
const ork::string&to_string(const severity_level val) {
switch(val) {
case severity_level::trace:
return trace;
case severity_level::debug:
return debug;
case severity_level::info:
return info;
case severity_level::warning:
return warning;
case severity_level::error:
return error;
case severity_level::fatal:
return fatal;
};
ORK_UNREACHABLE
}
severity_level string2severity_level(const ork::string&str) {
if(str == trace) {
return severity_level::trace;
}
if(str == debug) {
return severity_level::debug;
}
if(str == info) {
return severity_level::info;
}
if(str == warning) {
return severity_level::warning;
}
if(str == error) {
return severity_level::error;
}
if(str == fatal) {
return severity_level::fatal;
}
ORK_THROW(ORK("Invalid severity_level: ") << str);
}
//This is little more than a synchronous wrapper around an o_stream
class log_stream {
public:
using stream_ptr = std::shared_ptr<o_stream>;
private:
stream_ptr _stream;
std::mutex _mutex;
public:
explicit log_stream(stream_ptr stream_) : _stream{stream_}, _mutex{} {}
~log_stream() {
flush();
}
ORK_NON_COPYABLE(log_stream)
public:
void log(const string&message) {
std::lock_guard<std::mutex>lock(_mutex);
*_stream << message;
}
void flush() {
_stream->flush();
}
};
class log_sink {
public:
using stream_ptr = std::shared_ptr<log_stream>;
private:
std::vector<stream_ptr>_streams = {};
bool _auto_flush = true;
public:
log_sink() {}
log_sink(const bool auto_flush) : _auto_flush{auto_flush} {}
public:
void insert(const stream_ptr&ptr) {
_streams.push_back(ptr);
}
void log(const string&message) {
for(auto&stream : _streams) {
stream->log(message);
if(_auto_flush) {
stream->flush();
}
}
}
void set_auto_flush(const bool auto_flush) {
_auto_flush = auto_flush;
}
void flush() {
for(auto&stream : _streams) {
stream->flush();
}
}
};
std::shared_ptr<log_stream>open_file_log_stream(const file::path&file_name) {
if(!file::ensure_directory(file_name)) {
ORK_THROW(ORK("Could not create directory : ") << file_name.ORK_GEN_STR())
}
of_stream* p_stream = new of_stream();
p_stream->open(file_name);//std::ios::app | std::ios::ate
if(p_stream->fail()) {
ORK_THROW(ORK("Error opening log : ") << file_name)
}
//p_stream->rdbuf()->pubsetbuf(0, 0);//Less performance, more likely to catch error messages
return std::shared_ptr<log_stream>(new log_stream(log_stream::stream_ptr(p_stream)));
}
//This is where our logging system falls short of a generic filter system; try to hide it somewhat in one place
class log_multiplexer {
private:
std::array<log_sink, severity_levels.size()>_severity_sinks = {};
log_sink _data_sink = {};
public:
log_multiplexer(const file::path&root_directory){
auto lout = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CLOG, singleton_deleter<o_stream>()}}};
auto lerr = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CERR, singleton_deleter<o_stream>()}}};
auto flog = open_file_log_stream(root_directory / ORK("trace.log"));
auto fdata = open_file_log_stream(root_directory / ORK("output.log"));
for(const auto sv : severity_levels) {
auto sink = _severity_sinks[static_cast<size_t>(sv)];
if(sv < severity_level::error) {
sink.insert(lout);
sink.set_auto_flush(true);
}
else {
sink.insert(lerr);
}
sink.insert(flog);
}
_data_sink.insert(lout);
_data_sink.insert(fdata);
}
public:
void log(const log_channel channel, const severity_level severity, const o_string_stream&stream) {
const string message = stream.str();
switch(channel) {
case log_channel::debug_trace:
log_severity(severity, message);
break;
case log_channel::output_data:
_data_sink.log(stream.str());
break;
default:
ORK_UNREACHABLE
};
}
void flush_all() {
for(auto&sink : _severity_sinks) {
sink.flush();
}
_data_sink.flush();
}
private:
void log_severity(const severity_level severity, const string&message) {
const bool do_it = ORK_DEBUG || severity > severity_level::debug;
if ORK_CONSTEXPR(do_it || true) {
_severity_sinks[static_cast<size_t>(severity)].log(message);
}
}
};
struct log_scope::impl {
public:
std::shared_ptr<log_multiplexer>multiplexer;
log_channel channel;
severity_level severity;
o_string_stream stream;
public:
impl(std::shared_ptr<log_multiplexer>&mp, const log_channel lc, const severity_level sv)
: multiplexer{mp}
, channel{lc}
, severity{sv}
, stream{}
{}
~impl() {
multiplexer->log(channel, severity, stream);
}
ORK_MOVE_ONLY(impl)
};
log_scope::log_scope(std::unique_ptr<impl>&&ptr) : _pimpl{ std::move(ptr) } {}
log_scope::~log_scope() {}
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << val;\
return *this;\
}
LOG_STREAM_OPERATOR(bool)
LOG_STREAM_OPERATOR(short)
LOG_STREAM_OPERATOR(unsigned short)
LOG_STREAM_OPERATOR(int)
LOG_STREAM_OPERATOR(unsigned)
LOG_STREAM_OPERATOR(long)
LOG_STREAM_OPERATOR(unsigned long)
LOG_STREAM_OPERATOR(long long)
LOG_STREAM_OPERATOR(unsigned long long)
LOG_STREAM_OPERATOR(float)
LOG_STREAM_OPERATOR(double)
LOG_STREAM_OPERATOR(long double)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_BYTE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(char)
LOG_STREAM_OPERATOR(char*)
LOG_STREAM_OPERATOR(bstring&)
#undef LOG_STREAM_OPERATOR
#define LOG_STREAM_OPERATOR(TYPE) \
log_scope& log_scope::operator<< (const TYPE val) {\
_pimpl->stream << ORK_WIDE_2_STR(val);\
return *this;\
}
LOG_STREAM_OPERATOR(wchar_t)
LOG_STREAM_OPERATOR(wchar_t*)
LOG_STREAM_OPERATOR(wstring&)
log_scope& log_scope::operator<< (const void* val) {
_pimpl->stream << val;
return *this;
}
log_scope& log_scope::operator<< (const std::streambuf* sb) {
_pimpl->stream << sb;
return *this;
}
log_scope& log_scope::operator<< (std::ostream& (*pf)(std::ostream&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios& (*pf)(std::ios&)) {
_pimpl->stream << pf;
return *this;
}
log_scope& log_scope::operator<< (std::ios_base& (*pf)(std::ios_base&)) {
_pimpl->stream << pf;
return *this;
}
const string&to_formatted_string(const severity_level sv) {
static const std::array<const string, severity_levels.size()>strings = {{
ORK("TRACE")
, ORK("DEBUG")
, ORK("INFO ")
, ORK("WARN ")
, ORK("ERROR")
, ORK("FATAL")
}};
return strings[static_cast<size_t>(sv)];
}
struct logger::impl {
public:
file::path root_directory;
std::shared_ptr<log_multiplexer>multiplexer;
public:
impl(const file::path&directory)
: root_directory(directory)
, multiplexer{new log_multiplexer(directory)}
{}
void flush_all() {
multiplexer->flush_all();
}
};
logger::logger(const file::path&log_directory) : _pimpl(new impl(log_directory)) {}
logger::~logger() {}
const file::path& logger::root_directory() {
return _pimpl->root_directory;
}
log_scope logger::get_log_scope(
const string&file_
, const string&line_
, const string&function_
, const log_channel channel
, const severity_level severity)
{
const file::path fullpath(file_);
string file(fullpath.filename().ORK_GEN_STR());
file.resize(28, ORK(' '));
string line(line_);
line.resize(4, ORK(' '));
string function(function_);
function.resize(40, ORK(' '));
std::unique_ptr<log_scope::impl> ls_impl(new log_scope::impl(_pimpl->multiplexer, channel, severity));
log_scope scope(std::move(ls_impl));
//Output formatted context first
scope << ORK("[") << to_formatted_string(severity) << ORK("]:") << file << ORK("(") << line << ORK("):") << function << ORK("-- ");
//Finally, return the stream to the client
return std::move(scope);
}
void logger::flush_all() {
_pimpl->flush_all();
}
logger*_g_log = nullptr;
int make_global_log(const string&directory) {
static logger log(directory);
_g_log = &log;
return 0;
}
logger& get_global_log() {
return *_g_log;
}
}//namespace ork
<|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 <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>
#include <boost/config.hpp>
using boost::bind;
using namespace libtorrent;
namespace libtorrent
{
// defined in broadcast_socket.cpp
address guess_local_address(asio::io_service&);
}
lsd::lsd(io_service& ios, address const& listen_interface
, peer_callback_t const& cb)
: m_callback(cb)
, m_retry_count(0)
, m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143"), 6771)
, bind(&lsd::on_announce, self(), _1, _2, _3))
, m_broadcast_timer(ios)
, m_disabled(false)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
}
lsd::~lsd() {}
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(msg.c_str(), int(msg.size()), 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, self(), _1, msg));
}
void lsd::resend_announce(asio::error_code const& e, std::string msg) try
{
if (e) return;
asio::error_code ec;
m_socket.send(msg.c_str(), int(msg.size()), ec);
++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, self(), _1, msg));
}
catch (std::exception&)
{}
void lsd::on_announce(udp::endpoint const& from, char* buffer
, std::size_t bytes_transferred)
{
using namespace libtorrent::detail;
http_parser p;
p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred));
if (!p.header_finished())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: incomplete HTTP message\n";
#endif
return;
}
if (p.method() != "bt-search")
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid HTTP method: " << p.method() << std::endl;
#endif
return;
}
std::string const& port_str = p.header("port");
if (port_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing port" << std::endl;
#endif
return;
}
std::string const& ih_str = p.header("infohash");
if (ih_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing infohash" << std::endl;
#endif
return;
}
sha1_hash ih(0);
std::istringstream ih_sstr(ih_str);
ih_sstr >> ih;
int port = atoi(port_str.c_str());
if (!ih.is_all_zeros() && port != 0)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " *** incoming local announce " << from.address()
<< ":" << port << " ih: " << ih << std::endl;
#endif
// we got an announce, pass it on through the callback
try { m_callback(tcp::endpoint(from.address(), port), ih); }
catch (std::exception&) {}
}
}
void lsd::close()
{
m_socket.close();
}
<commit_msg>lsd close fix<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 <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>
#include <boost/config.hpp>
using boost::bind;
using namespace libtorrent;
namespace libtorrent
{
// defined in broadcast_socket.cpp
address guess_local_address(asio::io_service&);
}
lsd::lsd(io_service& ios, address const& listen_interface
, peer_callback_t const& cb)
: m_callback(cb)
, m_retry_count(0)
, m_socket(ios, udp::endpoint(address_v4::from_string("239.192.152.143"), 6771)
, bind(&lsd::on_announce, self(), _1, _2, _3))
, m_broadcast_timer(ios)
, m_disabled(false)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc);
#endif
}
lsd::~lsd() {}
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(msg.c_str(), int(msg.size()), 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, self(), _1, msg));
}
void lsd::resend_announce(asio::error_code const& e, std::string msg) try
{
if (e) return;
asio::error_code ec;
m_socket.send(msg.c_str(), int(msg.size()), ec);
++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, self(), _1, msg));
}
catch (std::exception&)
{}
void lsd::on_announce(udp::endpoint const& from, char* buffer
, std::size_t bytes_transferred)
{
using namespace libtorrent::detail;
http_parser p;
p.incoming(buffer::const_interval(buffer, buffer + bytes_transferred));
if (!p.header_finished())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: incomplete HTTP message\n";
#endif
return;
}
if (p.method() != "bt-search")
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid HTTP method: " << p.method() << std::endl;
#endif
return;
}
std::string const& port_str = p.header("port");
if (port_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing port" << std::endl;
#endif
return;
}
std::string const& ih_str = p.header("infohash");
if (ih_str.empty())
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " <== announce: invalid BT-SEARCH, missing infohash" << std::endl;
#endif
return;
}
sha1_hash ih(0);
std::istringstream ih_sstr(ih_str);
ih_sstr >> ih;
int port = atoi(port_str.c_str());
if (!ih.is_all_zeros() && port != 0)
{
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
m_log << time_now_string()
<< " *** incoming local announce " << from.address()
<< ":" << port << " ih: " << ih << std::endl;
#endif
// we got an announce, pass it on through the callback
try { m_callback(tcp::endpoint(from.address(), port), ih); }
catch (std::exception&) {}
}
}
void lsd::close()
{
asio::error_code ec;
m_socket.close(ec);
m_broadcast_timer.cancel();
}
<|endoftext|>
|
<commit_before> /**
* Copyright (C) 2014 Lantern
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "natty.h"
#include "peer_connection_client.h"
#include "talk/base/thread.h"
class CustomSocketServer : public talk_base::PhysicalSocketServer {
public:
CustomSocketServer(talk_base::Thread* thread)
: thread_(thread), natty_(NULL), client_(NULL) {}
virtual ~CustomSocketServer() {}
void set_client(PeerConnectionClient* client) { client_ = client; }
void set_natty(Natty* natty) { natty_ = natty; }
Natty* get_natty() { return natty_; }
virtual bool Wait(int cms, bool process_io) {
if (!natty_->connection_active() &&
client_ != NULL && !client_->is_connected()) {
thread_->Quit();
}
return talk_base::PhysicalSocketServer::Wait(0/*cms == -1 ? 1 : cms*/,
process_io);
}
protected:
talk_base::Thread* thread_;
Natty* natty_;
PeerConnectionClient* client_;
};
int main(int argc, char* argv[]) {
PeerConnectionClient client;
talk_base::Thread* thread = talk_base::Thread::Current();
talk_base::scoped_refptr<Natty> natty(
new talk_base::RefCountedObject<Natty>(&client, thread));
CustomSocketServer socket_server(thread);
thread->set_socketserver(&socket_server);
socket_server.set_client(natty->getClient());
socket_server.set_natty(natty);
thread->Run();
natty->SetupSocketServer();
sleep(3);
natty->Shutdown();
thread->set_socketserver(NULL);
return 0;
}
<commit_msg>update getclient case inconsistency<commit_after> /**
* Copyright (C) 2014 Lantern
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "natty.h"
#include "peer_connection_client.h"
#include "talk/base/thread.h"
class NattySocket : public talk_base::PhysicalSocketServer {
public:
NattySocket(talk_base::Thread* thread)
: thread_(thread), natty_(NULL), client_(NULL) {}
virtual ~NattySocket() {}
void set_client(PeerConnectionClient* client) { client_ = client; }
void set_natty(Natty* natty) { natty_ = natty; }
Natty* get_natty() { return natty_; }
virtual bool Wait(int cms, bool process_io) {
if (!natty_->connection_active() &&
client_ != NULL && !client_->is_connected()) {
thread_->Quit();
}
return talk_base::PhysicalSocketServer::Wait(0/*cms == -1 ? 1 : cms*/,
process_io);
}
protected:
talk_base::Thread* thread_;
Natty* natty_;
PeerConnectionClient* client_;
};
int main(int argc, char* argv[]) {
PeerConnectionClient client;
talk_base::Thread* thread = talk_base::Thread::Current();
talk_base::scoped_refptr<Natty> natty(
new talk_base::RefCountedObject<Natty>(&client, thread));
NattySocket socket_server(thread);
thread->set_socketserver(&socket_server);
socket_server.set_client(natty->GetClient());
socket_server.set_natty(natty);
thread->Run();
natty->SetupSocketServer();
sleep(3);
natty->Shutdown();
thread->set_socketserver(NULL);
return 0;
}
<|endoftext|>
|
<commit_before>#define GLEW_STATIC
#define RUN_GRAPHICS_DISPLAY 0x00;
#include <GL/glew.h>
#include <GL/gl.h>
#include <SDL2/SDL.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <iostream>
#include <memory>
#include <boost/program_options.hpp>
#include "common.h"
#include "GameWorld.h"
// Lousy global variables
const Uint8* keyboard_input;
bool use_mouse = false;
/*
* SDL timers run in separate threads. In the timer thread
* push an event onto the event queue. This event signifies
* to call display() from the thread in which the OpenGL
* context was created.
*/
Uint32 tick(Uint32 interval, void *param)
{
SDL_Event event;
event.type = SDL_USEREVENT;
event.user.code = RUN_GRAPHICS_DISPLAY;
event.user.data1 = 0;
event.user.data2 = 0;
SDL_PushEvent(&event);
return interval;
}
struct SDLWindowDeleter
{
inline void operator()(SDL_Window* window)
{
SDL_DestroyWindow(window);
}
};
/*
* Draws the game world and handles buffer switching.
*/
void Draw(const std::shared_ptr<SDL_Window> window, const std::shared_ptr<GameWorld> game_world)
{
if(use_mouse)
{
int x, y;
SDL_GetRelativeMouseState(&x, &y);
game_world->MoveCamera(x,y);
}
// Background colour for the window
glClearColor(0.0f, 0.2f, 0.2f, 0.3f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// Update game_world camera
if(keyboard_input[SDL_SCANCODE_W])
game_world->CameraController(1); // forward
if(keyboard_input[SDL_SCANCODE_A])
game_world->CameraController(2); // left
if(keyboard_input[SDL_SCANCODE_S])
game_world->CameraController(3); // back
if(keyboard_input[SDL_SCANCODE_D])
game_world->CameraController(4); // right
if(keyboard_input[SDL_SCANCODE_I])
game_world->CameraController(5); // cam up
if(keyboard_input[SDL_SCANCODE_J])
game_world->CameraController(6); // cam left
if(keyboard_input[SDL_SCANCODE_K])
game_world->CameraController(7); // cam down
if(keyboard_input[SDL_SCANCODE_L])
game_world->CameraController(8); // cam right
if(keyboard_input[SDL_SCANCODE_R])
game_world->CameraController(9); // player: +y ("fly" up)
if(keyboard_input[SDL_SCANCODE_F])
game_world->CameraController(10); // player: -y ("fly" down)
// Draw the gameworld
game_world->Draw();
// Swap buffers
SDL_GL_SwapWindow(window.get());
}
/*
* Handles the initialisation of the game world.
* Configures the SDL window and initialises GLEW
*/
std::shared_ptr<SDL_Window> InitWorld()
{
// Window properties
Uint32 width = 640;
Uint32 height = 480;
SDL_Window * _window;
std::shared_ptr<SDL_Window> window;
// Glew will later ensure that OpenGL 3 *is* supported
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
// Do double buffering in GL
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
// Initialise SDL - when using C/C++ it's common to have to
// initialise libraries by calling a function within them.
if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER) < 0)
{
std::cout << "Failed to initialise SDL: " << SDL_GetError() << std::endl;
return nullptr;
}
SDL_GetError();
// When we close a window quit the SDL application
atexit(SDL_Quit);
// Create a new window with an OpenGL surface
_window = SDL_CreateWindow("BlockWorld"
, SDL_WINDOWPOS_CENTERED
, SDL_WINDOWPOS_CENTERED
, width
, height
, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
if(!_window)
{
std::cout << "Failed to create SDL window: " << SDL_GetError() << std::endl;
return nullptr;
}
SDL_GLContext glContext = SDL_GL_CreateContext(_window);
if (!glContext)
{
std::cout << "Failed to create OpenGL context: " << SDL_GetError() << std::endl;
return nullptr;
}
// Initialise GLEW - an easy way to ensure OpenGl 3.0+
// The *must* be done after we have set the video mode - otherwise we have no
// OpenGL context to test.
glewInit();
if(!glewIsSupported("GL_VERSION_3_0"))
{
std::cerr << "OpenGL 3.0 not available" << std::endl;
return nullptr;
}
// OpenGL settings
glDisable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
window.reset(_window, SDL_DestroyWindow);
return window;
}
ApplicationMode ParseOptions (int argc, char ** argv)
{
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help", "print this help message")
("mouse", "Enabled experimental mouse-look")
("translate", "Show translation example (default)")
("rotate", "Show rotation example")
("scale", "Show scale example");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << desc << std::endl;
exit(0);
}
if(vm.count("mouse"))
{
use_mouse = true;
}
if(vm.count("rotate"))
{
return ROTATE;
}
if(vm.count("scale"))
{
return SCALE;
}
// The default
return TRANSFORM;
}
int main(int argc, char ** argv) {
Uint32 delay = 1000/60; // in milliseconds
auto mode = ParseOptions(argc, argv);
auto window = InitWorld();
auto game_world = std::make_shared<GameWorld>(mode);
if(!window)
{
SDL_Quit();
}
keyboard_input = SDL_GetKeyboardState(NULL);
// Call the function "tick" every delay milliseconds
SDL_AddTimer(delay, tick, NULL);
// Add the main event loop
SDL_Event event;
while (SDL_WaitEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
SDL_Quit();
break;
case SDL_USEREVENT:
Draw(window, game_world);
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_SPACE:
game_world->DoAction(1);
break;
case SDLK_q:
game_world->DoAction(2);
break;
case SDLK_g:
game_world->DoAction(3);
break;
case SDLK_ESCAPE:
exit(0);
break;
}
break;
default:
break;
}
}
}
<commit_msg>Remove glm function deprecated warning message<commit_after>#define GLEW_STATIC
#define RUN_GRAPHICS_DISPLAY 0x00;
#define GLM_FORCE_RADIANS
#include <GL/glew.h>
#include <GL/gl.h>
#include <SDL2/SDL.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <iostream>
#include <memory>
#include <boost/program_options.hpp>
#include "common.h"
#include "GameWorld.h"
// Lousy global variables
const Uint8* keyboard_input;
bool use_mouse = false;
/*
* SDL timers run in separate threads. In the timer thread
* push an event onto the event queue. This event signifies
* to call display() from the thread in which the OpenGL
* context was created.
*/
Uint32 tick(Uint32 interval, void *param)
{
SDL_Event event;
event.type = SDL_USEREVENT;
event.user.code = RUN_GRAPHICS_DISPLAY;
event.user.data1 = 0;
event.user.data2 = 0;
SDL_PushEvent(&event);
return interval;
}
struct SDLWindowDeleter
{
inline void operator()(SDL_Window* window)
{
SDL_DestroyWindow(window);
}
};
/*
* Draws the game world and handles buffer switching.
*/
void Draw(const std::shared_ptr<SDL_Window> window, const std::shared_ptr<GameWorld> game_world)
{
if(use_mouse)
{
int x, y;
SDL_GetRelativeMouseState(&x, &y);
game_world->MoveCamera(x,y);
}
// Background colour for the window
glClearColor(0.0f, 0.2f, 0.2f, 0.3f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// Update game_world camera
if(keyboard_input[SDL_SCANCODE_W])
game_world->CameraController(1); // forward
if(keyboard_input[SDL_SCANCODE_A])
game_world->CameraController(2); // left
if(keyboard_input[SDL_SCANCODE_S])
game_world->CameraController(3); // back
if(keyboard_input[SDL_SCANCODE_D])
game_world->CameraController(4); // right
if(keyboard_input[SDL_SCANCODE_I])
game_world->CameraController(5); // cam up
if(keyboard_input[SDL_SCANCODE_J])
game_world->CameraController(6); // cam left
if(keyboard_input[SDL_SCANCODE_K])
game_world->CameraController(7); // cam down
if(keyboard_input[SDL_SCANCODE_L])
game_world->CameraController(8); // cam right
if(keyboard_input[SDL_SCANCODE_R])
game_world->CameraController(9); // player: +y ("fly" up)
if(keyboard_input[SDL_SCANCODE_F])
game_world->CameraController(10); // player: -y ("fly" down)
// Draw the gameworld
game_world->Draw();
// Swap buffers
SDL_GL_SwapWindow(window.get());
}
/*
* Handles the initialisation of the game world.
* Configures the SDL window and initialises GLEW
*/
std::shared_ptr<SDL_Window> InitWorld()
{
// Window properties
Uint32 width = 640;
Uint32 height = 480;
SDL_Window * _window;
std::shared_ptr<SDL_Window> window;
// Glew will later ensure that OpenGL 3 *is* supported
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
// Do double buffering in GL
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
// Initialise SDL - when using C/C++ it's common to have to
// initialise libraries by calling a function within them.
if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER) < 0)
{
std::cout << "Failed to initialise SDL: " << SDL_GetError() << std::endl;
return nullptr;
}
SDL_GetError();
// When we close a window quit the SDL application
atexit(SDL_Quit);
// Create a new window with an OpenGL surface
_window = SDL_CreateWindow("BlockWorld"
, SDL_WINDOWPOS_CENTERED
, SDL_WINDOWPOS_CENTERED
, width
, height
, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
if(!_window)
{
std::cout << "Failed to create SDL window: " << SDL_GetError() << std::endl;
return nullptr;
}
SDL_GLContext glContext = SDL_GL_CreateContext(_window);
if (!glContext)
{
std::cout << "Failed to create OpenGL context: " << SDL_GetError() << std::endl;
return nullptr;
}
// Initialise GLEW - an easy way to ensure OpenGl 3.0+
// The *must* be done after we have set the video mode - otherwise we have no
// OpenGL context to test.
glewInit();
if(!glewIsSupported("GL_VERSION_3_0"))
{
std::cerr << "OpenGL 3.0 not available" << std::endl;
return nullptr;
}
// OpenGL settings
glDisable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
window.reset(_window, SDL_DestroyWindow);
return window;
}
ApplicationMode ParseOptions (int argc, char ** argv)
{
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help", "print this help message")
("mouse", "Enabled experimental mouse-look")
("translate", "Show translation example (default)")
("rotate", "Show rotation example")
("scale", "Show scale example");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help"))
{
std::cout << desc << std::endl;
exit(0);
}
if(vm.count("mouse"))
{
use_mouse = true;
}
if(vm.count("rotate"))
{
return ROTATE;
}
if(vm.count("scale"))
{
return SCALE;
}
// The default
return TRANSFORM;
}
int main(int argc, char ** argv) {
Uint32 delay = 1000/60; // in milliseconds
auto mode = ParseOptions(argc, argv);
auto window = InitWorld();
auto game_world = std::make_shared<GameWorld>(mode);
if(!window)
{
SDL_Quit();
}
keyboard_input = SDL_GetKeyboardState(NULL);
// Call the function "tick" every delay milliseconds
SDL_AddTimer(delay, tick, NULL);
// Add the main event loop
SDL_Event event;
while (SDL_WaitEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
SDL_Quit();
break;
case SDL_USEREVENT:
Draw(window, game_world);
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_SPACE:
game_world->DoAction(1);
break;
case SDLK_q:
game_world->DoAction(2);
break;
case SDLK_g:
game_world->DoAction(3);
break;
case SDLK_ESCAPE:
exit(0);
break;
}
break;
default:
break;
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012-2015, Nic McDonald
* 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 prim 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 HOLDER 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 <des/SpinLock.h>
#include <prim/prim.h>
#include <tclap/CmdLine.h>
#include <cmath>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <ratio>
#include <thread>
#include <vector>
bool doLock = true;
des::SpinLock lock_;
void bankTransaction(volatile s64* _balance, s64 _delta) {
if (doLock) {
lock_.lock();
}
*_balance += _delta;
if (doLock) {
lock_.unlock();
}
}
volatile bool go = false;
void bankTeller(u32 _id, volatile s64* _account, u64 _transactions,
f64* _delay) {
s64 amount = (s64)_id + 100;
printf("teller %u starting\n", _id);
while (!go) {} // attempt to sync threads
std::chrono::steady_clock::time_point start =
std::chrono::steady_clock::now();
for (u64 c = 0; c < _transactions; c++) {
bankTransaction(_account, c % 2 == 0 ? amount : -amount);
}
std::chrono::steady_clock::time_point end =
std::chrono::steady_clock::now();
double delay = std::chrono::duration_cast<
std::chrono::duration<double> >(end - start).count();
printf("teller %u ended (%f seconds)\n", _id, delay);
*_delay = delay;
}
int main(s32 _argc, char** _argv) {
u32 numThreads = U32_MAX;
u64 numRounds = U64_MAX;
try {
TCLAP::CmdLine cmd("Command description message", ' ', "0.0.1");
TCLAP::ValueArg<u32> threadsArg("t", "threads", "Number of threads", false,
2, "u32", cmd);
TCLAP::ValueArg<u64> roundsArg("r", "rounds", "Number of rounds", false,
1000000, "u64", cmd);
TCLAP::SwitchArg nolockArg("n", "nolock", "Turn off spinlocks", cmd, false);
cmd.parse(_argc, _argv);
numThreads = threadsArg.getValue();
numRounds = roundsArg.getValue();
doLock = !nolockArg.getValue();
} catch (TCLAP::ArgException &e) {
fprintf(stderr, "error: %s for arg %s\n",
e.error().c_str(), e.argId().c_str());
exit(-1);
}
if (numThreads > std::thread::hardware_concurrency()) {
fprintf(stderr, "WARNING: 'threads' is greater than the amount of hardware "
"concurrency. Prepare for terrible performance!\n");
}
if (!doLock) {
fprintf(stderr, "Disabling spinlock\n");
}
if (numRounds % 2 != 0) {
fprintf(stderr, "'rounds' must be an even number\n");
exit(-1);
}
std::vector<f64> delay(numThreads);
std::vector<std::thread> threads;
const s64 EXP = 12345;
volatile s64 balance = EXP;
for (u64 t = 0; t < numThreads; t++) {
threads.emplace_back(bankTeller, t, &balance, numRounds, &delay[t]);
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
go = true;
for (auto& t : threads) {
t.join();
}
printf("account balance is %li, expected %li\n", balance, EXP);
if (balance != EXP) {
fprintf(stderr, "ERROR!!!!!!!\n");
}
f64 maxDelay = *std::max_element(delay.cbegin(), delay.cend());
printf("max delay is %f\n", maxDelay);
printf("thread lock rate: %f\n", numRounds / maxDelay);
printf("total lock rate: %f\n", (numRounds * numThreads) / maxDelay);
return balance == EXP;
}
<commit_msg>updated license header<commit_after>/*
* Copyright (c) 2012-2016, Nic McDonald
* 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 prim 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 HOLDER 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 <des/SpinLock.h>
#include <prim/prim.h>
#include <tclap/CmdLine.h>
#include <cmath>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <ratio>
#include <thread>
#include <vector>
bool doLock = true;
des::SpinLock lock_;
void bankTransaction(volatile s64* _balance, s64 _delta) {
if (doLock) {
lock_.lock();
}
*_balance += _delta;
if (doLock) {
lock_.unlock();
}
}
volatile bool go = false;
void bankTeller(u32 _id, volatile s64* _account, u64 _transactions,
f64* _delay) {
s64 amount = (s64)_id + 100;
printf("teller %u starting\n", _id);
while (!go) {} // attempt to sync threads
std::chrono::steady_clock::time_point start =
std::chrono::steady_clock::now();
for (u64 c = 0; c < _transactions; c++) {
bankTransaction(_account, c % 2 == 0 ? amount : -amount);
}
std::chrono::steady_clock::time_point end =
std::chrono::steady_clock::now();
double delay = std::chrono::duration_cast<
std::chrono::duration<double> >(end - start).count();
printf("teller %u ended (%f seconds)\n", _id, delay);
*_delay = delay;
}
int main(s32 _argc, char** _argv) {
u32 numThreads = U32_MAX;
u64 numRounds = U64_MAX;
try {
TCLAP::CmdLine cmd("Command description message", ' ', "0.0.1");
TCLAP::ValueArg<u32> threadsArg("t", "threads", "Number of threads", false,
2, "u32", cmd);
TCLAP::ValueArg<u64> roundsArg("r", "rounds", "Number of rounds", false,
1000000, "u64", cmd);
TCLAP::SwitchArg nolockArg("n", "nolock", "Turn off spinlocks", cmd, false);
cmd.parse(_argc, _argv);
numThreads = threadsArg.getValue();
numRounds = roundsArg.getValue();
doLock = !nolockArg.getValue();
} catch (TCLAP::ArgException &e) {
fprintf(stderr, "error: %s for arg %s\n",
e.error().c_str(), e.argId().c_str());
exit(-1);
}
if (numThreads > std::thread::hardware_concurrency()) {
fprintf(stderr, "WARNING: 'threads' is greater than the amount of hardware "
"concurrency. Prepare for terrible performance!\n");
}
if (!doLock) {
fprintf(stderr, "Disabling spinlock\n");
}
if (numRounds % 2 != 0) {
fprintf(stderr, "'rounds' must be an even number\n");
exit(-1);
}
std::vector<f64> delay(numThreads);
std::vector<std::thread> threads;
const s64 EXP = 12345;
volatile s64 balance = EXP;
for (u64 t = 0; t < numThreads; t++) {
threads.emplace_back(bankTeller, t, &balance, numRounds, &delay[t]);
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
go = true;
for (auto& t : threads) {
t.join();
}
printf("account balance is %li, expected %li\n", balance, EXP);
if (balance != EXP) {
fprintf(stderr, "ERROR!!!!!!!\n");
}
f64 maxDelay = *std::max_element(delay.cbegin(), delay.cend());
printf("max delay is %f\n", maxDelay);
printf("thread lock rate: %f\n", numRounds / maxDelay);
printf("total lock rate: %f\n", (numRounds * numThreads) / maxDelay);
return balance == EXP;
}
<|endoftext|>
|
<commit_before>#define BOOST_TEST_MODULE path_element_tests
// boost.test
#include <boost/test/included/unit_test.hpp>
// boost.spirit
#include <boost/spirit/include/karma.hpp>
// boost.filesystem
#include <boost/filesystem.hpp>
// mapnik
#include <mapnik/map.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/feature_type_style.hpp>
#include <mapnik/svg/output/svg_renderer.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/expression.hpp>
#include <mapnik/color_factory.hpp>
// stl
#include <fstream>
#include <iterator>
namespace fs = boost::filesystem;
using namespace mapnik;
void prepare_map(Map& m)
{
const std::string mapnik_dir("/usr/local/lib/mapnik/");
std::cout << " looking for 'shape.input' plugin in... " << mapnik_dir << "input/" << "\n";
datasource_cache::instance().register_datasources(mapnik_dir + "input/");
// create styles
// Provinces (polygon)
feature_type_style provpoly_style;
rule provpoly_rule_on;
provpoly_rule_on.set_filter(parse_expression("[NAME_EN] = 'Ontario'"));
provpoly_rule_on.append(polygon_symbolizer(color(250, 190, 183)));
provpoly_style.add_rule(provpoly_rule_on);
rule provpoly_rule_qc;
provpoly_rule_qc.set_filter(parse_expression("[NOM_FR] = 'Québec'"));
provpoly_rule_qc.append(polygon_symbolizer(color(217, 235, 203)));
provpoly_style.add_rule(provpoly_rule_qc);
m.insert_style("provinces",provpoly_style);
// Provinces (polyline)
feature_type_style provlines_style;
stroke provlines_stk (color(0,0,0),1.0);
provlines_stk.add_dash(8, 4);
provlines_stk.add_dash(2, 2);
provlines_stk.add_dash(2, 2);
rule provlines_rule;
provlines_rule.append(line_symbolizer(provlines_stk));
provlines_style.add_rule(provlines_rule);
m.insert_style("provlines",provlines_style);
// Drainage
feature_type_style qcdrain_style;
rule qcdrain_rule;
qcdrain_rule.set_filter(parse_expression("[HYC] = 8"));
qcdrain_rule.append(polygon_symbolizer(color(153, 204, 255)));
qcdrain_style.add_rule(qcdrain_rule);
m.insert_style("drainage",qcdrain_style);
// Roads 3 and 4 (The "grey" roads)
feature_type_style roads34_style;
rule roads34_rule;
roads34_rule.set_filter(parse_expression("[CLASS] = 3 or [CLASS] = 4"));
stroke roads34_rule_stk(color(171,158,137),2.0);
roads34_rule_stk.set_line_cap(ROUND_CAP);
roads34_rule_stk.set_line_join(ROUND_JOIN);
roads34_rule.append(line_symbolizer(roads34_rule_stk));
roads34_style.add_rule(roads34_rule);
m.insert_style("smallroads",roads34_style);
// Roads 2 (The thin yellow ones)
feature_type_style roads2_style_1;
rule roads2_rule_1;
roads2_rule_1.set_filter(parse_expression("[CLASS] = 2"));
stroke roads2_rule_stk_1(color(171,158,137),4.0);
roads2_rule_stk_1.set_line_cap(ROUND_CAP);
roads2_rule_stk_1.set_line_join(ROUND_JOIN);
roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1));
roads2_style_1.add_rule(roads2_rule_1);
m.insert_style("road-border", roads2_style_1);
feature_type_style roads2_style_2;
rule roads2_rule_2;
roads2_rule_2.set_filter(parse_expression("[CLASS] = 2"));
stroke roads2_rule_stk_2(color(255,250,115),2.0);
roads2_rule_stk_2.set_line_cap(ROUND_CAP);
roads2_rule_stk_2.set_line_join(ROUND_JOIN);
roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2));
roads2_style_2.add_rule(roads2_rule_2);
m.insert_style("road-fill", roads2_style_2);
// Roads 1 (The big orange ones, the highways)
feature_type_style roads1_style_1;
rule roads1_rule_1;
roads1_rule_1.set_filter(parse_expression("[CLASS] = 1"));
stroke roads1_rule_stk_1(color(188,149,28),7.0);
roads1_rule_stk_1.set_line_cap(ROUND_CAP);
roads1_rule_stk_1.set_line_join(ROUND_JOIN);
roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1));
roads1_style_1.add_rule(roads1_rule_1);
m.insert_style("highway-border", roads1_style_1);
feature_type_style roads1_style_2;
rule roads1_rule_2;
roads1_rule_2.set_filter(parse_expression("[CLASS] = 1"));
stroke roads1_rule_stk_2(color(242,191,36),5.0);
roads1_rule_stk_2.set_line_cap(ROUND_CAP);
roads1_rule_stk_2.set_line_join(ROUND_JOIN);
roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2));
roads1_style_2.add_rule(roads1_rule_2);
m.insert_style("highway-fill", roads1_style_2);
// layers
// Provincial polygons
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/boundaries";
layer lyr("Provinces");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("provinces");
m.addLayer(lyr);
}
// Drainage
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/qcdrainage";
layer lyr("Quebec Hydrography");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("drainage");
m.addLayer(lyr);
}
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/ontdrainage";
layer lyr("Ontario Hydrography");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("drainage");
m.addLayer(lyr);
}
// Provincial boundaries
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/boundaries_l";
layer lyr("Provincial borders");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("provlines");
m.addLayer(lyr);
}
// Roads
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/roads";
layer lyr("Roads");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("smallroads");
lyr.add_style("road-border");
lyr.add_style("road-fill");
lyr.add_style("highway-border");
lyr.add_style("highway-fill");
m.addLayer(lyr);
}
}
void render_to_file(Map const& m, const std::string output_filename)
{
std::ofstream output_stream(output_filename.c_str());
if(output_stream)
{
typedef svg_renderer<std::ostream_iterator<char> > svg_ren;
std::ostream_iterator<char> output_stream_iterator(output_stream);
svg_ren renderer(m, output_stream_iterator);
renderer.apply();
output_stream.close();
fs::path output_filename_path =
fs::system_complete(fs::path(".")) / fs::path(output_filename);
BOOST_CHECK_MESSAGE(fs::exists(output_filename_path),
"File '"+output_filename_path.string()+"' was created.");
}
else
{
BOOST_FAIL("Could not create create/open file '"+output_filename+"'.");
}
}
BOOST_AUTO_TEST_CASE(path_element_test_case_1)
{
Map m(800,600);
m.set_background(parse_color("steelblue"));
prepare_map(m);
//m.zoom_to_box(box2d<double>(1405120.04127408, -247003.813399447,
//1706357.31328276, -25098.593149577));
m.zoom_all();
render_to_file(m, "path_element_test_case_1.svg");
}
<commit_msg>remove uneeded includes<commit_after>#define BOOST_TEST_MODULE path_element_tests
// boost.test
#include <boost/test/included/unit_test.hpp>
// boost.filesystem
#include <boost/filesystem.hpp>
// mapnik
#include <mapnik/map.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/feature_type_style.hpp>
#include <mapnik/svg/output/svg_renderer.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/expression.hpp>
#include <mapnik/color_factory.hpp>
// stl
#include <fstream>
#include <iterator>
namespace fs = boost::filesystem;
using namespace mapnik;
void prepare_map(Map& m)
{
const std::string mapnik_dir("/usr/local/lib/mapnik/");
std::cout << " looking for 'shape.input' plugin in... " << mapnik_dir << "input/" << "\n";
datasource_cache::instance().register_datasources(mapnik_dir + "input/");
// create styles
// Provinces (polygon)
feature_type_style provpoly_style;
rule provpoly_rule_on;
provpoly_rule_on.set_filter(parse_expression("[NAME_EN] = 'Ontario'"));
provpoly_rule_on.append(polygon_symbolizer(color(250, 190, 183)));
provpoly_style.add_rule(provpoly_rule_on);
rule provpoly_rule_qc;
provpoly_rule_qc.set_filter(parse_expression("[NOM_FR] = 'Québec'"));
provpoly_rule_qc.append(polygon_symbolizer(color(217, 235, 203)));
provpoly_style.add_rule(provpoly_rule_qc);
m.insert_style("provinces",provpoly_style);
// Provinces (polyline)
feature_type_style provlines_style;
stroke provlines_stk (color(0,0,0),1.0);
provlines_stk.add_dash(8, 4);
provlines_stk.add_dash(2, 2);
provlines_stk.add_dash(2, 2);
rule provlines_rule;
provlines_rule.append(line_symbolizer(provlines_stk));
provlines_style.add_rule(provlines_rule);
m.insert_style("provlines",provlines_style);
// Drainage
feature_type_style qcdrain_style;
rule qcdrain_rule;
qcdrain_rule.set_filter(parse_expression("[HYC] = 8"));
qcdrain_rule.append(polygon_symbolizer(color(153, 204, 255)));
qcdrain_style.add_rule(qcdrain_rule);
m.insert_style("drainage",qcdrain_style);
// Roads 3 and 4 (The "grey" roads)
feature_type_style roads34_style;
rule roads34_rule;
roads34_rule.set_filter(parse_expression("[CLASS] = 3 or [CLASS] = 4"));
stroke roads34_rule_stk(color(171,158,137),2.0);
roads34_rule_stk.set_line_cap(ROUND_CAP);
roads34_rule_stk.set_line_join(ROUND_JOIN);
roads34_rule.append(line_symbolizer(roads34_rule_stk));
roads34_style.add_rule(roads34_rule);
m.insert_style("smallroads",roads34_style);
// Roads 2 (The thin yellow ones)
feature_type_style roads2_style_1;
rule roads2_rule_1;
roads2_rule_1.set_filter(parse_expression("[CLASS] = 2"));
stroke roads2_rule_stk_1(color(171,158,137),4.0);
roads2_rule_stk_1.set_line_cap(ROUND_CAP);
roads2_rule_stk_1.set_line_join(ROUND_JOIN);
roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1));
roads2_style_1.add_rule(roads2_rule_1);
m.insert_style("road-border", roads2_style_1);
feature_type_style roads2_style_2;
rule roads2_rule_2;
roads2_rule_2.set_filter(parse_expression("[CLASS] = 2"));
stroke roads2_rule_stk_2(color(255,250,115),2.0);
roads2_rule_stk_2.set_line_cap(ROUND_CAP);
roads2_rule_stk_2.set_line_join(ROUND_JOIN);
roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2));
roads2_style_2.add_rule(roads2_rule_2);
m.insert_style("road-fill", roads2_style_2);
// Roads 1 (The big orange ones, the highways)
feature_type_style roads1_style_1;
rule roads1_rule_1;
roads1_rule_1.set_filter(parse_expression("[CLASS] = 1"));
stroke roads1_rule_stk_1(color(188,149,28),7.0);
roads1_rule_stk_1.set_line_cap(ROUND_CAP);
roads1_rule_stk_1.set_line_join(ROUND_JOIN);
roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1));
roads1_style_1.add_rule(roads1_rule_1);
m.insert_style("highway-border", roads1_style_1);
feature_type_style roads1_style_2;
rule roads1_rule_2;
roads1_rule_2.set_filter(parse_expression("[CLASS] = 1"));
stroke roads1_rule_stk_2(color(242,191,36),5.0);
roads1_rule_stk_2.set_line_cap(ROUND_CAP);
roads1_rule_stk_2.set_line_join(ROUND_JOIN);
roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2));
roads1_style_2.add_rule(roads1_rule_2);
m.insert_style("highway-fill", roads1_style_2);
// layers
// Provincial polygons
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/boundaries";
layer lyr("Provinces");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("provinces");
m.addLayer(lyr);
}
// Drainage
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/qcdrainage";
layer lyr("Quebec Hydrography");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("drainage");
m.addLayer(lyr);
}
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/ontdrainage";
layer lyr("Ontario Hydrography");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("drainage");
m.addLayer(lyr);
}
// Provincial boundaries
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/boundaries_l";
layer lyr("Provincial borders");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("provlines");
m.addLayer(lyr);
}
// Roads
{
parameters p;
p["type"]="shape";
p["file"]="../../../demo/data/roads";
layer lyr("Roads");
lyr.set_datasource(datasource_cache::instance().create(p));
lyr.add_style("smallroads");
lyr.add_style("road-border");
lyr.add_style("road-fill");
lyr.add_style("highway-border");
lyr.add_style("highway-fill");
m.addLayer(lyr);
}
}
void render_to_file(Map const& m, const std::string output_filename)
{
std::ofstream output_stream(output_filename.c_str());
if(output_stream)
{
typedef svg_renderer<std::ostream_iterator<char> > svg_ren;
std::ostream_iterator<char> output_stream_iterator(output_stream);
svg_ren renderer(m, output_stream_iterator);
renderer.apply();
output_stream.close();
fs::path output_filename_path =
fs::system_complete(fs::path(".")) / fs::path(output_filename);
BOOST_CHECK_MESSAGE(fs::exists(output_filename_path),
"File '"+output_filename_path.string()+"' was created.");
}
else
{
BOOST_FAIL("Could not create create/open file '"+output_filename+"'.");
}
}
BOOST_AUTO_TEST_CASE(path_element_test_case_1)
{
Map m(800,600);
m.set_background(parse_color("steelblue"));
prepare_map(m);
//m.zoom_to_box(box2d<double>(1405120.04127408, -247003.813399447,
//1706357.31328276, -25098.593149577));
m.zoom_all();
render_to_file(m, "path_element_test_case_1.svg");
}
<|endoftext|>
|
<commit_before>#include "davixuri.hpp"
#include "davixuri.h"
#include <ne_uri.h>
#include <cstring>
namespace Davix {
static std::string void_str;
struct UriPrivate{
UriPrivate() :
my_uri(),
code(StatusCode::UriParsingError),
proto(),
path(),
host(),
query(),
query_and_path(){
memset(&my_uri, 0, sizeof(my_uri));
}
UriPrivate(const UriPrivate & orig):
my_uri(),
code(orig.code),
proto(orig.proto),
path(orig.path),
host(orig.host),
query(orig.query),
query_and_path(orig.query_and_path){
ne_uri_copy(&my_uri, &(orig.my_uri));
}
~UriPrivate() {
ne_uri_free(&my_uri);
}
void parsing(const std::string & uri_string){
if(ne_uri_parse(uri_string.c_str(), &(my_uri)) == 0){
if(my_uri.scheme == NULL
|| my_uri.path == NULL
|| my_uri.host ==NULL)
return;
// fix a neon parser bug when port != number
if(my_uri.port == 0 && strcasecmp(my_uri.scheme, "http") ==0)
my_uri.port = 80;
if(my_uri.port == 0 && strcasecmp(my_uri.scheme, "https") ==0)
my_uri.port = 443;
if(my_uri.port == 0)
return;
code = StatusCode::OK;
proto = my_uri.scheme;
path = my_uri.path;
host = my_uri.host;
if(my_uri.query){
query = my_uri.query;
query_and_path= path + "?" + query;
}else{
query_and_path = path;
}
}
}
ne_uri my_uri;
StatusCode::Code code;
std::string proto;
std::string path;
std::string host;
std::string query;
std::string query_and_path;
};
Uri::Uri() :
uri_string(),
d_ptr(new UriPrivate()){
}
Uri::Uri(const std::string & uri) :
uri_string(uri),
d_ptr(new UriPrivate()){
d_ptr->parsing(uri);
}
Uri::Uri(const Uri & uri) :
uri_string(uri.uri_string),
d_ptr(new UriPrivate(*(uri.d_ptr))){
}
Uri::~Uri(){
ne_uri_free(&(d_ptr->my_uri));
delete d_ptr;
}
int Uri::getPort() const{
if(d_ptr->code != StatusCode::OK)
return -1;
return d_ptr->my_uri.port;
}
const std::string & Uri::getHost() const{
if(d_ptr->code != StatusCode::OK)
return void_str;
return d_ptr->host;
}
const std::string & Uri::getString() const{
return uri_string;
}
const std::string & Uri::getProtocol() const {
if(d_ptr->code != StatusCode::OK)
return void_str;
return d_ptr->proto;
}
const std::string & Uri::getPath() const {
if(d_ptr->code != StatusCode::OK)
return void_str;
return d_ptr->path;
}
const std::string & Uri::getPathAndQuery() const {
if(d_ptr->code != StatusCode::OK)
return void_str;
return d_ptr->query_and_path;
}
const std::string & Uri::getQuery() const{
if(d_ptr->code != StatusCode::OK)
return void_str;
return d_ptr->query;
}
Uri & Uri::operator =(const Uri & orig){
if (d_ptr) delete d_ptr;
d_ptr = new UriPrivate(*(orig.d_ptr));
return *this;
}
StatusCode::Code Uri::getStatus() const{
return d_ptr->code;
}
bool uriCheckError(const Uri &uri, DavixError **err){
if(uri.getStatus() == StatusCode::OK)
return true;
DavixError::setupError(err, davix_scope_uri_parser(), uri.getStatus(), std::string("Uri syntax Invalid : ").append(uri.getString()));
return false;
}
} // namespace Davix
DAVIX_C_DECL_BEGIN
using namespace Davix;
struct davix_uri_s;
davix_uri_t davix_uri_new(const char* url){
return (davix_uri_t) new Uri(url);
}
void davix_uri_free(davix_uri_t duri){
if(duri)
delete ((Uri*) duri);
}
int davix_uri_get_port(davix_uri_t duri){
g_assert(duri != NULL);
return ((Uri*) duri)->getPort();
}
const char* davix_uri_get_string(davix_uri_t duri){
g_assert(duri != NULL);
Uri* myself = (Uri*) duri;
return ((myself->getString().empty() == false)?(myself->getString().c_str()):NULL);
}
const char* davix_uri_get_path(davix_uri_t duri){
g_assert(duri != NULL);
Uri* myself = (Uri*) duri;
return ((myself->getPath().empty() == false)?(myself->getPath().c_str()):NULL);
}
const char* davix_uri_get_host(davix_uri_t duri){
g_assert(duri != NULL);
Uri* myself = (Uri*) duri;
return ((myself->getHost().empty() == false)?(myself->getHost().c_str()):NULL);
}
const char* davix_uri_get_path_and_query(davix_uri_t duri){
g_assert(duri != NULL);
Uri* myself = (Uri*) duri;
return ((myself->getPathAndQuery().empty() == false)?(myself->getPathAndQuery().c_str()):NULL);
}
const char* davix_uri_get_protocol(davix_uri_t duri){
g_assert(duri != NULL);
Uri* myself = (Uri*) duri;
return ((myself->getProtocol().empty() == false)?(myself->getProtocol().c_str()):NULL);
}
DAVIX_C_DECL_END
<commit_msg>- finish C davix uri API mapping<commit_after>#include "davixuri.hpp"
#include "davixuri.h"
#include <ne_uri.h>
#include <cstring>
namespace Davix {
static std::string void_str;
struct UriPrivate{
UriPrivate() :
my_uri(),
code(StatusCode::UriParsingError),
proto(),
path(),
host(),
query(),
query_and_path(){
memset(&my_uri, 0, sizeof(my_uri));
}
UriPrivate(const UriPrivate & orig):
my_uri(),
code(orig.code),
proto(orig.proto),
path(orig.path),
host(orig.host),
query(orig.query),
query_and_path(orig.query_and_path){
ne_uri_copy(&my_uri, &(orig.my_uri));
}
~UriPrivate() {
ne_uri_free(&my_uri);
}
void parsing(const std::string & uri_string){
if(ne_uri_parse(uri_string.c_str(), &(my_uri)) == 0){
if(my_uri.scheme == NULL
|| my_uri.path == NULL
|| my_uri.host ==NULL)
return;
// fix a neon parser bug when port != number
if(my_uri.port == 0 && strcasecmp(my_uri.scheme, "http") ==0)
my_uri.port = 80;
if(my_uri.port == 0 && strcasecmp(my_uri.scheme, "https") ==0)
my_uri.port = 443;
if(my_uri.port == 0)
return;
code = StatusCode::OK;
proto = my_uri.scheme;
path = my_uri.path;
host = my_uri.host;
if(my_uri.query){
query = my_uri.query;
query_and_path= path + "?" + query;
}else{
query_and_path = path;
}
}
}
ne_uri my_uri;
StatusCode::Code code;
std::string proto;
std::string path;
std::string host;
std::string query;
std::string query_and_path;
};
Uri::Uri() :
uri_string(),
d_ptr(new UriPrivate()){
}
Uri::Uri(const std::string & uri) :
uri_string(uri),
d_ptr(new UriPrivate()){
d_ptr->parsing(uri);
}
Uri::Uri(const Uri & uri) :
uri_string(uri.uri_string),
d_ptr(new UriPrivate(*(uri.d_ptr))){
}
Uri::~Uri(){
ne_uri_free(&(d_ptr->my_uri));
delete d_ptr;
}
int Uri::getPort() const{
if(d_ptr->code != StatusCode::OK)
return -1;
return d_ptr->my_uri.port;
}
const std::string & Uri::getHost() const{
if(d_ptr->code != StatusCode::OK)
return void_str;
return d_ptr->host;
}
const std::string & Uri::getString() const{
return uri_string;
}
const std::string & Uri::getProtocol() const {
if(d_ptr->code != StatusCode::OK)
return void_str;
return d_ptr->proto;
}
const std::string & Uri::getPath() const {
if(d_ptr->code != StatusCode::OK)
return void_str;
return d_ptr->path;
}
const std::string & Uri::getPathAndQuery() const {
if(d_ptr->code != StatusCode::OK)
return void_str;
return d_ptr->query_and_path;
}
const std::string & Uri::getQuery() const{
if(d_ptr->code != StatusCode::OK)
return void_str;
return d_ptr->query;
}
Uri & Uri::operator =(const Uri & orig){
if (d_ptr) delete d_ptr;
d_ptr = new UriPrivate(*(orig.d_ptr));
return *this;
}
StatusCode::Code Uri::getStatus() const{
return d_ptr->code;
}
bool uriCheckError(const Uri &uri, DavixError **err){
if(uri.getStatus() == StatusCode::OK)
return true;
DavixError::setupError(err, davix_scope_uri_parser(), uri.getStatus(), std::string("Uri syntax Invalid : ").append(uri.getString()));
return false;
}
} // namespace Davix
DAVIX_C_DECL_BEGIN
using namespace Davix;
struct davix_uri_s;
davix_uri_t davix_uri_new(const char* url){
return (davix_uri_t) new Uri(url);
}
davix_uri_t davix_uri_copy(davix_uri_t orig_uri){
g_assert(orig_uri != NULL);
Uri* myself = (Uri*) orig_uri;
return (davix_uri_t) new Uri(*myself);
}
void davix_uri_free(davix_uri_t duri){
if(duri)
delete ((Uri*) duri);
}
int davix_uri_get_port(davix_uri_t duri){
g_assert(duri != NULL);
return ((Uri*) duri)->getPort();
}
const char* davix_uri_get_string(davix_uri_t duri){
g_assert(duri != NULL);
Uri* myself = (Uri*) duri;
return ((myself->getString().empty() == false)?(myself->getString().c_str()):NULL);
}
const char* davix_uri_get_path(davix_uri_t duri){
g_assert(duri != NULL);
Uri* myself = (Uri*) duri;
return ((myself->getPath().empty() == false)?(myself->getPath().c_str()):NULL);
}
const char* davix_uri_get_host(davix_uri_t duri){
g_assert(duri != NULL);
Uri* myself = (Uri*) duri;
return ((myself->getHost().empty() == false)?(myself->getHost().c_str()):NULL);
}
const char* davix_uri_get_path_and_query(davix_uri_t duri){
g_assert(duri != NULL);
Uri* myself = (Uri*) duri;
return ((myself->getPathAndQuery().empty() == false)?(myself->getPathAndQuery().c_str()):NULL);
}
const char* davix_uri_get_protocol(davix_uri_t duri){
g_assert(duri != NULL);
Uri* myself = (Uri*) duri;
return ((myself->getProtocol().empty() == false)?(myself->getProtocol().c_str()):NULL);
}
int davix_uri_get_status(davix_uri_t duri){
g_assert(duri != NULL);
Uri* myself = (Uri*) duri;
return ((int)myself->getStatus());
}
DAVIX_C_DECL_END
<|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: map.cpp 17 2005-03-08 23:58:43Z pavlenko $,
#include <mapnik/style.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
namespace mapnik
{
Map::Map()
: width_(400),
height_(400),
srid_(-1) {}
Map::Map(int width,int height,int srid)
: width_(width),
height_(height),
srid_(srid),
background_(Color(255,255,255)) {}
Map::Map(const Map& rhs)
: width_(rhs.width_),
height_(rhs.height_),
srid_(rhs.srid_),
background_(rhs.background_),
styles_(rhs.styles_),
layers_(rhs.layers_),
currentExtent_(rhs.currentExtent_) {}
Map& Map::operator=(const Map& rhs)
{
if (this==&rhs) return *this;
width_=rhs.width_;
height_=rhs.height_;
srid_=rhs.srid_;
background_=rhs.background_;
styles_=rhs.styles_;
layers_=rhs.layers_;
return *this;
}
Map::style_iterator Map::begin_styles() const
{
return styles_.begin();
}
Map::style_iterator Map::end_styles() const
{
return styles_.end();
}
bool Map::insert_style(std::string const& name,feature_type_style const& style)
{
return styles_.insert(make_pair(name,style)).second;
}
void Map::remove_style(std::string const& name)
{
styles_.erase(name);
}
feature_type_style const& Map::find_style(std::string const& name) const
{
std::map<std::string,feature_type_style>::const_iterator itr
= styles_.find(name);
if (itr!=styles_.end())
return itr->second;
static feature_type_style default_style;
return default_style;
}
size_t Map::layerCount() const
{
return layers_.size();
}
void Map::addLayer(const Layer& l)
{
layers_.push_back(l);
}
void Map::removeLayer(size_t index)
{
layers_.erase(layers_.begin()+index);
}
void Map::remove_all()
{
layers_.clear();
}
const Layer& Map::getLayer(size_t index) const
{
return layers_[index];
}
Layer& Map::getLayer(size_t index)
{
return layers_[index];
}
std::vector<Layer> const& Map::layers() const
{
return layers_;
}
unsigned Map::getWidth() const
{
return width_;
}
unsigned Map::getHeight() const
{
return height_;
}
void Map::setWidth(unsigned width)
{
if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE)
{
width_=width;
fixAspectRatio();
}
}
void Map::setHeight(unsigned height)
{
if (height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)
{
height_=height;
fixAspectRatio();
}
}
void Map::resize(unsigned width,unsigned height)
{
if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE &&
height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)
{
width_=width;
height_=height;
fixAspectRatio();
}
}
int Map::srid() const
{
return srid_;
}
void Map::setBackground(const Color& c)
{
background_=c;
}
const Color& Map::getBackground() const
{
return background_;
}
void Map::zoom(double factor)
{
coord2d center = currentExtent_.center();
double w = factor * currentExtent_.width();
double h = factor * currentExtent_.height();
currentExtent_ = Envelope<double>(center.x - 0.5 * w, center.y - 0.5 * h,
center.x + 0.5 * w, center.y + 0.5 * h);
fixAspectRatio();
}
void Map::zoom_all()
{
std::vector<Layer>::const_iterator itr = layers_.begin();
Envelope<double> ext;
bool first = true;
while (itr != layers_.end())
{
if (first)
{
ext = itr->envelope();
first = false;
}
else
{
ext.expand_to_include(itr->envelope());
}
++itr;
}
zoomToBox(ext);
}
void Map::zoomToBox(const Envelope<double> &box)
{
currentExtent_=box;
fixAspectRatio();
}
void Map::fixAspectRatio()
{
double ratio1 = (double) width_ / (double) height_;
double ratio2 = currentExtent_.width() / currentExtent_.height();
if (ratio2 > ratio1)
{
currentExtent_.height(currentExtent_.width() / ratio1);
}
else if (ratio2 < ratio1)
{
currentExtent_.width(currentExtent_.height() * ratio1);
}
}
const Envelope<double>& Map::getCurrentExtent() const
{
return currentExtent_;
}
void Map::pan(int x,int y)
{
int dx = x - int(0.5 * width_);
int dy = int(0.5 * height_) - y;
double s = width_/currentExtent_.width();
double minx = currentExtent_.minx() + dx/s;
double maxx = currentExtent_.maxx() + dx/s;
double miny = currentExtent_.miny() + dy/s;
double maxy = currentExtent_.maxy() + dy/s;
currentExtent_.init(minx,miny,maxx,maxy);
}
void Map::pan_and_zoom(int x,int y,double factor)
{
pan(x,y);
zoom(factor);
}
double Map::scale() const
{
if (width_>0)
return currentExtent_.width()/width_;
return currentExtent_.width();
}
Map::~Map() {}
}
<commit_msg>in remove_all clear all styles as well!<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: map.cpp 17 2005-03-08 23:58:43Z pavlenko $,
#include <mapnik/style.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
namespace mapnik
{
Map::Map()
: width_(400),
height_(400),
srid_(-1) {}
Map::Map(int width,int height,int srid)
: width_(width),
height_(height),
srid_(srid),
background_(Color(255,255,255)) {}
Map::Map(const Map& rhs)
: width_(rhs.width_),
height_(rhs.height_),
srid_(rhs.srid_),
background_(rhs.background_),
styles_(rhs.styles_),
layers_(rhs.layers_),
currentExtent_(rhs.currentExtent_) {}
Map& Map::operator=(const Map& rhs)
{
if (this==&rhs) return *this;
width_=rhs.width_;
height_=rhs.height_;
srid_=rhs.srid_;
background_=rhs.background_;
styles_=rhs.styles_;
layers_=rhs.layers_;
return *this;
}
Map::style_iterator Map::begin_styles() const
{
return styles_.begin();
}
Map::style_iterator Map::end_styles() const
{
return styles_.end();
}
bool Map::insert_style(std::string const& name,feature_type_style const& style)
{
return styles_.insert(make_pair(name,style)).second;
}
void Map::remove_style(std::string const& name)
{
styles_.erase(name);
}
feature_type_style const& Map::find_style(std::string const& name) const
{
std::map<std::string,feature_type_style>::const_iterator itr
= styles_.find(name);
if (itr!=styles_.end())
return itr->second;
static feature_type_style default_style;
return default_style;
}
size_t Map::layerCount() const
{
return layers_.size();
}
void Map::addLayer(const Layer& l)
{
layers_.push_back(l);
}
void Map::removeLayer(size_t index)
{
layers_.erase(layers_.begin()+index);
}
void Map::remove_all()
{
layers_.clear();
styles_.clear();
}
const Layer& Map::getLayer(size_t index) const
{
return layers_[index];
}
Layer& Map::getLayer(size_t index)
{
return layers_[index];
}
std::vector<Layer> const& Map::layers() const
{
return layers_;
}
unsigned Map::getWidth() const
{
return width_;
}
unsigned Map::getHeight() const
{
return height_;
}
void Map::setWidth(unsigned width)
{
if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE)
{
width_=width;
fixAspectRatio();
}
}
void Map::setHeight(unsigned height)
{
if (height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)
{
height_=height;
fixAspectRatio();
}
}
void Map::resize(unsigned width,unsigned height)
{
if (width >= MIN_MAPSIZE && width <= MAX_MAPSIZE &&
height >= MIN_MAPSIZE && height <= MAX_MAPSIZE)
{
width_=width;
height_=height;
fixAspectRatio();
}
}
int Map::srid() const
{
return srid_;
}
void Map::setBackground(const Color& c)
{
background_=c;
}
const Color& Map::getBackground() const
{
return background_;
}
void Map::zoom(double factor)
{
coord2d center = currentExtent_.center();
double w = factor * currentExtent_.width();
double h = factor * currentExtent_.height();
currentExtent_ = Envelope<double>(center.x - 0.5 * w,
center.y - 0.5 * h,
center.x + 0.5 * w,
center.y + 0.5 * h);
fixAspectRatio();
}
void Map::zoom_all()
{
std::vector<Layer>::const_iterator itr = layers_.begin();
Envelope<double> ext;
bool first = true;
while (itr != layers_.end())
{
if (first)
{
ext = itr->envelope();
first = false;
}
else
{
ext.expand_to_include(itr->envelope());
}
++itr;
}
zoomToBox(ext);
}
void Map::zoomToBox(const Envelope<double> &box)
{
currentExtent_=box;
fixAspectRatio();
}
void Map::fixAspectRatio()
{
double ratio1 = (double) width_ / (double) height_;
double ratio2 = currentExtent_.width() / currentExtent_.height();
if (ratio2 > ratio1)
{
currentExtent_.height(currentExtent_.width() / ratio1);
}
else if (ratio2 < ratio1)
{
currentExtent_.width(currentExtent_.height() * ratio1);
}
}
const Envelope<double>& Map::getCurrentExtent() const
{
return currentExtent_;
}
void Map::pan(int x,int y)
{
int dx = x - int(0.5 * width_);
int dy = int(0.5 * height_) - y;
double s = width_/currentExtent_.width();
double minx = currentExtent_.minx() + dx/s;
double maxx = currentExtent_.maxx() + dx/s;
double miny = currentExtent_.miny() + dy/s;
double maxy = currentExtent_.maxy() + dy/s;
currentExtent_.init(minx,miny,maxx,maxy);
}
void Map::pan_and_zoom(int x,int y,double factor)
{
pan(x,y);
zoom(factor);
}
double Map::scale() const
{
if (width_>0)
return currentExtent_.width()/width_;
return currentExtent_.width();
}
Map::~Map() {}
}
<|endoftext|>
|
<commit_before>#include "wator.hpp"
using namespace Wator;
Net::Net()
{
}
Net::Net(const ifstream &in)
{
}<commit_msg>Update net.cpp<commit_after>/*
Copyright (c) 2015, Wator Vapor
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 wator 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 HOLDER 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 "wator.hpp"
using namespace Wator;
Net::Net()
{
}
Net::Net(const ifstream &in)
{
}
<|endoftext|>
|
<commit_before>///
/// @file phi.cpp
///
/// 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 "PhiCache.hpp"
#include "PhiTiny.hpp"
#include "pi_bsearch.hpp"
#include "pmath.hpp"
#include <primesieve.hpp>
#include <stdint.h>
#include <vector>
#include <cassert>
#ifdef _OPENMP
#include <omp.h>
#include "get_omp_threads.hpp"
#endif
namespace primecount {
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a, int threads)
{
if (x < 1) return 0;
if (a > x) return 1;
if (a < 1) return x;
static const PhiTiny phiTiny;
if (phiTiny.is_cached(a))
return phiTiny.phi(x, a);
std::vector<int32_t> primes;
primes.push_back(0);
primesieve::generate_n_primes(a, &primes);
if (primes.at(a) >= x)
return 1;
int64_t iters = pi_bsearch(primes, a, isqrt(x));
PhiCache cache(primes, phiTiny);
int64_t sum = x - a + iters;
#ifdef _OPENMP
#pragma omp parallel for firstprivate(cache) schedule(dynamic, 16) \
num_threads(get_omp_threads(threads)) reduction(+: sum)
#endif
for (int64_t a2 = 0; a2 < iters; a2++)
sum += cache.phi(x / primes[a2 + 1], a2, -1);
return sum;
}
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a, PhiCache* phiCache)
{
assert(phiCache != 0);
return phiCache->phi(x, a);
}
} // namespace primecount
<commit_msg>Use PhiTiny::MAX_A<commit_after>///
/// @file phi.cpp
///
/// 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 "PhiCache.hpp"
#include "PhiTiny.hpp"
#include "pi_bsearch.hpp"
#include "pmath.hpp"
#include <primesieve.hpp>
#include <stdint.h>
#include <vector>
#include <cassert>
#ifdef _OPENMP
#include <omp.h>
#include "get_omp_threads.hpp"
#endif
namespace primecount {
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a, int threads)
{
if (x < 1) return 0;
if (a > x) return 1;
if (a < 1) return x;
static const PhiTiny phiTiny;
if (a <= PhiTiny::MAX_A)
return phiTiny.phi(x, a);
std::vector<int32_t> primes;
primes.push_back(0);
primesieve::generate_n_primes(a, &primes);
if (primes.at(a) >= x)
return 1;
int64_t iters = pi_bsearch(primes, a, isqrt(x));
PhiCache cache(primes, phiTiny);
int64_t sum = x - a + iters;
#ifdef _OPENMP
#pragma omp parallel for firstprivate(cache) schedule(dynamic, 16) \
num_threads(get_omp_threads(threads)) reduction(+: sum)
#endif
for (int64_t a2 = 0; a2 < iters; a2++)
sum += cache.phi(x / primes[a2 + 1], a2, -1);
return sum;
}
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a, PhiCache* phiCache)
{
assert(phiCache != 0);
return phiCache->phi(x, a);
}
} // namespace primecount
<|endoftext|>
|
<commit_before>// Implements the Sink class
#include <algorithm>
#include <sstream>
#include <boost/lexical_cast.hpp>
#include "sink.h"
namespace cycamore {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Sink::Sink(cyclus::Context* ctx)
: cyclus::Facility(ctx),
capacity(std::numeric_limits<double>::max()) {
SetMaxInventorySize(std::numeric_limits<double>::max());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Sink::~Sink() {}
#pragma cyclus def schema cycamore::Sink
#pragma cyclus def annotations cycamore::Sink
#pragma cyclus def infiletodb cycamore::Sink
#pragma cyclus def snapshot cycamore::Sink
#pragma cyclus def snapshotinv cycamore::Sink
#pragma cyclus def initinv cycamore::Sink
#pragma cyclus def clone cycamore::Sink
#pragma cyclus def initfromdb cycamore::Sink
#pragma cyclus def initfromcopy cycamore::Sink
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string Sink::str() {
using std::string;
using std::vector;
std::stringstream ss;
ss << cyclus::Facility::str();
string msg = "";
msg += "accepts commodities ";
for (vector<string>::iterator commod = in_commods.begin();
commod != in_commods.end();
commod++) {
msg += (commod == in_commods.begin() ? "{" : ", ");
msg += (*commod);
}
msg += "} until its inventory is full at ";
ss << msg << inventory.capacity() << " kg.";
return "" + ss.str();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::set<cyclus::RequestPortfolio<cyclus::Material>::Ptr>
Sink::GetMatlRequests() {
using cyclus::CapacityConstraint;
using cyclus::Material;
using cyclus::RequestPortfolio;
using cyclus::Request;
std::set<RequestPortfolio<Material>::Ptr> ports;
RequestPortfolio<Material>::Ptr port(new RequestPortfolio<Material>());
double amt = RequestAmt();
Material::Ptr mat;
if (composition == "") {
mat = cyclus::NewBlankMaterial(amt);
} else {
this->context()->GetRecipe(composition);
mat = cyclus::Material::CreateUntracked(amt, this);
}
if (amt > cyclus::eps()) {
CapacityConstraint<Material> cc(amt);
port->AddConstraint(cc);
std::vector<std::string>::const_iterator it;
std::vector<Request<Material>*> mutuals;
for (it = in_commods.begin(); it != in_commods.end(); ++it) {
mutuals.push_back(port->AddRequest(mat, this, *it));
}
port->AddMutualReqs(mutuals);
ports.insert(port);
} // if amt > eps
return ports;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::set<cyclus::RequestPortfolio<cyclus::Product>::Ptr>
Sink::GetGenRsrcRequests() {
using cyclus::CapacityConstraint;
using cyclus::Product;
using cyclus::RequestPortfolio;
using cyclus::Request;
std::set<RequestPortfolio<Product>::Ptr> ports;
RequestPortfolio<Product>::Ptr
port(new RequestPortfolio<Product>());
double amt = RequestAmt();
if (amt > cyclus::eps()) {
CapacityConstraint<Product> cc(amt);
port->AddConstraint(cc);
std::vector<std::string>::const_iterator it;
for (it = in_commods.begin(); it != in_commods.end(); ++it) {
std::string quality = ""; // not clear what this should be..
Product::Ptr rsrc = Product::CreateUntracked(amt, quality);
port->AddRequest(rsrc, this, *it);
}
ports.insert(port);
} // if amt > eps
return ports;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Sink::AcceptMatlTrades(
const std::vector< std::pair<cyclus::Trade<cyclus::Material>,
cyclus::Material::Ptr> >& responses) {
std::vector< std::pair<cyclus::Trade<cyclus::Material>,
cyclus::Material::Ptr> >::const_iterator it;
for (it = responses.begin(); it != responses.end(); ++it) {
inventory.Push(it->second);
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Sink::AcceptGenRsrcTrades(
const std::vector< std::pair<cyclus::Trade<cyclus::Product>,
cyclus::Product::Ptr> >& responses) {
std::vector< std::pair<cyclus::Trade<cyclus::Product>,
cyclus::Product::Ptr> >::const_iterator it;
for (it = responses.begin(); it != responses.end(); ++it) {
inventory.Push(it->second);
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Sink::Tick() {
using std::string;
using std::vector;
LOG(cyclus::LEV_INFO3, "SnkFac") << prototype() << " is ticking {";
double requestAmt = RequestAmt();
// inform the simulation about what the sink facility will be requesting
if (requestAmt > cyclus::eps()) {
for (vector<string>::iterator commod = in_commods.begin();
commod != in_commods.end();
commod++) {
LOG(cyclus::LEV_INFO4, "SnkFac") << " will request " << requestAmt
<< " kg of " << *commod << ".";
}
}
LOG(cyclus::LEV_INFO3, "SnkFac") << "}";
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Sink::Tock() {
LOG(cyclus::LEV_INFO3, "SnkFac") << prototype() << " is tocking {";
// On the tock, the sink facility doesn't really do much.
// Maybe someday it will record things.
// For now, lets just print out what we have at each timestep.
LOG(cyclus::LEV_INFO4, "SnkFac") << "Sink " << this->id()
<< " is holding " << inventory.quantity()
<< " units of material at the close of month "
<< context()->time() << ".";
LOG(cyclus::LEV_INFO3, "SnkFac") << "}";
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" cyclus::Agent* ConstructSink(cyclus::Context* ctx) {
return new Sink(ctx);
}
} // namespace cycamore
<commit_msg>tried changing sink to allow recipe, not currently working<commit_after>// Implements the Sink class
#include <algorithm>
#include <sstream>
#include <boost/lexical_cast.hpp>
#include "sink.h"
namespace cycamore {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Sink::Sink(cyclus::Context* ctx)
: cyclus::Facility(ctx),
capacity(std::numeric_limits<double>::max()) {
SetMaxInventorySize(std::numeric_limits<double>::max());
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Sink::~Sink() {}
#pragma cyclus def schema cycamore::Sink
#pragma cyclus def annotations cycamore::Sink
#pragma cyclus def infiletodb cycamore::Sink
#pragma cyclus def snapshot cycamore::Sink
#pragma cyclus def snapshotinv cycamore::Sink
#pragma cyclus def initinv cycamore::Sink
#pragma cyclus def clone cycamore::Sink
#pragma cyclus def initfromdb cycamore::Sink
#pragma cyclus def initfromcopy cycamore::Sink
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::string Sink::str() {
using std::string;
using std::vector;
std::stringstream ss;
ss << cyclus::Facility::str();
string msg = "";
msg += "accepts commodities ";
for (vector<string>::iterator commod = in_commods.begin();
commod != in_commods.end();
commod++) {
msg += (commod == in_commods.begin() ? "{" : ", ");
msg += (*commod);
}
msg += "} until its inventory is full at ";
ss << msg << inventory.capacity() << " kg.";
return "" + ss.str();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::set<cyclus::RequestPortfolio<cyclus::Material>::Ptr>
Sink::GetMatlRequests() {
using cyclus::CapacityConstraint;
using cyclus::Material;
using cyclus::RequestPortfolio;
using cyclus::Request;
std::set<RequestPortfolio<Material>::Ptr> ports;
RequestPortfolio<Material>::Ptr port(new RequestPortfolio<Material>());
double amt = RequestAmt();
Material::Ptr mat;
if (composition == "") {
mat = cyclus::NewBlankMaterial(amt);
} else {
Composition::Ptr c = this->context()->GetRecipe(composition);
mat = cyclus::Material::CreateUntracked(amt, c);
}
if (amt > cyclus::eps()) {
CapacityConstraint<Material> cc(amt);
port->AddConstraint(cc);
std::vector<std::string>::const_iterator it;
std::vector<Request<Material>*> mutuals;
for (it = in_commods.begin(); it != in_commods.end(); ++it) {
mutuals.push_back(port->AddRequest(mat, this, *it));
}
port->AddMutualReqs(mutuals);
ports.insert(port);
} // if amt > eps
return ports;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
std::set<cyclus::RequestPortfolio<cyclus::Product>::Ptr>
Sink::GetGenRsrcRequests() {
using cyclus::CapacityConstraint;
using cyclus::Product;
using cyclus::RequestPortfolio;
using cyclus::Request;
std::set<RequestPortfolio<Product>::Ptr> ports;
RequestPortfolio<Product>::Ptr
port(new RequestPortfolio<Product>());
double amt = RequestAmt();
if (amt > cyclus::eps()) {
CapacityConstraint<Product> cc(amt);
port->AddConstraint(cc);
std::vector<std::string>::const_iterator it;
for (it = in_commods.begin(); it != in_commods.end(); ++it) {
std::string quality = ""; // not clear what this should be..
Product::Ptr rsrc = Product::CreateUntracked(amt, quality);
port->AddRequest(rsrc, this, *it);
}
ports.insert(port);
} // if amt > eps
return ports;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Sink::AcceptMatlTrades(
const std::vector< std::pair<cyclus::Trade<cyclus::Material>,
cyclus::Material::Ptr> >& responses) {
std::vector< std::pair<cyclus::Trade<cyclus::Material>,
cyclus::Material::Ptr> >::const_iterator it;
for (it = responses.begin(); it != responses.end(); ++it) {
inventory.Push(it->second);
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Sink::AcceptGenRsrcTrades(
const std::vector< std::pair<cyclus::Trade<cyclus::Product>,
cyclus::Product::Ptr> >& responses) {
std::vector< std::pair<cyclus::Trade<cyclus::Product>,
cyclus::Product::Ptr> >::const_iterator it;
for (it = responses.begin(); it != responses.end(); ++it) {
inventory.Push(it->second);
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Sink::Tick() {
using std::string;
using std::vector;
LOG(cyclus::LEV_INFO3, "SnkFac") << prototype() << " is ticking {";
double requestAmt = RequestAmt();
// inform the simulation about what the sink facility will be requesting
if (requestAmt > cyclus::eps()) {
for (vector<string>::iterator commod = in_commods.begin();
commod != in_commods.end();
commod++) {
LOG(cyclus::LEV_INFO4, "SnkFac") << " will request " << requestAmt
<< " kg of " << *commod << ".";
}
}
LOG(cyclus::LEV_INFO3, "SnkFac") << "}";
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void Sink::Tock() {
LOG(cyclus::LEV_INFO3, "SnkFac") << prototype() << " is tocking {";
// On the tock, the sink facility doesn't really do much.
// Maybe someday it will record things.
// For now, lets just print out what we have at each timestep.
LOG(cyclus::LEV_INFO4, "SnkFac") << "Sink " << this->id()
<< " is holding " << inventory.quantity()
<< " units of material at the close of month "
<< context()->time() << ".";
LOG(cyclus::LEV_INFO3, "SnkFac") << "}";
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
extern "C" cyclus::Agent* ConstructSink(cyclus::Context* ctx) {
return new Sink(ctx);
}
} // namespace cycamore
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <uri>
#include <regex>
#include <ostream>
namespace uri {
///////////////////////////////////////////////////////////////////////////////
URI::URI(const std::experimental::string_view uri)
: uri_str_{decode(std::move(uri.to_string()))}
{
parse();
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::scheme() const noexcept {
return scheme_;
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::userinfo() const noexcept {
return userinfo_;
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::host() const noexcept {
return host_;
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::port_str() const noexcept {
return port_str_;
}
///////////////////////////////////////////////////////////////////////////////
uint16_t URI::port() const noexcept {
if ((port_ == -1) && (not port_str_.empty())) {
port_ = static_cast<int32_t>(std::stoi(port_str_.to_string()));
}
return port_;
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::path() const noexcept {
return path_;
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::query() const noexcept {
return query_;
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::fragment() const noexcept {
return fragment_;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::query(const std::string& key) {
static bool queries_not_loaded {true};
static const std::string no_entry_value;
if (queries_not_loaded) {
load_queries();
queries_not_loaded = false;
}
auto target = queries_.find(key);
return (target not_eq queries_.end()) ? target->second : no_entry_value;
}
///////////////////////////////////////////////////////////////////////////////
bool URI::is_valid() const noexcept {
return not host_.empty() or not path_.empty();
}
///////////////////////////////////////////////////////////////////////////////
URI::operator bool() const noexcept {
return is_valid();
}
///////////////////////////////////////////////////////////////////////////////
std::string URI::to_string() const {
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
URI::operator std::string () const {
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
void URI::parse() {
using sview = std::experimental::string_view;
static const std::regex uri_pattern
{
"^([a-zA-Z]+[\\w\\+\\-\\.]+)?(\\://)?" //< scheme
"(([^:@]+)(\\:([^@]+))?@)?" //< username && password
"([^/:?#]+)?(\\:(\\d+))?" //< hostname && port
"([^?#]+)" //< path
"(\\?([^#]*))?" //< query
"(#(.*))?$" //< fragment
};
static std::smatch uri_parts;
if (std::regex_match(uri_str_, uri_parts, uri_pattern)) {
path_ = sview(uri_str_.data() + uri_parts.position(10), uri_parts.length(10));
scheme_ = uri_parts.length(1) ? sview(uri_str_.data() + uri_parts.position(1), uri_parts.length(1)) : sview{};
userinfo_ = uri_parts.length(3) ? sview(uri_str_.data() + uri_parts.position(3), uri_parts.length(3)) : sview{};
host_ = uri_parts.length(7) ? sview(uri_str_.data() + uri_parts.position(7), uri_parts.length(7)) : sview{};
port_str_ = uri_parts.length(9) ? sview(uri_str_.data() + uri_parts.position(9), uri_parts.length(9)) : sview{};
query_ = uri_parts.length(11) ? sview(uri_str_.data() + uri_parts.position(11), uri_parts.length(11)) : sview{};
fragment_ = uri_parts.length(13) ? sview(uri_str_.data() + uri_parts.position(13), uri_parts.length(13)) : sview{};
}
}
/////////////////////////////////////////////////////////////////////////////
void URI::load_queries() {
static const std::regex query_token_pattern {"[^?=&]+"};
auto query = query_.to_string();
auto it = std::sregex_iterator(query.cbegin(), query.cend(), query_token_pattern);
auto end = std::sregex_iterator();
while (it not_eq end) {
auto key = it->str();
if (++it not_eq end) {
queries_[key] = it->str();
} else {
queries_[key];
}
}
}
///////////////////////////////////////////////////////////////////////////////
bool operator < (const URI& lhs, const URI& rhs) noexcept {
return lhs.to_string() < rhs.to_string();
}
///////////////////////////////////////////////////////////////////////////////
bool operator == (const URI& lhs, const URI& rhs) noexcept {
return lhs.to_string() == rhs.to_string();
}
///////////////////////////////////////////////////////////////////////////////
std::ostream& operator<< (std::ostream& output_device, const URI& uri) {
return output_device << uri.to_string();
}
} //< namespace uri
<commit_msg>Stop blocking query string parsing with function local static bool guard.<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <uri>
#include <regex>
#include <ostream>
namespace uri {
///////////////////////////////////////////////////////////////////////////////
URI::URI(const std::experimental::string_view uri)
: uri_str_{decode(std::move(uri.to_string()))}
{
parse();
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::scheme() const noexcept {
return scheme_;
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::userinfo() const noexcept {
return userinfo_;
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::host() const noexcept {
return host_;
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::port_str() const noexcept {
return port_str_;
}
///////////////////////////////////////////////////////////////////////////////
uint16_t URI::port() const noexcept {
if ((port_ == -1) && (not port_str_.empty())) {
port_ = static_cast<int32_t>(std::stoi(port_str_.to_string()));
}
return port_;
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::path() const noexcept {
return path_;
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::query() const noexcept {
return query_;
}
///////////////////////////////////////////////////////////////////////////////
std::experimental::string_view URI::fragment() const noexcept {
return fragment_;
}
///////////////////////////////////////////////////////////////////////////////
const std::string& URI::query(const std::string& key) {
static const std::string no_entry_value;
if (not query_.empty() and queries_.empty()) {
load_queries();
}
auto target = queries_.find(key);
return (target not_eq queries_.end()) ? target->second : no_entry_value;
}
///////////////////////////////////////////////////////////////////////////////
bool URI::is_valid() const noexcept {
return not host_.empty() or not path_.empty();
}
///////////////////////////////////////////////////////////////////////////////
URI::operator bool() const noexcept {
return is_valid();
}
///////////////////////////////////////////////////////////////////////////////
std::string URI::to_string() const {
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
URI::operator std::string () const {
return uri_str_;
}
///////////////////////////////////////////////////////////////////////////////
void URI::parse() {
using sview = std::experimental::string_view;
static const std::regex uri_pattern
{
"^([a-zA-Z]+[\\w\\+\\-\\.]+)?(\\://)?" //< scheme
"(([^:@]+)(\\:([^@]+))?@)?" //< username && password
"([^/:?#]+)?(\\:(\\d+))?" //< hostname && port
"([^?#]+)" //< path
"(\\?([^#]*))?" //< query
"(#(.*))?$" //< fragment
};
static std::smatch uri_parts;
if (std::regex_match(uri_str_, uri_parts, uri_pattern)) {
path_ = sview(uri_str_.data() + uri_parts.position(10), uri_parts.length(10));
scheme_ = uri_parts.length(1) ? sview(uri_str_.data() + uri_parts.position(1), uri_parts.length(1)) : sview{};
userinfo_ = uri_parts.length(3) ? sview(uri_str_.data() + uri_parts.position(3), uri_parts.length(3)) : sview{};
host_ = uri_parts.length(7) ? sview(uri_str_.data() + uri_parts.position(7), uri_parts.length(7)) : sview{};
port_str_ = uri_parts.length(9) ? sview(uri_str_.data() + uri_parts.position(9), uri_parts.length(9)) : sview{};
query_ = uri_parts.length(11) ? sview(uri_str_.data() + uri_parts.position(11), uri_parts.length(11)) : sview{};
fragment_ = uri_parts.length(13) ? sview(uri_str_.data() + uri_parts.position(13), uri_parts.length(13)) : sview{};
}
}
/////////////////////////////////////////////////////////////////////////////
void URI::load_queries() {
static const std::regex query_token_pattern {"[^?=&]+"};
auto query = query_.to_string();
auto it = std::sregex_iterator(query.cbegin(), query.cend(), query_token_pattern);
auto end = std::sregex_iterator();
while (it not_eq end) {
auto key = it->str();
if (++it not_eq end) {
queries_[key] = it->str();
} else {
queries_[key];
}
}
}
///////////////////////////////////////////////////////////////////////////////
bool operator < (const URI& lhs, const URI& rhs) noexcept {
return lhs.to_string() < rhs.to_string();
}
///////////////////////////////////////////////////////////////////////////////
bool operator == (const URI& lhs, const URI& rhs) noexcept {
return lhs.to_string() == rhs.to_string();
}
///////////////////////////////////////////////////////////////////////////////
std::ostream& operator<< (std::ostream& output_device, const URI& uri) {
return output_device << uri.to_string();
}
} //< namespace uri
<|endoftext|>
|
<commit_before>//Bit
#define CARRY 0xD7
#define OF 0xD2
#define HCARRY 0xD6
#define INT_FLAG 0x00
#define EA_FLAG 0xAF
#define T0INT_FLAG 0xA9
#define T1INT_FLAG 0xAB
#define T0OF_FLAG 0x8D
#define T1OF_FLAG 0x8F
//Byte
#define AKKU 0xE0
#define B_address 0xF0
#define PSW 0xD0
#define stack_pointer 0x81
#define DTPTR 0x82
#define TCON 0x88
#define TMOD 0x89
#define TIMER_0 0x8A
#define TIMER_1 0x8B
#define PORT(a) 0x80+a*0x10
#define PORT0 0x80
#define PORT1 0x90
#define PORT2 0xA0
#define PORT3 0xB0
//Feste Adressen
<commit_msg>Delete ADDRESS_8051.hpp<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_browser_main_extra_parts_ash.h"
#include "ash/accelerators/accelerator_controller.h"
#include "ash/ash_switches.h"
#include "ash/shell.h"
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/browser/ui/views/ash/caps_lock_handler.h"
#include "chrome/browser/ui/views/ash/chrome_shell_delegate.h"
#include "chrome/browser/ui/views/ash/screen_orientation_listener.h"
#include "chrome/browser/ui/views/ash/screenshot_taker.h"
#include "chrome/browser/ui/views/ash/status_area_host_aura.h"
#include "ui/aura/env.h"
#include "ui/aura/aura_switches.h"
#include "ui/aura/monitor_manager.h"
#include "ui/aura/root_window.h"
#include "ui/gfx/compositor/compositor_setup.h"
#if defined(OS_CHROMEOS)
#include "base/chromeos/chromeos_version.h"
#include "chrome/browser/ui/views/ash/brightness_controller_chromeos.h"
#include "chrome/browser/ui/views/ash/ime_controller_chromeos.h"
#include "chrome/browser/ui/views/ash/volume_controller_chromeos.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#endif
ChromeBrowserMainExtraPartsAsh::ChromeBrowserMainExtraPartsAsh()
: ChromeBrowserMainExtraParts() {
}
void ChromeBrowserMainExtraPartsAsh::PreProfileInit() {
#if defined(OS_CHROMEOS)
aura::MonitorManager::set_use_fullscreen_host_window(true);
if (base::chromeos::IsRunningOnChromeOS() ||
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kAuraHostWindowUseFullscreen)) {
aura::MonitorManager::set_use_fullscreen_host_window(true);
aura::RootWindow::set_hide_host_cursor(true);
// Hide the mouse cursor completely at boot.
if (!chromeos::UserManager::Get()->IsUserLoggedIn())
ash::Shell::set_initially_hide_cursor(true);
}
#endif
// Shell takes ownership of ChromeShellDelegate.
ash::Shell* shell = ash::Shell::CreateInstance(new ChromeShellDelegate);
shell->accelerator_controller()->SetScreenshotDelegate(
scoped_ptr<ash::ScreenshotDelegate>(new ScreenshotTaker).Pass());
#if defined(OS_CHROMEOS)
shell->accelerator_controller()->SetBrightnessControlDelegate(
scoped_ptr<ash::BrightnessControlDelegate>(
new BrightnessController).Pass());
chromeos::input_method::XKeyboard* xkeyboard =
chromeos::input_method::InputMethodManager::GetInstance()->GetXKeyboard();
shell->accelerator_controller()->SetCapsLockDelegate(
scoped_ptr<ash::CapsLockDelegate>(new CapsLockHandler(xkeyboard)).Pass());
shell->accelerator_controller()->SetImeControlDelegate(
scoped_ptr<ash::ImeControlDelegate>(new ImeController).Pass());
shell->accelerator_controller()->SetVolumeControlDelegate(
scoped_ptr<ash::VolumeControlDelegate>(new VolumeController).Pass());
#endif
// Make sure the singleton ScreenOrientationListener object is created.
ScreenOrientationListener::GetInstance();
}
void ChromeBrowserMainExtraPartsAsh::PostProfileInit() {
// Add the status area buttons after Profile has been initialized.
if (CommandLine::ForCurrentProcess()->HasSwitch(
ash::switches::kDisableAshUberTray)) {
ChromeShellDelegate::instance()->status_area_host()->AddButtons();
}
}
void ChromeBrowserMainExtraPartsAsh::PostMainMessageLoopRun() {
ash::Shell::DeleteInstance();
}
<commit_msg>Remove test code that was checked in by accident<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_browser_main_extra_parts_ash.h"
#include "ash/accelerators/accelerator_controller.h"
#include "ash/ash_switches.h"
#include "ash/shell.h"
#include "base/command_line.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/browser/ui/views/ash/caps_lock_handler.h"
#include "chrome/browser/ui/views/ash/chrome_shell_delegate.h"
#include "chrome/browser/ui/views/ash/screen_orientation_listener.h"
#include "chrome/browser/ui/views/ash/screenshot_taker.h"
#include "chrome/browser/ui/views/ash/status_area_host_aura.h"
#include "ui/aura/env.h"
#include "ui/aura/aura_switches.h"
#include "ui/aura/monitor_manager.h"
#include "ui/aura/root_window.h"
#include "ui/gfx/compositor/compositor_setup.h"
#if defined(OS_CHROMEOS)
#include "base/chromeos/chromeos_version.h"
#include "chrome/browser/ui/views/ash/brightness_controller_chromeos.h"
#include "chrome/browser/ui/views/ash/ime_controller_chromeos.h"
#include "chrome/browser/ui/views/ash/volume_controller_chromeos.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#endif
ChromeBrowserMainExtraPartsAsh::ChromeBrowserMainExtraPartsAsh()
: ChromeBrowserMainExtraParts() {
}
void ChromeBrowserMainExtraPartsAsh::PreProfileInit() {
#if defined(OS_CHROMEOS)
if (base::chromeos::IsRunningOnChromeOS() ||
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kAuraHostWindowUseFullscreen)) {
aura::MonitorManager::set_use_fullscreen_host_window(true);
aura::RootWindow::set_hide_host_cursor(true);
// Hide the mouse cursor completely at boot.
if (!chromeos::UserManager::Get()->IsUserLoggedIn())
ash::Shell::set_initially_hide_cursor(true);
}
#endif
// Shell takes ownership of ChromeShellDelegate.
ash::Shell* shell = ash::Shell::CreateInstance(new ChromeShellDelegate);
shell->accelerator_controller()->SetScreenshotDelegate(
scoped_ptr<ash::ScreenshotDelegate>(new ScreenshotTaker).Pass());
#if defined(OS_CHROMEOS)
shell->accelerator_controller()->SetBrightnessControlDelegate(
scoped_ptr<ash::BrightnessControlDelegate>(
new BrightnessController).Pass());
chromeos::input_method::XKeyboard* xkeyboard =
chromeos::input_method::InputMethodManager::GetInstance()->GetXKeyboard();
shell->accelerator_controller()->SetCapsLockDelegate(
scoped_ptr<ash::CapsLockDelegate>(new CapsLockHandler(xkeyboard)).Pass());
shell->accelerator_controller()->SetImeControlDelegate(
scoped_ptr<ash::ImeControlDelegate>(new ImeController).Pass());
shell->accelerator_controller()->SetVolumeControlDelegate(
scoped_ptr<ash::VolumeControlDelegate>(new VolumeController).Pass());
#endif
// Make sure the singleton ScreenOrientationListener object is created.
ScreenOrientationListener::GetInstance();
}
void ChromeBrowserMainExtraPartsAsh::PostProfileInit() {
// Add the status area buttons after Profile has been initialized.
if (CommandLine::ForCurrentProcess()->HasSwitch(
ash::switches::kDisableAshUberTray)) {
ChromeShellDelegate::instance()->status_area_host()->AddButtons();
}
}
void ChromeBrowserMainExtraPartsAsh::PostMainMessageLoopRun() {
ash::Shell::DeleteInstance();
}
<|endoftext|>
|
<commit_before>
#include "stdafx.h"
#include "bonenode.h"
using namespace graphic;
cBoneNode::cBoneNode(const int id, vector<Matrix44> &palette, const sRawBone &rawBone) :
cNode(id, rawBone.name)
, m_track(NULL)
, m_mesh(NULL)
, m_palette(palette)
, m_aniStart(0)
, m_aniEnd(0)
, m_curPlayFrame(0)
, m_incPlayFrame(0)
, m_totalPlayTime(0)
, m_curPlayTime(0)
, m_incPlayTime(0)
, m_isAni(false)
, m_isLoop(false)
{
m_offset = rawBone.worldTm.Inverse();
m_localTM = rawBone.localTm;
m_mesh = new cMesh(id, rawBone);
}
cBoneNode::~cBoneNode()
{
SAFE_DELETE( m_track );
SAFE_DELETE( m_mesh );
}
// ִϸ̼ .
void cBoneNode::SetAnimation( const sRawAni &rawAni, int nAniFrame, bool bLoop)
{
int aniend = 0;
if (0 == nAniFrame)
{
m_totalPlayTime = (int)rawAni.end;
aniend = (int)rawAni.end;
}
else
{
m_totalPlayTime = nAniFrame;
aniend = (int)rawAni.end;
}
m_aniStart = rawAni.start;
m_aniEnd = aniend;
m_incPlayFrame = 0;
m_isLoop = bLoop;
m_isAni = true;
m_curPlayFrame = rawAni.start;
m_curPlayTime = rawAni.start * 0.03334f;
SAFE_DELETE(m_track)
m_track = new cTrack(rawAni);
}
// ϸ̼.
bool cBoneNode::Move(const float elapseTime)
{
RETV(!m_isAni, true);
RETV(!m_track, true);
m_curPlayTime += elapseTime;
m_incPlayTime += elapseTime;
m_curPlayFrame = (int)(m_curPlayTime * 30.f);
m_incPlayFrame = (int)(m_incPlayTime * 30.f);
BOOL ani_loop_end = (m_curPlayFrame > m_aniEnd); // ϸ̼ ٸ TRUE
BOOL ani_end = (!m_isLoop) && (m_incPlayFrame > m_totalPlayTime); // ѿϸ̼ ð ٸ TRUE
if (ani_loop_end || ani_end)
{
// ϸ̼ ݺ ϸ̶̼
// ϸ̼ ó .
if (m_isLoop)
{
m_curPlayFrame = m_aniStart;
m_curPlayTime = m_aniStart * 0.03334f;
m_track->InitAnimation(m_aniStart);
}
else
{
// ݺ ϸ̼ ƴ϶
// ϸ̼ ð ϸ̼ ϰ FALSE Ѵ.
// ʴٸ ϸ̼ ó .
if (ani_loop_end)
{
m_curPlayFrame = m_aniStart;
m_curPlayTime = m_aniStart * 0.03334f;
// ϸ̼ ʾҴٸ ϸ̼ ó ǵ.
// ϸ̼ ٸ ǵ ʰ ϰ д.
// ϸ̼ǿ DZ ؼ ξ Ѵ.
if (!ani_end)
m_track->InitAnimation(m_aniStart);
}
if (ani_end)
{
m_isAni = false;
return false;
}
}
}
m_aniTM.SetIdentity();
m_track->Move( m_curPlayFrame, m_aniTM );
m_accTM = m_localTM * m_aniTM * m_TM;
// posŰ local TM ǥ Ѵ
if( m_aniTM._41 == 0.0f && m_aniTM._42 == 0.0f && m_aniTM._43 == 0.0f )
{
m_accTM._41 = m_localTM._41;
m_accTM._42 = m_localTM._42;
m_accTM._43 = m_localTM._43;
}
else // posŰ ǥ Ѵ(̷ TM pos ιȴ)
{
m_accTM._41 = m_aniTM._41;
m_accTM._42 = m_aniTM._42;
m_accTM._43 = m_aniTM._43;
}
if (m_parent)
m_accTM = m_accTM * ((cBoneNode*)m_parent)->m_accTM;
m_palette[ m_id] = m_offset * m_accTM;
BOOST_FOREACH (auto p, m_children)
p->Move( elapseTime );
return true;
}
void cBoneNode::Render(const Matrix44 &parentTm)
{
RET(!m_mesh);
if (m_track)
m_mesh->Render(m_offset * m_accTM * parentTm);
else
m_mesh->Render(parentTm);
BOOST_FOREACH (auto p, m_children)
p->Render( parentTm );
}
void cBoneNode::SetCurrentFrame(const int curFrame)
{
m_curPlayTime = curFrame / 30.f;
m_curPlayFrame = curFrame;
if (m_track)
m_track->SetCurrentFramePos(curFrame);
}
// m_accTM Ʈ Ѵ.
void cBoneNode::UpdateAccTM()
{
m_accTM = m_localTM * m_aniTM * m_TM;
if (m_parent)
m_accTM = m_accTM * ((cBoneNode*)m_parent)->m_accTM;
m_palette[ m_id] = m_offset * m_accTM;
}
<commit_msg>update track, incPlayTime reset<commit_after>
#include "stdafx.h"
#include "bonenode.h"
using namespace graphic;
cBoneNode::cBoneNode(const int id, vector<Matrix44> &palette, const sRawBone &rawBone) :
cNode(id, rawBone.name)
, m_track(NULL)
, m_mesh(NULL)
, m_palette(palette)
, m_aniStart(0)
, m_aniEnd(0)
, m_curPlayFrame(0)
, m_incPlayFrame(0)
, m_totalPlayTime(0)
, m_curPlayTime(0)
, m_incPlayTime(0)
, m_isAni(false)
, m_isLoop(false)
{
m_offset = rawBone.worldTm.Inverse();
m_localTM = rawBone.localTm;
m_mesh = new cMesh(id, rawBone);
}
cBoneNode::~cBoneNode()
{
SAFE_DELETE( m_track );
SAFE_DELETE( m_mesh );
}
// ִϸ̼ .
void cBoneNode::SetAnimation( const sRawAni &rawAni, int nAniFrame, bool bLoop)
{
int aniend = 0;
if (0 == nAniFrame)
{
m_totalPlayTime = (int)rawAni.end;
aniend = (int)rawAni.end;
}
else
{
m_totalPlayTime = nAniFrame;
aniend = (int)rawAni.end;
}
m_aniStart = rawAni.start;
m_aniEnd = aniend;
m_incPlayFrame = 0;
m_incPlayTime = 0;
m_isLoop = bLoop;
m_isAni = true;
m_curPlayFrame = rawAni.start;
m_curPlayTime = rawAni.start * 0.03334f;
SAFE_DELETE(m_track)
m_track = new cTrack(rawAni);
}
// ϸ̼.
bool cBoneNode::Move(const float elapseTime)
{
RETV(!m_isAni, true);
RETV(!m_track, true);
m_curPlayTime += elapseTime;
m_incPlayTime += elapseTime;
m_curPlayFrame = (int)(m_curPlayTime * 30.f);
m_incPlayFrame = (int)(m_incPlayTime * 30.f);
BOOL ani_loop_end = (m_curPlayFrame > m_aniEnd); // ϸ̼ ٸ TRUE
BOOL ani_end = (!m_isLoop) && (m_incPlayFrame > m_totalPlayTime); // ѿϸ̼ ð ٸ TRUE
if (ani_loop_end || ani_end)
{
// ϸ̼ ݺ ϸ̶̼
// ϸ̼ ó .
if (m_isLoop)
{
m_curPlayFrame = m_aniStart;
m_curPlayTime = m_aniStart * 0.03334f;
m_track->InitAnimation(m_aniStart);
}
else
{
// ݺ ϸ̼ ƴ϶
// ϸ̼ ð ϸ̼ ϰ FALSE Ѵ.
// ʴٸ ϸ̼ ó .
if (ani_loop_end)
{
m_curPlayFrame = m_aniStart;
m_curPlayTime = m_aniStart * 0.03334f;
// ϸ̼ ʾҴٸ ϸ̼ ó ǵ.
// ϸ̼ ٸ ǵ ʰ ϰ д.
// ϸ̼ǿ DZ ؼ ξ Ѵ.
if (!ani_end)
m_track->InitAnimation(m_aniStart);
}
if (ani_end)
{
m_isAni = false;
return false;
}
}
}
m_aniTM.SetIdentity();
m_track->Move( m_curPlayFrame, m_aniTM );
m_accTM = m_localTM * m_aniTM * m_TM;
// posŰ local TM ǥ Ѵ
if( m_aniTM._41 == 0.0f && m_aniTM._42 == 0.0f && m_aniTM._43 == 0.0f )
{
m_accTM._41 = m_localTM._41;
m_accTM._42 = m_localTM._42;
m_accTM._43 = m_localTM._43;
}
else // posŰ ǥ Ѵ(̷ TM pos ιȴ)
{
m_accTM._41 = m_aniTM._41;
m_accTM._42 = m_aniTM._42;
m_accTM._43 = m_aniTM._43;
}
if (m_parent)
m_accTM = m_accTM * ((cBoneNode*)m_parent)->m_accTM;
m_palette[ m_id] = m_offset * m_accTM;
BOOST_FOREACH (auto p, m_children)
p->Move( elapseTime );
return true;
}
void cBoneNode::Render(const Matrix44 &parentTm)
{
RET(!m_mesh);
if (m_track)
m_mesh->Render(m_offset * m_accTM * parentTm);
else
m_mesh->Render(parentTm);
BOOST_FOREACH (auto p, m_children)
p->Render( parentTm );
}
void cBoneNode::SetCurrentFrame(const int curFrame)
{
m_curPlayTime = curFrame / 30.f;
m_curPlayFrame = curFrame;
if (m_track)
m_track->SetCurrentFramePos(curFrame);
}
// m_accTM Ʈ Ѵ.
void cBoneNode::UpdateAccTM()
{
m_accTM = m_localTM * m_aniTM * m_TM;
if (m_parent)
m_accTM = m_accTM * ((cBoneNode*)m_parent)->m_accTM;
m_palette[ m_id] = m_offset * m_accTM;
}
<|endoftext|>
|
<commit_before>#ifdef _WIN32
#define M_PI 3.14
#endif
#include <cmath>
#include <iostream>
#include <fstream>
#include "Body.hpp"
#define G 20 // TODO: Get the right number
#define DENSITY 100 // kg/m^3
using namespace sf;
using namespace std;
Body::Body(Vector2f pos, uint64_t m, Vector2f dir)
: position(pos), direction(dir), mass(m)
{
if (mass <= 0)
{
cout << "FATAL ERROR: MASS <= 0" << endl;
}
cout << "MASS=" << mass << endl;
// Radius
float volume = mass / DENSITY;
radius = cbrt((3*volume)/(4*M_PI));
if (radius < 1)
{
radius = 1;
}
Color color(Color::White);
Color clear_yellow(212, 193, 106);
Color brown(175, 75, 0);
if (mass <= 10000)
{
color = interpolate(Color::White, clear_yellow, mass / 10000.0f);
}
else if (mass <= 100000)
{
color = interpolate(clear_yellow, brown, mass / 100000.0f);
}
else if (mass >= 1000000)
{
color = Color::Red;
}
else
{
color = interpolate(brown, Color::Red, mass / 1000000.0f);
}
shape.setRadius(radius);
shape.setFillColor(color);
}
void Body::move(float dt)
{
position += direction * dt;
}
void Body::applyGravityOf(const Body &b, float dt)
{
float r = getDistanceTo(b);
if (r <= 0)
{
return;
}
float F = (G*mass*b.mass) / (r*r);
// Make the force proportional to the mass
F /= mass;
// Get the unit vector to the other body
Vector2f to_Body(b.position - position);
to_Body = to_Body / r;
// Apply the force in the direction of the other body
direction += (to_Body * F) * dt;
}
float Body::getDistanceTo(const Body &p)
{
Vector2f c = p.position - position;
return sqrt(c.x*c.x + c.y * c.y);
}
void Body::draw(RenderWindow &window)
{
shape.setPosition(position);
window.draw(shape);
}
bool Body::collideWith(const Body &p)
{
Vector2f a = position;
// a.x += radius;
// a.y += radius;
Vector2f b = p.position;
// b.x += p.radius;
// b.y += p.radius;
float d = (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y);
if (d <= (radius+p.radius)*(radius+p.radius))
return true;
return false;
}
bool Body::contains(const Vector2f &point)
{
Vector2f a = position;
a.x += radius;
a.y += radius;
Vector2f b = point;
Vector2f c = b - a;
if ((c.x*c.x + c.y * c.y) <= radius*radius)
{
return true;
}
return false;
}
// Handy helper fonctions
/*
* ratio is a number between 0.0f and 1.0f
*/
Color interpolate(Color a, Color b, float ratio)
{
Color c;
c.r = (b.r-a.r) * ratio + a.r;
c.g = (b.g-a.g) * ratio + a.g;
c.b = (b.b-a.b) * ratio + a.b;
return c;
}
<commit_msg>fixed the center of gravity being in the top left hand corner<commit_after>#ifdef _WIN32
#define M_PI 3.14
#endif
#include <cmath>
#include <iostream>
#include <fstream>
#include "Body.hpp"
#define G 20 // TODO: Get the right number
#define DENSITY 100 // kg/m^3
using namespace sf;
using namespace std;
Body::Body(Vector2f pos, uint64_t m, Vector2f dir)
: position(pos), direction(dir), mass(m)
{
if (mass <= 0)
{
cout << "FATAL ERROR: MASS <= 0" << endl;
}
cout << "MASS=" << mass << endl;
// Radius
float volume = mass / DENSITY;
radius = cbrt((3*volume)/(4*M_PI));
if (radius < 1)
{
radius = 1;
}
Color color(Color::White);
Color clear_yellow(212, 193, 106);
Color brown(175, 75, 0);
if (mass <= 10000)
{
color = interpolate(Color::White, clear_yellow, mass / 10000.0f);
}
else if (mass <= 100000)
{
color = interpolate(clear_yellow, brown, mass / 100000.0f);
}
else if (mass >= 1000000)
{
color = Color::Red;
}
else
{
color = interpolate(brown, Color::Red, mass / 1000000.0f);
}
shape.setRadius(radius);
shape.setFillColor(color);
}
void Body::move(float dt)
{
position += direction * dt;
}
void Body::applyGravityOf(const Body &b, float dt)
{
float r = getDistanceTo(b);
if (r <= 0)
{
cout << "return" << endl;
return;
}
float F = (G*mass*b.mass) / (r*r);
// Make the force proportional to the mass
F /= mass;
// Get the unit vector to the other body
Vector2f target(b.position.x+b.radius, b.position.y+b.radius);
Vector2f center(position.x+radius, position.y+radius);
Vector2f to_Body(target - center);
to_Body = to_Body / r;
// Apply the force in the direction of the other body
direction += (to_Body * F) * dt;
}
float Body::getDistanceTo(const Body &b)
{
Vector2f target(b.position.x+b.radius, b.position.y+b.radius);
Vector2f center(position.x+radius, position.y+radius);
Vector2f c = target - center;
return sqrt(c.x*c.x + c.y * c.y);
}
void Body::draw(RenderWindow &window)
{
shape.setPosition(position);
window.draw(shape);
}
bool Body::collideWith(const Body &p)
{
Vector2f a = position;
a.x += radius;
a.y += radius;
Vector2f b = p.position;
b.x += p.radius;
b.y += p.radius;
float d = (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y);
if (d <= (radius+p.radius)*(radius+p.radius))
return true;
return false;
}
bool Body::contains(const Vector2f &point)
{
Vector2f c = point - position;
if ((c.x*c.x + c.y * c.y) <= radius*radius)
{
return true;
}
return false;
}
// Handy helper fonctions
/*
* ratio is a number between 0.0f and 1.0f
*/
Color interpolate(Color a, Color b, float ratio)
{
Color c;
c.r = (b.r-a.r) * ratio + a.r;
c.g = (b.g-a.g) * ratio + a.g;
c.b = (b.b-a.b) * ratio + a.b;
return c;
}
<|endoftext|>
|
<commit_before>// playHistoryTracker.cpp : Defines the entry point for the DLL application.
//
#include "bzfsAPI.h"
#include <string>
#include <map>
BZ_GET_PLUGIN_VERSION
// event handler callback
class PlayHistoryTracker : public bz_EventHandler
{
public:
PlayHistoryTracker();
virtual ~PlayHistoryTracker();
virtual void process ( bz_EventData *eventData );
virtual bool autoDelete ( void ) { return false;} // this will be used for more then one event
protected:
typedef struct
{
int playerID;
std::string callsign;
double startTime;
double lastUpdateTime;
int spreeTotal;
}trPlayerHistoryRecord;
std::map<int, trPlayerHistoryRecord > playerList;
};
PlayHistoryTracker historyTracker;
BZF_PLUGIN_CALL int bz_Load ( const char* commandLine )
{
bz_debugMessage(4,"PlayHistoryTracker plugin loaded");
bz_registerEvent(bz_ePlayerDieEvent,&historyTracker);
bz_registerEvent(bz_ePlayerPartEvent,&historyTracker);
bz_registerEvent(bz_ePlayerSpawnEvent,&historyTracker);
bz_registerEvent(bz_ePlayerJoinEvent,&historyTracker);
return 0;
}
BZF_PLUGIN_CALL int bz_Unload ( void )
{
bz_removeEvent(bz_ePlayerDieEvent,&historyTracker);
bz_removeEvent(bz_ePlayerPartEvent,&historyTracker);
bz_removeEvent(bz_ePlayerSpawnEvent,&historyTracker);
bz_removeEvent(bz_ePlayerJoinEvent,&historyTracker);
bz_debugMessage(4,"PlayHistoryTracker plugin unloaded");
return 0;
}
// ----------------- SpreeTracker-----------------
/*typedef struct
{
int playerID;
std::string callsign;
double startTime;
double lastUpdateTime;
int spreeTotal;
}trPlayerHistoryRecord;
std::map<int, trPlayerHistoryRecord > playerList; */
PlayHistoryTracker::PlayHistoryTracker()
{
}
PlayHistoryTracker::~PlayHistoryTracker()
{
}
void PlayHistoryTracker::process ( bz_EventData *eventData )
{
switch (eventData->eventType)
{
default:
// really WTF!!!!
break;
case bz_ePlayerDieEvent:
{
bz_PlayerDieEventData *deathRecord = ( bz_PlayerDieEventData*)eventData;
std::string killerCallSign = "UNKNOWN";
bz_PlayerRecord *killerData;
killerData = bz_getPlayerByIndex(deathRecord->killerID);
if (killerData)
killerCallSign = killerData->callsign.c_str();
std::string soundToPlay;
// clear out the dude who got shot, since he won't be having any SPREEs
if (playerList.find(deathRecord->playerID) != playerList.end())
{
trPlayerHistoryRecord &record = playerList.find(deathRecord->playerID)->second;
std::string message;
if ( record.spreeTotal >= 5 && record.spreeTotal < 10 )
message = record.callsign + std::string("'s rampage was stopped by ") + killerCallSign;
if ( record.spreeTotal >= 10 && record.spreeTotal < 20 )
message = record.callsign + std::string("'s killing spree was halted by ") + killerCallSign;
if ( record.spreeTotal >= 20 )
message = std::string("The unstoppable reign of ") + record.callsign + std::string(" was ended by ") + killerCallSign;
if (message.size())
{
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, message.c_str());
soundToPlay = "spree4";
}
record.spreeTotal = 0;
record.startTime = deathRecord->time;
record.lastUpdateTime = deathRecord->time;
}
// chock up another win for our killer
// if they weren't the same as the killer ( suicide ).
if ( (deathRecord->playerID != deathRecord->killerID) && playerList.find(deathRecord->killerID) != playerList.end())
{
trPlayerHistoryRecord &record = playerList.find(deathRecord->killerID)->second;
record.spreeTotal++;
record.lastUpdateTime = deathRecord->time;
std::string message;
if ( record.spreeTotal == 5 )
{
message = record.callsign + std::string(" is on a Rampage!");
if (!soundToPlay.size())
soundToPlay = "spree1";
}
if ( record.spreeTotal == 10 )
{
message = record.callsign + std::string(" is on a Killing Spree!");
if (!soundToPlay.size())
soundToPlay = "spree2";
}
if ( record.spreeTotal == 20 )
{
message = record.callsign + std::string(" is Unstoppable!!");
if (!soundToPlay.size())
soundToPlay = "spree3";
}
if ( record.spreeTotal > 20 && record.spreeTotal%5 == 0 )
{
message = record.callsign + std::string(" continues to rage on");
if (!soundToPlay.size())
soundToPlay = "spree4";
}
if (message.size())
{
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, message.c_str());
}
}
bz_freePlayerRecord(killerData);
if (soundToPlay.size())
bz_sendPlayCustomLocalSound(BZ_ALLUSERS,soundToPlay.c_str());
}
break;
case bz_ePlayerSpawnEvent:
// really WTF!!!!
break;
case bz_ePlayerJoinEvent:
{
trPlayerHistoryRecord playerRecord;
playerRecord.playerID = (( bz_PlayerJoinPartEventData*)eventData)->playerID;
playerRecord.callsign = (( bz_PlayerJoinPartEventData*)eventData)->callsign.c_str();
playerRecord.spreeTotal = 0;
playerRecord.lastUpdateTime = (( bz_PlayerJoinPartEventData*)eventData)->time;
playerRecord.startTime = playerRecord.lastUpdateTime;
playerList[(( bz_PlayerJoinPartEventData*)eventData)->playerID] = playerRecord;
}
break;
case bz_ePlayerPartEvent:
{
std::map<int, trPlayerHistoryRecord >::iterator itr = playerList.find( (( bz_PlayerJoinPartEventData*)eventData)->playerID );
if (itr != playerList.end())
playerList.erase(itr);
}
break;
}
}
<commit_msg>remove sound playing as it "may" be bugy<commit_after>// playHistoryTracker.cpp : Defines the entry point for the DLL application.
//
#include "bzfsAPI.h"
#include <string>
#include <map>
BZ_GET_PLUGIN_VERSION
// event handler callback
class PlayHistoryTracker : public bz_EventHandler
{
public:
PlayHistoryTracker();
virtual ~PlayHistoryTracker();
virtual void process ( bz_EventData *eventData );
virtual bool autoDelete ( void ) { return false;} // this will be used for more then one event
protected:
typedef struct
{
int playerID;
std::string callsign;
double startTime;
double lastUpdateTime;
int spreeTotal;
}trPlayerHistoryRecord;
std::map<int, trPlayerHistoryRecord > playerList;
};
PlayHistoryTracker historyTracker;
BZF_PLUGIN_CALL int bz_Load ( const char* commandLine )
{
bz_debugMessage(4,"PlayHistoryTracker plugin loaded");
bz_registerEvent(bz_ePlayerDieEvent,&historyTracker);
bz_registerEvent(bz_ePlayerPartEvent,&historyTracker);
bz_registerEvent(bz_ePlayerSpawnEvent,&historyTracker);
bz_registerEvent(bz_ePlayerJoinEvent,&historyTracker);
return 0;
}
BZF_PLUGIN_CALL int bz_Unload ( void )
{
bz_removeEvent(bz_ePlayerDieEvent,&historyTracker);
bz_removeEvent(bz_ePlayerPartEvent,&historyTracker);
bz_removeEvent(bz_ePlayerSpawnEvent,&historyTracker);
bz_removeEvent(bz_ePlayerJoinEvent,&historyTracker);
bz_debugMessage(4,"PlayHistoryTracker plugin unloaded");
return 0;
}
// ----------------- SpreeTracker-----------------
/*typedef struct
{
int playerID;
std::string callsign;
double startTime;
double lastUpdateTime;
int spreeTotal;
}trPlayerHistoryRecord;
std::map<int, trPlayerHistoryRecord > playerList; */
PlayHistoryTracker::PlayHistoryTracker()
{
}
PlayHistoryTracker::~PlayHistoryTracker()
{
}
void PlayHistoryTracker::process ( bz_EventData *eventData )
{
switch (eventData->eventType)
{
default:
// really WTF!!!!
break;
case bz_ePlayerDieEvent:
{
bz_PlayerDieEventData *deathRecord = ( bz_PlayerDieEventData*)eventData;
std::string killerCallSign = "UNKNOWN";
bz_PlayerRecord *killerData;
killerData = bz_getPlayerByIndex(deathRecord->killerID);
if (killerData)
killerCallSign = killerData->callsign.c_str();
std::string soundToPlay;
// clear out the dude who got shot, since he won't be having any SPREEs
if (playerList.find(deathRecord->playerID) != playerList.end())
{
trPlayerHistoryRecord &record = playerList.find(deathRecord->playerID)->second;
std::string message;
if ( record.spreeTotal >= 5 && record.spreeTotal < 10 )
message = record.callsign + std::string("'s rampage was stopped by ") + killerCallSign;
if ( record.spreeTotal >= 10 && record.spreeTotal < 20 )
message = record.callsign + std::string("'s killing spree was halted by ") + killerCallSign;
if ( record.spreeTotal >= 20 )
message = std::string("The unstoppable reign of ") + record.callsign + std::string(" was ended by ") + killerCallSign;
if (message.size())
{
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, message.c_str());
soundToPlay = "spree4";
}
record.spreeTotal = 0;
record.startTime = deathRecord->time;
record.lastUpdateTime = deathRecord->time;
}
// chock up another win for our killer
// if they weren't the same as the killer ( suicide ).
if ( (deathRecord->playerID != deathRecord->killerID) && playerList.find(deathRecord->killerID) != playerList.end())
{
trPlayerHistoryRecord &record = playerList.find(deathRecord->killerID)->second;
record.spreeTotal++;
record.lastUpdateTime = deathRecord->time;
std::string message;
if ( record.spreeTotal == 5 )
{
message = record.callsign + std::string(" is on a Rampage!");
if (!soundToPlay.size())
soundToPlay = "spree1";
}
if ( record.spreeTotal == 10 )
{
message = record.callsign + std::string(" is on a Killing Spree!");
if (!soundToPlay.size())
soundToPlay = "spree2";
}
if ( record.spreeTotal == 20 )
{
message = record.callsign + std::string(" is Unstoppable!!");
if (!soundToPlay.size())
soundToPlay = "spree3";
}
if ( record.spreeTotal > 20 && record.spreeTotal%5 == 0 )
{
message = record.callsign + std::string(" continues to rage on");
if (!soundToPlay.size())
soundToPlay = "spree4";
}
if (message.size())
{
bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, message.c_str());
}
}
bz_freePlayerRecord(killerData);
//if (soundToPlay.size())
// bz_sendPlayCustomLocalSound(BZ_ALLUSERS,soundToPlay.c_str());
}
break;
case bz_ePlayerSpawnEvent:
// really WTF!!!!
break;
case bz_ePlayerJoinEvent:
{
trPlayerHistoryRecord playerRecord;
playerRecord.playerID = (( bz_PlayerJoinPartEventData*)eventData)->playerID;
playerRecord.callsign = (( bz_PlayerJoinPartEventData*)eventData)->callsign.c_str();
playerRecord.spreeTotal = 0;
playerRecord.lastUpdateTime = (( bz_PlayerJoinPartEventData*)eventData)->time;
playerRecord.startTime = playerRecord.lastUpdateTime;
playerList[(( bz_PlayerJoinPartEventData*)eventData)->playerID] = playerRecord;
}
break;
case bz_ePlayerPartEvent:
{
std::map<int, trPlayerHistoryRecord >::iterator itr = playerList.find( (( bz_PlayerJoinPartEventData*)eventData)->playerID );
if (itr != playerList.end())
playerList.erase(itr);
}
break;
}
}
<|endoftext|>
|
<commit_before>// 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 "chrome/browser/importer/firefox_importer_utils.h"
#include <shlobj.h>
#include "base/file_util.h"
#include "base/win/registry.h"
// NOTE: Keep these in order since we need test all those paths according
// to priority. For example. One machine has multiple users. One non-admin
// user installs Firefox 2, which causes there is a Firefox2 entry under HKCU.
// One admin user installs Firefox 3, which causes there is a Firefox 3 entry
// under HKLM. So when the non-admin user log in, we should deal with Firefox 2
// related data instead of Firefox 3.
static const HKEY kFireFoxRegistryPaths[] = {
HKEY_CURRENT_USER,
HKEY_LOCAL_MACHINE
};
int GetCurrentFirefoxMajorVersionFromRegistry() {
TCHAR ver_buffer[128];
DWORD ver_buffer_length = sizeof(ver_buffer);
int highest_version = 0;
// When installing Firefox with admin account, the product keys will be
// written under HKLM\Mozilla. Otherwise it the keys will be written under
// HKCU\Mozilla.
for (int i = 0; i < arraysize(kFireFoxRegistryPaths); ++i) {
base::win::RegKey reg_key(kFireFoxRegistryPaths[i],
L"Software\\Mozilla\\Mozilla Firefox", KEY_READ);
LONG result = reg_key.ReadValue(L"CurrentVersion", ver_buffer,
&ver_buffer_length, NULL);
if (result != ERROR_SUCCESS)
continue;
highest_version = std::max(highest_version, _wtoi(ver_buffer));
}
return highest_version;
}
FilePath GetFirefoxInstallPathFromRegistry() {
// Detects the path that Firefox is installed in.
std::wstring registry_path = L"Software\\Mozilla\\Mozilla Firefox";
wchar_t buffer[MAX_PATH];
DWORD buffer_length = sizeof(buffer);
base::win::RegKey reg_key(HKEY_LOCAL_MACHINE, registry_path.c_str(),
KEY_READ);
LONG result = reg_key.ReadValue(L"CurrentVersion", buffer,
&buffer_length, NULL);
if (result != ERROR_SUCCESS)
return FilePath();
registry_path += L"\\" + std::wstring(buffer) + L"\\Main";
buffer_length = sizeof(buffer);
base::win::RegKey reg_key_directory(HKEY_LOCAL_MACHINE,
registry_path.c_str(), KEY_READ);
result = reg_key_directory.ReadValue(L"Install Directory", buffer,
&buffer_length, NULL);
return (result != ERROR_SUCCESS) ? FilePath() : FilePath(buffer);
}
FilePath GetProfilesINI() {
FilePath ini_file;
// The default location of the profile folder containing user data is
// under the "Application Data" folder in Windows XP.
wchar_t buffer[MAX_PATH] = {0};
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL,
SHGFP_TYPE_CURRENT, buffer))) {
ini_file = FilePath(buffer).Append(L"Mozilla\\Firefox\\profiles.ini");
}
if (file_util::PathExists(ini_file))
return ini_file;
return FilePath();
}
<commit_msg>importer: Convert two wstrings to string16 in GetFirefoxInstallPathFromRegistry().<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 "chrome/browser/importer/firefox_importer_utils.h"
#include <shlobj.h>
#include "base/file_util.h"
#include "base/string16.h"
#include "base/win/registry.h"
// NOTE: Keep these in order since we need test all those paths according
// to priority. For example. One machine has multiple users. One non-admin
// user installs Firefox 2, which causes there is a Firefox2 entry under HKCU.
// One admin user installs Firefox 3, which causes there is a Firefox 3 entry
// under HKLM. So when the non-admin user log in, we should deal with Firefox 2
// related data instead of Firefox 3.
static const HKEY kFireFoxRegistryPaths[] = {
HKEY_CURRENT_USER,
HKEY_LOCAL_MACHINE
};
int GetCurrentFirefoxMajorVersionFromRegistry() {
TCHAR ver_buffer[128];
DWORD ver_buffer_length = sizeof(ver_buffer);
int highest_version = 0;
// When installing Firefox with admin account, the product keys will be
// written under HKLM\Mozilla. Otherwise it the keys will be written under
// HKCU\Mozilla.
for (int i = 0; i < arraysize(kFireFoxRegistryPaths); ++i) {
base::win::RegKey reg_key(kFireFoxRegistryPaths[i],
L"Software\\Mozilla\\Mozilla Firefox", KEY_READ);
LONG result = reg_key.ReadValue(L"CurrentVersion", ver_buffer,
&ver_buffer_length, NULL);
if (result != ERROR_SUCCESS)
continue;
highest_version = std::max(highest_version, _wtoi(ver_buffer));
}
return highest_version;
}
FilePath GetFirefoxInstallPathFromRegistry() {
// Detects the path that Firefox is installed in.
string16 registry_path = L"Software\\Mozilla\\Mozilla Firefox";
wchar_t buffer[MAX_PATH];
DWORD buffer_length = sizeof(buffer);
base::win::RegKey reg_key(HKEY_LOCAL_MACHINE, registry_path.c_str(),
KEY_READ);
LONG result = reg_key.ReadValue(L"CurrentVersion", buffer,
&buffer_length, NULL);
if (result != ERROR_SUCCESS)
return FilePath();
registry_path += L"\\" + string16(buffer) + L"\\Main";
buffer_length = sizeof(buffer);
base::win::RegKey reg_key_directory(HKEY_LOCAL_MACHINE,
registry_path.c_str(), KEY_READ);
result = reg_key_directory.ReadValue(L"Install Directory", buffer,
&buffer_length, NULL);
return (result != ERROR_SUCCESS) ? FilePath() : FilePath(buffer);
}
FilePath GetProfilesINI() {
FilePath ini_file;
// The default location of the profile folder containing user data is
// under the "Application Data" folder in Windows XP.
wchar_t buffer[MAX_PATH] = {0};
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL,
SHGFP_TYPE_CURRENT, buffer))) {
ini_file = FilePath(buffer).Append(L"Mozilla\\Firefox\\profiles.ini");
}
if (file_util::PathExists(ini_file))
return ini_file;
return FilePath();
}
<|endoftext|>
|
<commit_before>#include "mitkToolManager.h"
#include "mitkGlobalInteraction.h"
#include <itkObjectFactoryBase.h>
#include <itkCommand.h>
#include <list>
mitk::ToolManager::ToolManager(const char* groups)
:m_ActiveTool(NULL),
m_ActiveToolID(-1),
m_RegisteredClients(0)
{
// get a list of all known mitk::Tools
std::list<itk::LightObject::Pointer> thingsThatClaimToBeATool = itk::ObjectFactoryBase::CreateAllInstance("mitkTool");
std::string allowedGroups;
if (groups != NULL)
{
allowedGroups = groups;
}
// remember these tools
for ( std::list<itk::LightObject::Pointer>::iterator iter = thingsThatClaimToBeATool.begin();
iter != thingsThatClaimToBeATool.end();
++iter )
{
if ( Tool* tool = dynamic_cast<Tool*>( iter->GetPointer() ) )
{
tool->SetToolManager(this); // important to call right after instantiation
if ( (groups == NULL) || ( allowedGroups.find( tool->GetGroup() ) != std::string::npos ) ||
( allowedGroups.find( tool->GetName() ) != std::string::npos )
)
{
m_Tools.push_back( tool );
}
}
}
//ActivateTool(0); // first one is default
}
mitk::ToolManager::~ToolManager()
{
}
const mitk::ToolManager::ToolVectorTypeConst mitk::ToolManager::GetTools()
{
ToolVectorTypeConst resultList;
for ( ToolVectorType::iterator iter = m_Tools.begin();
iter != m_Tools.end();
++iter )
{
resultList.push_back( iter->GetPointer() );
}
return resultList;
}
mitk::Tool* mitk::ToolManager::GetToolById(int id)
{
try
{
return m_Tools.at(id);
}
catch(std::exception&)
{
return NULL;
}
}
bool mitk::ToolManager::ActivateTool(int id)
{
if ( GetToolById( id ) == m_ActiveTool ) return true; // no change needed
if (m_ActiveTool)
{
m_ActiveTool->Deactivated();
mitk::GlobalInteraction::GetInstance()->RemoveListener( m_ActiveTool );
}
m_ActiveTool = GetToolById( id );
m_ActiveToolID = m_ActiveTool ? id : -1; // current ID if tool is valid, otherwise -1
if (m_ActiveTool)
{
if (m_RegisteredClients)
{
m_ActiveTool->Activated();
mitk::GlobalInteraction::GetInstance()->AddListener( m_ActiveTool );
}
}
InvokeEvent( ToolSelectedEvent() );
return (m_ActiveTool != NULL);
}
void mitk::ToolManager::SetReferenceData(DataVectorType data)
{
if (data != m_ReferenceData)
{
// remove observers from old nodes
for ( DataVectorType::iterator dataIter = m_ReferenceData.begin(); dataIter != m_ReferenceData.end(); ++dataIter )
{
NodeTagMapType::iterator searchIter = m_ReferenceDataObserverTags.find( *dataIter );
if ( searchIter != m_ReferenceDataObserverTags.end() )
{
//std::cout << "Stopping observation of " << (void*)(*dataIter) << std::endl;
(*dataIter)->RemoveObserver( searchIter->second );
}
}
m_ReferenceData = data;
// TODO tell active tool?
// attach new observers
m_ReferenceDataObserverTags.clear();
for ( DataVectorType::iterator dataIter = m_ReferenceData.begin(); dataIter != m_ReferenceData.end(); ++dataIter )
{
//std::cout << "Observing " << (void*)(*dataIter) << std::endl;
itk::MemberCommand<ToolManager>::Pointer command = itk::MemberCommand<ToolManager>::New();
command->SetCallbackFunction( this, &ToolManager::OnOneOfTheReferenceDataDeleted );
command->SetCallbackFunction( this, &ToolManager::OnOneOfTheReferenceDataDeletedConst );
m_ReferenceDataObserverTags.insert( std::pair<DataTreeNode*, unsigned long>( (*dataIter), (*dataIter)->AddObserver( itk::DeleteEvent(), command ) ) );
}
InvokeEvent( ToolReferenceDataChangedEvent() );
}
}
void mitk::ToolManager::OnOneOfTheReferenceDataDeletedConst(const itk::Object* caller, const itk::EventObject& e)
{
OnOneOfTheReferenceDataDeleted( const_cast<itk::Object*>(caller), e );
}
void mitk::ToolManager::OnOneOfTheReferenceDataDeleted(itk::Object* caller, const itk::EventObject& itkNotUsed(e))
{
//std::cout << "Deleted: " << (void*)caller << " Removing from reference data list." << std::endl;
DataVectorType v;
for (DataVectorType::iterator dataIter = m_ReferenceData.begin(); dataIter != m_ReferenceData.end(); ++dataIter )
{
//std::cout << " In list: " << (void*)(*dataIter);
if ( (void*)(*dataIter) != (void*)caller )
{
v.push_back( *dataIter );
//std::cout << " kept" << std::endl;
}
else
{
//std::cout << " removed" << std::endl;
m_ReferenceDataObserverTags.erase( *dataIter ); // no tag to remove anymore
}
}
this->SetReferenceData( v );
}
void mitk::ToolManager::SetReferenceData(DataTreeNode* data)
{
//std::cout << "ToolManager::SetReferenceData(" << (void*)data << ")" << std::endl;
DataVectorType v;
v.push_back(data);
SetReferenceData(v);
}
void mitk::ToolManager::SetWorkingData(DataVectorType data)
{
if ( data != m_WorkingData )
{
// remove observers from old nodes
for ( DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter )
{
NodeTagMapType::iterator searchIter = m_WorkingDataObserverTags.find( *dataIter );
if ( searchIter != m_WorkingDataObserverTags.end() )
{
//std::cout << "Stopping observation of " << (void*)(*dataIter) << std::endl;
(*dataIter)->RemoveObserver( searchIter->second );
}
}
m_WorkingData = data;
// TODO tell active tool?
// attach new observers
m_WorkingDataObserverTags.clear();
for ( DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter )
{
//std::cout << "Observing " << (void*)(*dataIter) << std::endl;
itk::MemberCommand<ToolManager>::Pointer command = itk::MemberCommand<ToolManager>::New();
command->SetCallbackFunction( this, &ToolManager::OnOneOfTheWorkingDataDeleted );
command->SetCallbackFunction( this, &ToolManager::OnOneOfTheWorkingDataDeletedConst );
m_WorkingDataObserverTags.insert( std::pair<DataTreeNode*, unsigned long>( (*dataIter), (*dataIter)->AddObserver( itk::DeleteEvent(), command ) ) );
}
InvokeEvent( ToolWorkingDataChangedEvent() );
}
}
void mitk::ToolManager::OnOneOfTheWorkingDataDeletedConst(const itk::Object* caller, const itk::EventObject& e)
{
OnOneOfTheWorkingDataDeleted( const_cast<itk::Object*>(caller), e );
}
void mitk::ToolManager::OnOneOfTheWorkingDataDeleted(itk::Object* caller, const itk::EventObject& itkNotUsed(e))
{
//std::cout << "Deleted: " << (void*)caller << " Removing from reference data list." << std::endl;
DataVectorType v;
for (DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter )
{
//std::cout << " In list: " << (void*)(*dataIter);
if ( (void*)(*dataIter) != (void*)caller )
{
v.push_back( *dataIter );
//std::cout << " kept" << std::endl;
}
else
{
//std::cout << " removed" << std::endl;
m_WorkingDataObserverTags.erase( *dataIter ); // no tag to remove anymore
}
}
this->SetWorkingData( v );
}
void mitk::ToolManager::SetWorkingData(DataTreeNode* data)
{
DataVectorType v;
if (data) // don't allow for NULL nodes
{
v.push_back(data);
}
SetWorkingData(v);
}
mitk::ToolManager::DataVectorType mitk::ToolManager::GetReferenceData()
{
return m_ReferenceData;
}
mitk::DataTreeNode* mitk::ToolManager::GetReferenceData(int idx)
{
try
{
return m_ReferenceData.at(idx);
}
catch(std::exception&)
{
return NULL;
}
}
mitk::ToolManager::DataVectorType mitk::ToolManager::GetWorkingData()
{
return m_WorkingData;
}
mitk::DataTreeNode* mitk::ToolManager::GetWorkingData(int idx)
{
try
{
return m_WorkingData.at(idx);
}
catch(std::exception&)
{
return NULL;
}
}
int mitk::ToolManager::GetActiveToolID()
{
return m_ActiveToolID;
}
mitk::Tool* mitk::ToolManager::GetActiveTool()
{
return m_ActiveTool;
}
void mitk::ToolManager::RegisterClient()
{
if ( m_RegisteredClients == 0 )
{
if ( m_ActiveTool )
{
m_ActiveTool->Activated();
mitk::GlobalInteraction::GetInstance()->AddListener( m_ActiveTool );
}
}
++m_RegisteredClients;
}
void mitk::ToolManager::UnregisterClient()
{
--m_RegisteredClients;
if ( m_RegisteredClients == 0 )
{
if ( m_ActiveTool )
{
m_ActiveTool->Deactivated();
mitk::GlobalInteraction::GetInstance()->RemoveListener( m_ActiveTool );
}
}
}
<commit_msg>FIX (#1029) Place of first instantiation is unclear for CoreObjectFactory<commit_after>#include "mitkToolManager.h"
#include "mitkGlobalInteraction.h"
#include "mitkCoreObjectFactory.h"
#include <itkObjectFactoryBase.h>
#include <itkCommand.h>
#include <list>
mitk::ToolManager::ToolManager(const char* groups)
:m_ActiveTool(NULL),
m_ActiveToolID(-1),
m_RegisteredClients(0)
{
mitk::CoreObjectFactory::GetInstance(); // to make sure a CoreObjectFactory was instantiated (and in turn, possible tools are registered) - bug 1029
// get a list of all known mitk::Tools
std::list<itk::LightObject::Pointer> thingsThatClaimToBeATool = itk::ObjectFactoryBase::CreateAllInstance("mitkTool");
std::string allowedGroups;
if (groups != NULL)
{
allowedGroups = groups;
}
// remember these tools
for ( std::list<itk::LightObject::Pointer>::iterator iter = thingsThatClaimToBeATool.begin();
iter != thingsThatClaimToBeATool.end();
++iter )
{
if ( Tool* tool = dynamic_cast<Tool*>( iter->GetPointer() ) )
{
tool->SetToolManager(this); // important to call right after instantiation
if ( (groups == NULL) || ( allowedGroups.find( tool->GetGroup() ) != std::string::npos ) ||
( allowedGroups.find( tool->GetName() ) != std::string::npos )
)
{
m_Tools.push_back( tool );
}
}
}
//ActivateTool(0); // first one is default
}
mitk::ToolManager::~ToolManager()
{
}
const mitk::ToolManager::ToolVectorTypeConst mitk::ToolManager::GetTools()
{
ToolVectorTypeConst resultList;
for ( ToolVectorType::iterator iter = m_Tools.begin();
iter != m_Tools.end();
++iter )
{
resultList.push_back( iter->GetPointer() );
}
return resultList;
}
mitk::Tool* mitk::ToolManager::GetToolById(int id)
{
try
{
return m_Tools.at(id);
}
catch(std::exception&)
{
return NULL;
}
}
bool mitk::ToolManager::ActivateTool(int id)
{
if ( GetToolById( id ) == m_ActiveTool ) return true; // no change needed
if (m_ActiveTool)
{
m_ActiveTool->Deactivated();
mitk::GlobalInteraction::GetInstance()->RemoveListener( m_ActiveTool );
}
m_ActiveTool = GetToolById( id );
m_ActiveToolID = m_ActiveTool ? id : -1; // current ID if tool is valid, otherwise -1
if (m_ActiveTool)
{
if (m_RegisteredClients)
{
m_ActiveTool->Activated();
mitk::GlobalInteraction::GetInstance()->AddListener( m_ActiveTool );
}
}
InvokeEvent( ToolSelectedEvent() );
return (m_ActiveTool != NULL);
}
void mitk::ToolManager::SetReferenceData(DataVectorType data)
{
if (data != m_ReferenceData)
{
// remove observers from old nodes
for ( DataVectorType::iterator dataIter = m_ReferenceData.begin(); dataIter != m_ReferenceData.end(); ++dataIter )
{
NodeTagMapType::iterator searchIter = m_ReferenceDataObserverTags.find( *dataIter );
if ( searchIter != m_ReferenceDataObserverTags.end() )
{
//std::cout << "Stopping observation of " << (void*)(*dataIter) << std::endl;
(*dataIter)->RemoveObserver( searchIter->second );
}
}
m_ReferenceData = data;
// TODO tell active tool?
// attach new observers
m_ReferenceDataObserverTags.clear();
for ( DataVectorType::iterator dataIter = m_ReferenceData.begin(); dataIter != m_ReferenceData.end(); ++dataIter )
{
//std::cout << "Observing " << (void*)(*dataIter) << std::endl;
itk::MemberCommand<ToolManager>::Pointer command = itk::MemberCommand<ToolManager>::New();
command->SetCallbackFunction( this, &ToolManager::OnOneOfTheReferenceDataDeleted );
command->SetCallbackFunction( this, &ToolManager::OnOneOfTheReferenceDataDeletedConst );
m_ReferenceDataObserverTags.insert( std::pair<DataTreeNode*, unsigned long>( (*dataIter), (*dataIter)->AddObserver( itk::DeleteEvent(), command ) ) );
}
InvokeEvent( ToolReferenceDataChangedEvent() );
}
}
void mitk::ToolManager::OnOneOfTheReferenceDataDeletedConst(const itk::Object* caller, const itk::EventObject& e)
{
OnOneOfTheReferenceDataDeleted( const_cast<itk::Object*>(caller), e );
}
void mitk::ToolManager::OnOneOfTheReferenceDataDeleted(itk::Object* caller, const itk::EventObject& itkNotUsed(e))
{
//std::cout << "Deleted: " << (void*)caller << " Removing from reference data list." << std::endl;
DataVectorType v;
for (DataVectorType::iterator dataIter = m_ReferenceData.begin(); dataIter != m_ReferenceData.end(); ++dataIter )
{
//std::cout << " In list: " << (void*)(*dataIter);
if ( (void*)(*dataIter) != (void*)caller )
{
v.push_back( *dataIter );
//std::cout << " kept" << std::endl;
}
else
{
//std::cout << " removed" << std::endl;
m_ReferenceDataObserverTags.erase( *dataIter ); // no tag to remove anymore
}
}
this->SetReferenceData( v );
}
void mitk::ToolManager::SetReferenceData(DataTreeNode* data)
{
//std::cout << "ToolManager::SetReferenceData(" << (void*)data << ")" << std::endl;
DataVectorType v;
v.push_back(data);
SetReferenceData(v);
}
void mitk::ToolManager::SetWorkingData(DataVectorType data)
{
if ( data != m_WorkingData )
{
// remove observers from old nodes
for ( DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter )
{
NodeTagMapType::iterator searchIter = m_WorkingDataObserverTags.find( *dataIter );
if ( searchIter != m_WorkingDataObserverTags.end() )
{
//std::cout << "Stopping observation of " << (void*)(*dataIter) << std::endl;
(*dataIter)->RemoveObserver( searchIter->second );
}
}
m_WorkingData = data;
// TODO tell active tool?
// attach new observers
m_WorkingDataObserverTags.clear();
for ( DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter )
{
//std::cout << "Observing " << (void*)(*dataIter) << std::endl;
itk::MemberCommand<ToolManager>::Pointer command = itk::MemberCommand<ToolManager>::New();
command->SetCallbackFunction( this, &ToolManager::OnOneOfTheWorkingDataDeleted );
command->SetCallbackFunction( this, &ToolManager::OnOneOfTheWorkingDataDeletedConst );
m_WorkingDataObserverTags.insert( std::pair<DataTreeNode*, unsigned long>( (*dataIter), (*dataIter)->AddObserver( itk::DeleteEvent(), command ) ) );
}
InvokeEvent( ToolWorkingDataChangedEvent() );
}
}
void mitk::ToolManager::OnOneOfTheWorkingDataDeletedConst(const itk::Object* caller, const itk::EventObject& e)
{
OnOneOfTheWorkingDataDeleted( const_cast<itk::Object*>(caller), e );
}
void mitk::ToolManager::OnOneOfTheWorkingDataDeleted(itk::Object* caller, const itk::EventObject& itkNotUsed(e))
{
//std::cout << "Deleted: " << (void*)caller << " Removing from reference data list." << std::endl;
DataVectorType v;
for (DataVectorType::iterator dataIter = m_WorkingData.begin(); dataIter != m_WorkingData.end(); ++dataIter )
{
//std::cout << " In list: " << (void*)(*dataIter);
if ( (void*)(*dataIter) != (void*)caller )
{
v.push_back( *dataIter );
//std::cout << " kept" << std::endl;
}
else
{
//std::cout << " removed" << std::endl;
m_WorkingDataObserverTags.erase( *dataIter ); // no tag to remove anymore
}
}
this->SetWorkingData( v );
}
void mitk::ToolManager::SetWorkingData(DataTreeNode* data)
{
DataVectorType v;
if (data) // don't allow for NULL nodes
{
v.push_back(data);
}
SetWorkingData(v);
}
mitk::ToolManager::DataVectorType mitk::ToolManager::GetReferenceData()
{
return m_ReferenceData;
}
mitk::DataTreeNode* mitk::ToolManager::GetReferenceData(int idx)
{
try
{
return m_ReferenceData.at(idx);
}
catch(std::exception&)
{
return NULL;
}
}
mitk::ToolManager::DataVectorType mitk::ToolManager::GetWorkingData()
{
return m_WorkingData;
}
mitk::DataTreeNode* mitk::ToolManager::GetWorkingData(int idx)
{
try
{
return m_WorkingData.at(idx);
}
catch(std::exception&)
{
return NULL;
}
}
int mitk::ToolManager::GetActiveToolID()
{
return m_ActiveToolID;
}
mitk::Tool* mitk::ToolManager::GetActiveTool()
{
return m_ActiveTool;
}
void mitk::ToolManager::RegisterClient()
{
if ( m_RegisteredClients == 0 )
{
if ( m_ActiveTool )
{
m_ActiveTool->Activated();
mitk::GlobalInteraction::GetInstance()->AddListener( m_ActiveTool );
}
}
++m_RegisteredClients;
}
void mitk::ToolManager::UnregisterClient()
{
--m_RegisteredClients;
if ( m_RegisteredClients == 0 )
{
if ( m_ActiveTool )
{
m_ActiveTool->Deactivated();
mitk::GlobalInteraction::GetInstance()->RemoveListener( m_ActiveTool );
}
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2013, Koichiro Yamaguchi
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 holder 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 HOLDER 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 "AdaBoost.h"
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include "readSampleDataFile.h"
struct SampleElement {
int sampleIndex;
double sampleValue;
bool operator<(const SampleElement& comparisonElement) const { return sampleValue < comparisonElement.sampleValue; }
};
void AdaBoost::DecisionStump::set(const int featureIndex,
const double threshold,
const double outputLarger,
const double outputSmaller,
const double error)
{
featureIndex_ = featureIndex;
threshold_ = threshold;
outputLarger_ = outputLarger;
outputSmaller_ = outputSmaller;
error_ = error;
}
double AdaBoost::DecisionStump::evaluate(const double featureValue) const {
if (featureValue > threshold_) return outputLarger_;
else return outputSmaller_;
}
double AdaBoost::DecisionStump::evaluate(const std::vector<double>& featureVector) const {
if (featureVector[featureIndex_] > threshold_) return outputLarger_;
else return outputSmaller_;
}
void AdaBoost::setBoostingType(const int boostingType) {
if (boostingType < 0 || boostingType > 2) {
std::cerr << "error: invalid type of boosting" << std::endl;
exit(1);
}
boostingType_ = boostingType;
}
void AdaBoost::setTrainingSamples(const std::string& trainingDataFilename) {
readSampleDataFile(trainingDataFilename, samples_, labels_);
sampleTotal_ = static_cast<int>(samples_.size());
if (sampleTotal_ == 0) {
std::cerr << "error: no training sample" << std::endl;
exit(1);
}
featureTotal_ = static_cast<int>(samples_[0].size());
initializeWeights();
sortSampleIndices();
weakClassifiers_.clear();
}
void AdaBoost::train(const int roundTotal, const bool verbose) {
for (int roundCount = 0; roundCount < roundTotal; ++roundCount) {
trainRound();
if (verbose) {
std::cout << "Round " << roundCount << ": " << std::endl;
std::cout << "feature = " << weakClassifiers_[roundCount].featureIndex() << ", ";
std::cout << "threshold = " << weakClassifiers_[roundCount].threshold() << ", ";
std::cout << "output = [ " << weakClassifiers_[roundCount].outputLarger() << ", ";
std::cout << weakClassifiers_[roundCount].outputSmaller() << "], ";
std::cout << "error = " << weakClassifiers_[roundCount].error() << std::endl;
}
}
// Prediction test
if (verbose) {
int positiveTotal = 0;
int positiveCorrectTotal = 0;
int negativeTotal = 0;
int negativeCorrectTotal = 0;
for (int sampleIndex = 0; sampleIndex < sampleTotal_; ++sampleIndex) {
double score = this->predict(samples_[sampleIndex]);
if (labels_[sampleIndex]) {
++positiveTotal;
if (score > 0) ++positiveCorrectTotal;
} else {
++negativeTotal;
if (score <= 0) ++negativeCorrectTotal;
}
}
std::cout << std::endl;
std::cout << "Training set" << std::endl;
std::cout << " positive: " << static_cast<double>(positiveCorrectTotal)/positiveTotal;
std::cout << " (" << positiveCorrectTotal << " / " << positiveTotal << "), ";
std::cout << "negative: " << static_cast<double>(negativeCorrectTotal)/negativeTotal;
std::cout << " (" << negativeCorrectTotal << " / " << negativeTotal << ")" << std::endl;;
}
}
double AdaBoost::predict(const std::vector<double>& featureVector) const {
double score = 0.0;
for (int classifierIndex = 0; classifierIndex < static_cast<int>(weakClassifiers_.size()); ++classifierIndex) {
score += weakClassifiers_[classifierIndex].evaluate(featureVector);
}
return score;
}
void AdaBoost::initializeWeights() {
double initialWeight = 1.0/sampleTotal_;
weights_.resize(sampleTotal_);
for (int i = 0; i < sampleTotal_; ++i) weights_[i] = initialWeight;
}
void AdaBoost::sortSampleIndices() {
sortedSampleIndices_.resize(featureTotal_);
for (int d = 0; d < featureTotal_; ++d) {
std::vector<SampleElement> featureElements(sampleTotal_);
for (int sampleIndex = 0; sampleIndex < sampleTotal_; ++sampleIndex) {
featureElements[sampleIndex].sampleIndex = sampleIndex;
featureElements[sampleIndex].sampleValue = samples_[sampleIndex][d];
}
std::sort(featureElements.begin(), featureElements.end());
sortedSampleIndices_[d].resize(sampleTotal_);
for (int i = 0; i < sampleTotal_; ++i) {
sortedSampleIndices_[d][i] = featureElements[i].sampleIndex;
}
}
}
void AdaBoost::trainRound() {
calcWeightSum();
DecisionStump bestClassifier;
for (int featureIndex = 0; featureIndex < featureTotal_; ++featureIndex) {
DecisionStump optimalClassifier = learnOptimalClassifier(featureIndex);
if (optimalClassifier.featureIndex() < 0) continue;
if (bestClassifier.error() < 0 || optimalClassifier.error() < bestClassifier.error()) {
bestClassifier = optimalClassifier;
}
}
updateWeight(bestClassifier);
weakClassifiers_.push_back(bestClassifier);
}
void AdaBoost::calcWeightSum() {
weightSum_ = 0;
weightLabelSum_ = 0;
positiveWeightSum_ = 0;
negativeWeightSum_ = 0;
for (int sampleIndex = 0; sampleIndex < sampleTotal_; ++sampleIndex) {
weightSum_ += weights_[sampleIndex];
if (labels_[sampleIndex]) {
weightLabelSum_ += weights_[sampleIndex];
positiveWeightSum_ += weights_[sampleIndex];
} else {
weightLabelSum_ -= weights_[sampleIndex];
negativeWeightSum_ += weights_[sampleIndex];
}
}
}
AdaBoost::DecisionStump AdaBoost::learnOptimalClassifier(const int featureIndex) {
const double epsilonValue = 1e-6;
double weightSumLarger = weightSum_;
double weightLabelSumLarger = weightLabelSum_;
double positiveWeightSumLarger = positiveWeightSum_;
double negativeWeightSumLarger = negativeWeightSum_;
DecisionStump optimalClassifier;
for (int sortIndex = 0; sortIndex < sampleTotal_ - 1; ++sortIndex) {
int sampleIndex = sortedSampleIndices_[featureIndex][sortIndex];
double threshold = samples_[sampleIndex][featureIndex];
double sampleWeight = weights_[sampleIndex];
weightSumLarger -= sampleWeight;
if (labels_[sampleIndex]) {
weightLabelSumLarger -= sampleWeight;
positiveWeightSumLarger -= sampleWeight;
} else {
weightLabelSumLarger += sampleWeight;
negativeWeightSumLarger -= sampleWeight;
}
while (sortIndex < sampleTotal_ - 1
&& samples_[sampleIndex][featureIndex] == samples_[sortedSampleIndices_[featureIndex][sortIndex + 1]][featureIndex])
{
++sortIndex;
sampleIndex = sortedSampleIndices_[featureIndex][sortIndex];
sampleWeight = weights_[sampleIndex];
weightSumLarger -= sampleWeight;
if (labels_[sampleIndex]) {
weightLabelSumLarger -= sampleWeight;
positiveWeightSumLarger -= sampleWeight;
} else {
weightLabelSumLarger += sampleWeight;
negativeWeightSumLarger -= sampleWeight;
}
}
if (sortIndex >= sampleTotal_ - 1) break;
if (fabs(weightLabelSumLarger) < epsilonValue || fabs(weightSum_ - weightSumLarger) < epsilonValue) continue;
double outputLarger, outputSmaller;
computeClassifierOutputs(weightSumLarger, weightLabelSumLarger, positiveWeightSumLarger, negativeWeightSumLarger,
outputLarger, outputSmaller);
double error = computeError(positiveWeightSumLarger, negativeWeightSumLarger, outputLarger, outputSmaller);
if (optimalClassifier.error() < 0 || error < optimalClassifier.error()) {
double classifierThreshold = (threshold + samples_[sortedSampleIndices_[featureIndex][sortIndex + 1]][featureIndex])/2.0;
if (boostingType_ == 0) {
double classifierWeight = log((1.0 - error)/error)/2.0;
outputLarger *= classifierWeight;
outputSmaller *= classifierWeight;
}
optimalClassifier.set(featureIndex, classifierThreshold, outputLarger, outputSmaller, error);
}
}
return optimalClassifier;
}
void AdaBoost::computeClassifierOutputs(const double weightSumLarger,
const double weightLabelSumLarger,
const double positiveWeightSumLarger,
const double negativeWeightSumLarger,
double &outputLarger,
double &outputSmaller) const
{
if (boostingType_ == 0) {
// Discrete AdaBoost
if (weightLabelSumLarger > 0) {
outputLarger = 1.0;
outputSmaller = -1.0;
} else {
outputLarger = -1.0;
outputSmaller = 1.0;
}
} else if (boostingType_ == 1) {
// Real AdaBoost
const double epsilonReal = 0.0001;
outputLarger = log((positiveWeightSumLarger + epsilonReal)/(negativeWeightSumLarger + epsilonReal))/2.0;
outputSmaller = log((positiveWeightSum_ - positiveWeightSumLarger + epsilonReal)
/(negativeWeightSum_ - negativeWeightSumLarger + epsilonReal))/2.0;
} else {
// Gentle AdaBoost
outputLarger = weightLabelSumLarger/weightSumLarger;
outputSmaller = (weightLabelSum_ - weightLabelSumLarger)/(weightSum_ - weightSumLarger);
}
}
double AdaBoost::computeError(const double positiveWeightSumLarger,
const double negativeWeightSumLarger,
const double outputLarger,
const double outputSmaller) const
{
double error = 0.0;
if (boostingType_ == 0) {
// Discrete AdaBoost
error = positiveWeightSumLarger*(1.0 - outputLarger)/2.0
+ (positiveWeightSum_ - positiveWeightSumLarger)*(1.0 - outputSmaller)/2.0
+ negativeWeightSumLarger*(-1.0 - outputLarger)/-2.0
+ (negativeWeightSum_ - negativeWeightSumLarger)*(-1.0 - outputSmaller)/-2.0;
} else if (boostingType_ == 1) {
// Real AdaBoost
error = positiveWeightSumLarger*exp(-outputLarger)
+ (positiveWeightSum_ - positiveWeightSumLarger)*exp(-outputSmaller)
+ negativeWeightSumLarger*exp(outputLarger)
+ (negativeWeightSum_ - negativeWeightSumLarger)*exp(outputSmaller);
} else {
// Gentle AdaBoost
error = positiveWeightSumLarger*(1.0 - outputLarger)*(1.0 - outputLarger)
+ (positiveWeightSum_ - positiveWeightSumLarger)*(1.0 - outputSmaller)*(1.0 - outputSmaller)
+ negativeWeightSumLarger*(-1.0 - outputLarger)*(-1.0 - outputLarger)
+ (negativeWeightSum_ - negativeWeightSumLarger)*(-1.0 - outputSmaller)*(-1.0 - outputSmaller);
}
return error;
}
void AdaBoost::updateWeight(const AdaBoost::DecisionStump& bestClassifier) {
double updatedWeightSum = 0.0;
for (int sampleIndex = 0; sampleIndex < sampleTotal_; ++sampleIndex) {
int labelInteger;
if (labels_[sampleIndex]) labelInteger = 1;
else labelInteger = -1;
weights_[sampleIndex] *= exp(-1.0*labelInteger*bestClassifier.evaluate(samples_[sampleIndex]));
updatedWeightSum += weights_[sampleIndex];
}
for (int sampleIndex = 0; sampleIndex < sampleTotal_; ++sampleIndex) {
weights_[sampleIndex] /= updatedWeightSum;
}
}
void AdaBoost::writeFile(const std::string filename) const {
std::ofstream outputModelStream(filename.c_str(), std::ios_base::out);
if (outputModelStream.fail()) {
std::cerr << "error: can't open file (" << filename << ")" << std::endl;
exit(1);
}
int roundTotal = static_cast<int>(weakClassifiers_.size());
outputModelStream << roundTotal << std::endl;
for (int roundIndex = 0; roundIndex < roundTotal; ++roundIndex) {
outputModelStream << weakClassifiers_[roundIndex].featureIndex() << " ";
outputModelStream << weakClassifiers_[roundIndex].threshold() << " ";
outputModelStream << weakClassifiers_[roundIndex].outputLarger() << " ";
outputModelStream << weakClassifiers_[roundIndex].outputSmaller() << std::endl;
}
outputModelStream.close();
}
void AdaBoost::readFile(const std::string filename) {
std::ifstream inputModelStream(filename.c_str(), std::ios_base::in);
if (inputModelStream.fail()) {
std::cerr << "error: can't open file (" << filename << ")" << std::endl;
exit(1);
}
int roundTotal;
inputModelStream >> roundTotal;
weakClassifiers_.resize(roundTotal);
for (int roundIndex = 0; roundIndex < roundTotal; ++roundIndex) {
int featureIndex;
double threshold, outputLarger, outputSmaller;
inputModelStream >> featureIndex;
inputModelStream >> threshold;
inputModelStream >> outputLarger;
inputModelStream >> outputSmaller;
weakClassifiers_[roundIndex].set(featureIndex, threshold, outputLarger, outputSmaller);
}
inputModelStream.close();
}
<commit_msg>bugfix<commit_after>/*
Copyright (c) 2013, Koichiro Yamaguchi
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 holder 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 HOLDER 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 "AdaBoost.h"
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include "readSampleDataFile.h"
struct SampleElement {
int sampleIndex;
double sampleValue;
bool operator<(const SampleElement& comparisonElement) const { return sampleValue < comparisonElement.sampleValue; }
};
void AdaBoost::DecisionStump::set(const int featureIndex,
const double threshold,
const double outputLarger,
const double outputSmaller,
const double error)
{
featureIndex_ = featureIndex;
threshold_ = threshold;
outputLarger_ = outputLarger;
outputSmaller_ = outputSmaller;
error_ = error;
}
double AdaBoost::DecisionStump::evaluate(const double featureValue) const {
if (featureValue > threshold_) return outputLarger_;
else return outputSmaller_;
}
double AdaBoost::DecisionStump::evaluate(const std::vector<double>& featureVector) const {
if (featureVector[featureIndex_] > threshold_) return outputLarger_;
else return outputSmaller_;
}
void AdaBoost::setBoostingType(const int boostingType) {
if (boostingType < 0 || boostingType > 2) {
std::cerr << "error: invalid type of boosting" << std::endl;
exit(1);
}
boostingType_ = boostingType;
}
void AdaBoost::setTrainingSamples(const std::string& trainingDataFilename) {
readSampleDataFile(trainingDataFilename, samples_, labels_);
sampleTotal_ = static_cast<int>(samples_.size());
if (sampleTotal_ == 0) {
std::cerr << "error: no training sample" << std::endl;
exit(1);
}
featureTotal_ = static_cast<int>(samples_[0].size());
initializeWeights();
sortSampleIndices();
weakClassifiers_.clear();
}
void AdaBoost::train(const int roundTotal, const bool verbose) {
for (int roundCount = 0; roundCount < roundTotal; ++roundCount) {
trainRound();
if (verbose) {
std::cout << "Round " << roundCount << ": " << std::endl;
std::cout << "feature = " << weakClassifiers_[roundCount].featureIndex() << ", ";
std::cout << "threshold = " << weakClassifiers_[roundCount].threshold() << ", ";
std::cout << "output = [ " << weakClassifiers_[roundCount].outputLarger() << ", ";
std::cout << weakClassifiers_[roundCount].outputSmaller() << "], ";
std::cout << "error = " << weakClassifiers_[roundCount].error() << std::endl;
}
}
// Prediction test
if (verbose) {
int positiveTotal = 0;
int positiveCorrectTotal = 0;
int negativeTotal = 0;
int negativeCorrectTotal = 0;
for (int sampleIndex = 0; sampleIndex < sampleTotal_; ++sampleIndex) {
double score = this->predict(samples_[sampleIndex]);
if (labels_[sampleIndex]) {
++positiveTotal;
if (score > 0) ++positiveCorrectTotal;
} else {
++negativeTotal;
if (score <= 0) ++negativeCorrectTotal;
}
}
std::cout << std::endl;
std::cout << "Training set" << std::endl;
std::cout << " positive: " << static_cast<double>(positiveCorrectTotal)/positiveTotal;
std::cout << " (" << positiveCorrectTotal << " / " << positiveTotal << "), ";
std::cout << "negative: " << static_cast<double>(negativeCorrectTotal)/negativeTotal;
std::cout << " (" << negativeCorrectTotal << " / " << negativeTotal << ")" << std::endl;;
}
}
double AdaBoost::predict(const std::vector<double>& featureVector) const {
double score = 0.0;
for (int classifierIndex = 0; classifierIndex < static_cast<int>(weakClassifiers_.size()); ++classifierIndex) {
score += weakClassifiers_[classifierIndex].evaluate(featureVector);
}
return score;
}
void AdaBoost::initializeWeights() {
double initialWeight = 1.0/sampleTotal_;
weights_.resize(sampleTotal_);
for (int i = 0; i < sampleTotal_; ++i) weights_[i] = initialWeight;
}
void AdaBoost::sortSampleIndices() {
sortedSampleIndices_.resize(featureTotal_);
for (int d = 0; d < featureTotal_; ++d) {
std::vector<SampleElement> featureElements(sampleTotal_);
for (int sampleIndex = 0; sampleIndex < sampleTotal_; ++sampleIndex) {
featureElements[sampleIndex].sampleIndex = sampleIndex;
featureElements[sampleIndex].sampleValue = samples_[sampleIndex][d];
}
std::sort(featureElements.begin(), featureElements.end());
sortedSampleIndices_[d].resize(sampleTotal_);
for (int i = 0; i < sampleTotal_; ++i) {
sortedSampleIndices_[d][i] = featureElements[i].sampleIndex;
}
}
}
void AdaBoost::trainRound() {
calcWeightSum();
DecisionStump bestClassifier;
for (int featureIndex = 0; featureIndex < featureTotal_; ++featureIndex) {
DecisionStump optimalClassifier = learnOptimalClassifier(featureIndex);
if (optimalClassifier.featureIndex() < 0) continue;
if (bestClassifier.error() < 0 || optimalClassifier.error() < bestClassifier.error()) {
bestClassifier = optimalClassifier;
}
}
updateWeight(bestClassifier);
weakClassifiers_.push_back(bestClassifier);
}
void AdaBoost::calcWeightSum() {
weightSum_ = 0;
weightLabelSum_ = 0;
positiveWeightSum_ = 0;
negativeWeightSum_ = 0;
for (int sampleIndex = 0; sampleIndex < sampleTotal_; ++sampleIndex) {
weightSum_ += weights_[sampleIndex];
if (labels_[sampleIndex]) {
weightLabelSum_ += weights_[sampleIndex];
positiveWeightSum_ += weights_[sampleIndex];
} else {
weightLabelSum_ -= weights_[sampleIndex];
negativeWeightSum_ += weights_[sampleIndex];
}
}
}
AdaBoost::DecisionStump AdaBoost::learnOptimalClassifier(const int featureIndex) {
const double epsilonValue = 1e-6;
double weightSumLarger = weightSum_;
double weightLabelSumLarger = weightLabelSum_;
double positiveWeightSumLarger = positiveWeightSum_;
double negativeWeightSumLarger = negativeWeightSum_;
DecisionStump optimalClassifier;
for (int sortIndex = 0; sortIndex < sampleTotal_ - 1; ++sortIndex) {
int sampleIndex = sortedSampleIndices_[featureIndex][sortIndex];
double threshold = samples_[sampleIndex][featureIndex];
double sampleWeight = weights_[sampleIndex];
weightSumLarger -= sampleWeight;
if (labels_[sampleIndex]) {
weightLabelSumLarger -= sampleWeight;
positiveWeightSumLarger -= sampleWeight;
} else {
weightLabelSumLarger += sampleWeight;
negativeWeightSumLarger -= sampleWeight;
}
while (sortIndex < sampleTotal_ - 1
&& samples_[sampleIndex][featureIndex] == samples_[sortedSampleIndices_[featureIndex][sortIndex + 1]][featureIndex])
{
++sortIndex;
sampleIndex = sortedSampleIndices_[featureIndex][sortIndex];
sampleWeight = weights_[sampleIndex];
weightSumLarger -= sampleWeight;
if (labels_[sampleIndex]) {
weightLabelSumLarger -= sampleWeight;
positiveWeightSumLarger -= sampleWeight;
} else {
weightLabelSumLarger += sampleWeight;
negativeWeightSumLarger -= sampleWeight;
}
}
if (sortIndex >= sampleTotal_ - 1) break;
if (fabs(weightSumLarger) < epsilonValue || fabs(weightSum_ - weightSumLarger) < epsilonValue) continue;
double outputLarger, outputSmaller;
computeClassifierOutputs(weightSumLarger, weightLabelSumLarger, positiveWeightSumLarger, negativeWeightSumLarger,
outputLarger, outputSmaller);
double error = computeError(positiveWeightSumLarger, negativeWeightSumLarger, outputLarger, outputSmaller);
if (optimalClassifier.error() < 0 || error < optimalClassifier.error()) {
double classifierThreshold = (threshold + samples_[sortedSampleIndices_[featureIndex][sortIndex + 1]][featureIndex])/2.0;
if (boostingType_ == 0) {
double classifierWeight = log((1.0 - error)/error)/2.0;
outputLarger *= classifierWeight;
outputSmaller *= classifierWeight;
}
optimalClassifier.set(featureIndex, classifierThreshold, outputLarger, outputSmaller, error);
}
}
return optimalClassifier;
}
void AdaBoost::computeClassifierOutputs(const double weightSumLarger,
const double weightLabelSumLarger,
const double positiveWeightSumLarger,
const double negativeWeightSumLarger,
double &outputLarger,
double &outputSmaller) const
{
if (boostingType_ == 0) {
// Discrete AdaBoost
if (weightLabelSumLarger > 0) {
outputLarger = 1.0;
outputSmaller = -1.0;
} else {
outputLarger = -1.0;
outputSmaller = 1.0;
}
} else if (boostingType_ == 1) {
// Real AdaBoost
const double epsilonReal = 0.0001;
outputLarger = log((positiveWeightSumLarger + epsilonReal)/(negativeWeightSumLarger + epsilonReal))/2.0;
outputSmaller = log((positiveWeightSum_ - positiveWeightSumLarger + epsilonReal)
/(negativeWeightSum_ - negativeWeightSumLarger + epsilonReal))/2.0;
} else {
// Gentle AdaBoost
outputLarger = weightLabelSumLarger/weightSumLarger;
outputSmaller = (weightLabelSum_ - weightLabelSumLarger)/(weightSum_ - weightSumLarger);
}
}
double AdaBoost::computeError(const double positiveWeightSumLarger,
const double negativeWeightSumLarger,
const double outputLarger,
const double outputSmaller) const
{
double error = 0.0;
if (boostingType_ == 0) {
// Discrete AdaBoost
error = positiveWeightSumLarger*(1.0 - outputLarger)/2.0
+ (positiveWeightSum_ - positiveWeightSumLarger)*(1.0 - outputSmaller)/2.0
+ negativeWeightSumLarger*(-1.0 - outputLarger)/-2.0
+ (negativeWeightSum_ - negativeWeightSumLarger)*(-1.0 - outputSmaller)/-2.0;
} else if (boostingType_ == 1) {
// Real AdaBoost
error = positiveWeightSumLarger*exp(-outputLarger)
+ (positiveWeightSum_ - positiveWeightSumLarger)*exp(-outputSmaller)
+ negativeWeightSumLarger*exp(outputLarger)
+ (negativeWeightSum_ - negativeWeightSumLarger)*exp(outputSmaller);
} else {
// Gentle AdaBoost
error = positiveWeightSumLarger*(1.0 - outputLarger)*(1.0 - outputLarger)
+ (positiveWeightSum_ - positiveWeightSumLarger)*(1.0 - outputSmaller)*(1.0 - outputSmaller)
+ negativeWeightSumLarger*(-1.0 - outputLarger)*(-1.0 - outputLarger)
+ (negativeWeightSum_ - negativeWeightSumLarger)*(-1.0 - outputSmaller)*(-1.0 - outputSmaller);
}
return error;
}
void AdaBoost::updateWeight(const AdaBoost::DecisionStump& bestClassifier) {
double updatedWeightSum = 0.0;
for (int sampleIndex = 0; sampleIndex < sampleTotal_; ++sampleIndex) {
int labelInteger;
if (labels_[sampleIndex]) labelInteger = 1;
else labelInteger = -1;
weights_[sampleIndex] *= exp(-1.0*labelInteger*bestClassifier.evaluate(samples_[sampleIndex]));
updatedWeightSum += weights_[sampleIndex];
}
for (int sampleIndex = 0; sampleIndex < sampleTotal_; ++sampleIndex) {
weights_[sampleIndex] /= updatedWeightSum;
}
}
void AdaBoost::writeFile(const std::string filename) const {
std::ofstream outputModelStream(filename.c_str(), std::ios_base::out);
if (outputModelStream.fail()) {
std::cerr << "error: can't open file (" << filename << ")" << std::endl;
exit(1);
}
int roundTotal = static_cast<int>(weakClassifiers_.size());
outputModelStream << roundTotal << std::endl;
for (int roundIndex = 0; roundIndex < roundTotal; ++roundIndex) {
outputModelStream << weakClassifiers_[roundIndex].featureIndex() << " ";
outputModelStream << weakClassifiers_[roundIndex].threshold() << " ";
outputModelStream << weakClassifiers_[roundIndex].outputLarger() << " ";
outputModelStream << weakClassifiers_[roundIndex].outputSmaller() << std::endl;
}
outputModelStream.close();
}
void AdaBoost::readFile(const std::string filename) {
std::ifstream inputModelStream(filename.c_str(), std::ios_base::in);
if (inputModelStream.fail()) {
std::cerr << "error: can't open file (" << filename << ")" << std::endl;
exit(1);
}
int roundTotal;
inputModelStream >> roundTotal;
weakClassifiers_.resize(roundTotal);
for (int roundIndex = 0; roundIndex < roundTotal; ++roundIndex) {
int featureIndex;
double threshold, outputLarger, outputSmaller;
inputModelStream >> featureIndex;
inputModelStream >> threshold;
inputModelStream >> outputLarger;
inputModelStream >> outputSmaller;
weakClassifiers_[roundIndex].set(featureIndex, threshold, outputLarger, outputSmaller);
}
inputModelStream.close();
}
<|endoftext|>
|
<commit_before>#include <omp.h>
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <fstream>
#include <iostream>
#include <armadillo>
#include <iomanip>
#include <vector>
#include <hdf5.h>
#include "omp.h"
using namespace std;
using namespace arma;
// #include "aux-functions-def.hpp"
// #include "aux-functions-impl.hpp"
// #include "riemannian-metrics-def.hpp"
// #include "riemannian-metrics-impl.hpp"
#include "grassmann-metrics-def.hpp"
#include "grassmann-metrics-impl.hpp"
#include "kth-cross-validation-one-def.hpp"
#include "kth-cross-validation-one-impl.hpp"
//Home
//const std::string path = "/media/johanna/HD1T/codes/datasets_codes/KTH/";
//WANDA
const std::string path = "/home/johanna/codes/codes-git/study-paper/trunk/";
const std::string peopleList = "people_list.txt";
const std::string actionNames = "actionNames.txt";
///kth
// int ori_col = 160;
// int ori_row = 120;
int
main(int argc, char** argv)
{
if(argc < 3 )
{
cout << "usage: " << argv[0] << " scale_factor " << " shift_factor " << endl;
return -1;
}
int scale_factor = atoi( argv[1] );
int shift = atoi( argv[2] );
int total_scenes = 1; //Only for Scenario 1.
int dim = 14;
int p = 12;//PQ NO SE> POR BOBA> FUE UN ERROR :(
field<string> all_people;
all_people.load(peopleList);
//Cross Validation
kth_cv_omp kth_CV_omp_onesegment(path, actionNames, all_people, scale_factor, shift, total_scenes, dim);
//kth_CV_omp_onesegment.logEucl();
kth_CV_omp.SteinDiv();
//kth_CV_omp.proj_grass(p);
//kth_CV_omp.BC_grass();
return 0;
}
<commit_msg>Run Stein_Div. One cov matrix per video<commit_after>#include <omp.h>
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <fstream>
#include <iostream>
#include <armadillo>
#include <iomanip>
#include <vector>
#include <hdf5.h>
#include "omp.h"
using namespace std;
using namespace arma;
// #include "aux-functions-def.hpp"
// #include "aux-functions-impl.hpp"
// #include "riemannian-metrics-def.hpp"
// #include "riemannian-metrics-impl.hpp"
#include "grassmann-metrics-def.hpp"
#include "grassmann-metrics-impl.hpp"
#include "kth-cross-validation-one-def.hpp"
#include "kth-cross-validation-one-impl.hpp"
//Home
//const std::string path = "/media/johanna/HD1T/codes/datasets_codes/KTH/";
//WANDA
const std::string path = "/home/johanna/codes/codes-git/study-paper/trunk/";
const std::string peopleList = "people_list.txt";
const std::string actionNames = "actionNames.txt";
///kth
// int ori_col = 160;
// int ori_row = 120;
int
main(int argc, char** argv)
{
if(argc < 3 )
{
cout << "usage: " << argv[0] << " scale_factor " << " shift_factor " << endl;
return -1;
}
int scale_factor = atoi( argv[1] );
int shift = atoi( argv[2] );
int total_scenes = 1; //Only for Scenario 1.
int dim = 14;
int p = 12;//PQ NO SE> POR BOBA> FUE UN ERROR :(
field<string> all_people;
all_people.load(peopleList);
//Cross Validation
kth_cv_omp kth_CV_omp_onesegment(path, actionNames, all_people, scale_factor, shift, total_scenes, dim);
//kth_CV_omp_onesegment.logEucl();
kth_CV_omp_onesegment.SteinDiv();
//kth_CV_omp.proj_grass(p);
//kth_CV_omp.BC_grass();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright Paul Dardeau, SwampBits LLC 2014
// BSD License
#include <cstdio>
#include "HttpRequest.h"
#include "Socket.h"
#include "BasicException.h"
#include "StrUtils.h"
#include "StringTokenizer.h"
#include "Logger.h"
static const std::string ENC_DOUBLE_QUOTE = "%22"; // "
static const std::string ENC_SINGLE_QUOTE = "%27"; // '
static const std::string ENC_AMPERSAND = "%26"; // &
static const std::string ENC_PERCENT = "%25"; // %
static const std::string ENC_ATSIGN = "%40"; // @
static const std::string ENC_DOLLAR = "%24"; // $
static const std::string ENC_POUND = "%23"; // #
static const std::string ENC_EXCLAMATION = "%21"; // !
static const std::string ENC_TILDE = "%7E"; // ~
static const std::string ENC_CARET = "%5E"; // ^
static const std::string ENC_OPEN_PAREN = "%28"; // (
static const std::string ENC_CLOSE_PAREN = "%29"; // )
static const std::string ENC_PLUS = "%2B"; // +
static const std::string ENC_BACKTICK = "%60"; // `
static const std::string ENC_EQUAL = "%3D"; // =
static const std::string ENC_OPEN_BRACE = "%7B"; // {
static const std::string ENC_CLOSE_BRACE = "%7D"; // }
static const std::string ENC_VERT_BAR = "%7C"; // |
static const std::string ENC_OPEN_BRACKET = "%5B"; // [
static const std::string ENC_CLOSE_BRACKET = "%5D"; // ]
static const std::string ENC_BACKSLASH = "%5C"; //
static const std::string ENC_COLON = "%3A"; // :
static const std::string ENC_SEMICOLON = "%3B"; // ;
static const std::string ENC_LESS_THAN = "%3C"; // <
static const std::string ENC_GREATER_THAN = "%3E"; // >
static const std::string ENC_QUESTION = "%3F"; // ?
static const std::string ENC_COMMA = "%2C"; // ,
static const std::string ENC_SLASH = "%2F"; // /
static const std::string DOUBLE_QUOTE = "\"";
static const std::string SINGLE_QUOTE = "'";
static const std::string AMPERSAND = "&";
static const std::string PERCENT = "%";
static const std::string ATSIGN = "@";
static const std::string DOLLAR = "$";
static const std::string POUND = "#";
static const std::string EXCLAMATION = "!";
static const std::string TILDE = "~";
static const std::string CARET = "^";
static const std::string OPEN_PAREN = "(";
static const std::string CLOSE_PAREN = ")";
static const std::string PLUS = "+";
static const std::string BACKTICK = "`";
static const std::string EQUAL = "="; // =
static const std::string OPEN_BRACE = "{"; // {
static const std::string CLOSE_BRACE = "}"; // }
static const std::string VERT_BAR = "|"; // |
static const std::string OPEN_BRACKET = "["; // [
static const std::string CLOSE_BRACKET = "]"; // ]
static const std::string BACKSLASH = "\\"; //
static const std::string COLON = ":"; // :
static const std::string SEMICOLON = ";"; // ;
static const std::string LESS_THAN = "<"; // <
static const std::string GREATER_THAN = ">"; // >
static const std::string QUESTION = "?"; // ?
static const std::string COMMA = ","; // ,
static const std::string SLASH = "/"; // /
static const std::string SPACE = " ";
//******************************************************************************
HttpRequest::HttpRequest(Socket& socket) :
m_initialized(false)
{
Logger::logInstanceCreate("HttpRequest");
m_initialized = streamFromSocket(socket);
}
//******************************************************************************
HttpRequest::HttpRequest(const HttpRequest& copy) noexcept :
HttpTransaction(copy),
m_method(copy.m_method),
m_path(copy.m_path),
m_arguments(copy.m_arguments),
m_initialized(copy.m_initialized)
{
Logger::logInstanceCreate("HttpRequest");
}
//******************************************************************************
HttpRequest::HttpRequest(HttpRequest&& move) noexcept :
HttpTransaction(move),
m_method(std::move(move.m_method)),
m_path(std::move(move.m_path)),
m_arguments(std::move(move.m_arguments)),
m_initialized(move.m_initialized)
{
Logger::logInstanceCreate("HttpRequest");
move.m_initialized = false;
}
//******************************************************************************
HttpRequest::~HttpRequest() noexcept
{
Logger::logInstanceDestroy("HttpRequest");
}
//******************************************************************************
HttpRequest& HttpRequest::operator=(const HttpRequest& copy) noexcept
{
if (this == ©) {
return *this;
}
HttpTransaction::operator=(copy);
m_method = copy.m_method;
m_path = copy.m_path;
m_arguments = copy.m_arguments;
return *this;
}
//******************************************************************************
HttpRequest& HttpRequest::operator=(HttpRequest&& move) noexcept
{
if (this == &move) {
return *this;
}
HttpTransaction::operator=(move);
m_method = std::move(move.m_method);
m_path = std::move(move.m_path);
m_arguments = std::move(move.m_arguments);
return *this;
}
//******************************************************************************
bool HttpRequest::streamFromSocket(Socket& socket)
{
const bool isLoggingDebug = Logger::isLogging(Logger::LogLevel::Debug);
if (isLoggingDebug) {
Logger::debug("==== start of HttpRequest::streamFromSocket");
}
bool streamSuccess = false;
if (HttpTransaction::streamFromSocket(socket)) {
if (isLoggingDebug) {
Logger::debug("calling getFirstLineValues");
}
const std::vector<std::string>& vecFirstLineValues = getFirstLineValues();
if (3 == vecFirstLineValues.size()) {
m_method = vecFirstLineValues[0];
m_path = vecFirstLineValues[1];
setProtocol(vecFirstLineValues[2]);
if (isLoggingDebug) {
Logger::debug("HttpRequest: calling parseBody");
}
parseBody();
streamSuccess = true;
} else {
if (Logger::isLogging(Logger::LogLevel::Warning)) {
char msg[128];
std::snprintf(msg, 128, "number of tokens: %lu", vecFirstLineValues.size());
Logger::warning(std::string(msg));
for (const std::string& s : vecFirstLineValues) {
Logger::warning(s);
}
}
//throw BasicException("unable to parse request line");
}
} else {
//throw BasicException("unable to parse headers");
}
return streamSuccess;
}
//******************************************************************************
bool HttpRequest::isInitialized() const noexcept
{
return m_initialized;
}
//******************************************************************************
const std::string& HttpRequest::getRequest() const noexcept
{
return getFirstLine();
}
//******************************************************************************
const std::string& HttpRequest::getMethod() const noexcept
{
return m_method;
}
//******************************************************************************
const std::string& HttpRequest::getPath() const noexcept
{
return m_path;
}
//******************************************************************************
const std::string& HttpRequest::getRequestLine() const noexcept
{
return getFirstLine();
}
//******************************************************************************
bool HttpRequest::hasArgument(const std::string& key) const noexcept
{
return m_arguments.hasKey(key);
}
//******************************************************************************
const std::string& HttpRequest::getArgument(const std::string& key) const noexcept
{
return m_arguments.getValue(key);
}
//******************************************************************************
void HttpRequest::getArgumentKeys(std::vector<std::string>& vecKeys) const noexcept
{
m_arguments.getKeys(vecKeys);
}
//******************************************************************************
void HttpRequest::parseBody() noexcept
{
const std::string& body = getBody();
StringTokenizer st1(body, AMPERSAND);
const auto numVariables = st1.countTokens();
std::string pair;
std::string::size_type posEqual;
std::string key;
std::string value;
for (int i = 0; i < numVariables; ++i) {
pair = st1.nextToken();
StrUtils::replaceAll(pair, PLUS, SPACE);
StrUtils::replaceAll(pair, ENC_DOUBLE_QUOTE, DOUBLE_QUOTE);
StrUtils::replaceAll(pair, ENC_SINGLE_QUOTE, SINGLE_QUOTE);
StrUtils::replaceAll(pair, ENC_AMPERSAND, AMPERSAND);
StrUtils::replaceAll(pair, ENC_PERCENT, PERCENT);
StrUtils::replaceAll(pair, ENC_ATSIGN, ATSIGN);
StrUtils::replaceAll(pair, ENC_DOLLAR, DOLLAR);
StrUtils::replaceAll(pair, ENC_POUND, POUND);
StrUtils::replaceAll(pair, ENC_EXCLAMATION, EXCLAMATION);
StrUtils::replaceAll(pair, ENC_TILDE, TILDE);
StrUtils::replaceAll(pair, ENC_CARET, CARET);
StrUtils::replaceAll(pair, ENC_OPEN_PAREN, OPEN_PAREN);
StrUtils::replaceAll(pair, ENC_CLOSE_PAREN, CLOSE_PAREN);
StrUtils::replaceAll(pair, ENC_PLUS, PLUS);
StrUtils::replaceAll(pair, ENC_BACKTICK, BACKTICK);
StrUtils::replaceAll(pair, ENC_OPEN_BRACE, OPEN_BRACE);
StrUtils::replaceAll(pair, ENC_CLOSE_BRACE, CLOSE_BRACE);
StrUtils::replaceAll(pair, ENC_VERT_BAR, VERT_BAR);
StrUtils::replaceAll(pair, ENC_OPEN_BRACKET, OPEN_BRACKET);
StrUtils::replaceAll(pair, ENC_CLOSE_BRACKET, CLOSE_BRACKET);
StrUtils::replaceAll(pair, ENC_BACKSLASH, BACKSLASH);
StrUtils::replaceAll(pair, ENC_COLON, COLON);
StrUtils::replaceAll(pair, ENC_SEMICOLON, SEMICOLON);
StrUtils::replaceAll(pair, ENC_LESS_THAN, LESS_THAN);
StrUtils::replaceAll(pair, ENC_GREATER_THAN, GREATER_THAN);
StrUtils::replaceAll(pair, ENC_QUESTION, QUESTION);
StrUtils::replaceAll(pair, ENC_COMMA, COMMA);
StrUtils::replaceAll(pair, ENC_SLASH, SLASH);
posEqual = pair.find('=');
if (posEqual != std::string::npos) {
key = pair.substr(0, posEqual);
value = pair.substr(posEqual + 1);
StrUtils::replaceAll(value, ENC_EQUAL, EQUAL);
m_arguments.addPair(key, value);
}
}
}
//******************************************************************************
<commit_msg>tuning changes of parseBody<commit_after>// Copyright Paul Dardeau, SwampBits LLC 2014
// BSD License
#include <cstdio>
#include "HttpRequest.h"
#include "Socket.h"
#include "BasicException.h"
#include "StrUtils.h"
#include "StringTokenizer.h"
#include "Logger.h"
static const std::string ENC_DOUBLE_QUOTE = "%22"; // "
static const std::string ENC_SINGLE_QUOTE = "%27"; // '
static const std::string ENC_AMPERSAND = "%26"; // &
static const std::string ENC_PERCENT = "%25"; // %
static const std::string ENC_ATSIGN = "%40"; // @
static const std::string ENC_DOLLAR = "%24"; // $
static const std::string ENC_POUND = "%23"; // #
static const std::string ENC_EXCLAMATION = "%21"; // !
static const std::string ENC_TILDE = "%7E"; // ~
static const std::string ENC_CARET = "%5E"; // ^
static const std::string ENC_OPEN_PAREN = "%28"; // (
static const std::string ENC_CLOSE_PAREN = "%29"; // )
static const std::string ENC_PLUS = "%2B"; // +
static const std::string ENC_BACKTICK = "%60"; // `
static const std::string ENC_EQUAL = "%3D"; // =
static const std::string ENC_OPEN_BRACE = "%7B"; // {
static const std::string ENC_CLOSE_BRACE = "%7D"; // }
static const std::string ENC_VERT_BAR = "%7C"; // |
static const std::string ENC_OPEN_BRACKET = "%5B"; // [
static const std::string ENC_CLOSE_BRACKET = "%5D"; // ]
static const std::string ENC_BACKSLASH = "%5C"; //
static const std::string ENC_COLON = "%3A"; // :
static const std::string ENC_SEMICOLON = "%3B"; // ;
static const std::string ENC_LESS_THAN = "%3C"; // <
static const std::string ENC_GREATER_THAN = "%3E"; // >
static const std::string ENC_QUESTION = "%3F"; // ?
static const std::string ENC_COMMA = "%2C"; // ,
static const std::string ENC_SLASH = "%2F"; // /
static const std::string DOUBLE_QUOTE = "\"";
static const std::string SINGLE_QUOTE = "'";
static const std::string AMPERSAND = "&";
static const std::string PERCENT = "%";
static const std::string ATSIGN = "@";
static const std::string DOLLAR = "$";
static const std::string POUND = "#";
static const std::string EXCLAMATION = "!";
static const std::string TILDE = "~";
static const std::string CARET = "^";
static const std::string OPEN_PAREN = "(";
static const std::string CLOSE_PAREN = ")";
static const std::string PLUS = "+";
static const std::string BACKTICK = "`";
static const std::string EQUAL = "="; // =
static const std::string OPEN_BRACE = "{"; // {
static const std::string CLOSE_BRACE = "}"; // }
static const std::string VERT_BAR = "|"; // |
static const std::string OPEN_BRACKET = "["; // [
static const std::string CLOSE_BRACKET = "]"; // ]
static const std::string BACKSLASH = "\\"; //
static const std::string COLON = ":"; // :
static const std::string SEMICOLON = ";"; // ;
static const std::string LESS_THAN = "<"; // <
static const std::string GREATER_THAN = ">"; // >
static const std::string QUESTION = "?"; // ?
static const std::string COMMA = ","; // ,
static const std::string SLASH = "/"; // /
static const std::string SPACE = " ";
//******************************************************************************
HttpRequest::HttpRequest(Socket& socket) :
m_initialized(false)
{
Logger::logInstanceCreate("HttpRequest");
m_initialized = streamFromSocket(socket);
}
//******************************************************************************
HttpRequest::HttpRequest(const HttpRequest& copy) noexcept :
HttpTransaction(copy),
m_method(copy.m_method),
m_path(copy.m_path),
m_arguments(copy.m_arguments),
m_initialized(copy.m_initialized)
{
Logger::logInstanceCreate("HttpRequest");
}
//******************************************************************************
HttpRequest::HttpRequest(HttpRequest&& move) noexcept :
HttpTransaction(move),
m_method(std::move(move.m_method)),
m_path(std::move(move.m_path)),
m_arguments(std::move(move.m_arguments)),
m_initialized(move.m_initialized)
{
Logger::logInstanceCreate("HttpRequest");
move.m_initialized = false;
}
//******************************************************************************
HttpRequest::~HttpRequest() noexcept
{
Logger::logInstanceDestroy("HttpRequest");
}
//******************************************************************************
HttpRequest& HttpRequest::operator=(const HttpRequest& copy) noexcept
{
if (this == ©) {
return *this;
}
HttpTransaction::operator=(copy);
m_method = copy.m_method;
m_path = copy.m_path;
m_arguments = copy.m_arguments;
return *this;
}
//******************************************************************************
HttpRequest& HttpRequest::operator=(HttpRequest&& move) noexcept
{
if (this == &move) {
return *this;
}
HttpTransaction::operator=(move);
m_method = std::move(move.m_method);
m_path = std::move(move.m_path);
m_arguments = std::move(move.m_arguments);
return *this;
}
//******************************************************************************
bool HttpRequest::streamFromSocket(Socket& socket)
{
const bool isLoggingDebug = Logger::isLogging(Logger::LogLevel::Debug);
if (isLoggingDebug) {
Logger::debug("==== start of HttpRequest::streamFromSocket");
}
bool streamSuccess = false;
if (HttpTransaction::streamFromSocket(socket)) {
if (isLoggingDebug) {
Logger::debug("calling getFirstLineValues");
}
const std::vector<std::string>& vecFirstLineValues = getFirstLineValues();
if (3 == vecFirstLineValues.size()) {
m_method = vecFirstLineValues[0];
m_path = vecFirstLineValues[1];
setProtocol(vecFirstLineValues[2]);
if (isLoggingDebug) {
Logger::debug("HttpRequest: calling parseBody");
}
parseBody();
streamSuccess = true;
} else {
if (Logger::isLogging(Logger::LogLevel::Warning)) {
char msg[128];
std::snprintf(msg, 128, "number of tokens: %lu", vecFirstLineValues.size());
Logger::warning(std::string(msg));
for (const std::string& s : vecFirstLineValues) {
Logger::warning(s);
}
}
//throw BasicException("unable to parse request line");
}
} else {
//throw BasicException("unable to parse headers");
}
return streamSuccess;
}
//******************************************************************************
bool HttpRequest::isInitialized() const noexcept
{
return m_initialized;
}
//******************************************************************************
const std::string& HttpRequest::getRequest() const noexcept
{
return getFirstLine();
}
//******************************************************************************
const std::string& HttpRequest::getMethod() const noexcept
{
return m_method;
}
//******************************************************************************
const std::string& HttpRequest::getPath() const noexcept
{
return m_path;
}
//******************************************************************************
const std::string& HttpRequest::getRequestLine() const noexcept
{
return getFirstLine();
}
//******************************************************************************
bool HttpRequest::hasArgument(const std::string& key) const noexcept
{
return m_arguments.hasKey(key);
}
//******************************************************************************
const std::string& HttpRequest::getArgument(const std::string& key) const noexcept
{
return m_arguments.getValue(key);
}
//******************************************************************************
void HttpRequest::getArgumentKeys(std::vector<std::string>& vecKeys) const noexcept
{
m_arguments.getKeys(vecKeys);
}
//******************************************************************************
void HttpRequest::parseBody() noexcept
{
const std::string& body = getBody();
if (!body.empty() && StrUtils::containsString(body, AMPERSAND)) {
StringTokenizer st1(body, AMPERSAND);
while (st1.hasMoreTokens()) {
std::string pair(st1.nextToken());
StrUtils::replaceAll(pair, PLUS, SPACE);
StrUtils::replaceAll(pair, ENC_DOUBLE_QUOTE, DOUBLE_QUOTE);
StrUtils::replaceAll(pair, ENC_SINGLE_QUOTE, SINGLE_QUOTE);
StrUtils::replaceAll(pair, ENC_AMPERSAND, AMPERSAND);
StrUtils::replaceAll(pair, ENC_PERCENT, PERCENT);
StrUtils::replaceAll(pair, ENC_ATSIGN, ATSIGN);
StrUtils::replaceAll(pair, ENC_DOLLAR, DOLLAR);
StrUtils::replaceAll(pair, ENC_POUND, POUND);
StrUtils::replaceAll(pair, ENC_EXCLAMATION, EXCLAMATION);
StrUtils::replaceAll(pair, ENC_TILDE, TILDE);
StrUtils::replaceAll(pair, ENC_CARET, CARET);
StrUtils::replaceAll(pair, ENC_OPEN_PAREN, OPEN_PAREN);
StrUtils::replaceAll(pair, ENC_CLOSE_PAREN, CLOSE_PAREN);
StrUtils::replaceAll(pair, ENC_PLUS, PLUS);
StrUtils::replaceAll(pair, ENC_BACKTICK, BACKTICK);
StrUtils::replaceAll(pair, ENC_OPEN_BRACE, OPEN_BRACE);
StrUtils::replaceAll(pair, ENC_CLOSE_BRACE, CLOSE_BRACE);
StrUtils::replaceAll(pair, ENC_VERT_BAR, VERT_BAR);
StrUtils::replaceAll(pair, ENC_OPEN_BRACKET, OPEN_BRACKET);
StrUtils::replaceAll(pair, ENC_CLOSE_BRACKET, CLOSE_BRACKET);
StrUtils::replaceAll(pair, ENC_BACKSLASH, BACKSLASH);
StrUtils::replaceAll(pair, ENC_COLON, COLON);
StrUtils::replaceAll(pair, ENC_SEMICOLON, SEMICOLON);
StrUtils::replaceAll(pair, ENC_LESS_THAN, LESS_THAN);
StrUtils::replaceAll(pair, ENC_GREATER_THAN, GREATER_THAN);
StrUtils::replaceAll(pair, ENC_QUESTION, QUESTION);
StrUtils::replaceAll(pair, ENC_COMMA, COMMA);
StrUtils::replaceAll(pair, ENC_SLASH, SLASH);
const auto posEqual = pair.find('=');
if (posEqual != std::string::npos) {
const std::string& key = pair.substr(0, posEqual);
std::string value(pair.substr(posEqual + 1));
StrUtils::replaceAll(value, ENC_EQUAL, EQUAL);
m_arguments.addPair(key, value);
}
}
}
}
//******************************************************************************
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009 Tommi Maekitalo
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/*
This demo implements a rpc server and a rpc client.
To run the demo start the server with "rpcecho -S". It listens by default on
port 7002. It waits for incoming xmlrpc requests. The only service function
is echo, which takes a string as a parameter just returns that string.
To use the server run rpcecho with a text e.g. "rpcecho hello". It sends the
text to the server and prints the return string to standard out. You may pass
with -f <filename> a file, which will be sent to the server instead.
*/
#include <iostream>
#include <cxxtools/arg.h>
#include <cxxtools/loginit.h>
#include <cxxtools/xmlrpc/service.h>
#include <cxxtools/http/server.h>
#include <cxxtools/xmlrpc/remoteprocedure.h>
#include <cxxtools/xmlrpc/httpclient.h>
#include <cxxtools/clock.h>
#include <fstream>
////////////////////////////////////////////////////////////////////////
// This defines a xmlrpc service. A xmlrpc service defines functions, which
// can be called remotely.
//
class EchoServerService : public cxxtools::xmlrpc::Service
{
public:
EchoServerService()
{
registerMethod("echo", *this, &EchoServerService::echo);
}
std::string echo(const std::string& message, bool tostdout);
};
std::string EchoServerService::echo(const std::string& message, bool tostdout)
{
if (tostdout)
std::cout << message << std::endl;
return message;
}
////////////////////////////////////////////////////////////////////////
// main
//
int main(int argc, char* argv[])
{
try
{
log_init();
cxxtools::Arg<bool> server(argc, argv, 'S');
cxxtools::Arg<std::string> ip(argc, argv, 'i', server.isSet() ? "0.0.0.0" : "127.0.0.1");
cxxtools::Arg<unsigned short> port(argc, argv, 'p', 7002);
if (server)
{
std::cout << "run rpcecho server" << std::endl;
// the http server is instantiated with a ip address and a port number
cxxtools::http::Server server(ip, port);
// we create an instance of the service class
EchoServerService service;
// ... and register it under a url
server.addService("/myservice", service);
// now run the server
server.run();
}
else
{
std::cout << "run rpcecho client" << std::endl;
// take option -n <number> to specify, how often the request should be called (1 by default)
cxxtools::Arg<unsigned> number(argc, argv, 'c', 1);
cxxtools::Arg<bool> doEcho(argc, argv, 'e');
// define a xlmrpc client
cxxtools::xmlrpc::HttpClient client(ip, port, "/myservice");
// define remote procedure with std::string return value and a std::string and a bool parameter:
cxxtools::xmlrpc::RemoteProcedure<std::string, std::string, bool> echo(client, "echo");
// optionally pass a filename with -f
cxxtools::Arg<const char*> filename(argc, argv, 'f');
// option -n - do not output return value (good for benchmarking)
cxxtools::Arg<bool> noout(argc, argv, 'n');
cxxtools::Clock clock;
clock.start();
unsigned size = 0;
if (filename.isSet())
{
// read a file into a stringstream
std::ifstream in(filename);
std::ostringstream data;
data << in.rdbuf(); // read file into stringstream
// send data from file to server and print reply to std::cout
for (unsigned n = 0; n < number; ++n)
{
std::string v = echo(data.str(), doEcho);
size += v.size();
if (!noout)
std::cout << v;
}
}
else
{
// no filename given, so send just the parameters to the server.
for (unsigned n = 0; n < number; ++n)
{
for (int a = 1; a < argc; ++a)
{
std::string v = echo(argv[a], doEcho);
size += v.size();
if (!noout)
std::cout << v << '\n';
}
}
}
cxxtools::Timespan t = clock.stop();
double T = t.toUSecs() / 1e6;
unsigned kbytes = size / 1024.0;
std::cerr << T << " s, " << (number.getValue() / T) << " msg/s\n"
<< kbytes << " kbytes, " << (kbytes / T) << " kbytes/s\n";
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
<commit_msg>remove warning<commit_after>/*
* Copyright (C) 2009 Tommi Maekitalo
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
* NON-INFRINGEMENT. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/*
This demo implements a rpc server and a rpc client.
To run the demo start the server with "rpcecho -S". It listens by default on
port 7002. It waits for incoming xmlrpc requests. The only service function
is echo, which takes a string as a parameter just returns that string.
To use the server run rpcecho with a text e.g. "rpcecho hello". It sends the
text to the server and prints the return string to standard out. You may pass
with -f <filename> a file, which will be sent to the server instead.
*/
#include <iostream>
#include <cxxtools/arg.h>
#include <cxxtools/loginit.h>
#include <cxxtools/xmlrpc/service.h>
#include <cxxtools/http/server.h>
#include <cxxtools/xmlrpc/remoteprocedure.h>
#include <cxxtools/xmlrpc/httpclient.h>
#include <cxxtools/clock.h>
#include <fstream>
////////////////////////////////////////////////////////////////////////
// This defines a xmlrpc service. A xmlrpc service defines functions, which
// can be called remotely.
//
class EchoServerService : public cxxtools::xmlrpc::Service
{
public:
EchoServerService()
{
registerMethod("echo", *this, &EchoServerService::echo);
}
std::string echo(const std::string& message, bool tostdout);
};
std::string EchoServerService::echo(const std::string& message, bool tostdout)
{
if (tostdout)
std::cout << message << std::endl;
return message;
}
////////////////////////////////////////////////////////////////////////
// main
//
int main(int argc, char* argv[])
{
try
{
log_init();
cxxtools::Arg<bool> server(argc, argv, 'S');
cxxtools::Arg<std::string> ip(argc, argv, 'i', server.isSet() ? "0.0.0.0" : "127.0.0.1");
cxxtools::Arg<unsigned short> port(argc, argv, 'p', 7002);
if (server)
{
std::cout << "run rpcecho server" << std::endl;
// the http server is instantiated with a ip address and a port number
cxxtools::http::Server server(ip, port);
// we create an instance of the service class
EchoServerService service;
// ... and register it under a url
server.addService("/myservice", service);
// now run the server
server.run();
}
else
{
std::cout << "run rpcecho client" << std::endl;
// take option -n <number> to specify, how often the request should be called (1 by default)
cxxtools::Arg<unsigned> number(argc, argv, 'c', 1);
cxxtools::Arg<bool> doEcho(argc, argv, 'e');
// define a xlmrpc client
cxxtools::xmlrpc::HttpClient client(ip, port, "/myservice");
// define remote procedure with std::string return value and a std::string and a bool parameter:
cxxtools::xmlrpc::RemoteProcedure<std::string, std::string, bool> echo(client, "echo");
// optionally pass a filename with -f
cxxtools::Arg<const char*> filename(argc, argv, 'f');
// option -n - do not output return value (good for benchmarking)
cxxtools::Arg<bool> noout(argc, argv, 'n');
cxxtools::Clock clock;
clock.start();
unsigned size = 0;
if (filename.isSet())
{
// read a file into a stringstream
std::ifstream in(filename);
std::ostringstream data;
data << in.rdbuf(); // read file into stringstream
// send data from file to server and print reply to std::cout
for (unsigned n = 0; n < number; ++n)
{
std::string v = echo(data.str(), doEcho);
size += v.size();
if (!noout)
std::cout << v;
}
}
else
{
// no filename given, so send just the parameters to the server.
for (unsigned n = 0; n < number; ++n)
{
for (int a = 1; a < argc; ++a)
{
std::string v = echo(argv[a], doEcho);
size += v.size();
if (!noout)
std::cout << v << '\n';
}
}
}
cxxtools::Timespan t = clock.stop();
double T = t.toUSecs() / 1e6;
unsigned kbytes = size / 1024;
std::cerr << T << " s, " << (number.getValue() / T) << " msg/s\n"
<< kbytes << " kbytes, " << (kbytes / T) << " kbytes/s\n";
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright © 2012 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/** @file brw_fs_register_coalesce.cpp
*
* Implements register coalescing: Checks if the two registers involved in a
* raw move don't interfere, in which case they can both be stored in the same
* place and the MOV removed.
*
* To do this, all uses of the source of the MOV in the shader are replaced
* with the destination of the MOV. For example:
*
* add vgrf3:F, vgrf1:F, vgrf2:F
* mov vgrf4:F, vgrf3:F
* mul vgrf5:F, vgrf5:F, vgrf4:F
*
* becomes
*
* add vgrf4:F, vgrf1:F, vgrf2:F
* mul vgrf5:F, vgrf5:F, vgrf4:F
*/
#include "brw_fs.h"
#include "brw_fs_live_variables.h"
static bool
is_coalesce_candidate(const fs_inst *inst, const int *virtual_grf_sizes)
{
if (inst->opcode != BRW_OPCODE_MOV ||
inst->is_partial_write() ||
inst->saturate ||
inst->src[0].file != GRF ||
inst->src[0].negate ||
inst->src[0].abs ||
!inst->src[0].is_contiguous() ||
inst->dst.file != GRF ||
inst->dst.type != inst->src[0].type) {
return false;
}
if (virtual_grf_sizes[inst->src[0].reg] >
virtual_grf_sizes[inst->dst.reg])
return false;
return true;
}
static bool
can_coalesce_vars(brw::fs_live_variables *live_intervals,
const exec_list *instructions, const fs_inst *inst,
int var_to, int var_from)
{
if (live_intervals->vars_interfere(var_from, var_to) &&
!inst->dst.equals(inst->src[0])) {
/* We know that the live ranges of A (var_from) and B (var_to)
* interfere because of the ->vars_interfere() call above. If the end
* of B's live range is after the end of A's range, then we know two
* things:
* - the start of B's live range must be in A's live range (since we
* already know the two ranges interfere, this is the only remaining
* possibility)
* - the interference isn't of the form we're looking for (where B is
* entirely inside A)
*/
if (live_intervals->end[var_to] > live_intervals->end[var_from])
return false;
int scan_ip = -1;
foreach_list(n, instructions) {
fs_inst *scan_inst = (fs_inst *)n;
scan_ip++;
if (scan_inst->is_control_flow())
return false;
if (scan_ip <= live_intervals->start[var_to])
continue;
if (scan_ip > live_intervals->end[var_to])
break;
if (scan_inst->dst.equals(inst->dst) ||
scan_inst->dst.equals(inst->src[0]))
return false;
}
}
return true;
}
bool
fs_visitor::register_coalesce()
{
bool progress = false;
calculate_live_intervals();
int src_size = 0;
int channels_remaining = 0;
int reg_from = -1, reg_to = -1;
int reg_to_offset[MAX_SAMPLER_MESSAGE_SIZE];
fs_inst *mov[MAX_SAMPLER_MESSAGE_SIZE];
int var_to[MAX_SAMPLER_MESSAGE_SIZE];
int var_from[MAX_SAMPLER_MESSAGE_SIZE];
foreach_list(node, &this->instructions) {
fs_inst *inst = (fs_inst *)node;
if (!is_coalesce_candidate(inst, virtual_grf_sizes))
continue;
if (reg_from != inst->src[0].reg) {
reg_from = inst->src[0].reg;
src_size = virtual_grf_sizes[inst->src[0].reg];
assert(src_size <= MAX_SAMPLER_MESSAGE_SIZE);
channels_remaining = src_size;
memset(mov, 0, sizeof(mov));
reg_to = inst->dst.reg;
}
if (reg_to != inst->dst.reg)
continue;
const int offset = inst->src[0].reg_offset;
reg_to_offset[offset] = inst->dst.reg_offset;
mov[offset] = inst;
channels_remaining--;
if (channels_remaining)
continue;
bool can_coalesce = true;
for (int i = 0; i < src_size; i++) {
var_to[i] = live_intervals->var_from_vgrf[reg_to] + reg_to_offset[i];
var_from[i] = live_intervals->var_from_vgrf[reg_from] + i;
if (!can_coalesce_vars(live_intervals, &instructions, inst,
var_to[i], var_from[i])) {
can_coalesce = false;
reg_from = -1;
break;
}
}
if (!can_coalesce)
continue;
for (int i = 0; i < src_size; i++) {
if (mov[i]) {
mov[i]->opcode = BRW_OPCODE_NOP;
mov[i]->conditional_mod = BRW_CONDITIONAL_NONE;
mov[i]->dst = reg_undef;
mov[i]->src[0] = reg_undef;
mov[i]->src[1] = reg_undef;
mov[i]->src[2] = reg_undef;
}
}
foreach_list(node, &this->instructions) {
fs_inst *scan_inst = (fs_inst *)node;
for (int i = 0; i < src_size; i++) {
if (mov[i]) {
if (scan_inst->dst.file == GRF &&
scan_inst->dst.reg == reg_from &&
scan_inst->dst.reg_offset == i) {
scan_inst->dst.reg = reg_to;
scan_inst->dst.reg_offset = reg_to_offset[i];
}
for (int j = 0; j < 3; j++) {
if (scan_inst->src[j].file == GRF &&
scan_inst->src[j].reg == reg_from &&
scan_inst->src[j].reg_offset == i) {
scan_inst->src[j].reg = reg_to;
scan_inst->src[j].reg_offset = reg_to_offset[i];
}
}
}
}
}
for (int i = 0; i < src_size; i++) {
live_intervals->start[var_to[i]] =
MIN2(live_intervals->start[var_to[i]],
live_intervals->start[var_from[i]]);
live_intervals->end[var_to[i]] =
MAX2(live_intervals->end[var_to[i]],
live_intervals->end[var_from[i]]);
}
reg_from = -1;
}
foreach_list_safe(node, &this->instructions) {
fs_inst *inst = (fs_inst *)node;
if (inst->opcode == BRW_OPCODE_NOP) {
inst->remove();
progress = true;
}
}
if (progress)
invalidate_live_intervals();
return progress;
}
<commit_msg>i965/fs: Only sweep NOPs if register coalescing made progress.<commit_after>/*
* Copyright © 2012 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/** @file brw_fs_register_coalesce.cpp
*
* Implements register coalescing: Checks if the two registers involved in a
* raw move don't interfere, in which case they can both be stored in the same
* place and the MOV removed.
*
* To do this, all uses of the source of the MOV in the shader are replaced
* with the destination of the MOV. For example:
*
* add vgrf3:F, vgrf1:F, vgrf2:F
* mov vgrf4:F, vgrf3:F
* mul vgrf5:F, vgrf5:F, vgrf4:F
*
* becomes
*
* add vgrf4:F, vgrf1:F, vgrf2:F
* mul vgrf5:F, vgrf5:F, vgrf4:F
*/
#include "brw_fs.h"
#include "brw_fs_live_variables.h"
static bool
is_coalesce_candidate(const fs_inst *inst, const int *virtual_grf_sizes)
{
if (inst->opcode != BRW_OPCODE_MOV ||
inst->is_partial_write() ||
inst->saturate ||
inst->src[0].file != GRF ||
inst->src[0].negate ||
inst->src[0].abs ||
!inst->src[0].is_contiguous() ||
inst->dst.file != GRF ||
inst->dst.type != inst->src[0].type) {
return false;
}
if (virtual_grf_sizes[inst->src[0].reg] >
virtual_grf_sizes[inst->dst.reg])
return false;
return true;
}
static bool
can_coalesce_vars(brw::fs_live_variables *live_intervals,
const exec_list *instructions, const fs_inst *inst,
int var_to, int var_from)
{
if (live_intervals->vars_interfere(var_from, var_to) &&
!inst->dst.equals(inst->src[0])) {
/* We know that the live ranges of A (var_from) and B (var_to)
* interfere because of the ->vars_interfere() call above. If the end
* of B's live range is after the end of A's range, then we know two
* things:
* - the start of B's live range must be in A's live range (since we
* already know the two ranges interfere, this is the only remaining
* possibility)
* - the interference isn't of the form we're looking for (where B is
* entirely inside A)
*/
if (live_intervals->end[var_to] > live_intervals->end[var_from])
return false;
int scan_ip = -1;
foreach_list(n, instructions) {
fs_inst *scan_inst = (fs_inst *)n;
scan_ip++;
if (scan_inst->is_control_flow())
return false;
if (scan_ip <= live_intervals->start[var_to])
continue;
if (scan_ip > live_intervals->end[var_to])
break;
if (scan_inst->dst.equals(inst->dst) ||
scan_inst->dst.equals(inst->src[0]))
return false;
}
}
return true;
}
bool
fs_visitor::register_coalesce()
{
bool progress = false;
calculate_live_intervals();
int src_size = 0;
int channels_remaining = 0;
int reg_from = -1, reg_to = -1;
int reg_to_offset[MAX_SAMPLER_MESSAGE_SIZE];
fs_inst *mov[MAX_SAMPLER_MESSAGE_SIZE];
int var_to[MAX_SAMPLER_MESSAGE_SIZE];
int var_from[MAX_SAMPLER_MESSAGE_SIZE];
foreach_list(node, &this->instructions) {
fs_inst *inst = (fs_inst *)node;
if (!is_coalesce_candidate(inst, virtual_grf_sizes))
continue;
if (reg_from != inst->src[0].reg) {
reg_from = inst->src[0].reg;
src_size = virtual_grf_sizes[inst->src[0].reg];
assert(src_size <= MAX_SAMPLER_MESSAGE_SIZE);
channels_remaining = src_size;
memset(mov, 0, sizeof(mov));
reg_to = inst->dst.reg;
}
if (reg_to != inst->dst.reg)
continue;
const int offset = inst->src[0].reg_offset;
reg_to_offset[offset] = inst->dst.reg_offset;
mov[offset] = inst;
channels_remaining--;
if (channels_remaining)
continue;
bool can_coalesce = true;
for (int i = 0; i < src_size; i++) {
var_to[i] = live_intervals->var_from_vgrf[reg_to] + reg_to_offset[i];
var_from[i] = live_intervals->var_from_vgrf[reg_from] + i;
if (!can_coalesce_vars(live_intervals, &instructions, inst,
var_to[i], var_from[i])) {
can_coalesce = false;
reg_from = -1;
break;
}
}
if (!can_coalesce)
continue;
for (int i = 0; i < src_size; i++) {
if (mov[i]) {
mov[i]->opcode = BRW_OPCODE_NOP;
mov[i]->conditional_mod = BRW_CONDITIONAL_NONE;
mov[i]->dst = reg_undef;
mov[i]->src[0] = reg_undef;
mov[i]->src[1] = reg_undef;
mov[i]->src[2] = reg_undef;
}
}
foreach_list(node, &this->instructions) {
fs_inst *scan_inst = (fs_inst *)node;
for (int i = 0; i < src_size; i++) {
if (mov[i]) {
if (scan_inst->dst.file == GRF &&
scan_inst->dst.reg == reg_from &&
scan_inst->dst.reg_offset == i) {
scan_inst->dst.reg = reg_to;
scan_inst->dst.reg_offset = reg_to_offset[i];
}
for (int j = 0; j < 3; j++) {
if (scan_inst->src[j].file == GRF &&
scan_inst->src[j].reg == reg_from &&
scan_inst->src[j].reg_offset == i) {
scan_inst->src[j].reg = reg_to;
scan_inst->src[j].reg_offset = reg_to_offset[i];
}
}
}
}
}
for (int i = 0; i < src_size; i++) {
live_intervals->start[var_to[i]] =
MIN2(live_intervals->start[var_to[i]],
live_intervals->start[var_from[i]]);
live_intervals->end[var_to[i]] =
MAX2(live_intervals->end[var_to[i]],
live_intervals->end[var_from[i]]);
}
reg_from = -1;
}
if (progress) {
foreach_list_safe(node, &this->instructions) {
fs_inst *inst = (fs_inst *)node;
if (inst->opcode == BRW_OPCODE_NOP) {
inst->remove();
progress = true;
}
}
invalidate_live_intervals();
}
return progress;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
TEST(LanguageMenuButtonTest, GetTextForIndicatorTest) {
// Test normal cases. Two-letter language code should be returned.
{
InputMethodDescriptor desc("m17n:fa:isiri", // input method engine id
"isiri (m17n)", // input method name
"us", // keyboard layout name
"fa"); // language name
EXPECT_EQ(L"FA", LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("hangul", "Korean", "us", "ko");
EXPECT_EQ(L"KO", LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("invalid-id", "unregistered string", "us", "xx");
// Upper-case string of the unknown language code, "xx", should be returned.
EXPECT_EQ(L"XX", LanguageMenuButton::GetTextForIndicator(desc));
}
// Test special cases.
{
InputMethodDescriptor desc("xkb:us:dvorak:eng", "Dvorak", "us", "us");
EXPECT_EQ(L"DV", LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("mozc", "Mozc", "us", "ja");
EXPECT_EQ(UTF8ToWide("\xe3\x81\x82"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("mozc-jp", "Mozc", "jp", "ja");
EXPECT_EQ(UTF8ToWide("\xe3\x81\x82"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("pinyin", "Pinyin", "us", "zh-CN");
EXPECT_EQ(UTF8ToWide("\xe6\x8b\xbc"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("chewing", "Chewing", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("\xe9\x85\xb7"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:zh:cangjie", "Cangjie", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("\xe5\x80\x89"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:zh:quick", "Quick", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("TW"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("pinyin", "Pinyin", "us", "zh-CN");
EXPECT_EQ(UTF8ToWide("CN"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("chewing", "Chewing", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("TW"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:zh:cangjie", "Cangjie", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("TW"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:zh:quick", "Quick", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("TW"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:t:latn-pre", "latn-pre", "us", "t");
EXPECT_EQ(L"LAT",
LanguageMenuButton::GetTextForIndicator(desc));
}
}
TEST(LanguageMenuButtonTest, GetTextForTooltipTest) {
const bool kAddMethodName = true;
{
InputMethodDescriptor desc("m17n:fa:isiri", "isiri (m17n)", "us", "fa");
EXPECT_EQ(L"Persian - Persian input method (ISIRI 2901 layout)",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
{
InputMethodDescriptor desc("hangul", "Korean", "us", "ko");
EXPECT_EQ(L"Korean - Korean input method",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
{
InputMethodDescriptor desc("invalid-id", "unregistered string", "us", "xx");
// You can safely ignore the "Resouce ID is not found for: unregistered
// string" error.
EXPECT_EQ(L"xx - unregistered string",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
{
InputMethodDescriptor desc("m17n:t:latn-pre", "latn-pre", "us", "t");
EXPECT_EQ(L"latn-pre",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
}
} // namespace chromeos
<commit_msg>Fix GetTextForIndicatorTest.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
TEST(LanguageMenuButtonTest, GetTextForIndicatorTest) {
// Test normal cases. Two-letter language code should be returned.
{
InputMethodDescriptor desc("m17n:fa:isiri", // input method engine id
"isiri (m17n)", // input method name
"us", // keyboard layout name
"fa"); // language name
EXPECT_EQ(L"FA", LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("hangul", "Korean", "us", "ko");
EXPECT_EQ(L"KO", LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("invalid-id", "unregistered string", "us", "xx");
// Upper-case string of the unknown language code, "xx", should be returned.
EXPECT_EQ(L"XX", LanguageMenuButton::GetTextForIndicator(desc));
}
// Test special cases.
{
InputMethodDescriptor desc("xkb:us:dvorak:eng", "Dvorak", "us", "us");
EXPECT_EQ(L"DV", LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("mozc", "Mozc", "us", "ja");
EXPECT_EQ(UTF8ToWide("\xe3\x81\x82"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("mozc-jp", "Mozc", "jp", "ja");
EXPECT_EQ(UTF8ToWide("\xe3\x81\x82"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("pinyin", "Pinyin", "us", "zh-CN");
EXPECT_EQ(UTF8ToWide("\xe6\x8b\xbc"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("chewing", "Chewing", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("\xe9\x85\xb7"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:zh:cangjie", "Cangjie", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("\xe5\x80\x89"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:zh:quick", "Quick", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("TW"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:t:latn-pre", "latn-pre", "us", "t");
EXPECT_EQ(L"LAT",
LanguageMenuButton::GetTextForIndicator(desc));
}
}
TEST(LanguageMenuButtonTest, GetTextForTooltipTest) {
const bool kAddMethodName = true;
{
InputMethodDescriptor desc("m17n:fa:isiri", "isiri (m17n)", "us", "fa");
EXPECT_EQ(L"Persian - Persian input method (ISIRI 2901 layout)",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
{
InputMethodDescriptor desc("hangul", "Korean", "us", "ko");
EXPECT_EQ(L"Korean - Korean input method",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
{
InputMethodDescriptor desc("invalid-id", "unregistered string", "us", "xx");
// You can safely ignore the "Resouce ID is not found for: unregistered
// string" error.
EXPECT_EQ(L"xx - unregistered string",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
{
InputMethodDescriptor desc("m17n:t:latn-pre", "latn-pre", "us", "t");
EXPECT_EQ(L"latn-pre",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
TEST(LanguageMenuButtonTest, GetTextForIndicatorTest) {
// Test normal cases. Two-letter language code should be returned.
{
InputMethodDescriptor desc("m17n:fa:isiri", // input method engine id
"isiri (m17n)", // input method name
"us", // keyboard layout name
"fa"); // language name
EXPECT_EQ(L"FA", LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("hangul", "Korean", "us", "ko");
EXPECT_EQ(L"KO", LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("invalid-id", "unregistered string", "us", "xx");
// Upper-case string of the unknown language code, "xx", should be returned.
EXPECT_EQ(L"XX", LanguageMenuButton::GetTextForIndicator(desc));
}
// Test special cases.
{
InputMethodDescriptor desc("xkb:us:dvorak:eng", "Dvorak", "us", "us");
EXPECT_EQ(L"DV", LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("mozc", "Mozc", "us", "ja");
EXPECT_EQ(UTF8ToWide("\xe3\x81\x82"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("mozc-jp", "Mozc", "jp", "ja");
EXPECT_EQ(UTF8ToWide("\xe3\x81\x82"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("pinyin", "Pinyin", "us", "zh-CN");
EXPECT_EQ(UTF8ToWide("\xe6\x8b\xbc"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("chewing", "Chewing", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("\xe9\x85\xb7"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:zh:cangjie", "Cangjie", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("\xe5\x80\x89"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:zh:quick", "Quick", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("TW"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("pinyin", "Pinyin", "us", "zh-CN");
EXPECT_EQ(UTF8ToWide("CN"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("chewing", "Chewing", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("TW"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:zh:cangjie", "Cangjie", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("TW"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:zh:quick", "Quick", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("TW"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:t:latn-pre", "latn-pre", "us", "t");
EXPECT_EQ(L"LAT",
LanguageMenuButton::GetTextForIndicator(desc));
}
}
TEST(LanguageMenuButtonTest, GetTextForTooltipTest) {
const bool kAddMethodName = true;
{
InputMethodDescriptor desc("m17n:fa:isiri", "isiri (m17n)", "us", "fa");
EXPECT_EQ(L"Persian - Persian input method (ISIRI 2901 layout)",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
{
InputMethodDescriptor desc("hangul", "Korean", "us", "ko");
EXPECT_EQ(L"Korean - Korean input method",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
{
InputMethodDescriptor desc("invalid-id", "unregistered string", "us", "xx");
// You can safely ignore the "Resouce ID is not found for: unregistered
// string" error.
EXPECT_EQ(L"xx - unregistered string",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
{
InputMethodDescriptor desc("m17n:t:latn-pre", "latn-pre", "us", "t");
EXPECT_EQ(L"latn-pre",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
}
} // namespace chromeos
<commit_msg>Fix GetTextForIndicatorTest.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/status/language_menu_button.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
TEST(LanguageMenuButtonTest, GetTextForIndicatorTest) {
// Test normal cases. Two-letter language code should be returned.
{
InputMethodDescriptor desc("m17n:fa:isiri", // input method engine id
"isiri (m17n)", // input method name
"us", // keyboard layout name
"fa"); // language name
EXPECT_EQ(L"FA", LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("hangul", "Korean", "us", "ko");
EXPECT_EQ(L"KO", LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("invalid-id", "unregistered string", "us", "xx");
// Upper-case string of the unknown language code, "xx", should be returned.
EXPECT_EQ(L"XX", LanguageMenuButton::GetTextForIndicator(desc));
}
// Test special cases.
{
InputMethodDescriptor desc("xkb:us:dvorak:eng", "Dvorak", "us", "us");
EXPECT_EQ(L"DV", LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("mozc", "Mozc", "us", "ja");
EXPECT_EQ(UTF8ToWide("\xe3\x81\x82"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("mozc-jp", "Mozc", "jp", "ja");
EXPECT_EQ(UTF8ToWide("\xe3\x81\x82"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("pinyin", "Pinyin", "us", "zh-CN");
EXPECT_EQ(UTF8ToWide("\xe6\x8b\xbc"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("chewing", "Chewing", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("\xe9\x85\xb7"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:zh:cangjie", "Cangjie", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("\xe5\x80\x89"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:zh:quick", "Quick", "us", "zh-TW");
EXPECT_EQ(UTF8ToWide("TW"),
LanguageMenuButton::GetTextForIndicator(desc));
}
{
InputMethodDescriptor desc("m17n:t:latn-pre", "latn-pre", "us", "t");
EXPECT_EQ(L"LAT",
LanguageMenuButton::GetTextForIndicator(desc));
}
}
TEST(LanguageMenuButtonTest, GetTextForTooltipTest) {
const bool kAddMethodName = true;
{
InputMethodDescriptor desc("m17n:fa:isiri", "isiri (m17n)", "us", "fa");
EXPECT_EQ(L"Persian - Persian input method (ISIRI 2901 layout)",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
{
InputMethodDescriptor desc("hangul", "Korean", "us", "ko");
EXPECT_EQ(L"Korean - Korean input method",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
{
InputMethodDescriptor desc("invalid-id", "unregistered string", "us", "xx");
// You can safely ignore the "Resouce ID is not found for: unregistered
// string" error.
EXPECT_EQ(L"xx - unregistered string",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
{
InputMethodDescriptor desc("m17n:t:latn-pre", "latn-pre", "us", "t");
EXPECT_EQ(L"latn-pre",
LanguageMenuButton::GetTextForMenu(desc, kAddMethodName));
}
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>#include "evas_common.h"
#include "evas_engine.h"
int
evas_software_ddraw_init (HWND window,
int depth,
int fullscreen,
Outbuf *buf)
{
DDSURFACEDESC surface_desc;
DDPIXELFORMAT pixel_format;
HRESULT res;
int width;
int height;
if (!buf)
return 0;
buf->priv.dd.window = window;
res = DirectDrawCreate(NULL, &buf->priv.dd.object, NULL);
if (FAILED(res))
return 0;
if (buf->priv.dd.fullscreen)
{
DDSCAPS caps;
res = buf->priv.dd.object->SetCooperativeLevel(window,
DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN);
if (FAILED(res))
goto release_object;
width = GetSystemMetrics(SM_CXSCREEN);
height = GetSystemMetrics(SM_CYSCREEN);
ZeroMemory(&pixel_format, sizeof(pixel_format));
pixel_format.dwSize = sizeof(pixel_format);
buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format);
if (pixel_format.dwRGBBitCount != depth)
goto release_object;
buf->priv.dd.depth = depth;
res = buf->priv.dd.object->SetDisplayMode(width, height, depth);
if (FAILED(res))
goto release_object;
memset(&surface_desc, 0, sizeof(surface_desc));
surface_desc.dwSize = sizeof(surface_desc);
surface_desc.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_COMPLEX;
surface_desc.dwBackBufferCount = 1;
res = buf->priv.dd.object->CreateSurface(&surface_desc,
&buf->priv.dd.surface_primary, NULL);
if (FAILED(res))
goto release_object;
caps.dwCaps = DDSCAPS_BACKBUFFER;
res = buf->priv.dd.surface_primary->GetAttachedSurface(&caps,
&buf->priv.dd.surface_back);
if (FAILED(res))
goto release_surface_primary;
}
else
{
RECT rect;
if (!GetClientRect(window, &rect))
goto release_object;
width = rect.right - rect.left;
height = rect.bottom - rect.top;
res = buf->priv.dd.object->SetCooperativeLevel(window, DDSCL_NORMAL);
if (FAILED(res))
goto release_object;
res = buf->priv.dd.object->CreateClipper(0, &buf->priv.dd.clipper, NULL);
if (FAILED(res))
goto release_object;
res = buf->priv.dd.clipper->SetHWnd(0, window);
if (FAILED(res))
goto release_clipper;
memset(&surface_desc, 0, sizeof(surface_desc));
surface_desc.dwSize = sizeof(surface_desc);
surface_desc.dwFlags = DDSD_CAPS;
surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_primary, NULL);
if (FAILED(res))
goto release_clipper;
res = buf->priv.dd.surface_primary->SetClipper(buf->priv.dd.clipper);
if (FAILED(res))
goto release_surface_primary;
memset (&surface_desc, 0, sizeof(surface_desc));
surface_desc.dwSize = sizeof(surface_desc);
surface_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
surface_desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
surface_desc.dwWidth = width;
surface_desc.dwHeight = height;
res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_back, NULL);
if (FAILED(res))
goto release_surface_primary;
ZeroMemory(&pixel_format, sizeof(pixel_format));
pixel_format.dwSize = sizeof(pixel_format);
buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format);
if (pixel_format.dwRGBBitCount != depth)
goto release_surface_back;
buf->priv.dd.depth = depth;
}
return 1;
release_surface_back:
buf->priv.dd.surface_back->Release();
release_surface_primary:
buf->priv.dd.surface_primary->Release();
release_clipper:
if (buf->priv.dd.fullscreen)
buf->priv.dd.clipper->Release();
release_object:
buf->priv.dd.object->Release();
return 0;
}
void
evas_software_ddraw_shutdown(Outbuf *buf)
{
if (!buf)
return;
if (buf->priv.dd.fullscreen)
if (buf->priv.dd.surface_back)
buf->priv.dd.surface_back->Release();
if (buf->priv.dd.surface_primary)
buf->priv.dd.surface_primary->Release();
if (buf->priv.dd.fullscreen)
if (buf->priv.dd.clipper)
buf->priv.dd.clipper->Release();
if (buf->priv.dd.object)
buf->priv.dd.object->Release();
}
int
evas_software_ddraw_masks_get(Outbuf *buf)
{
DDPIXELFORMAT pixel_format;
ZeroMemory(&pixel_format, sizeof(pixel_format));
pixel_format.dwSize = sizeof(pixel_format);
if (FAILED(buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format)))
return 0;
buf->priv.mask.r = pixel_format.dwRBitMask;
buf->priv.mask.g = pixel_format.dwGBitMask;
buf->priv.mask.b = pixel_format.dwBBitMask;
return 1;
}
void *
evas_software_ddraw_lock(Outbuf *buf,
int *ddraw_width,
int *ddraw_height,
int *ddraw_pitch,
int *ddraw_depth)
{
DDSURFACEDESC surface_desc;
ZeroMemory(&surface_desc, sizeof(surface_desc));
surface_desc.dwSize = sizeof(surface_desc);
if (FAILED(buf->priv.dd.surface_back->Lock(NULL,
&surface_desc,
DDLOCK_WAIT | DDLOCK_WRITEONLY | DDLOCK_SURFACEMEMORYPTR | DDLOCK_NOSYSLOCK,
NULL)))
return NULL;
*ddraw_width = surface_desc.dwWidth;
*ddraw_height = surface_desc.dwHeight;
*ddraw_pitch = surface_desc.lPitch;
*ddraw_depth = surface_desc.ddpfPixelFormat.dwRGBBitCount >> 3;
return surface_desc.lpSurface;
}
void
evas_software_ddraw_unlock_and_flip(Outbuf *buf)
{
RECT dst_rect;
RECT src_rect;
POINT p;
if (FAILED(buf->priv.dd.surface_back->Unlock(NULL)))
return;
/* we figure out where on the primary surface our window lives */
p.x = 0;
p.y = 0;
ClientToScreen(buf->priv.dd.window, &p);
GetClientRect(buf->priv.dd.window, &dst_rect);
OffsetRect(&dst_rect, p.x, p.y);
SetRect(&src_rect, 0, 0, buf->width, buf->height);
/* nothing to do if the function fails, so we don't check the result */
buf->priv.dd.surface_primary->Blt(&dst_rect,
buf->priv.dd.surface_back,
&src_rect,
DDBLT_WAIT, NULL);
}
void
evas_software_ddraw_surface_resize(Outbuf *buf)
{
DDSURFACEDESC surface_desc;
buf->priv.dd.surface_back->Release();
memset (&surface_desc, 0, sizeof (surface_desc));
surface_desc.dwSize = sizeof (surface_desc);
/* FIXME: that code does not compile. Must know why */
#if 0
surface_desc.dwFlags = DDSD_HEIGHT | DDSD_WIDTH;
surface_desc.dwWidth = width;
surface_desc.dwHeight = height;
buf->priv.dd.surface_back->SetSurfaceDesc(&surface_desc, NULL);
#else
surface_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
surface_desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
surface_desc.dwWidth = buf->width;
surface_desc.dwHeight = buf->height;
buf->priv.dd.object->CreateSurface(&surface_desc,
&buf->priv.dd.surface_back,
NULL);
#endif
}
<commit_msg>release the clipper only it has been created, that is in windowed mode<commit_after>#include "evas_common.h"
#include "evas_engine.h"
int
evas_software_ddraw_init (HWND window,
int depth,
int fullscreen,
Outbuf *buf)
{
DDSURFACEDESC surface_desc;
DDPIXELFORMAT pixel_format;
HRESULT res;
int width;
int height;
if (!buf)
return 0;
buf->priv.dd.window = window;
res = DirectDrawCreate(NULL, &buf->priv.dd.object, NULL);
if (FAILED(res))
return 0;
if (buf->priv.dd.fullscreen)
{
DDSCAPS caps;
res = buf->priv.dd.object->SetCooperativeLevel(window,
DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN);
if (FAILED(res))
goto release_object;
width = GetSystemMetrics(SM_CXSCREEN);
height = GetSystemMetrics(SM_CYSCREEN);
ZeroMemory(&pixel_format, sizeof(pixel_format));
pixel_format.dwSize = sizeof(pixel_format);
buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format);
if (pixel_format.dwRGBBitCount != depth)
goto release_object;
buf->priv.dd.depth = depth;
res = buf->priv.dd.object->SetDisplayMode(width, height, depth);
if (FAILED(res))
goto release_object;
memset(&surface_desc, 0, sizeof(surface_desc));
surface_desc.dwSize = sizeof(surface_desc);
surface_desc.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_COMPLEX;
surface_desc.dwBackBufferCount = 1;
res = buf->priv.dd.object->CreateSurface(&surface_desc,
&buf->priv.dd.surface_primary, NULL);
if (FAILED(res))
goto release_object;
caps.dwCaps = DDSCAPS_BACKBUFFER;
res = buf->priv.dd.surface_primary->GetAttachedSurface(&caps,
&buf->priv.dd.surface_back);
if (FAILED(res))
goto release_surface_primary;
}
else
{
RECT rect;
if (!GetClientRect(window, &rect))
goto release_object;
width = rect.right - rect.left;
height = rect.bottom - rect.top;
res = buf->priv.dd.object->SetCooperativeLevel(window, DDSCL_NORMAL);
if (FAILED(res))
goto release_object;
res = buf->priv.dd.object->CreateClipper(0, &buf->priv.dd.clipper, NULL);
if (FAILED(res))
goto release_object;
res = buf->priv.dd.clipper->SetHWnd(0, window);
if (FAILED(res))
goto release_clipper;
memset(&surface_desc, 0, sizeof(surface_desc));
surface_desc.dwSize = sizeof(surface_desc);
surface_desc.dwFlags = DDSD_CAPS;
surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_primary, NULL);
if (FAILED(res))
goto release_clipper;
res = buf->priv.dd.surface_primary->SetClipper(buf->priv.dd.clipper);
if (FAILED(res))
goto release_surface_primary;
memset (&surface_desc, 0, sizeof(surface_desc));
surface_desc.dwSize = sizeof(surface_desc);
surface_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
surface_desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
surface_desc.dwWidth = width;
surface_desc.dwHeight = height;
res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_back, NULL);
if (FAILED(res))
goto release_surface_primary;
ZeroMemory(&pixel_format, sizeof(pixel_format));
pixel_format.dwSize = sizeof(pixel_format);
buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format);
if (pixel_format.dwRGBBitCount != depth)
goto release_surface_back;
buf->priv.dd.depth = depth;
}
return 1;
release_surface_back:
buf->priv.dd.surface_back->Release();
release_surface_primary:
buf->priv.dd.surface_primary->Release();
release_clipper:
if (!buf->priv.dd.fullscreen)
buf->priv.dd.clipper->Release();
release_object:
buf->priv.dd.object->Release();
return 0;
}
void
evas_software_ddraw_shutdown(Outbuf *buf)
{
if (!buf)
return;
if (buf->priv.dd.fullscreen)
if (buf->priv.dd.surface_back)
buf->priv.dd.surface_back->Release();
if (buf->priv.dd.surface_primary)
buf->priv.dd.surface_primary->Release();
if (!buf->priv.dd.fullscreen)
if (buf->priv.dd.clipper)
buf->priv.dd.clipper->Release();
if (buf->priv.dd.object)
buf->priv.dd.object->Release();
}
int
evas_software_ddraw_masks_get(Outbuf *buf)
{
DDPIXELFORMAT pixel_format;
ZeroMemory(&pixel_format, sizeof(pixel_format));
pixel_format.dwSize = sizeof(pixel_format);
if (FAILED(buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format)))
return 0;
buf->priv.mask.r = pixel_format.dwRBitMask;
buf->priv.mask.g = pixel_format.dwGBitMask;
buf->priv.mask.b = pixel_format.dwBBitMask;
return 1;
}
void *
evas_software_ddraw_lock(Outbuf *buf,
int *ddraw_width,
int *ddraw_height,
int *ddraw_pitch,
int *ddraw_depth)
{
DDSURFACEDESC surface_desc;
ZeroMemory(&surface_desc, sizeof(surface_desc));
surface_desc.dwSize = sizeof(surface_desc);
if (FAILED(buf->priv.dd.surface_back->Lock(NULL,
&surface_desc,
DDLOCK_WAIT | DDLOCK_WRITEONLY | DDLOCK_SURFACEMEMORYPTR | DDLOCK_NOSYSLOCK,
NULL)))
return NULL;
*ddraw_width = surface_desc.dwWidth;
*ddraw_height = surface_desc.dwHeight;
*ddraw_pitch = surface_desc.lPitch;
*ddraw_depth = surface_desc.ddpfPixelFormat.dwRGBBitCount >> 3;
return surface_desc.lpSurface;
}
void
evas_software_ddraw_unlock_and_flip(Outbuf *buf)
{
RECT dst_rect;
RECT src_rect;
POINT p;
if (FAILED(buf->priv.dd.surface_back->Unlock(NULL)))
return;
/* we figure out where on the primary surface our window lives */
p.x = 0;
p.y = 0;
ClientToScreen(buf->priv.dd.window, &p);
GetClientRect(buf->priv.dd.window, &dst_rect);
OffsetRect(&dst_rect, p.x, p.y);
SetRect(&src_rect, 0, 0, buf->width, buf->height);
/* nothing to do if the function fails, so we don't check the result */
buf->priv.dd.surface_primary->Blt(&dst_rect,
buf->priv.dd.surface_back,
&src_rect,
DDBLT_WAIT, NULL);
}
void
evas_software_ddraw_surface_resize(Outbuf *buf)
{
DDSURFACEDESC surface_desc;
buf->priv.dd.surface_back->Release();
memset (&surface_desc, 0, sizeof (surface_desc));
surface_desc.dwSize = sizeof (surface_desc);
/* FIXME: that code does not compile. Must know why */
#if 0
surface_desc.dwFlags = DDSD_HEIGHT | DDSD_WIDTH;
surface_desc.dwWidth = width;
surface_desc.dwHeight = height;
buf->priv.dd.surface_back->SetSurfaceDesc(&surface_desc, NULL);
#else
surface_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
surface_desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
surface_desc.dwWidth = buf->width;
surface_desc.dwHeight = buf->height;
buf->priv.dd.object->CreateSurface(&surface_desc,
&buf->priv.dd.surface_back,
NULL);
#endif
}
<|endoftext|>
|
<commit_before>// 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 "chrome/browser/ui/blocked_content/blocked_content_tab_helper.h"
#include "base/auto_reset.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/content_settings/tab_specific_content_settings.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/blocked_content/blocked_content_container.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/navigation_details.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_service.h"
BlockedContentTabHelper::BlockedContentTabHelper(
TabContentsWrapper* tab_contents)
: TabContentsObserver(tab_contents->tab_contents()),
blocked_contents_(new BlockedContentContainer(tab_contents)),
all_contents_blocked_(false),
tab_contents_wrapper_(tab_contents) {
}
BlockedContentTabHelper::~BlockedContentTabHelper() {
}
void BlockedContentTabHelper::DidNavigateMainFramePostCommit(
const content::LoadCommittedDetails& details,
const ViewHostMsg_FrameNavigate_Params& params) {
// Clear all page actions, blocked content notifications and browser actions
// for this tab, unless this is an in-page navigation.
if (!details.is_in_page) {
// Close blocked popups.
if (blocked_contents_->GetBlockedContentsCount()) {
blocked_contents_->Clear();
PopupNotificationVisibilityChanged(false);
}
}
}
void BlockedContentTabHelper::PopupNotificationVisibilityChanged(
bool visible) {
if (tab_contents()->is_being_destroyed())
return;
tab_contents_wrapper_->content_settings()->SetPopupsBlocked(visible);
}
void BlockedContentTabHelper::SetAllContentsBlocked(bool value) {
if (all_contents_blocked_ == value)
return;
all_contents_blocked_ = value;
if (!all_contents_blocked_ && blocked_contents_->GetBlockedContentsCount()) {
std::vector<TabContentsWrapper*> blocked;
blocked_contents_->GetBlockedContents(&blocked);
for (size_t i = 0; i < blocked.size(); ++i)
blocked_contents_->LaunchForContents(blocked[i]);
}
}
void BlockedContentTabHelper::AddTabContents(TabContentsWrapper* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_pos,
bool user_gesture) {
if (!blocked_contents_->GetBlockedContentsCount())
PopupNotificationVisibilityChanged(true);
blocked_contents_->AddTabContents(
new_contents, disposition, initial_pos, user_gesture);
}
void BlockedContentTabHelper::AddPopup(TabContentsWrapper* new_contents,
const gfx::Rect& initial_pos,
bool user_gesture) {
// A page can't spawn popups (or do anything else, either) until its load
// commits, so when we reach here, the popup was spawned by the
// NavigationController's last committed entry, not the active entry. For
// example, if a page opens a popup in an onunload() handler, then the active
// entry is the page to be loaded as we navigate away from the unloading
// page. For this reason, we can't use GetURL() to get the opener URL,
// because it returns the active entry.
NavigationEntry* entry = tab_contents()->controller().GetLastCommittedEntry();
GURL creator = entry ? entry->virtual_url() : GURL::EmptyGURL();
if (creator.is_valid() &&
tab_contents()->profile()->GetHostContentSettingsMap()->GetContentSetting(
creator,
creator,
CONTENT_SETTINGS_TYPE_POPUPS,
"") == CONTENT_SETTING_ALLOW) {
tab_contents()->AddNewContents(new_contents->tab_contents(),
NEW_POPUP,
initial_pos,
true); // user_gesture
} else {
// Call blocked_contents_->AddTabContents with user_gesture == true
// so that the contents will not get blocked again.
blocked_contents_->AddTabContents(new_contents,
NEW_POPUP,
initial_pos,
true); // user_gesture
tab_contents_wrapper_->content_settings()->OnContentBlocked(
CONTENT_SETTINGS_TYPE_POPUPS, std::string());
}
}
void BlockedContentTabHelper::LaunchForContents(
TabContentsWrapper* tab_contents) {
blocked_contents_->LaunchForContents(tab_contents);
if (!blocked_contents_->GetBlockedContentsCount())
PopupNotificationVisibilityChanged(false);
}
size_t BlockedContentTabHelper::GetBlockedContentsCount() const {
return blocked_contents_->GetBlockedContentsCount();
}
void BlockedContentTabHelper::GetBlockedContents(
std::vector<TabContentsWrapper*>* blocked_contents) const {
blocked_contents_->GetBlockedContents(blocked_contents);
}
<commit_msg>Properly initialize delegate variable.<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 "chrome/browser/ui/blocked_content/blocked_content_tab_helper.h"
#include "base/auto_reset.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/content_settings/tab_specific_content_settings.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/blocked_content/blocked_content_container.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/navigation_details.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_service.h"
BlockedContentTabHelper::BlockedContentTabHelper(
TabContentsWrapper* tab_contents)
: TabContentsObserver(tab_contents->tab_contents()),
blocked_contents_(new BlockedContentContainer(tab_contents)),
all_contents_blocked_(false),
tab_contents_wrapper_(tab_contents),
delegate_(NULL) {
}
BlockedContentTabHelper::~BlockedContentTabHelper() {
}
void BlockedContentTabHelper::DidNavigateMainFramePostCommit(
const content::LoadCommittedDetails& details,
const ViewHostMsg_FrameNavigate_Params& params) {
// Clear all page actions, blocked content notifications and browser actions
// for this tab, unless this is an in-page navigation.
if (!details.is_in_page) {
// Close blocked popups.
if (blocked_contents_->GetBlockedContentsCount()) {
blocked_contents_->Clear();
PopupNotificationVisibilityChanged(false);
}
}
}
void BlockedContentTabHelper::PopupNotificationVisibilityChanged(
bool visible) {
if (tab_contents()->is_being_destroyed())
return;
tab_contents_wrapper_->content_settings()->SetPopupsBlocked(visible);
}
void BlockedContentTabHelper::SetAllContentsBlocked(bool value) {
if (all_contents_blocked_ == value)
return;
all_contents_blocked_ = value;
if (!all_contents_blocked_ && blocked_contents_->GetBlockedContentsCount()) {
std::vector<TabContentsWrapper*> blocked;
blocked_contents_->GetBlockedContents(&blocked);
for (size_t i = 0; i < blocked.size(); ++i)
blocked_contents_->LaunchForContents(blocked[i]);
}
}
void BlockedContentTabHelper::AddTabContents(TabContentsWrapper* new_contents,
WindowOpenDisposition disposition,
const gfx::Rect& initial_pos,
bool user_gesture) {
if (!blocked_contents_->GetBlockedContentsCount())
PopupNotificationVisibilityChanged(true);
blocked_contents_->AddTabContents(
new_contents, disposition, initial_pos, user_gesture);
}
void BlockedContentTabHelper::AddPopup(TabContentsWrapper* new_contents,
const gfx::Rect& initial_pos,
bool user_gesture) {
// A page can't spawn popups (or do anything else, either) until its load
// commits, so when we reach here, the popup was spawned by the
// NavigationController's last committed entry, not the active entry. For
// example, if a page opens a popup in an onunload() handler, then the active
// entry is the page to be loaded as we navigate away from the unloading
// page. For this reason, we can't use GetURL() to get the opener URL,
// because it returns the active entry.
NavigationEntry* entry = tab_contents()->controller().GetLastCommittedEntry();
GURL creator = entry ? entry->virtual_url() : GURL::EmptyGURL();
if (creator.is_valid() &&
tab_contents()->profile()->GetHostContentSettingsMap()->GetContentSetting(
creator,
creator,
CONTENT_SETTINGS_TYPE_POPUPS,
"") == CONTENT_SETTING_ALLOW) {
tab_contents()->AddNewContents(new_contents->tab_contents(),
NEW_POPUP,
initial_pos,
true); // user_gesture
} else {
// Call blocked_contents_->AddTabContents with user_gesture == true
// so that the contents will not get blocked again.
blocked_contents_->AddTabContents(new_contents,
NEW_POPUP,
initial_pos,
true); // user_gesture
tab_contents_wrapper_->content_settings()->OnContentBlocked(
CONTENT_SETTINGS_TYPE_POPUPS, std::string());
}
}
void BlockedContentTabHelper::LaunchForContents(
TabContentsWrapper* tab_contents) {
blocked_contents_->LaunchForContents(tab_contents);
if (!blocked_contents_->GetBlockedContentsCount())
PopupNotificationVisibilityChanged(false);
}
size_t BlockedContentTabHelper::GetBlockedContentsCount() const {
return blocked_contents_->GetBlockedContentsCount();
}
void BlockedContentTabHelper::GetBlockedContents(
std::vector<TabContentsWrapper*>* blocked_contents) const {
blocked_contents_->GetBlockedContents(blocked_contents);
}
<|endoftext|>
|
<commit_before>/*************************************************************************************
* Copyright (C) 2012 by Alejandro Fiestas Olivares <[email protected]> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
*************************************************************************************/
#include "daemon.h"
#include "serializer.h"
#include "generator.h"
#include "device.h"
#include "kscreenadaptor.h"
#include "debug.h"
#include <QTimer>
#include <QAction>
#include <QShortcut>
#include <QLoggingCategory>
#include <KLocalizedString>
#include <KActionCollection>
#include <KPluginFactory>
#include <KGlobalAccel>
#include <kscreen/config.h>
#include <kscreen/configmonitor.h>
#include <kscreen/getconfigoperation.h>
#include <kscreen/setconfigoperation.h>
K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();)
KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& )
: KDEDModule(parent)
, m_monitoredConfig(0)
, m_iteration(0)
, m_monitoring(false)
, m_changeCompressor(new QTimer())
, m_buttonTimer(new QTimer())
, m_saveTimer(new QTimer())
, m_lidClosedTimer(new QTimer())
{
QMetaObject::invokeMethod(this, "requestConfig", Qt::QueuedConnection);
}
void KScreenDaemon::requestConfig()
{
connect(new KScreen::GetConfigOperation, &KScreen::GetConfigOperation::finished,
this, &KScreenDaemon::configReady);
}
void KScreenDaemon::configReady(KScreen::ConfigOperation* op)
{
if (op->hasError()) {
return;
}
m_monitoredConfig = qobject_cast<KScreen::GetConfigOperation*>(op)->config();
qCDebug(KSCREEN_KDED) << "Config" << m_monitoredConfig.data() << "is ready";
KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig);
init();
}
KScreenDaemon::~KScreenDaemon()
{
delete m_changeCompressor;
delete m_saveTimer;
delete m_buttonTimer;
delete m_lidClosedTimer;
Generator::destroy();
Device::destroy();
}
void KScreenDaemon::init()
{
KActionCollection *coll = new KActionCollection(this);
QAction* action = coll->addAction(QStringLiteral("display"));
action->setText(i18n("Switch Display" ));
KGlobalAccel::self()->setGlobalShortcut(action, Qt::Key_Display);
connect(action, &QAction::triggered, [&](bool) { displayButton(); });
new KScreenAdaptor(this);
m_buttonTimer->setInterval(300);
m_buttonTimer->setSingleShot(true);
connect(m_buttonTimer, &QTimer::timeout, this, &KScreenDaemon::applyGenericConfig);
m_saveTimer->setInterval(300);
m_saveTimer->setSingleShot(true);
connect(m_saveTimer, &QTimer::timeout, this, &KScreenDaemon::saveCurrentConfig);
m_changeCompressor->setInterval(10);
m_changeCompressor->setSingleShot(true);
connect(m_changeCompressor, &QTimer::timeout, this, &KScreenDaemon::applyConfig);
m_lidClosedTimer->setInterval(1000);
m_lidClosedTimer->setSingleShot(true);
connect(m_lidClosedTimer, &QTimer::timeout, this, &KScreenDaemon::lidClosedTimeout);
connect(Device::self(), &Device::lidClosedChanged, this, &KScreenDaemon::lidClosedChanged);
connect(Device::self(), &Device::resumingFromSuspend,
[&]() {
qCDebug(KSCREEN_KDED) << "Resumed from suspend, checking for screen changes";
// We don't care about the result, we just want to force the backend
// to query XRandR so that it will detect possible changes that happened
// while the computer was suspended, and will emit the change events.
new KScreen::GetConfigOperation(KScreen::GetConfigOperation::NoEDID, this);
});
connect(Device::self(), &Device::aboutToSuspend,
[&]() {
qCDebug(KSCREEN_KDED) << "System is going to suspend, won't be changing config (waited for " << (m_lidClosedTimer->interval() - m_lidClosedTimer->remainingTime()) << "ms)";
m_lidClosedTimer->stop();
});
connect(Generator::self(), &Generator::ready,
this, &KScreenDaemon::applyConfig);
Generator::self()->setCurrentConfig(m_monitoredConfig);
monitorConnectedChange();
}
void KScreenDaemon::doApplyConfig(const KScreen::ConfigPtr& config)
{
qCDebug(KSCREEN_KDED) << "doApplyConfig()";
setMonitorForChanges(false);
connect(new KScreen::SetConfigOperation(config), &KScreen::SetConfigOperation::finished,
[&]() {
qCDebug(KSCREEN_KDED) << "Config applied";
setMonitorForChanges(true);
});
}
void KScreenDaemon::applyConfig()
{
qCDebug(KSCREEN_KDED) << "Applying config";
if (Serializer::configExists(m_monitoredConfig)) {
applyKnownConfig();
return;
}
applyIdealConfig();
}
void KScreenDaemon::applyKnownConfig()
{
const QString configId = Serializer::configId(m_monitoredConfig);
qCDebug(KSCREEN_KDED) << "Applying known config" << configId;
KScreen::ConfigPtr config = Serializer::config(m_monitoredConfig, configId);
if (!KScreen::Config::canBeApplied(config)) {
return applyIdealConfig();
}
doApplyConfig(config);
}
void KScreenDaemon::applyIdealConfig()
{
qCDebug(KSCREEN_KDED) << "Applying ideal config";
doApplyConfig(Generator::self()->idealConfig(m_monitoredConfig));
}
void KScreenDaemon::configChanged()
{
qCDebug(KSCREEN_KDED) << "Change detected";
// Reset timer, delay the writeback
m_saveTimer->start();
}
void KScreenDaemon::saveCurrentConfig()
{
qCDebug(KSCREEN_KDED) << "Saving current config to file";
Serializer::saveConfig(m_monitoredConfig, Serializer::configId(m_monitoredConfig));
}
void KScreenDaemon::displayButton()
{
qCDebug(KSCREEN_KDED) << "displayBtn triggered";
if (m_buttonTimer->isActive()) {
qCDebug(KSCREEN_KDED) << "Too fast, cowboy";
return;
}
m_buttonTimer->start();
}
void KScreenDaemon::resetDisplaySwitch()
{
qCDebug(KSCREEN_KDED) << "resetDisplaySwitch()";
m_iteration = 0;
}
void KScreenDaemon::applyGenericConfig()
{
if (m_iteration == 5) {
m_iteration = 0;
}
m_iteration++;
qCDebug(KSCREEN_KDED) << "displayButton: " << m_iteration;
doApplyConfig(Generator::self()->displaySwitch(m_iteration));
}
void KScreenDaemon::lidClosedChanged(bool lidIsClosed)
{
if (lidIsClosed) {
// Lid is closed, now we wait for couple seconds to find out whether it
// will trigger a suspend (see Device::aboutToSuspend), or whether we should
// turn off the screen
qCDebug(KSCREEN_KDED) << "Lid closed, waiting to see if the computer goes to sleep...";
m_lidClosedTimer->start();
return;
} else {
qCDebug(KSCREEN_KDED) << "Lid opened!";
// We should have a config with "_lidOpened" suffix lying around. If not,
// then the configuration has changed while the lid was closed and we just
// use applyConfig() and see what we can do ...
const QString openConfigId = Serializer::configId(m_monitoredConfig) + QLatin1String("_lidOpened");
if (Serializer::configExists(openConfigId)) {
const KScreen::ConfigPtr openedConfig = Serializer::config(m_monitoredConfig, openConfigId);
Serializer::removeConfig(openConfigId);
doApplyConfig(openedConfig);
/*
KScreen::OutputPtr closedLidOutput = findEmbeddedOutput(m_monitoredConfig);
if (!closedLidOutput) {
// WTF?
return;
}
const KScreen::OutputPtr openedLidOutput = openedConfig->output(closedLidOutput->id());
if (!openedLidOutput) {
// WTF?
return;
}
closedLidOutput->setEnabled(true);
closedLidOutput->setPos(openedLidOutput->pos());
closedLidOutput->setCurrentModeId(openedLidOutput->currentModeId());
closedLidOutput->setPrimary(openedLidOutput->isPrimary());
closedLidOutput->setRotation(openedLidOutput->rotation());
const KScreen::ModePtr newMode = closedLidOutput->currentMode();
if (!newMode) {
// WTF?
return;
}
const QRect closedGeometry = closedLidOutput->geometry();
for (KScreen::OutputPtr &output : m_monitoredConfig->outputs()) {
if (output == closedLidOutput) {
continue;
}
const QRect geom = output->geometry();
if (geom.left() >= closedGeometry.left() &&
geom.top() >= closedGeometry.top() && geom.top() <= closedGeometry.bottom()) {
output->pos().rx() += closedGeometry.width();
}
}
*/
}
}
}
void KScreenDaemon::lidClosedTimeout()
{
// Make sure nothing has changed in the past 2 seconds.. :-)
if (!Device::self()->isLidClosed()) {
return;
}
// If we are here, it means that closing the lid did not result in suspend
// action.
// FIXME: This could be simply because the suspend took longer than m_lidClosedTimer
// timeout. Ideally we need to be able to look into PowerDevil config to see
// what's the configured action for lid events, but there's no API to do that
// and I'm no parsing PowerDevil's configs...
qCDebug(KSCREEN_KDED) << "Lid closed without system going to suspend -> turning off the screen";
for (KScreen::OutputPtr &output : m_monitoredConfig->outputs()) {
if (output->type() == KScreen::Output::Panel) {
if (output->isConnected() && output->isEnabled()) {
// Save the current config with opened lid, just so that we know
// how to restore it later
const QString configId = Serializer::configId(m_monitoredConfig) + QLatin1String("_lidOpened");
Serializer::saveConfig(m_monitoredConfig, configId);
disableOutput(m_monitoredConfig, output);
doApplyConfig(m_monitoredConfig);
return;
}
}
}
}
void KScreenDaemon::outputConnectedChanged()
{
if (!m_changeCompressor->isActive()) {
m_changeCompressor->start();
}
resetDisplaySwitch();
KScreen::Output *output = qobject_cast<KScreen::Output*>(sender());
qCDebug(KSCREEN_KDED) << "outputConnectedChanged():" << output->name();
if (output->isConnected()) {
Q_EMIT outputConnected(output->name());
if (!Serializer::configExists(m_monitoredConfig)) {
Q_EMIT unknownOutputConnected(output->name());
}
}
}
void KScreenDaemon::monitorConnectedChange()
{
KScreen::OutputList outputs = m_monitoredConfig->outputs();
Q_FOREACH(const KScreen::OutputPtr &output, outputs) {
connect(output.data(), &KScreen::Output::isConnectedChanged,
this, &KScreenDaemon::outputConnectedChanged,
Qt::UniqueConnection);
}
}
void KScreenDaemon::setMonitorForChanges(bool enabled)
{
if (m_monitoring == enabled) {
return;
}
qCDebug(KSCREEN_KDED) << "Monitor for changes: " << enabled;
m_monitoring = enabled;
if (m_monitoring) {
connect(KScreen::ConfigMonitor::instance(), &KScreen::ConfigMonitor::configurationChanged,
this, &KScreenDaemon::configChanged, Qt::UniqueConnection);
} else {
disconnect(KScreen::ConfigMonitor::instance(), &KScreen::ConfigMonitor::configurationChanged,
this, &KScreenDaemon::configChanged);
}
}
void KScreenDaemon::disableOutput(KScreen::ConfigPtr &config, KScreen::OutputPtr &output)
{
const QRect geom = output->geometry();
qCDebug(KSCREEN_KDED) << "Laptop geometry:" << geom << output->pos() << (output->currentMode() ? output->currentMode()->size() : QSize());
// Move all outputs right from the @p output to left
for (KScreen::OutputPtr &otherOutput : config->outputs()) {
if (otherOutput == output || !otherOutput->isConnected() || !otherOutput->isEnabled()) {
continue;
}
QPoint otherPos = otherOutput->pos();
if (otherPos.x() >= geom.right() && otherPos.y() >= geom.top() && otherPos.y() <= geom.bottom()) {
otherPos.setX(otherPos.x() - geom.width());
}
qCDebug(KSCREEN_KDED) << "Moving" << otherOutput->name() << "from" << otherOutput->pos() << "to" << otherPos;
otherOutput->setPos(otherPos);
}
// Disable the output
output->setEnabled(false);
}
KScreen::OutputPtr KScreenDaemon::findEmbeddedOutput(const KScreen::ConfigPtr &config)
{
Q_FOREACH (const KScreen::OutputPtr &output, config->outputs()) {
if (output->type() == KScreen::Output::Panel) {
return output;
}
}
return KScreen::OutputPtr();
}
#include "daemon.moc"
<commit_msg>Remove disabled code<commit_after>/*************************************************************************************
* Copyright (C) 2012 by Alejandro Fiestas Olivares <[email protected]> *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
*************************************************************************************/
#include "daemon.h"
#include "serializer.h"
#include "generator.h"
#include "device.h"
#include "kscreenadaptor.h"
#include "debug.h"
#include <QTimer>
#include <QAction>
#include <QShortcut>
#include <QLoggingCategory>
#include <KLocalizedString>
#include <KActionCollection>
#include <KPluginFactory>
#include <KGlobalAccel>
#include <kscreen/config.h>
#include <kscreen/configmonitor.h>
#include <kscreen/getconfigoperation.h>
#include <kscreen/setconfigoperation.h>
K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();)
KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& )
: KDEDModule(parent)
, m_monitoredConfig(0)
, m_iteration(0)
, m_monitoring(false)
, m_changeCompressor(new QTimer())
, m_buttonTimer(new QTimer())
, m_saveTimer(new QTimer())
, m_lidClosedTimer(new QTimer())
{
QMetaObject::invokeMethod(this, "requestConfig", Qt::QueuedConnection);
}
void KScreenDaemon::requestConfig()
{
connect(new KScreen::GetConfigOperation, &KScreen::GetConfigOperation::finished,
this, &KScreenDaemon::configReady);
}
void KScreenDaemon::configReady(KScreen::ConfigOperation* op)
{
if (op->hasError()) {
return;
}
m_monitoredConfig = qobject_cast<KScreen::GetConfigOperation*>(op)->config();
qCDebug(KSCREEN_KDED) << "Config" << m_monitoredConfig.data() << "is ready";
KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig);
init();
}
KScreenDaemon::~KScreenDaemon()
{
delete m_changeCompressor;
delete m_saveTimer;
delete m_buttonTimer;
delete m_lidClosedTimer;
Generator::destroy();
Device::destroy();
}
void KScreenDaemon::init()
{
KActionCollection *coll = new KActionCollection(this);
QAction* action = coll->addAction(QStringLiteral("display"));
action->setText(i18n("Switch Display" ));
KGlobalAccel::self()->setGlobalShortcut(action, Qt::Key_Display);
connect(action, &QAction::triggered, [&](bool) { displayButton(); });
new KScreenAdaptor(this);
m_buttonTimer->setInterval(300);
m_buttonTimer->setSingleShot(true);
connect(m_buttonTimer, &QTimer::timeout, this, &KScreenDaemon::applyGenericConfig);
m_saveTimer->setInterval(300);
m_saveTimer->setSingleShot(true);
connect(m_saveTimer, &QTimer::timeout, this, &KScreenDaemon::saveCurrentConfig);
m_changeCompressor->setInterval(10);
m_changeCompressor->setSingleShot(true);
connect(m_changeCompressor, &QTimer::timeout, this, &KScreenDaemon::applyConfig);
m_lidClosedTimer->setInterval(1000);
m_lidClosedTimer->setSingleShot(true);
connect(m_lidClosedTimer, &QTimer::timeout, this, &KScreenDaemon::lidClosedTimeout);
connect(Device::self(), &Device::lidClosedChanged, this, &KScreenDaemon::lidClosedChanged);
connect(Device::self(), &Device::resumingFromSuspend,
[&]() {
qCDebug(KSCREEN_KDED) << "Resumed from suspend, checking for screen changes";
// We don't care about the result, we just want to force the backend
// to query XRandR so that it will detect possible changes that happened
// while the computer was suspended, and will emit the change events.
new KScreen::GetConfigOperation(KScreen::GetConfigOperation::NoEDID, this);
});
connect(Device::self(), &Device::aboutToSuspend,
[&]() {
qCDebug(KSCREEN_KDED) << "System is going to suspend, won't be changing config (waited for " << (m_lidClosedTimer->interval() - m_lidClosedTimer->remainingTime()) << "ms)";
m_lidClosedTimer->stop();
});
connect(Generator::self(), &Generator::ready,
this, &KScreenDaemon::applyConfig);
Generator::self()->setCurrentConfig(m_monitoredConfig);
monitorConnectedChange();
}
void KScreenDaemon::doApplyConfig(const KScreen::ConfigPtr& config)
{
qCDebug(KSCREEN_KDED) << "doApplyConfig()";
setMonitorForChanges(false);
connect(new KScreen::SetConfigOperation(config), &KScreen::SetConfigOperation::finished,
[&]() {
qCDebug(KSCREEN_KDED) << "Config applied";
setMonitorForChanges(true);
});
}
void KScreenDaemon::applyConfig()
{
qCDebug(KSCREEN_KDED) << "Applying config";
if (Serializer::configExists(m_monitoredConfig)) {
applyKnownConfig();
return;
}
applyIdealConfig();
}
void KScreenDaemon::applyKnownConfig()
{
const QString configId = Serializer::configId(m_monitoredConfig);
qCDebug(KSCREEN_KDED) << "Applying known config" << configId;
KScreen::ConfigPtr config = Serializer::config(m_monitoredConfig, configId);
if (!KScreen::Config::canBeApplied(config)) {
return applyIdealConfig();
}
doApplyConfig(config);
}
void KScreenDaemon::applyIdealConfig()
{
qCDebug(KSCREEN_KDED) << "Applying ideal config";
doApplyConfig(Generator::self()->idealConfig(m_monitoredConfig));
}
void KScreenDaemon::configChanged()
{
qCDebug(KSCREEN_KDED) << "Change detected";
// Reset timer, delay the writeback
m_saveTimer->start();
}
void KScreenDaemon::saveCurrentConfig()
{
qCDebug(KSCREEN_KDED) << "Saving current config to file";
Serializer::saveConfig(m_monitoredConfig, Serializer::configId(m_monitoredConfig));
}
void KScreenDaemon::displayButton()
{
qCDebug(KSCREEN_KDED) << "displayBtn triggered";
if (m_buttonTimer->isActive()) {
qCDebug(KSCREEN_KDED) << "Too fast, cowboy";
return;
}
m_buttonTimer->start();
}
void KScreenDaemon::resetDisplaySwitch()
{
qCDebug(KSCREEN_KDED) << "resetDisplaySwitch()";
m_iteration = 0;
}
void KScreenDaemon::applyGenericConfig()
{
if (m_iteration == 5) {
m_iteration = 0;
}
m_iteration++;
qCDebug(KSCREEN_KDED) << "displayButton: " << m_iteration;
doApplyConfig(Generator::self()->displaySwitch(m_iteration));
}
void KScreenDaemon::lidClosedChanged(bool lidIsClosed)
{
if (lidIsClosed) {
// Lid is closed, now we wait for couple seconds to find out whether it
// will trigger a suspend (see Device::aboutToSuspend), or whether we should
// turn off the screen
qCDebug(KSCREEN_KDED) << "Lid closed, waiting to see if the computer goes to sleep...";
m_lidClosedTimer->start();
return;
} else {
qCDebug(KSCREEN_KDED) << "Lid opened!";
// We should have a config with "_lidOpened" suffix lying around. If not,
// then the configuration has changed while the lid was closed and we just
// use applyConfig() and see what we can do ...
const QString openConfigId = Serializer::configId(m_monitoredConfig) + QLatin1String("_lidOpened");
if (Serializer::configExists(openConfigId)) {
const KScreen::ConfigPtr openedConfig = Serializer::config(m_monitoredConfig, openConfigId);
Serializer::removeConfig(openConfigId);
doApplyConfig(openedConfig);
}
}
}
void KScreenDaemon::lidClosedTimeout()
{
// Make sure nothing has changed in the past second... :-)
if (!Device::self()->isLidClosed()) {
return;
}
// If we are here, it means that closing the lid did not result in suspend
// action.
// FIXME: This could be simply because the suspend took longer than m_lidClosedTimer
// timeout. Ideally we need to be able to look into PowerDevil config to see
// what's the configured action for lid events, but there's no API to do that
// and I'm no parsing PowerDevil's configs...
qCDebug(KSCREEN_KDED) << "Lid closed without system going to suspend -> turning off the screen";
for (KScreen::OutputPtr &output : m_monitoredConfig->outputs()) {
if (output->type() == KScreen::Output::Panel) {
if (output->isConnected() && output->isEnabled()) {
// Save the current config with opened lid, just so that we know
// how to restore it later
const QString configId = Serializer::configId(m_monitoredConfig) + QLatin1String("_lidOpened");
Serializer::saveConfig(m_monitoredConfig, configId);
disableOutput(m_monitoredConfig, output);
doApplyConfig(m_monitoredConfig);
return;
}
}
}
}
void KScreenDaemon::outputConnectedChanged()
{
if (!m_changeCompressor->isActive()) {
m_changeCompressor->start();
}
resetDisplaySwitch();
KScreen::Output *output = qobject_cast<KScreen::Output*>(sender());
qCDebug(KSCREEN_KDED) << "outputConnectedChanged():" << output->name();
if (output->isConnected()) {
Q_EMIT outputConnected(output->name());
if (!Serializer::configExists(m_monitoredConfig)) {
Q_EMIT unknownOutputConnected(output->name());
}
}
}
void KScreenDaemon::monitorConnectedChange()
{
KScreen::OutputList outputs = m_monitoredConfig->outputs();
Q_FOREACH(const KScreen::OutputPtr &output, outputs) {
connect(output.data(), &KScreen::Output::isConnectedChanged,
this, &KScreenDaemon::outputConnectedChanged,
Qt::UniqueConnection);
}
}
void KScreenDaemon::setMonitorForChanges(bool enabled)
{
if (m_monitoring == enabled) {
return;
}
qCDebug(KSCREEN_KDED) << "Monitor for changes: " << enabled;
m_monitoring = enabled;
if (m_monitoring) {
connect(KScreen::ConfigMonitor::instance(), &KScreen::ConfigMonitor::configurationChanged,
this, &KScreenDaemon::configChanged, Qt::UniqueConnection);
} else {
disconnect(KScreen::ConfigMonitor::instance(), &KScreen::ConfigMonitor::configurationChanged,
this, &KScreenDaemon::configChanged);
}
}
void KScreenDaemon::disableOutput(KScreen::ConfigPtr &config, KScreen::OutputPtr &output)
{
const QRect geom = output->geometry();
qCDebug(KSCREEN_KDED) << "Laptop geometry:" << geom << output->pos() << (output->currentMode() ? output->currentMode()->size() : QSize());
// Move all outputs right from the @p output to left
for (KScreen::OutputPtr &otherOutput : config->outputs()) {
if (otherOutput == output || !otherOutput->isConnected() || !otherOutput->isEnabled()) {
continue;
}
QPoint otherPos = otherOutput->pos();
if (otherPos.x() >= geom.right() && otherPos.y() >= geom.top() && otherPos.y() <= geom.bottom()) {
otherPos.setX(otherPos.x() - geom.width());
}
qCDebug(KSCREEN_KDED) << "Moving" << otherOutput->name() << "from" << otherOutput->pos() << "to" << otherPos;
otherOutput->setPos(otherPos);
}
// Disable the output
output->setEnabled(false);
}
KScreen::OutputPtr KScreenDaemon::findEmbeddedOutput(const KScreen::ConfigPtr &config)
{
Q_FOREACH (const KScreen::OutputPtr &output, config->outputs()) {
if (output->type() == KScreen::Output::Panel) {
return output;
}
}
return KScreen::OutputPtr();
}
#include "daemon.moc"
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkSTLThreadTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// On some old sgi compilers, this test gets into an infinite loop without the following
#if defined(__sgi) && COMPILER_VERSION <= 730
#define _PTHREADS
#endif
#include "itkMultiThreader.h"
#include <list>
namespace itkSTLThreadTestImpl
{
int done = 0;
int numberOfIterations = 10;
ITK_THREAD_RETURN_TYPE Runner(void*);
int Thread(int);
} // namespace itkSTLThreadTestImpl
int itkSTLThreadTest(int argc, char* argv[])
{
// Choose a number of threads.
int numThreads = 10;
if(argc > 1)
{
int nt = atoi(argv[1]);
if(nt > 1)
{
numThreads = nt;
}
}
// Choose a number of iterations (0 is infinite).
if(argc > 2)
{
int ni = atoi(argv[2]);
if(ni >= 0)
{
itkSTLThreadTestImpl::numberOfIterations = ni;
}
}
// Report what we'll do.
std::cout << "Using " << numThreads << " threads.\n";
if(itkSTLThreadTestImpl::numberOfIterations)
{
std::cout << "Using " << itkSTLThreadTestImpl::numberOfIterations
<< " iterations.\n";
}
else
{
std::cout << "Using infinite iterations.\n";
}
// Create result array. Assume failure.
int* results = new int[numThreads];
int i;
for(i=0; i < numThreads; ++i)
{
results[i] = 0;
}
// Create and execute the threads.
itk::MultiThreader::Pointer threader = itk::MultiThreader::New();
threader->SetSingleMethod(itkSTLThreadTestImpl::Runner, results);
threader->SetNumberOfThreads(numThreads);
threader->SingleMethodExecute();
// Report results.
int result = 0;
for(i=0; i < numThreads; ++i)
{
if(!results[i])
{
std::cerr << "Thread " << i << "failed." << std::endl;
result = 1;
}
}
delete [] results;
// Test other methods for coverage.
std::cout << "Done with primary test. Testing more methods..."
<< std::endl;
threader->SetGlobalMaximumNumberOfThreads(1);
threader->SetGlobalDefaultNumberOfThreads(1);
std::cout << "threader->GetGlobalMaximumNumberOfThreads(): "
<< threader->GetGlobalMaximumNumberOfThreads() << std::endl;
int threadId = threader->SpawnThread(itkSTLThreadTestImpl::Runner, 0);
std::cout << "SpawnThread(itkSTLThreadTestImpl::Runner, results): "
<< threadId << std::endl;
threader->TerminateThread(threadId);
std::cout << "Spawned thread terminated." << std::endl;
return result;
}
namespace itkSTLThreadTestImpl
{
ITK_THREAD_RETURN_TYPE Runner(void* infoIn)
{
// Get the thread id and result pointer and run the method for this
// thread.
itk::MultiThreader::ThreadInfoStruct* info =
static_cast<itk::MultiThreader::ThreadInfoStruct*>(infoIn);
int tnum = info->ThreadID;
int* results = static_cast<int*>(info->UserData);
if(results)
{
results[tnum] = itkSTLThreadTestImpl::Thread(tnum);
}
else
{
itkSTLThreadTestImpl::Thread(tnum);
}
#ifndef ITK_USE_SPROC
return 0;
#endif
}
int Thread(int tnum)
{
// Implementation in individual thread. We don't care about
// mutexing the output because it doesn't matter for the test.
std::cout << "Starting " << tnum << "\n";
// Create a list with which to play.
std::list<int> l;
// Choose a size for each iteration for this thread.
int count = 10000+100*tnum;
int iteration=0;
while(!done && !(numberOfIterations && (iteration >= numberOfIterations)))
{
// Output progress of this thread.
std::cout << tnum << ": " << iteration << "\n";
// Fill the list.
int j;
for(j=0; j < count; ++j)
{
l.push_back(j);
}
// Empty the list while making sure values match. Threading
// errors can cause mismatches here, which is the purpose of the
// test.
for(j=0; j < count; ++j)
{
if(l.front() != j)
{
std::cerr << "Mismatch in thread " << tnum << "!\n";
done = 1;
}
l.pop_front();
}
++iteration;
}
// Only get here on failure or iterations finished.
if(numberOfIterations && (iteration >= numberOfIterations))
{
// Success.
return 1;
}
else
{
// Failure.
return 0;
}
}
} // namespace itkSTLThreadTestImpl
<commit_msg>BUG: Fixed spacing in output.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkSTLThreadTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// On some old sgi compilers, this test gets into an infinite loop without the following
#if defined(__sgi) && COMPILER_VERSION <= 730
#define _PTHREADS
#endif
#include "itkMultiThreader.h"
#include <list>
namespace itkSTLThreadTestImpl
{
int done = 0;
int numberOfIterations = 10;
ITK_THREAD_RETURN_TYPE Runner(void*);
int Thread(int);
} // namespace itkSTLThreadTestImpl
int itkSTLThreadTest(int argc, char* argv[])
{
// Choose a number of threads.
int numThreads = 10;
if(argc > 1)
{
int nt = atoi(argv[1]);
if(nt > 1)
{
numThreads = nt;
}
}
// Choose a number of iterations (0 is infinite).
if(argc > 2)
{
int ni = atoi(argv[2]);
if(ni >= 0)
{
itkSTLThreadTestImpl::numberOfIterations = ni;
}
}
// Report what we'll do.
std::cout << "Using " << numThreads << " threads.\n";
if(itkSTLThreadTestImpl::numberOfIterations)
{
std::cout << "Using " << itkSTLThreadTestImpl::numberOfIterations
<< " iterations.\n";
}
else
{
std::cout << "Using infinite iterations.\n";
}
// Create result array. Assume failure.
int* results = new int[numThreads];
int i;
for(i=0; i < numThreads; ++i)
{
results[i] = 0;
}
// Create and execute the threads.
itk::MultiThreader::Pointer threader = itk::MultiThreader::New();
threader->SetSingleMethod(itkSTLThreadTestImpl::Runner, results);
threader->SetNumberOfThreads(numThreads);
threader->SingleMethodExecute();
// Report results.
int result = 0;
for(i=0; i < numThreads; ++i)
{
if(!results[i])
{
std::cerr << "Thread " << i << " failed." << std::endl;
result = 1;
}
}
delete [] results;
// Test other methods for coverage.
std::cout << "Done with primary test. Testing more methods..."
<< std::endl;
threader->SetGlobalMaximumNumberOfThreads(1);
threader->SetGlobalDefaultNumberOfThreads(1);
std::cout << "threader->GetGlobalMaximumNumberOfThreads(): "
<< threader->GetGlobalMaximumNumberOfThreads() << std::endl;
int threadId = threader->SpawnThread(itkSTLThreadTestImpl::Runner, 0);
std::cout << "SpawnThread(itkSTLThreadTestImpl::Runner, results): "
<< threadId << std::endl;
threader->TerminateThread(threadId);
std::cout << "Spawned thread terminated." << std::endl;
return result;
}
namespace itkSTLThreadTestImpl
{
ITK_THREAD_RETURN_TYPE Runner(void* infoIn)
{
// Get the thread id and result pointer and run the method for this
// thread.
itk::MultiThreader::ThreadInfoStruct* info =
static_cast<itk::MultiThreader::ThreadInfoStruct*>(infoIn);
int tnum = info->ThreadID;
int* results = static_cast<int*>(info->UserData);
if(results)
{
results[tnum] = itkSTLThreadTestImpl::Thread(tnum);
}
else
{
itkSTLThreadTestImpl::Thread(tnum);
}
#ifndef ITK_USE_SPROC
return 0;
#endif
}
int Thread(int tnum)
{
// Implementation in individual thread. We don't care about
// mutexing the output because it doesn't matter for the test.
std::cout << "Starting " << tnum << "\n";
// Create a list with which to play.
std::list<int> l;
// Choose a size for each iteration for this thread.
int count = 10000+100*tnum;
int iteration=0;
while(!done && !(numberOfIterations && (iteration >= numberOfIterations)))
{
// Output progress of this thread.
std::cout << tnum << ": " << iteration << "\n";
// Fill the list.
int j;
for(j=0; j < count; ++j)
{
l.push_back(j);
}
// Empty the list while making sure values match. Threading
// errors can cause mismatches here, which is the purpose of the
// test.
for(j=0; j < count; ++j)
{
if(l.front() != j)
{
std::cerr << "Mismatch in thread " << tnum << "!\n";
done = 1;
}
l.pop_front();
}
++iteration;
}
// Only get here on failure or iterations finished.
if(numberOfIterations && (iteration >= numberOfIterations))
{
// Success.
return 1;
}
else
{
// Failure.
return 0;
}
}
} // namespace itkSTLThreadTestImpl
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 <SimpleITKTestHarness.h>
#include <itkSliceImageFilter.h>
#include "itkPhysicalPointImageSource.h"
#include "itkGaussianImageSource.h"
#include "itkImageRegionConstIterator.h"
// This test verifies the principle that the SliceImageFilter should
// not change the physical location of the signal. This is done by
// constructing an image of points, each corresponding to the phycical
// location of the center of the voxel, then verifying that the value
// still matches the physcial location.
namespace
{
// This function checks that all values in an image are equivalent to
// the physical point of the image.
template <typename TImageType>
bool CheckValueIsPhysicalPoint( const TImageType *img )
{
typedef itk::ImageRegionConstIterator<TImageType> IteratorType;
IteratorType it(img, img->GetBufferedRegion() );
bool match = true;
typename TImageType::PointType pt;
img->TransformIndexToPhysicalPoint( it.GetIndex(), pt );
while( !it.IsAtEnd() )
{
for ( unsigned int i = 0; i < TImageType::ImageDimension; ++i )
{
img->TransformIndexToPhysicalPoint( it.GetIndex(), pt );
EXPECT_DOUBLE_EQ( pt[i], it.Get()[i] ) << "Index: " << it.GetIndex() << " Point: " << pt << " Value: " << it.Get() << std::endl, match = false;
}
++it;
}
return match;
}
template <typename TImageType>
typename TImageType::Pointer RunFilter( const TImageType *img,
typename TImageType::IndexType start,
typename TImageType::IndexType stop,
int step[TImageType::ImageDimension]
)
{
typedef itk::SliceImageFilter<TImageType, TImageType> FilterType;
typename FilterType::Pointer sliceFilter = FilterType::New();
sliceFilter->SetInput( img );
sliceFilter->SetStart( start );
sliceFilter->SetStop( stop );
sliceFilter->SetStep( step );
sliceFilter->UpdateLargestPossibleRegion();
return sliceFilter->GetOutput();
}
}
TEST(SliceImageFilterTests, PhysicalPoint1)
{
const unsigned int ImageDimension = 2;
typedef itk::Point<double, ImageDimension> PixelType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::PhysicalPointImageSource<ImageType> SourceType;
SourceType::Pointer source = SourceType::New();
// these size are chossen as a power of two and a prime number.
SourceType::SizeValueType size[] = {128,127};
source->SetSize( size );
float origin[] = {1.1, 2.22};
source->SetOrigin( origin );
int step[ImageDimension];
ImageType::IndexType start;
ImageType::IndexType stop;
stop[0] = size[0];
stop[1] = size[1];
for( start[0] = 0; start[0] < 10; ++start[0] )
for( start[1] = 0; start[1] < 10; ++start[1] )
for( step[0] = 1; step[0] < 10; ++step[0] )
for( step[1] = 1; step[1] < 10; ++step[1] )
{
ImageType::Pointer img;
img = RunFilter<ImageType>( source->GetOutput(), start, stop, step );
EXPECT_TRUE( CheckValueIsPhysicalPoint( img.GetPointer() ) ) << "== Failed - step:" << step[0] << " " << step[1] << " start: " <<start[0] << " " << start[1] << std::endl;
}
}
TEST(SliceImageFilterTests, PhysicalPoint2)
{
const unsigned int ImageDimension = 2;
typedef itk::Point<double, ImageDimension> PixelType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::PhysicalPointImageSource<ImageType> SourceType;
SourceType::Pointer source = SourceType::New();
// these size are chossen as a power of two and a prime number.
SourceType::SizeValueType size[] = {128,127};
source->SetSize( size );
float origin[] = {3.33, 4.4444};
source->SetOrigin( origin );
int step[ImageDimension] = {3,4};
ImageType::IndexType start;
ImageType::IndexType stop;
for( start[0] = 0; start[0] < 10; ++start[0] )
for( start[1] = 0; start[1] < 10; ++start[1] )
for( stop[0] = size[0]; stop[0] > size[0] - 10; --stop[0] )
for( stop[1] = size[1]; stop[1] > size[1] -10; --stop[1] )
{
ImageType::Pointer img;
img = RunFilter<ImageType>( source->GetOutput(), start, stop, step );
EXPECT_TRUE( CheckValueIsPhysicalPoint( img.GetPointer() ) ) << "== Failed - step:" << step[0] << " " << step[1] << " start: " <<start[0] << " " << start[1] << " stop: " << stop[0] << " " << stop[1] << std::endl;
}
}
TEST(SliceImageFilterTests, PhysicalPoint3)
{
const unsigned int ImageDimension = 2;
typedef itk::Point<double, ImageDimension> PixelType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::PhysicalPointImageSource<ImageType> SourceType;
SourceType::Pointer source = SourceType::New();
// these size are chossen as a power of two and a prime number.
SourceType::SizeValueType size[] = {16,17};
source->SetSize( size );
float origin[] = {3.33, 4.4444};
source->SetOrigin( origin );
int step[ImageDimension] = {-2,-2};
ImageType::IndexType start;
ImageType::IndexType stop;
for( start[0] = 10; start[0] < 20; ++start[0] )
for( start[1] = 10; start[1] < 20; ++start[1] )
for( stop[0] = -5; stop[0] > 12; --stop[0] )
for( stop[1] = -5; stop[1] > 12; --stop[1] )
{
ImageType::Pointer img;
img = RunFilter<ImageType>( source->GetOutput(), start, stop, step );
EXPECT_TRUE( CheckValueIsPhysicalPoint( img.GetPointer() ) ) << "== Failed - step:" << step[0] << " " << step[1] << " start: " <<start[0] << " " << start[1] << " stop: " << stop[0] << " " << stop[1] << std::endl;
}
}
TEST(SliceImageFilterTests,Empty)
{
const unsigned int ImageDimension = 2;
typedef itk::Point<double, ImageDimension> PixelType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::PhysicalPointImageSource<ImageType> SourceType;
SourceType::Pointer source = SourceType::New();
// these size are chossen as a power of two and a prime number.
SourceType::SizeValueType size[] = {32,32};
source->SetSize( size );
int step[ImageDimension] = {1,1};
ImageType::IndexType start;
start.Fill( 10 );
ImageType::IndexType stop;
stop.Fill( 10 );
ImageType::Pointer img;
img = RunFilter<ImageType>( source->GetOutput(), start, stop, step );
std::cout << img;
for( unsigned int i = 0; i < ImageDimension; ++i)
{
EXPECT_EQ( 0u, img->GetLargestPossibleRegion().GetSize()[i] );
}
start[0] = 2;
start[1] = 2;
stop[0] = 10;
stop[1] = 2;
img = RunFilter<ImageType>( source->GetOutput(), start, stop, step );
EXPECT_EQ( 8u, img->GetLargestPossibleRegion().GetSize()[0] );
EXPECT_EQ( 0u, img->GetLargestPossibleRegion().GetSize()[1] );
}
TEST(SliceImageFilterTests,Coverage)
{
const unsigned int ImageDimension = 3;
typedef itk::Image<float, ImageDimension> ImageType;
typedef itk::SliceImageFilter<ImageType, ImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
std::cout << filter;
FilterType::IndexType idx;
idx.Fill( 10 );
filter->SetStart(idx);
EXPECT_EQ( idx, filter->GetStart() );
idx.Fill(11);
filter->SetStart(11);
EXPECT_EQ( idx, filter->GetStart() );
idx.Fill(12);
filter->SetStop(idx);
EXPECT_EQ( idx, filter->GetStop() );
idx.Fill(13);
filter->SetStop(13);
EXPECT_EQ( idx, filter->GetStop() );
FilterType::ArrayType a;
a.Fill(14);
filter->SetStep(a);
EXPECT_EQ( a, filter->GetStep() );
a.Fill(15);
filter->SetStep(15);
EXPECT_EQ(a, filter->GetStep() );
}
TEST(SliceImageFilterTests,Sizes)
{
const unsigned int ImageDimension = 3;
typedef itk::Image<float, ImageDimension> ImageType;
typedef itk::GaussianImageSource<ImageType> SourceType;
SourceType::Pointer source = SourceType::New();
SourceType::SizeType size = {{64,64,64}};
source->SetSize(size);
source->ReleaseDataFlagOn();
typedef itk::SliceImageFilter<ImageType, ImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( source->GetOutput() );
// check with default start, stop, step
EXPECT_NO_THROW(filter->Update());
EXPECT_EQ(filter->GetOutput()->GetLargestPossibleRegion().GetSize(), size) << "Check full size for defaults";
filter = FilterType::New();
filter->SetInput( source->GetOutput() );
filter->SetStart( 64 );
filter->SetStop(-1);
filter->SetStep(-1);
EXPECT_NO_THROW(filter->Update());
EXPECT_EQ(filter->GetOutput()->GetLargestPossibleRegion().GetSize(), size) << "Check full size for negative step";
std::cout << "Filter size: " << filter->GetOutput()->GetLargestPossibleRegion() << std::endl;
std::cout << "Filter buffered size: " << filter->GetOutput()->GetBufferedRegion() << std::endl;
std::cout << "Input size: " << size << std::endl;
}
TEST(SliceImageFilterTests,ExceptionalCases)
{
const unsigned int ImageDimension = 3;
typedef itk::Image<float, ImageDimension> ImageType;
typedef itk::GaussianImageSource<ImageType> SourceType;
SourceType::Pointer source = SourceType::New();
typedef itk::SliceImageFilter<ImageType, ImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( source->GetOutput() );
filter->SetStep( 0 );
EXPECT_ANY_THROW( filter->Update() ) << "Check with 0 step";
// for some reason after the above exception, the pipeline is not
// clean, and Verify input information will not get executed again,
// so just create a new filter...
filter = FilterType::New();
filter->SetInput( source->GetOutput() );
filter->SetStart(10000);
filter->SetStop(10001);
EXPECT_NO_THROW( filter->Update() ) << "Check with over-sized start stop are clamped to zero";
EXPECT_EQ( 0u, filter->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() );
filter = FilterType::New();
filter->SetInput( source->GetOutput() );
filter->SetStart(12);
filter->SetStop(10);
EXPECT_NO_THROW( filter->Update() ) << "Check stop is clamped" ;
EXPECT_EQ( 0u, filter->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() );
filter = FilterType::New();
filter->SetInput( source->GetOutput() );
filter->SetStart(-12);
filter->SetStop(-10);
EXPECT_NO_THROW( filter->Update() ) << "Check undersized start and stop" ;
EXPECT_EQ( 0u, filter->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() );
filter = FilterType::New();
filter->SetInput( source->GetOutput() );
filter->SetStart(-12);
filter->SetStop(-10);
filter->SetStep(-1);
EXPECT_NO_THROW( filter->Update() ) << "Check undersized start and stop" ;
EXPECT_EQ( 0u, filter->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() );
}
<commit_msg>Fix warning in itkSlinceImageFilterTest with integer conversion<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 <SimpleITKTestHarness.h>
#include <itkSliceImageFilter.h>
#include "itkPhysicalPointImageSource.h"
#include "itkGaussianImageSource.h"
#include "itkImageRegionConstIterator.h"
// This test verifies the principle that the SliceImageFilter should
// not change the physical location of the signal. This is done by
// constructing an image of points, each corresponding to the phycical
// location of the center of the voxel, then verifying that the value
// still matches the physcial location.
namespace
{
// This function checks that all values in an image are equivalent to
// the physical point of the image.
template <typename TImageType>
bool CheckValueIsPhysicalPoint( const TImageType *img )
{
typedef itk::ImageRegionConstIterator<TImageType> IteratorType;
IteratorType it(img, img->GetBufferedRegion() );
bool match = true;
typename TImageType::PointType pt;
img->TransformIndexToPhysicalPoint( it.GetIndex(), pt );
while( !it.IsAtEnd() )
{
for ( unsigned int i = 0; i < TImageType::ImageDimension; ++i )
{
img->TransformIndexToPhysicalPoint( it.GetIndex(), pt );
EXPECT_DOUBLE_EQ( pt[i], it.Get()[i] ) << "Index: " << it.GetIndex() << " Point: " << pt << " Value: " << it.Get() << std::endl, match = false;
}
++it;
}
return match;
}
template <typename TImageType>
typename TImageType::Pointer RunFilter( const TImageType *img,
typename TImageType::IndexType start,
typename TImageType::IndexType stop,
int step[TImageType::ImageDimension]
)
{
typedef itk::SliceImageFilter<TImageType, TImageType> FilterType;
typename FilterType::Pointer sliceFilter = FilterType::New();
sliceFilter->SetInput( img );
sliceFilter->SetStart( start );
sliceFilter->SetStop( stop );
sliceFilter->SetStep( step );
sliceFilter->UpdateLargestPossibleRegion();
return sliceFilter->GetOutput();
}
}
TEST(SliceImageFilterTests, PhysicalPoint1)
{
const unsigned int ImageDimension = 2;
typedef itk::Point<double, ImageDimension> PixelType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::PhysicalPointImageSource<ImageType> SourceType;
SourceType::Pointer source = SourceType::New();
// these size are chossen as a power of two and a prime number.
SourceType::SizeValueType size[] = {128,127};
source->SetSize( size );
float origin[] = {1.1, 2.22};
source->SetOrigin( origin );
int step[ImageDimension];
ImageType::IndexType start;
ImageType::IndexType stop;
stop[0] = size[0];
stop[1] = size[1];
for( start[0] = 0; start[0] < 10; ++start[0] )
for( start[1] = 0; start[1] < 10; ++start[1] )
for( step[0] = 1; step[0] < 10; ++step[0] )
for( step[1] = 1; step[1] < 10; ++step[1] )
{
ImageType::Pointer img;
img = RunFilter<ImageType>( source->GetOutput(), start, stop, step );
EXPECT_TRUE( CheckValueIsPhysicalPoint( img.GetPointer() ) ) << "== Failed - step:" << step[0] << " " << step[1] << " start: " <<start[0] << " " << start[1] << std::endl;
}
}
TEST(SliceImageFilterTests, PhysicalPoint2)
{
const unsigned int ImageDimension = 2;
typedef itk::Point<double, ImageDimension> PixelType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::PhysicalPointImageSource<ImageType> SourceType;
SourceType::Pointer source = SourceType::New();
// these size are chossen as a power of two and a prime number.
SourceType::SizeValueType size[] = {128,127};
source->SetSize( size );
float origin[] = {3.33, 4.4444};
source->SetOrigin( origin );
int step[ImageDimension] = {3,4};
ImageType::IndexType start;
ImageType::IndexType stop;
ASSERT_TRUE(size[0] > 10);
ASSERT_TRUE(size[1] > 10);
for( start[0] = 0; start[0] < 10; ++start[0] )
for( start[1] = 0; start[1] < 10; ++start[1] )
for( stop[0] = size[0]; stop[0] > (size_t)(size[0] - 10); --stop[0] )
for( stop[1] = size[1]; stop[1] > (size_t)(size[1] -10); --stop[1] )
{
ImageType::Pointer img;
img = RunFilter<ImageType>( source->GetOutput(), start, stop, step );
EXPECT_TRUE( CheckValueIsPhysicalPoint( img.GetPointer() ) ) << "== Failed - step:" << step[0] << " " << step[1] << " start: " <<start[0] << " " << start[1] << " stop: " << stop[0] << " " << stop[1] << std::endl;
}
}
TEST(SliceImageFilterTests, PhysicalPoint3)
{
const unsigned int ImageDimension = 2;
typedef itk::Point<double, ImageDimension> PixelType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::PhysicalPointImageSource<ImageType> SourceType;
SourceType::Pointer source = SourceType::New();
// these size are chossen as a power of two and a prime number.
SourceType::SizeValueType size[] = {16,17};
source->SetSize( size );
float origin[] = {3.33, 4.4444};
source->SetOrigin( origin );
int step[ImageDimension] = {-2,-2};
ImageType::IndexType start;
ImageType::IndexType stop;
for( start[0] = 10; start[0] < 20; ++start[0] )
for( start[1] = 10; start[1] < 20; ++start[1] )
for( stop[0] = -5; stop[0] > 12; --stop[0] )
for( stop[1] = -5; stop[1] > 12; --stop[1] )
{
ImageType::Pointer img;
img = RunFilter<ImageType>( source->GetOutput(), start, stop, step );
EXPECT_TRUE( CheckValueIsPhysicalPoint( img.GetPointer() ) ) << "== Failed - step:" << step[0] << " " << step[1] << " start: " <<start[0] << " " << start[1] << " stop: " << stop[0] << " " << stop[1] << std::endl;
}
}
TEST(SliceImageFilterTests,Empty)
{
const unsigned int ImageDimension = 2;
typedef itk::Point<double, ImageDimension> PixelType;
typedef itk::Image<PixelType, ImageDimension> ImageType;
typedef itk::PhysicalPointImageSource<ImageType> SourceType;
SourceType::Pointer source = SourceType::New();
// these size are chossen as a power of two and a prime number.
SourceType::SizeValueType size[] = {32,32};
source->SetSize( size );
int step[ImageDimension] = {1,1};
ImageType::IndexType start;
start.Fill( 10 );
ImageType::IndexType stop;
stop.Fill( 10 );
ImageType::Pointer img;
img = RunFilter<ImageType>( source->GetOutput(), start, stop, step );
std::cout << img;
for( unsigned int i = 0; i < ImageDimension; ++i)
{
EXPECT_EQ( 0u, img->GetLargestPossibleRegion().GetSize()[i] );
}
start[0] = 2;
start[1] = 2;
stop[0] = 10;
stop[1] = 2;
img = RunFilter<ImageType>( source->GetOutput(), start, stop, step );
EXPECT_EQ( 8u, img->GetLargestPossibleRegion().GetSize()[0] );
EXPECT_EQ( 0u, img->GetLargestPossibleRegion().GetSize()[1] );
}
TEST(SliceImageFilterTests,Coverage)
{
const unsigned int ImageDimension = 3;
typedef itk::Image<float, ImageDimension> ImageType;
typedef itk::SliceImageFilter<ImageType, ImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
std::cout << filter;
FilterType::IndexType idx;
idx.Fill( 10 );
filter->SetStart(idx);
EXPECT_EQ( idx, filter->GetStart() );
idx.Fill(11);
filter->SetStart(11);
EXPECT_EQ( idx, filter->GetStart() );
idx.Fill(12);
filter->SetStop(idx);
EXPECT_EQ( idx, filter->GetStop() );
idx.Fill(13);
filter->SetStop(13);
EXPECT_EQ( idx, filter->GetStop() );
FilterType::ArrayType a;
a.Fill(14);
filter->SetStep(a);
EXPECT_EQ( a, filter->GetStep() );
a.Fill(15);
filter->SetStep(15);
EXPECT_EQ(a, filter->GetStep() );
}
TEST(SliceImageFilterTests,Sizes)
{
const unsigned int ImageDimension = 3;
typedef itk::Image<float, ImageDimension> ImageType;
typedef itk::GaussianImageSource<ImageType> SourceType;
SourceType::Pointer source = SourceType::New();
SourceType::SizeType size = {{64,64,64}};
source->SetSize(size);
source->ReleaseDataFlagOn();
typedef itk::SliceImageFilter<ImageType, ImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( source->GetOutput() );
// check with default start, stop, step
EXPECT_NO_THROW(filter->Update());
EXPECT_EQ(filter->GetOutput()->GetLargestPossibleRegion().GetSize(), size) << "Check full size for defaults";
filter = FilterType::New();
filter->SetInput( source->GetOutput() );
filter->SetStart( 64 );
filter->SetStop(-1);
filter->SetStep(-1);
EXPECT_NO_THROW(filter->Update());
EXPECT_EQ(filter->GetOutput()->GetLargestPossibleRegion().GetSize(), size) << "Check full size for negative step";
std::cout << "Filter size: " << filter->GetOutput()->GetLargestPossibleRegion() << std::endl;
std::cout << "Filter buffered size: " << filter->GetOutput()->GetBufferedRegion() << std::endl;
std::cout << "Input size: " << size << std::endl;
}
TEST(SliceImageFilterTests,ExceptionalCases)
{
const unsigned int ImageDimension = 3;
typedef itk::Image<float, ImageDimension> ImageType;
typedef itk::GaussianImageSource<ImageType> SourceType;
SourceType::Pointer source = SourceType::New();
typedef itk::SliceImageFilter<ImageType, ImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( source->GetOutput() );
filter->SetStep( 0 );
EXPECT_ANY_THROW( filter->Update() ) << "Check with 0 step";
// for some reason after the above exception, the pipeline is not
// clean, and Verify input information will not get executed again,
// so just create a new filter...
filter = FilterType::New();
filter->SetInput( source->GetOutput() );
filter->SetStart(10000);
filter->SetStop(10001);
EXPECT_NO_THROW( filter->Update() ) << "Check with over-sized start stop are clamped to zero";
EXPECT_EQ( 0u, filter->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() );
filter = FilterType::New();
filter->SetInput( source->GetOutput() );
filter->SetStart(12);
filter->SetStop(10);
EXPECT_NO_THROW( filter->Update() ) << "Check stop is clamped" ;
EXPECT_EQ( 0u, filter->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() );
filter = FilterType::New();
filter->SetInput( source->GetOutput() );
filter->SetStart(-12);
filter->SetStop(-10);
EXPECT_NO_THROW( filter->Update() ) << "Check undersized start and stop" ;
EXPECT_EQ( 0u, filter->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() );
filter = FilterType::New();
filter->SetInput( source->GetOutput() );
filter->SetStart(-12);
filter->SetStop(-10);
filter->SetStep(-1);
EXPECT_NO_THROW( filter->Update() ) << "Check undersized start and stop" ;
EXPECT_EQ( 0u, filter->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels() );
}
<|endoftext|>
|
<commit_before>/* $Id$ */
/* Copyright W. Bangerth, University of Heidelberg, 1998 */
#include <grid/tria_boundary_lib.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <grid/tria_accessor.h>
#include <cmath>
template <int dim>
HyperBallBoundary<dim>::HyperBallBoundary (const Point<dim> p,
const double radius) :
center(p), radius(radius)
{};
template <int dim>
Point<dim>
HyperBallBoundary<dim>::get_new_point_on_line (const typename Triangulation<dim>::line_iterator &line) const
{
Point<dim> middle = StraightBoundary<dim>::get_new_point_on_line (line);
middle -= center;
// project to boundary
middle *= radius / sqrt(middle.square());
middle += center;
return middle;
};
#if deal_II_dimension == 1
template <>
Point<1>
HyperBallBoundary<1>::
get_new_point_on_quad (const Triangulation<1>::quad_iterator &) const
{
Assert (false, ExcInternalError());
return Point<1>();
};
#endif
template <int dim>
Point<dim>
HyperBallBoundary<dim>::
get_new_point_on_quad (const typename Triangulation<dim>::quad_iterator &quad) const
{
Point<dim> middle = StraightBoundary<dim>::get_new_point_on_quad (quad);
middle -= center;
// project to boundary
middle *= radius / sqrt(middle.square());
middle += center;
return middle;
};
template <int dim>
HalfHyperBallBoundary<dim>::HalfHyperBallBoundary (const Point<dim> center,
const double radius) :
HyperBallBoundary<dim> (center, radius)
{};
template <int dim>
Point<dim>
HalfHyperBallBoundary<dim>::
get_new_point_on_line (const typename Triangulation<dim>::line_iterator &line) const
{
const Point<dim> line_center = line->center();
if (line_center(0) == center(0))
return line_center;
else
return HyperBallBoundary<dim>::get_new_point_on_line (line);
};
template <int dim>
Point<dim>
HalfHyperBallBoundary<dim>::
get_new_point_on_quad (const typename Triangulation<dim>::quad_iterator &quad) const
{
const Point<dim> quad_center = quad->center();
if (quad_center(0) == center(0))
return quad_center;
else
return HyperBallBoundary<dim>::get_new_point_on_quad (quad);
};
template <int dim>
HyperShellBoundary<dim>::HyperShellBoundary (const Point<dim> ¢er) :
center (center)
{};
template <int dim>
Point<dim>
HyperShellBoundary<dim>::
get_new_point_on_line (const typename Triangulation<dim>::line_iterator &line) const
{
const Point<dim> middle = StraightBoundary<dim>::get_new_point_on_line (line);
// compute the position of the points relative to the origin
const Point<dim> middle_relative = middle - center,
vertex_relative = line->vertex(0) - center;
// take vertex(0) to gauge the
// radius corresponding to the line
// under consideration
const double radius = sqrt(vertex_relative.square());
// scale and shift back to the
// original coordinate system
return (middle_relative * (radius / sqrt(middle_relative.square()))) + center;
};
#if deal_II_dimension == 1
template <>
Point<1>
HyperShellBoundary<1>::
get_new_point_on_quad (const Triangulation<1>::quad_iterator &) const
{
Assert (false, ExcInternalError());
return Point<1>();
};
#endif
template <int dim>
Point<dim>
HyperShellBoundary<dim>::
get_new_point_on_quad (const typename Triangulation<dim>::quad_iterator &quad) const
{
const Point<dim> middle = StraightBoundary<dim>::get_new_point_on_quad (quad);
// compute the position of the points relative to the origin
const Point<dim> middle_relative = middle - center,
vertex_relative = quad->vertex(0) - center;
// take vertex(0) to gauge the
// radius corresponding to the line
// under consideration
const double radius = sqrt(vertex_relative.square());
// scale and shift back to the
// original coordinate system
return (middle_relative * (radius / sqrt(middle_relative.square()))) + center;
};
// explicit instantiations
template class HyperBallBoundary<deal_II_dimension>;
template class HalfHyperBallBoundary<deal_II_dimension>;
template class HyperShellBoundary<deal_II_dimension>;
<commit_msg>Make this thing compilable in 1d.<commit_after>/* $Id$ */
/* Copyright W. Bangerth, University of Heidelberg, 1998 */
#include <grid/tria_boundary_lib.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <grid/tria_accessor.h>
#include <cmath>
template <int dim>
HyperBallBoundary<dim>::HyperBallBoundary (const Point<dim> p,
const double radius) :
center(p), radius(radius)
{};
template <int dim>
Point<dim>
HyperBallBoundary<dim>::get_new_point_on_line (const typename Triangulation<dim>::line_iterator &line) const
{
Point<dim> middle = StraightBoundary<dim>::get_new_point_on_line (line);
middle -= center;
// project to boundary
middle *= radius / sqrt(middle.square());
middle += center;
return middle;
};
#if deal_II_dimension == 1
template <>
Point<1>
HyperBallBoundary<1>::
get_new_point_on_quad (const Triangulation<1>::quad_iterator &) const
{
Assert (false, ExcInternalError());
return Point<1>();
};
#endif
template <int dim>
Point<dim>
HyperBallBoundary<dim>::
get_new_point_on_quad (const typename Triangulation<dim>::quad_iterator &quad) const
{
Point<dim> middle = StraightBoundary<dim>::get_new_point_on_quad (quad);
middle -= center;
// project to boundary
middle *= radius / sqrt(middle.square());
middle += center;
return middle;
};
template <int dim>
HalfHyperBallBoundary<dim>::HalfHyperBallBoundary (const Point<dim> center,
const double radius) :
HyperBallBoundary<dim> (center, radius)
{};
template <int dim>
Point<dim>
HalfHyperBallBoundary<dim>::
get_new_point_on_line (const typename Triangulation<dim>::line_iterator &line) const
{
const Point<dim> line_center = line->center();
if (line_center(0) == center(0))
return line_center;
else
return HyperBallBoundary<dim>::get_new_point_on_line (line);
};
#if deal_II_dimension == 1
template <>
Point<1>
HalfHyperBallBoundary<1>::
get_new_point_on_quad (const typename Triangulation<1>::quad_iterator &) const
{
Assert (false, ExcInternalError());
return Point<1>();
};
#endif
template <int dim>
Point<dim>
HalfHyperBallBoundary<dim>::
get_new_point_on_quad (const typename Triangulation<dim>::quad_iterator &quad) const
{
const Point<dim> quad_center = quad->center();
if (quad_center(0) == center(0))
return quad_center;
else
return HyperBallBoundary<dim>::get_new_point_on_quad (quad);
};
template <int dim>
HyperShellBoundary<dim>::HyperShellBoundary (const Point<dim> ¢er) :
center (center)
{};
template <int dim>
Point<dim>
HyperShellBoundary<dim>::
get_new_point_on_line (const typename Triangulation<dim>::line_iterator &line) const
{
const Point<dim> middle = StraightBoundary<dim>::get_new_point_on_line (line);
// compute the position of the points relative to the origin
const Point<dim> middle_relative = middle - center,
vertex_relative = line->vertex(0) - center;
// take vertex(0) to gauge the
// radius corresponding to the line
// under consideration
const double radius = sqrt(vertex_relative.square());
// scale and shift back to the
// original coordinate system
return (middle_relative * (radius / sqrt(middle_relative.square()))) + center;
};
#if deal_II_dimension == 1
template <>
Point<1>
HyperShellBoundary<1>::
get_new_point_on_quad (const Triangulation<1>::quad_iterator &) const
{
Assert (false, ExcInternalError());
return Point<1>();
};
#endif
template <int dim>
Point<dim>
HyperShellBoundary<dim>::
get_new_point_on_quad (const typename Triangulation<dim>::quad_iterator &quad) const
{
const Point<dim> middle = StraightBoundary<dim>::get_new_point_on_quad (quad);
// compute the position of the points relative to the origin
const Point<dim> middle_relative = middle - center,
vertex_relative = quad->vertex(0) - center;
// take vertex(0) to gauge the
// radius corresponding to the line
// under consideration
const double radius = sqrt(vertex_relative.square());
// scale and shift back to the
// original coordinate system
return (middle_relative * (radius / sqrt(middle_relative.square()))) + center;
};
// explicit instantiations
template class HyperBallBoundary<deal_II_dimension>;
template class HalfHyperBallBoundary<deal_II_dimension>;
template class HyperShellBoundary<deal_II_dimension>;
<|endoftext|>
|
<commit_before><?hh //strict
// Inspired from: www.idontplaydarts.com https://www.idontplaydarts.com/static/ga.php_.txt
class Google_Authenticator {
public static ImmMap<string, int> $Characters = ImmMap {
'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3,
'E' => 4, 'F' => 5, 'G' => 6, 'H' => 7,
'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11,
'M' => 12, 'N' => 13, 'O' => 14, 'P' => 15,
'Q' => 16, 'R' => 17, 'S' => 18, 'T' => 19,
'U' => 20, 'V' => 21, 'W' => 22, 'X' => 23,
'Y' => 24, 'Z' => 25, '2' => 26, '3' => 27,
'4' => 28, '5' => 29, '6' => 30, '7' => 31
};
public string $Secret;
public string $RawSecret;
public function __construct(string $Secret) {
$Secret = strtoupper($Secret);
if (!preg_match('/^[A-Z2-7]+$/', $Secret)) {
throw new InvalidArgumentException('Invalid Secret provided');
}
$Length = strlen($Secret);
$this->RawSecret = $Secret;
$this->Secret = '';
$A = 0;
$B = 0;
for($i = 0; $i < $Length; ++$i) {
$A = ($A << 5) + static::$Characters[$Secret[$i]];
if (($B += 5) >= 8) {
$B -= 8;
$this->Secret .= chr(($A & (0xFF << $B)) >> $B);
}
}
if (strlen($this->Secret) < 8) {
throw new Exception('Secret is too short');
}
}
public function generate(?float $Time = null): string {
if ($Time === null) {
$Time = floor(microtime(true) / 30);
}
$Time = pack('N*', 0) . pack('N*', $Time);
$Hash = hash_hmac('sha1', $Time, $this->Secret, true);
$HashOffset = ord($Hash[19]) & 0xf;
$Hash = (
((ord($Hash[$HashOffset+0]) & 0x7f) << 24 ) |
((ord($Hash[$HashOffset+1]) & 0xff) << 16 ) |
((ord($Hash[$HashOffset+2]) & 0xff) << 8 ) |
(ord($Hash[$HashOffset+3]) & 0xff)
) % pow(10, 6);
return str_pad($Hash, 6, '0', STR_PAD_LEFT);
}
// Note: apt-get install qrencode
public function generateQRCode(string $Title, int $Size = 5): string {
return shell_exec('qrencode '.escapeshellarg('otpauth://totp/'.$Title.'?secret='.$this->RawSecret). ' -o - -s '.$Size);
}
public function verify(string $Key): bool {
return $this->generate() === $Key;
}
<<__Memoize>>
public static function getInstance(string $Secret): Google_Authenticator {
return new Google_Authenticator($Secret);
}
}
<commit_msg>:bug: Fix space/tab issues<commit_after><?hh //strict
// Inspired from: www.idontplaydarts.com https://www.idontplaydarts.com/static/ga.php_.txt
class Google_Authenticator {
public static ImmMap<string, int> $Characters = ImmMap {
'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3,
'E' => 4, 'F' => 5, 'G' => 6, 'H' => 7,
'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11,
'M' => 12, 'N' => 13, 'O' => 14, 'P' => 15,
'Q' => 16, 'R' => 17, 'S' => 18, 'T' => 19,
'U' => 20, 'V' => 21, 'W' => 22, 'X' => 23,
'Y' => 24, 'Z' => 25, '2' => 26, '3' => 27,
'4' => 28, '5' => 29, '6' => 30, '7' => 31
};
public string $Secret;
public string $RawSecret;
public function __construct(string $Secret) {
$Secret = strtoupper($Secret);
if (!preg_match('/^[A-Z2-7]+$/', $Secret)) {
throw new InvalidArgumentException('Invalid Secret provided');
}
$Length = strlen($Secret);
$this->RawSecret = $Secret;
$this->Secret = '';
$A = 0;
$B = 0;
for($i = 0; $i < $Length; ++$i) {
$A = ($A << 5) + static::$Characters[$Secret[$i]];
if (($B += 5) >= 8) {
$B -= 8;
$this->Secret .= chr(($A & (0xFF << $B)) >> $B);
}
}
if (strlen($this->Secret) < 8) {
throw new Exception('Secret is too short');
}
}
public function generate(?float $Time = null): string {
if ($Time === null) {
$Time = floor(microtime(true) / 30);
}
$Time = pack('N*', 0) . pack('N*', $Time);
$Hash = hash_hmac('sha1', $Time, $this->Secret, true);
$HashOffset = ord($Hash[19]) & 0xf;
$Hash = (
((ord($Hash[$HashOffset+0]) & 0x7f) << 24 ) |
((ord($Hash[$HashOffset+1]) & 0xff) << 16 ) |
((ord($Hash[$HashOffset+2]) & 0xff) << 8 ) |
(ord($Hash[$HashOffset+3]) & 0xff)
) % pow(10, 6);
return str_pad($Hash, 6, '0', STR_PAD_LEFT);
}
// Note: apt-get install qrencode
public function generateQRCode(string $Title, int $Size = 5): string {
return shell_exec('qrencode '.escapeshellarg('otpauth://totp/'.$Title.'?secret='.$this->RawSecret). ' -o - -s '.$Size);
}
public function verify(string $Key): bool {
return $this->generate() === $Key;
}
<<__Memoize>>
public static function getInstance(string $Secret): Google_Authenticator {
return new Google_Authenticator($Secret);
}
}
<|endoftext|>
|
<commit_before>#include <array.h>
#include <drivers/vga.hpp>
#include <kernel/cpu/gdt.hpp>
#include <kernel/cpu/idt.hpp>
#include <kernel/vfs/vfs.hpp>
#include <kernel/vfs/file.hpp>
#include <kernel/vfs/ramfs.hpp>
#include <kernel/boot/boot.hpp>
#include <kernel/cpu/reboot.hpp>
#include <kernel/cpp_support.hpp>
#include <kernel/memory/memory.hpp>
#include <kernel/console/logger.hpp>
#include <kernel/console/console.hpp>
#include <kernel/scheduler/process.hpp>
utils::array<char, 2048> user_stack;
#define switch_to_user() \
asm volatile( \
"pushl %0;" \
"pushl %2;" \
"pushl $0x0;" \
"pushl %1;" \
"push $1f;" \
"iret;" \
"1:" \
"mov %0, %%eax;" \
"mov %%ax, %%ds;" \
"mov %%ax, %%es;" \
"mov %%ax, %%fs;" \
"mov %%ax, %%gs;" \
:: "i" (cpu::segment::user_ds), \
"i" (cpu::segment::user_cs), \
"r" (&user_stack[2048]) \
)
void print_info() {
console::cout << "Bootloader name: " << boot::bootloader_name << "\n";
console::cout << "Boot command-line: " << boot::cmdline << "\n";
console::cout << "Upper mem: " << (int)(boot::upper_mem / 1024) << "MiB\n";
console::cout << "Allocator: " << (uint32_t)(memory::__end) << "\n";
console::cout << "Page tables: " << (int)memory::paging::page_tables_number << "\n";
for (auto i = 0u; boot::modules[i].end != 0; ++i) {
console::cout << "Module: " << boot::modules[i].name << " @ " << boot::modules[i].start << " - " << boot::modules[i].end << "\n";
console::cout << "Module content: " << (char *)memory::virt_address(boot::modules[0].start);
}
console::cout << "\nHello World!\n";
}
asmlinkage __noreturn void main() {
memory::initialize();
cpp_support::initialize();
cpu::gdt::initialize();
cpu::idt::initialize();
scheduler::initialize();
drivers::vga::initialize();
console::initialize(drivers::vga::print);
ramfs::ramfs ramfs;
vfs::initialize(ramfs);
print_info();
switch_to_user();
while (1);
}
<commit_msg>Make switch_to_user a function<commit_after>#include <array.h>
#include <drivers/vga.hpp>
#include <kernel/cpu/gdt.hpp>
#include <kernel/cpu/idt.hpp>
#include <kernel/vfs/vfs.hpp>
#include <kernel/vfs/file.hpp>
#include <kernel/vfs/ramfs.hpp>
#include <kernel/boot/boot.hpp>
#include <kernel/cpu/reboot.hpp>
#include <kernel/cpp_support.hpp>
#include <kernel/memory/memory.hpp>
#include <kernel/console/logger.hpp>
#include <kernel/console/console.hpp>
#include <kernel/scheduler/process.hpp>
utils::array<char, 2048> user_stack;
void switch_to_user() {
asm volatile(R"(
pushl %0
pushl %2
pushl $0x0
pushl %1
push $1f
iret
1:
mov %0, %%eax
mov %%ax, %%ds
mov %%ax, %%es
mov %%ax, %%fs
mov %%ax, %%gs)"
:: "i" (cpu::segment::user_ds),
"i" (cpu::segment::user_cs),
"r" (&user_stack[2048])
);
}
void print_info() {
console::cout << "Bootloader name: " << boot::bootloader_name << "\n";
console::cout << "Boot command-line: " << boot::cmdline << "\n";
console::cout << "Upper mem: " << (int)(boot::upper_mem / 1024) << "MiB\n";
console::cout << "Allocator: " << (uint32_t)(memory::__end) << "\n";
console::cout << "Page tables: " << (int)memory::paging::page_tables_number << "\n";
for (auto i = 0u; boot::modules[i].end != 0; ++i) {
console::cout << "Module: " << boot::modules[i].name << " @ " << boot::modules[i].start << " - " << boot::modules[i].end << "\n";
console::cout << "Module content: " << (char *)memory::virt_address(boot::modules[0].start);
}
console::cout << "\nHello World!\n";
}
asmlinkage void main() {
memory::initialize();
cpp_support::initialize();
cpu::gdt::initialize();
cpu::idt::initialize();
scheduler::initialize();
drivers::vga::initialize();
console::initialize(drivers::vga::print);
ramfs::ramfs ramfs;
vfs::initialize(ramfs);
print_info();
switch_to_user();
while (1);
}
<|endoftext|>
|
<commit_before>/***********************************************************************************************************************
* SimpleTest.cpp
*
* Created on: Mar 24, 2011
* Author: Dimitar Asenov
**********************************************************************************************************************/
#include "custommethodcall.h"
#include "SelfTest/headers/SelfTestSuite.h"
#include "CustomVisualization.h"
#include "OOModel/headers/allOOModelNodes.h"
#include "VisualizationBase/headers/node_extensions/Position.h"
#include "VisualizationBase/headers/Scene.h"
#include "VisualizationBase/headers/views/MainView.h"
using namespace OOModel;
using namespace Visualization;
namespace CustomMethodCall {
Class* addCollection(Model::Model* model, Project* parent)
{
Class* col = NULL;
if (!parent) col = dynamic_cast<Class*> (model->createRoot("Class"));
model->beginModification(parent ? static_cast<Model::Node*> (parent) :col, "Adding a collection class.");
if (!col) col = parent->classes()->append<Class>();
col->setName("Collection");
col->setVisibility(Visibility::PUBLIC);
Method* find = col->methods()->append<Method>();
find->setName("find");
find->extension<CustomVisualization>()->setVisName("FindMethodVis");
FormalArgument* findArg = find->arguments()->append<FormalArgument>();
findArg->setType<PrimitiveType>()->setType(PrimitiveType::INT);
findArg->setName("x");
find->results()->append<FormalResult>()->setType<PrimitiveType>()->setType(PrimitiveType::INT);
Method* insert = col->methods()->append<Method>();
insert->setName("insert");
insert->extension<CustomVisualization>()->setVisName("InsertMethodVis");
insert->extension<Position>()->setY(100);
FormalArgument* insertArg = insert->arguments()->append<FormalArgument>();
insertArg->setType<PrimitiveType>()->setType(PrimitiveType::INT);
insertArg->setName("x");
Method* empty = col->methods()->append<Method>();
empty->setName("empty");
empty->extension<CustomVisualization>()->setVisName("EmptyMethodVis");
empty->extension<Position>()->setY(200);
empty->results()->append<FormalResult>()->setType<PrimitiveType>()->setType(PrimitiveType::BOOLEAN);
Method* exists = col->methods()->append<Method>();
exists->setName(QChar(0x2203));
exists->extension<CustomVisualization>()->setVisName("ExistsMethodVis");
exists->extension<Position>()->setY(300);
FormalArgument* existsArg = exists->arguments()->append<FormalArgument>();
existsArg->setType<PrimitiveType>()->setType(PrimitiveType::INT);
existsArg->setName("x");
exists->results()->append<FormalResult>()->setType<PrimitiveType>()->setType(PrimitiveType::BOOLEAN);
Method* sum = col->methods()->append<Method>();
sum->setName("sum");
sum->extension<CustomVisualization>()->setVisName("SumMethodVis");
sum->extension<Position>()->setY(400);
FormalArgument* sumArgFrom = sum->arguments()->append<FormalArgument>();
sumArgFrom->setType<PrimitiveType>()->setType(PrimitiveType::INT);
sumArgFrom->setName("from");
FormalArgument* sumArgTo = sum->arguments()->append<FormalArgument>();
sumArgTo->setType<PrimitiveType>()->setType(PrimitiveType::INT);
sumArgTo->setName("to");
sum->results()->append<FormalResult>()->setType<PrimitiveType>()->setType(PrimitiveType::INT);
Method* test = col->methods()->append<Method>();
test->setName("test");
test->extension<Position>()->setX(300);
IfStatement* ifs = test->items()->append<IfStatement>();
BinaryOperation* orIf = ifs->setCondition<BinaryOperation>();
orIf->setOp(BinaryOperation::CONDITIONAL_OR);
MethodCallExpression* emptyCall = orIf->setLeft<MethodCallExpression>();
emptyCall->ref()->set("method:empty");
UnaryOperation* negation = orIf->setRight<UnaryOperation>();
negation->setOp(UnaryOperation::NOT);
MethodCallExpression* existsCall = negation->setOperand<MethodCallExpression>();
existsCall->ref()->set(QString("method:%1").arg(QChar(0x2203)));
existsCall->arguments()->append<IntegerLiteral>()->setValue(42);
MethodCallStatement* insertCall = ifs->thenBranch()->append<MethodCallStatement>();
insertCall->ref()->set("method:insert");
insertCall->arguments()->append<IntegerLiteral>()->setValue(42);
VariableDeclaration* indexVar = test->items()->append<VariableDeclaration>();
indexVar->setName("index");
indexVar->setType<PrimitiveType>()->setType(PrimitiveType::INT);
MethodCallExpression* findCall = indexVar->setInitialValue<MethodCallExpression>();
findCall->ref()->set("method:find");
findCall->arguments()->append<IntegerLiteral>()->setValue(42);
MethodCallExpression* sumCall = test->items()->append<ReturnStatement>()->values()->append<MethodCallExpression>();
sumCall->ref()->set("method:sum");
sumCall->arguments()->append<IntegerLiteral>()->setValue(0);
sumCall->arguments()->append<VariableAccess>()->ref()->set("local:index");
model->endModification();
return col;
}
TEST(CustomMethodCall, CustomVisTest)
{
Scene* scene = new Scene();
////////////////////////////////////////////////// Create Model
Model::Model* model = new Model::Model();
Class* collection = NULL;
collection = addCollection(model, NULL);
////////////////////////////////////////////////// Set Scene
Model::Node* top_level = NULL;
if(collection) top_level = collection;
scene->addTopLevelItem( scene->defaultRenderer()->render(NULL, top_level) );
scene->scheduleUpdate();
scene->listenToModel(model);
// Create view
MainView* view = new MainView(scene);
CHECK_CONDITION(view != NULL);
}
}
<commit_msg>FIXED: The example test method did not have a return type.<commit_after>/***********************************************************************************************************************
* SimpleTest.cpp
*
* Created on: Mar 24, 2011
* Author: Dimitar Asenov
**********************************************************************************************************************/
#include "custommethodcall.h"
#include "SelfTest/headers/SelfTestSuite.h"
#include "CustomVisualization.h"
#include "OOModel/headers/allOOModelNodes.h"
#include "VisualizationBase/headers/node_extensions/Position.h"
#include "VisualizationBase/headers/Scene.h"
#include "VisualizationBase/headers/views/MainView.h"
using namespace OOModel;
using namespace Visualization;
namespace CustomMethodCall {
Class* addCollection(Model::Model* model, Project* parent)
{
Class* col = NULL;
if (!parent) col = dynamic_cast<Class*> (model->createRoot("Class"));
model->beginModification(parent ? static_cast<Model::Node*> (parent) :col, "Adding a collection class.");
if (!col) col = parent->classes()->append<Class>();
col->setName("Collection");
col->setVisibility(Visibility::PUBLIC);
Method* find = col->methods()->append<Method>();
find->setName("find");
find->extension<CustomVisualization>()->setVisName("FindMethodVis");
FormalArgument* findArg = find->arguments()->append<FormalArgument>();
findArg->setType<PrimitiveType>()->setType(PrimitiveType::INT);
findArg->setName("x");
find->results()->append<FormalResult>()->setType<PrimitiveType>()->setType(PrimitiveType::INT);
Method* insert = col->methods()->append<Method>();
insert->setName("insert");
insert->extension<CustomVisualization>()->setVisName("InsertMethodVis");
insert->extension<Position>()->setY(100);
FormalArgument* insertArg = insert->arguments()->append<FormalArgument>();
insertArg->setType<PrimitiveType>()->setType(PrimitiveType::INT);
insertArg->setName("x");
Method* empty = col->methods()->append<Method>();
empty->setName("empty");
empty->extension<CustomVisualization>()->setVisName("EmptyMethodVis");
empty->extension<Position>()->setY(200);
empty->results()->append<FormalResult>()->setType<PrimitiveType>()->setType(PrimitiveType::BOOLEAN);
Method* exists = col->methods()->append<Method>();
exists->setName(QChar(0x2203));
exists->extension<CustomVisualization>()->setVisName("ExistsMethodVis");
exists->extension<Position>()->setY(300);
FormalArgument* existsArg = exists->arguments()->append<FormalArgument>();
existsArg->setType<PrimitiveType>()->setType(PrimitiveType::INT);
existsArg->setName("x");
exists->results()->append<FormalResult>()->setType<PrimitiveType>()->setType(PrimitiveType::BOOLEAN);
Method* sum = col->methods()->append<Method>();
sum->setName("sum");
sum->extension<CustomVisualization>()->setVisName("SumMethodVis");
sum->extension<Position>()->setY(400);
FormalArgument* sumArgFrom = sum->arguments()->append<FormalArgument>();
sumArgFrom->setType<PrimitiveType>()->setType(PrimitiveType::INT);
sumArgFrom->setName("from");
FormalArgument* sumArgTo = sum->arguments()->append<FormalArgument>();
sumArgTo->setType<PrimitiveType>()->setType(PrimitiveType::INT);
sumArgTo->setName("to");
sum->results()->append<FormalResult>()->setType<PrimitiveType>()->setType(PrimitiveType::INT);
Method* test = col->methods()->append<Method>();
test->setName("test");
test->extension<Position>()->setX(300);
IfStatement* ifs = test->items()->append<IfStatement>();
BinaryOperation* orIf = ifs->setCondition<BinaryOperation>();
orIf->setOp(BinaryOperation::CONDITIONAL_OR);
MethodCallExpression* emptyCall = orIf->setLeft<MethodCallExpression>();
emptyCall->ref()->set("method:empty");
UnaryOperation* negation = orIf->setRight<UnaryOperation>();
negation->setOp(UnaryOperation::NOT);
MethodCallExpression* existsCall = negation->setOperand<MethodCallExpression>();
existsCall->ref()->set(QString("method:%1").arg(QChar(0x2203)));
existsCall->arguments()->append<IntegerLiteral>()->setValue(42);
MethodCallStatement* insertCall = ifs->thenBranch()->append<MethodCallStatement>();
insertCall->ref()->set("method:insert");
insertCall->arguments()->append<IntegerLiteral>()->setValue(42);
VariableDeclaration* indexVar = test->items()->append<VariableDeclaration>();
indexVar->setName("index");
indexVar->setType<PrimitiveType>()->setType(PrimitiveType::INT);
MethodCallExpression* findCall = indexVar->setInitialValue<MethodCallExpression>();
findCall->ref()->set("method:find");
findCall->arguments()->append<IntegerLiteral>()->setValue(42);
MethodCallExpression* sumCall = test->items()->append<ReturnStatement>()->values()->append<MethodCallExpression>();
sumCall->ref()->set("method:sum");
sumCall->arguments()->append<IntegerLiteral>()->setValue(0);
sumCall->arguments()->append<VariableAccess>()->ref()->set("local:index");
test->results()->append<FormalResult>()->setType<PrimitiveType>()->setType(PrimitiveType::INT);
model->endModification();
return col;
}
TEST(CustomMethodCall, CustomVisTest)
{
Scene* scene = new Scene();
////////////////////////////////////////////////// Create Model
Model::Model* model = new Model::Model();
Class* collection = NULL;
collection = addCollection(model, NULL);
////////////////////////////////////////////////// Set Scene
Model::Node* top_level = NULL;
if(collection) top_level = collection;
scene->addTopLevelItem( scene->defaultRenderer()->render(NULL, top_level) );
scene->scheduleUpdate();
scene->listenToModel(model);
// Create view
MainView* view = new MainView(scene);
CHECK_CONDITION(view != NULL);
}
}
<|endoftext|>
|
<commit_before>#include <osgTerrain/TerrainTile>
#include <osgDB/ObjectWrapper>
#include <osgDB/InputStream>
#include <osgDB/OutputStream>
// _tileID
static bool checkTileID( const osgTerrain::TerrainTile& tile )
{
return tile.getTileID().valid();
}
static bool readTileID( osgDB::InputStream& is, osgTerrain::TerrainTile& tile )
{
osgTerrain::TileID id;
is >> id.level >> id.x >> id.y;
tile.setTileID( id );
return true;
}
static bool writeTileID( osgDB::OutputStream& os, const osgTerrain::TerrainTile& tile )
{
const osgTerrain::TileID& id = tile.getTileID();
os << id.level << id.x << id.y << std::endl;
return true;
}
// _colorLayers
static bool checkColorLayers( const osgTerrain::TerrainTile& tile )
{
return tile.getNumColorLayers()>0;
}
static bool readColorLayers( osgDB::InputStream& is, osgTerrain::TerrainTile& tile )
{
unsigned int numValidLayers = 0; is >> numValidLayers >> osgDB::BEGIN_BRACKET;
for ( unsigned int i=0; i<numValidLayers; ++i )
{
unsigned int layerNum=0; is >> osgDB::PROPERTY("Layer") >> layerNum;
osgTerrain::Layer* layer = dynamic_cast<osgTerrain::Layer*>( is.readObject() );
if ( layer ) tile.setColorLayer( layerNum, layer );
}
is >> osgDB::END_BRACKET;
return true;
}
static bool writeColorLayers( osgDB::OutputStream& os, const osgTerrain::TerrainTile& tile )
{
unsigned int numValidLayers = 0;
for ( unsigned int i=0; i<tile.getNumColorLayers(); ++i )
{
if (tile.getColorLayer(i)) ++numValidLayers;
}
os << numValidLayers << osgDB::BEGIN_BRACKET << std::endl;
for ( unsigned int i=0; i<tile.getNumColorLayers(); ++i )
{
if (tile.getColorLayer(i)) os << osgDB::PROPERTY("Layer") << i << tile.getColorLayer(i);
}
os << osgDB::END_BRACKET << std::endl;
return true;
}
// TileLoadedCallback
static bool checkTileLoadedCallback( const osgTerrain::TerrainTile& tile )
{ return true; }
static bool readTileLoadedCallback( osgDB::InputStream& is, osgTerrain::TerrainTile& tile )
{
if ( osgTerrain::TerrainTile::getTileLoadedCallback().valid() )
osgTerrain::TerrainTile::getTileLoadedCallback()->loaded( &tile, is.getOptions() );
return true;
}
static bool writeTileLoadedCallback( osgDB::OutputStream& os, const osgTerrain::TerrainTile& tile )
{ return true; }
REGISTER_OBJECT_WRAPPER( osgTerrain_TerrainTile,
new osgTerrain::TerrainTile,
osgTerrain::TerrainTile,
"osg::Object osg::Node osg::Group osgTerrain::TerrainTile" )
{
ADD_USER_SERIALIZER( TileID ); // _tileID
ADD_OBJECT_SERIALIZER( TerrainTechnique, osgTerrain::TerrainTechnique, NULL ); // _terrainTechnique
ADD_OBJECT_SERIALIZER( Locator, osgTerrain::Locator, NULL ); // _locator
ADD_OBJECT_SERIALIZER( ElevationLayer, osgTerrain::Layer, NULL ); // _elevationLayer
ADD_USER_SERIALIZER( ColorLayers ); // _colorLayers
ADD_BOOL_SERIALIZER( RequiresNormals, true ); // _requiresNormals
ADD_BOOL_SERIALIZER( TreatBoundariesToValidDataAsDefaultValue, false ); // _treatBoundariesToValidDataAsDefaultValue
BEGIN_ENUM_SERIALIZER( BlendingPolicy, INHERIT );
ADD_ENUM_VALUE( INHERIT );
ADD_ENUM_VALUE( DO_NOT_SET_BLENDING );
ADD_ENUM_VALUE( ENABLE_BLENDING );
ADD_ENUM_VALUE( ENABLE_BLENDING_WHEN_ALPHA_PRESENT );
END_ENUM_SERIALIZER(); // BlendingPolicy
ADD_USER_SERIALIZER( TileLoadedCallback );
}
<commit_msg>Added a os<<std::endl; to work around a problem with the ascii serializers doing a negative seek that eats characters<commit_after>#include <osgTerrain/TerrainTile>
#include <osgDB/ObjectWrapper>
#include <osgDB/InputStream>
#include <osgDB/OutputStream>
// _tileID
static bool checkTileID( const osgTerrain::TerrainTile& tile )
{
return tile.getTileID().valid();
}
static bool readTileID( osgDB::InputStream& is, osgTerrain::TerrainTile& tile )
{
osgTerrain::TileID id;
is >> id.level >> id.x >> id.y;
tile.setTileID( id );
return true;
}
static bool writeTileID( osgDB::OutputStream& os, const osgTerrain::TerrainTile& tile )
{
const osgTerrain::TileID& id = tile.getTileID();
os << id.level << id.x << id.y << std::endl;
return true;
}
// _colorLayers
static bool checkColorLayers( const osgTerrain::TerrainTile& tile )
{
return tile.getNumColorLayers()>0;
}
static bool readColorLayers( osgDB::InputStream& is, osgTerrain::TerrainTile& tile )
{
unsigned int numValidLayers = 0; is >> numValidLayers >> osgDB::BEGIN_BRACKET;
for ( unsigned int i=0; i<numValidLayers; ++i )
{
unsigned int layerNum=0; is >> osgDB::PROPERTY("Layer") >> layerNum;
osgTerrain::Layer* layer = dynamic_cast<osgTerrain::Layer*>( is.readObject() );
if ( layer ) tile.setColorLayer( layerNum, layer );
}
is >> osgDB::END_BRACKET;
return true;
}
static bool writeColorLayers( osgDB::OutputStream& os, const osgTerrain::TerrainTile& tile )
{
unsigned int numValidLayers = 0;
for ( unsigned int i=0; i<tile.getNumColorLayers(); ++i )
{
if (tile.getColorLayer(i)) ++numValidLayers;
}
os << numValidLayers << osgDB::BEGIN_BRACKET << std::endl;
for ( unsigned int i=0; i<tile.getNumColorLayers(); ++i )
{
if (tile.getColorLayer(i)) os << osgDB::PROPERTY("Layer") << i << tile.getColorLayer(i);
}
os << osgDB::END_BRACKET << std::endl;
return true;
}
// TileLoadedCallback
static bool checkTileLoadedCallback( const osgTerrain::TerrainTile& tile )
{ return true; }
static bool readTileLoadedCallback( osgDB::InputStream& is, osgTerrain::TerrainTile& tile )
{
if ( osgTerrain::TerrainTile::getTileLoadedCallback().valid() )
osgTerrain::TerrainTile::getTileLoadedCallback()->loaded( &tile, is.getOptions() );
return true;
}
static bool writeTileLoadedCallback( osgDB::OutputStream& os, const osgTerrain::TerrainTile& tile )
{
os<<std::endl;
return true;
}
REGISTER_OBJECT_WRAPPER( osgTerrain_TerrainTile,
new osgTerrain::TerrainTile,
osgTerrain::TerrainTile,
"osg::Object osg::Node osg::Group osgTerrain::TerrainTile" )
{
ADD_USER_SERIALIZER( TileID ); // _tileID
ADD_OBJECT_SERIALIZER( TerrainTechnique, osgTerrain::TerrainTechnique, NULL ); // _terrainTechnique
ADD_OBJECT_SERIALIZER( Locator, osgTerrain::Locator, NULL ); // _locator
ADD_OBJECT_SERIALIZER( ElevationLayer, osgTerrain::Layer, NULL ); // _elevationLayer
ADD_USER_SERIALIZER( ColorLayers ); // _colorLayers
ADD_BOOL_SERIALIZER( RequiresNormals, true ); // _requiresNormals
ADD_BOOL_SERIALIZER( TreatBoundariesToValidDataAsDefaultValue, false ); // _treatBoundariesToValidDataAsDefaultValue
BEGIN_ENUM_SERIALIZER( BlendingPolicy, INHERIT );
ADD_ENUM_VALUE( INHERIT );
ADD_ENUM_VALUE( DO_NOT_SET_BLENDING );
ADD_ENUM_VALUE( ENABLE_BLENDING );
ADD_ENUM_VALUE( ENABLE_BLENDING_WHEN_ALPHA_PRESENT );
END_ENUM_SERIALIZER(); // BlendingPolicy
ADD_USER_SERIALIZER( TileLoadedCallback );
}
<|endoftext|>
|
<commit_before>#ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_NOTIFICATIONMANAGER_HPP
#define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_NOTIFICATIONMANAGER_HPP
#include "internal/common.hpp"
#include "NotificationListModel.hpp"
#include <QObject>
#include <QMutexLocker>
#include <limits>
namespace cutehmi {
/**
* %Notification manager.
*/
class CUTEHMI_API Notifier:
public QObject
{
Q_OBJECT
public:
Q_PROPERTY(NotificationListModel * model READ model CONSTANT)
Q_PROPERTY(int maxNotifications READ maxNotifications WRITE setMaxNotifications NOTIFY maxNotificationsChanged)
explicit Notifier(QObject * parent = nullptr);
NotificationListModel * model() const;
int maxNotifications() const;
void setMaxNotifications(int maxNotifications);
public slots:
/**
* Add notification.
* @param notification_l notification to add. Parameter will be used locally by this function.
* It's passed by a pointer instead of a reference for easier integration with QML.
*
* @threadsafe
*/
void add(Notification * notification_l);
void clear();
signals:
void maxNotificationsChanged();
private:
struct Members
{
std::unique_ptr<NotificationListModel> model {new NotificationListModel};
QMutex modelMutex {};
int maxNotifications {std::numeric_limits<int>::max()};
};
MPtr<Members> m;
};
}
#endif
//(c)MP: Copyright © 2019, Michal Policht. All rights reserved.
//(c)MP: 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/.
<commit_msg>Update include guards.<commit_after>#ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_NOTIFIER_HPP
#define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_NOTIFIER_HPP
#include "internal/common.hpp"
#include "NotificationListModel.hpp"
#include <QObject>
#include <QMutexLocker>
#include <limits>
namespace cutehmi {
/**
* %Notification manager.
*/
class CUTEHMI_API Notifier:
public QObject
{
Q_OBJECT
public:
Q_PROPERTY(NotificationListModel * model READ model CONSTANT)
Q_PROPERTY(int maxNotifications READ maxNotifications WRITE setMaxNotifications NOTIFY maxNotificationsChanged)
explicit Notifier(QObject * parent = nullptr);
NotificationListModel * model() const;
int maxNotifications() const;
void setMaxNotifications(int maxNotifications);
public slots:
/**
* Add notification.
* @param notification_l notification to add. Parameter will be used locally by this function.
* It's passed by a pointer instead of a reference for easier integration with QML.
*
* @threadsafe
*/
void add(Notification * notification_l);
void clear();
signals:
void maxNotificationsChanged();
private:
struct Members
{
std::unique_ptr<NotificationListModel> model {new NotificationListModel};
QMutex modelMutex {};
int maxNotifications {std::numeric_limits<int>::max()};
};
MPtr<Members> m;
};
}
#endif
//(c)MP: Copyright © 2019, Michal Policht. All rights reserved.
//(c)MP: 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/.
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "bitcoinrpc.h"
#include <boost/algorithm/string/predicate.hpp>
void DetectShutdownThread(boost::thread_group* threadGroup)
{
bool shutdown = ShutdownRequested();
// Tell the main threads to shutdown.
while (!shutdown)
{
MilliSleep(200);
shutdown = ShutdownRequested();
}
if (threadGroup)
threadGroup->interrupt_all();
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
return false;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause)
if (!SelectParamsFromCommandLine()) {
fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
return false;
}
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" bitcoind [options] " + "\n" +
" bitcoind [options] <command> [params] " + _("Send command to -server or bitcoind") + "\n" +
" bitcoind [options] help " + _("List commands") + "\n" +
" bitcoind [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
#ifndef WIN32
fDaemon = GetBoolArg("-daemon", false);
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
CreatePidFile(GetPidFile(), pid);
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
}
if (detectShutdownThread)
{
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
fHaveGUI = false;
// Connect bitcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return (fRet ? 0 : 1);
}
<commit_msg>add missing Boost Thread join_all() call during shutdown<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "bitcoinrpc.h"
#include <boost/algorithm/string/predicate.hpp>
void DetectShutdownThread(boost::thread_group* threadGroup)
{
bool fShutdown = ShutdownRequested();
// Tell the main threads to shutdown.
while (!fShutdown)
{
MilliSleep(200);
fShutdown = ShutdownRequested();
}
if (threadGroup)
{
threadGroup->interrupt_all();
threadGroup->join_all();
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
return false;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause)
if (!SelectParamsFromCommandLine()) {
fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
return false;
}
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = _("Bitcoin version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" bitcoind [options] " + "\n" +
" bitcoind [options] <command> [params] " + _("Send command to -server or bitcoind") + "\n" +
" bitcoind [options] help " + _("List commands") + "\n" +
" bitcoind [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
#ifndef WIN32
fDaemon = GetBoolArg("-daemon", false);
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
CreatePidFile(GetPidFile(), pid);
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet)
{
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
// threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
// the startup-failure cases to make sure they don't result in a hang due to some
// thread-blocking-waiting-for-another-thread-during-startup case
}
if (detectShutdownThread)
{
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
fHaveGUI = false;
// Connect bitcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return (fRet ? 0 : 1);
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: [email protected] (Naomi Forman)
//
// This file contains unit tests for the MetaTagFilter.
#include "net/instaweb/rewriter/public/meta_tag_filter.h"
#include "net/instaweb/http/public/meta_data.h" // for HttpAttributes, etc
#include "net/instaweb/http/public/response_headers.h"
#include "net/instaweb/rewriter/public/rewrite_test_base.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/util/public/gtest.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/string_util.h"
namespace net_instaweb {
namespace {
// Test fixture for MetaTagFilter unit tests.
class MetaTagFilterTest : public RewriteTestBase {
protected:
virtual void SetUp() {
options()->EnableFilter(RewriteOptions::kConvertMetaTags);
RewriteTestBase::SetUp();
rewrite_driver()->AddFilters();
headers_.Clear();
rewrite_driver()->set_response_headers_ptr(&headers_);
headers_.Replace(HttpAttributes::kContentType, "text/html");
}
ResponseHeaders* headers() {
return &headers_;
}
private:
ResponseHeaders headers_;
};
const char kMetaTagDoc[] =
"<html><head>"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
"<META HTTP-EQUIV=\"CONTENT-LANGUAGE\" CONTENT=\"en-US,fr\">"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestTags) {
ValidateNoChanges("convert_tags", kMetaTagDoc);
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
EXPECT_TRUE(StringCaseEqual(*values[0], "text/html; charset=UTF-8"))
<< *values[0];
}
const char kMetaTagDoubleDoc[] =
"<html><head>"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
"<META HTTP-EQUIV=\"CONTENT-LANGUAGE\" CONTENT=\"en-US,FR\">"
"<META HTTP-EQUIV=\"CONTENT-LANGUAGE\" CONTENT=\"en-US,fr\">"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestDoubleTags) {
ValidateNoChanges("convert_tags_once", kMetaTagDoubleDoc);
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
EXPECT_TRUE(StringCaseEqual(*values[0], "text/html; charset=UTF-8"))
<< *values[0];
}
TEST_F(MetaTagFilterTest, TestEquivNoValue) {
// Make sure we don't crash when a meta http-equiv has no content given.
ValidateNoChanges("no_value", "<meta http-equiv='NoValue'>");
}
const char kMetaTagConflictDoc[] =
"<html><head>"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
"<meta http-equiv=\"Content-Type\" content=\"text/xml; charset=UTF-16\">"
"<meta http-equiv=\"Content-Type\" content=\"text/xml\">"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestConflictingTags) {
ValidateNoChanges("convert_tags_first", kMetaTagConflictDoc);
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
EXPECT_TRUE(StringCaseEqual(*values[0], "text/html; charset=UTF-8"))
<< *values[0];
}
const char kMetaTagCharset[] =
"<html><head>"
"<meta http-equiv=\"Content-Type\" content=\"text/html\">"
"<meta charset=\"UTF-8\">"
"<meta http-equiv=\"Content-Type\" content=\"text/xml; charset=UTF-16\">"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestCharset) {
ValidateNoChanges("convert_charset", kMetaTagCharset);
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
const GoogleString* val = values[0];
EXPECT_TRUE(StringCaseEqual(*val, "text/html; charset=UTF-8"))
<< *val;
}
const char kMetaTagCharsetOnly[] =
"<html><head>"
"<meta charset=\"UTF-8\">"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestCharsetOnly) {
// Merges charset into pre-existing mimetype.
ValidateNoChanges("convert_charset_only", kMetaTagCharsetOnly);
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
const GoogleString* val = values[0];
EXPECT_TRUE(StringCaseEqual(*val, "text/html; charset=UTF-8"))
<< *val;
}
TEST_F(MetaTagFilterTest, TestCharsetNoUpstream) {
// No mimetype to merge charset into, it gets dropped.
headers()->RemoveAll(HttpAttributes::kContentType);
ValidateNoChanges("convert_charset_only", kMetaTagCharsetOnly);
ConstStringStarVector values;
EXPECT_FALSE(headers()->Lookup(HttpAttributes::kContentType, &values));
}
const char kMetaTagDoNothing[] =
"<html><head>"
"<meta http-equiv=\"\" content=\"\">"
"<meta http-equiv=\" \" content=\"\">"
"<meta http-equiv=\" :\" content=\"\">"
"<meta http-equiv=\"Content-Length\" content=\"123\">"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestDoNothing) {
ValidateNoChanges("do_nothing", kMetaTagDoNothing);
ASSERT_EQ(1, headers()->NumAttributes());
EXPECT_STREQ("text/html", headers()->Lookup1(HttpAttributes::kContentType));
}
const char kMetaTagNoScriptDoc[] =
"<html><head>"
"<noscript>"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
"</noscript>"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestNoScript) {
ValidateNoChanges("no_script", kMetaTagDoNothing);
ASSERT_EQ(1, headers()->NumAttributes());
EXPECT_STREQ("text/html", headers()->Lookup1(HttpAttributes::kContentType));
}
const char kMetaTagNoQuotes[] =
"<html><head>"
"<meta http-equiv=Content-Type content=text/html; charset=UTF-8>"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestNoQuotes) {
// See http://webdesign.about.com/od/metatags/qt/meta-charset.htm for an
// explanation of why we are testing this invalid format.
ValidateNoChanges("convert_tags", kMetaTagNoQuotes);
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
EXPECT_TRUE(StringCaseEqual(*values[0], "text/html; charset=UTF-8"))
<< *values[0];
}
TEST_F(MetaTagFilterTest, DoNotOverrideWithXhtmlUnsure) {
// We shouldn't override with XHTML even if mimetype is unknown
headers()->RemoveAll(HttpAttributes::kContentType);
ValidateNoChanges("no_override", "<meta http-equiv=\"Content-Type\" "
"content=\"text/xhtml; charset=UTF-8\">");
ConstStringStarVector values;
EXPECT_FALSE(headers()->Lookup(HttpAttributes::kContentType, &values));
}
TEST_F(MetaTagFilterTest, DoNotOverrideWithXhtmlKnown) {
// We shouldn't override with XHTML if the server already knows it's HTML
ValidateNoChanges("no_override", "<meta http-equiv=\"Content-Type\" "
"content=\"text/xhtml; charset=UTF-8\">");
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
EXPECT_TRUE(StringCaseEqual(*values[0], "text/html"))
<< *values[0];
}
} // namespace
} // namespace net_instaweb
<commit_msg>Do some small cleanups + a test addition suggested by sligocki to MetaTagFilterTest, along with a few more tests of my own.<commit_after>/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: [email protected] (Naomi Forman)
//
// This file contains unit tests for the MetaTagFilter.
#include "net/instaweb/rewriter/public/meta_tag_filter.h"
#include "net/instaweb/http/public/content_type.h"
#include "net/instaweb/http/public/meta_data.h" // for HttpAttributes, etc
#include "net/instaweb/http/public/response_headers.h"
#include "net/instaweb/rewriter/public/rewrite_test_base.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/util/public/gtest.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/string_util.h"
namespace net_instaweb {
namespace {
// Test fixture for MetaTagFilter unit tests.
class MetaTagFilterTest : public RewriteTestBase {
protected:
virtual void SetUp() {
options()->EnableFilter(RewriteOptions::kConvertMetaTags);
RewriteTestBase::SetUp();
rewrite_driver()->AddFilters();
headers_.Clear();
rewrite_driver()->set_response_headers_ptr(&headers_);
headers_.Replace(HttpAttributes::kContentType, "text/html");
}
ResponseHeaders* headers() {
return &headers_;
}
private:
ResponseHeaders headers_;
};
const char kMetaTagDoc[] =
"<html><head>"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
"<META HTTP-EQUIV=\"CONTENT-LANGUAGE\" CONTENT=\"en-US,fr\">"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestTags) {
ValidateNoChanges("convert_tags", kMetaTagDoc);
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
EXPECT_TRUE(StringCaseEqual(*values[0], "text/html; charset=UTF-8"))
<< *values[0];
}
const char kMetaTagDoubleDoc[] =
"<html><head>"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
"<META HTTP-EQUIV=\"CONTENT-LANGUAGE\" CONTENT=\"en-US,FR\">"
"<META HTTP-EQUIV=\"CONTENT-LANGUAGE\" CONTENT=\"en-US,fr\">"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestDoubleTags) {
ValidateNoChanges("convert_tags_once", kMetaTagDoubleDoc);
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
EXPECT_TRUE(StringCaseEqual(*values[0], "text/html; charset=UTF-8"))
<< *values[0];
}
TEST_F(MetaTagFilterTest, TestEquivNoValue) {
// Make sure we don't crash when a meta http-equiv has no content given.
ValidateNoChanges("no_value", "<meta http-equiv='NoValue'>");
}
const char kMetaTagConflictDoc[] =
"<html><head>"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
"<meta http-equiv=\"Content-Type\" content=\"text/xml; charset=UTF-16\">"
"<meta http-equiv=\"Content-Type\" content=\"text/xml\">"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestConflictingTags) {
ValidateNoChanges("convert_tags_first", kMetaTagConflictDoc);
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
EXPECT_TRUE(StringCaseEqual(*values[0], "text/html; charset=UTF-8"))
<< *values[0];
}
const char kMetaTagCharset[] =
"<html><head>"
"<meta http-equiv=\"Content-Type\" content=\"text/html\">"
"<meta charset=\"UTF-8\">"
"<meta http-equiv=\"Content-Type\" content=\"text/xml; charset=UTF-16\">"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestCharset) {
ValidateNoChanges("convert_charset", kMetaTagCharset);
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
const GoogleString* val = values[0];
EXPECT_TRUE(StringCaseEqual(*val, "text/html; charset=UTF-8")) << *val;
}
const char kMetaTagCharsetOnly[] =
"<html><head>"
"<meta charset=\"UTF-8\">"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestCharsetOnly) {
// Merges charset into pre-existing mimetype.
ValidateNoChanges("convert_charset_only", kMetaTagCharsetOnly);
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
const GoogleString* val = values[0];
EXPECT_TRUE(StringCaseEqual(*val, "text/html; charset=UTF-8")) << *val;
}
TEST_F(MetaTagFilterTest, TestCharsetNoUpstream) {
// No mimetype to merge charset into, it gets dropped.
headers()->RemoveAll(HttpAttributes::kContentType);
ValidateNoChanges("convert_charset_only", kMetaTagCharsetOnly);
ConstStringStarVector values;
EXPECT_FALSE(headers()->Lookup(HttpAttributes::kContentType, &values));
}
const char kMetaTagDoNothing[] =
"<html><head>"
"<meta http-equiv=\"\" content=\"\">"
"<meta http-equiv=\" \" content=\"\">"
"<meta http-equiv=\" :\" content=\"\">"
"<meta http-equiv=\"Content-Length\" content=\"123\">"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestDoNothing) {
ValidateNoChanges("do_nothing", kMetaTagDoNothing);
ASSERT_EQ(1, headers()->NumAttributes());
EXPECT_STREQ("text/html", headers()->Lookup1(HttpAttributes::kContentType));
}
const char kMetaTagNoScriptDoc[] =
"<html><head>"
"<noscript>"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
"</noscript>"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestNoScript) {
ValidateNoChanges("no_script", kMetaTagDoNothing);
ASSERT_EQ(1, headers()->NumAttributes());
EXPECT_STREQ("text/html", headers()->Lookup1(HttpAttributes::kContentType));
}
const char kMetaTagNoQuotes[] =
"<html><head>"
"<meta http-equiv=Content-Type content=text/html; charset=UTF-8>"
"</head><body></body></html>";
TEST_F(MetaTagFilterTest, TestNoQuotes) {
// See http://webdesign.about.com/od/metatags/qt/meta-charset.htm for an
// explanation of why we are testing this invalid format.
ValidateNoChanges("convert_tags", kMetaTagNoQuotes);
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
EXPECT_TRUE(StringCaseEqual(*values[0], "text/html; charset=UTF-8"))
<< *values[0];
}
TEST_F(MetaTagFilterTest, DoNotOverrideWithFakeXhtmlUnsure) {
// We shouldn't override with XHTML even if mimetype is unknown.
// This uses a bogus "XHTML" mimetype which we recognized for some versions.
headers()->RemoveAll(HttpAttributes::kContentType);
ValidateNoChanges("no_override", "<meta http-equiv=\"Content-Type\" "
"content=\"text/xhtml; charset=UTF-8\">");
ConstStringStarVector values;
EXPECT_FALSE(headers()->Lookup(HttpAttributes::kContentType, &values));
}
TEST_F(MetaTagFilterTest, DoNotOverrideWithRealXhtmlUnsure) {
// We shouldn't override with XHTML even if mimetype is unknown.
headers()->RemoveAll(HttpAttributes::kContentType);
ValidateNoChanges("no_override",
StrCat("<meta http-equiv=\"Content-Type\" content=\"",
kContentTypeXhtml.mime_type(),
" ;charset=UTF-8\">"));
ConstStringStarVector values;
EXPECT_FALSE(headers()->Lookup(HttpAttributes::kContentType, &values));
}
TEST_F(MetaTagFilterTest, DoNotOverrideWithFakeXhtmlKnown) {
// We shouldn't override with XHTML if the server already knows it's HTML
// This uses a bogus "XHTML" mimetype which we recognized for some versions.
ValidateNoChanges("no_override", "<meta http-equiv=\"Content-Type\" "
"content=\"text/xhtml; charset=UTF-8\">");
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
EXPECT_TRUE(StringCaseEqual(*values[0], "text/html")) << *values[0];
}
TEST_F(MetaTagFilterTest, DoNotOverrideWithRealXhtmlKnown) {
// We shouldn't override with XHTML if the server already knows it's HTML
ValidateNoChanges("no_override",
StrCat("<meta http-equiv=\"Content-Type\" content=\"",
kContentTypeXhtml.mime_type(), ";charset=UTF-8\">"));
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
EXPECT_TRUE(StringCaseEqual(*values[0], "text/html")) << *values[0];
}
TEST_F(MetaTagFilterTest, DoNotOverrideCharsetBothXhtml) {
// An XHTML document specifying a non-utf8 encoding via a http-equiv meta
// should not take effect, either.
GoogleString initial_header = StrCat(kContentTypeXhtml.mime_type(),
"; charset=UTF-8");
headers()->Replace(HttpAttributes::kContentType, initial_header);
ValidateNoChanges("no_override",
StrCat("<meta http-equiv=\"Content-Type\" content=\"",
kContentTypeXhtml.mime_type(),
"; charset=KOI8-R\">"));
ConstStringStarVector values;
EXPECT_TRUE(headers()->Lookup(HttpAttributes::kContentType, &values));
ASSERT_EQ(1, values.size());
EXPECT_EQ(initial_header, *values[0]);
}
} // namespace
} // namespace net_instaweb
<|endoftext|>
|
<commit_before><commit_msg>tried F.cpp to 'F'<commit_after><|endoftext|>
|
<commit_before>#include "kwm.h"
static const CGKeyCode kVK_SPECIAL_Å = 0x21;
static const CGKeyCode kVK_SPECIAL_Ø = 0x29;
static const CGKeyCode kVK_SPECIAL_Æ = 0x27;
std::string KwmcFilePath;
std::string KwmcCommandToExecute;
// This function is run once every time
// hotkeys.so is recompiled.
//
// The path to Kwmc is set in KwmcFilePath
// To bind a Kwmc command, simply set the
// value of KwmcCommandToExecute.
//
// e.g KwmcCommandToExecute = "window -f prev"
void GetKwmcFilePath()
{
if(!KwmcFilePath.empty())
return;
char PathBuf[PROC_PIDPATHINFO_MAXSIZE];
pid_t Pid = getpid();
std::string Path;
int Ret = proc_pidpath(Pid, PathBuf, sizeof(PathBuf));
if (Ret > 0)
{
Path = PathBuf;
std::size_t Split = Path.find_last_of("/\\");
Path = Path.substr(0, Split);
KwmcFilePath = Path + "/kwmc";
std::cout << "GetKwmcFilePath()" << std::endl;
}
}
extern "C" KWM_KEY_REMAP(RemapKeys)
{
*Result = -1;
/*
if(*CmdKey && *AltKey && *CtrlKey)
{
}
switch(Keycode)
{
case kVK_ANSI_A:
{
*Result = kVK_ANSI_S;
} break;
}
Change wether a modifier flag should be set or not.
If a modifier is not changed, the value already set for
the event will be used.
*CmdKey = true;
*AltKey = true;
*CtrlKey = true;
*ShiftKey = true;
*/
}
extern "C" KWM_HOTKEY_COMMANDS(KWMHotkeyCommands)
{
bool Result = true;
GetKwmcFilePath();
if(CmdKey && AltKey && CtrlKey)
{
switch(Keycode)
{
// Toggle Focus-Mode
case kVK_ANSI_T:
{
KwmcCommandToExecute = "config focus toggle";
} break;
// Mark Container to split
case kVK_ANSI_M:
{
KwmcCommandToExecute = "window -t mark";
} break;
// Toggle window floating
case kVK_ANSI_W:
{
KwmcCommandToExecute = "window -t float";
} break;
// Reapply node container to window
case kVK_ANSI_R:
{
KwmcCommandToExecute = "window -c refresh";
} break;
// Restart Kwm
case kVK_ANSI_Q:
{
KwmcCommandToExecute = "quit";
} break;
// Use Width/Height ratio to determine split mode
case kVK_ANSI_O:
{
KwmcCommandToExecute = "screen -s optimal";
} break;
// Vertical Split-Mode
case kVK_ANSI_7:
{
KwmcCommandToExecute = "screen -s vertical";
} break;
// Horizontal Split-Mode
case kVK_ANSI_Slash:
{
KwmcCommandToExecute = "screen -s horizontal";
} break;
// Toggle Split-Type of existing container
case kVK_ANSI_S:
{
KwmcCommandToExecute = "window -c split";
} break;
// Resize Panes
case kVK_ANSI_H:
{
KwmcCommandToExecute = "space -m left";
} break;
case kVK_ANSI_L:
{
KwmcCommandToExecute = "space -m right";
} break;
case kVK_ANSI_J:
{
KwmcCommandToExecute = "space -m down";
} break;
case kVK_ANSI_K:
{
KwmcCommandToExecute = "space -m up";
} break;
// Toggle Fullscreen / Parent Container
case kVK_ANSI_F:
{
KwmcCommandToExecute = "window -t fullscreen";
} break;
case kVK_ANSI_P:
{
KwmcCommandToExecute = "window -t parent";
} break;
default:
{
Result = false;
} break;
}
}
else if(CmdKey && AltKey && !CtrlKey)
{
switch(Keycode)
{
// Toggle space floating/tiling
case kVK_ANSI_T:
{
KwmcCommandToExecute = "space -t toggle";
} break;
// Swap focused window with the previous window
case kVK_ANSI_P:
{
KwmcCommandToExecute = "window -s prev";
} break;
// Swap focused window with the next window
case kVK_ANSI_N:
{
KwmcCommandToExecute = "window -s next";
} break;
// Swap focused window with the marked window
case kVK_ANSI_M:
{
KwmcCommandToExecute = "window -s mark";
} break;
// Shift focus to the previous window
case kVK_ANSI_H:
{
KwmcCommandToExecute = "window -f prev";
} break;
// Shift focus to the next window
case kVK_ANSI_L:
{
KwmcCommandToExecute = "window -f next";
} break;
// Rotate window-tree by 180 degrees
case kVK_ANSI_R:
{
KwmcCommandToExecute = "space -r 180";
} break;
// Decrease space gaps
case kVK_ANSI_X:
{
KwmcCommandToExecute = "space -g decrease horizontal";
} break;
case kVK_ANSI_Y:
{
KwmcCommandToExecute = "space -g decrease vertical";
} break;
// Decrease space padding
case kVK_LeftArrow:
{
KwmcCommandToExecute = "space -p decrease left";
} break;
case kVK_RightArrow:
{
KwmcCommandToExecute = "space -p decrease right";
} break;
case kVK_UpArrow:
{
KwmcCommandToExecute = "space -p decrease top";
} break;
case kVK_DownArrow:
{
KwmcCommandToExecute = "space -p decrease bottom";
} break;
default:
{
Result = false;
} break;
}
}
else if(!CmdKey && CtrlKey && AltKey)
{
switch(Keycode)
{
// Send window to previous screen
case kVK_ANSI_P:
{
KwmcCommandToExecute = "screen -m prev";
} break;
// Send window to next screen
case kVK_ANSI_N:
{
KwmcCommandToExecute = "screen -m next";
} break;
// Send window to screen 0
case kVK_ANSI_1:
{
KwmcCommandToExecute = "screen -m 0";
} break;
// Send window to screen 1
case kVK_ANSI_2:
{
KwmcCommandToExecute = "screen -m 1";
} break;
// Send window to screen 2
case kVK_ANSI_3:
{
KwmcCommandToExecute = "screen -m 2";
} break;
// Increase space gaps
case kVK_ANSI_X:
{
KwmcCommandToExecute = "space -g increase horizontal";
} break;
case kVK_ANSI_Y:
{
KwmcCommandToExecute = "space -g increase vertical";
} break;
// Increase space padding
case kVK_LeftArrow:
{
KwmcCommandToExecute = "space -p increase left";
} break;
case kVK_RightArrow:
{
KwmcCommandToExecute = "space -p increase right";
} break;
case kVK_UpArrow:
{
KwmcCommandToExecute = "space -p increase top";
} break;
case kVK_DownArrow:
{
KwmcCommandToExecute = "space -p increase bottom";
} break;
default:
{
Result = false;
};
}
}
else
{
Result = false;
}
if(Result)
{
std::string SysArg = KwmcFilePath + " " + KwmcCommandToExecute;
system(SysArg.c_str());
KwmcCommandToExecute = "";
}
return Result;
}
extern "C" KWM_HOTKEY_COMMANDS(SystemHotkeyCommands)
{
bool Result = true;
if (CmdKey && !CtrlKey && !AltKey)
{
switch(Keycode)
{
default:
{
Result = false;
} break;
}
}
else
{
Result = false;
}
return Result;
}
extern "C" KWM_HOTKEY_COMMANDS(CustomHotkeyCommands)
{
bool Result = true;
if(CmdKey && AltKey && CtrlKey)
{
switch(Keycode)
{
// Open New iTerm Window
case kVK_Return:
{
system("open -na /Applications/iTerm.app");
} break;
default:
{
Result = false;
} break;
}
}
else
{
Result = false;
}
return Result;
}
<commit_msg>example - a hotkey can do different commands depending on focused window<commit_after>#include "kwm.h"
static const CGKeyCode kVK_SPECIAL_Å = 0x21;
static const CGKeyCode kVK_SPECIAL_Ø = 0x29;
static const CGKeyCode kVK_SPECIAL_Æ = 0x27;
std::string KwmcFilePath;
std::string KwmcCommandToExecute;
// This function is run once every time
// hotkeys.so is recompiled.
//
// The path to Kwmc is set in KwmcFilePath
// To bind a Kwmc command, simply set the
// value of KwmcCommandToExecute.
//
// e.g KwmcCommandToExecute = "window -f prev"
void GetKwmcFilePath()
{
if(!KwmcFilePath.empty())
return;
char PathBuf[PROC_PIDPATHINFO_MAXSIZE];
pid_t Pid = getpid();
std::string Path;
int Ret = proc_pidpath(Pid, PathBuf, sizeof(PathBuf));
if (Ret > 0)
{
Path = PathBuf;
std::size_t Split = Path.find_last_of("/\\");
Path = Path.substr(0, Split);
KwmcFilePath = Path + "/kwmc";
std::cout << "GetKwmcFilePath()" << std::endl;
}
}
// Takes a command and executes it using popen,
// reads from stdout and returns the value
std::string GetOutputAndExec(std::string Cmd)
{
std::shared_ptr<FILE> Pipe(popen(Cmd.c_str(), "r"), pclose);
if (!Pipe)
return "ERROR";
char Buffer[128];
std::string Result = "";
while (!feof(Pipe.get()))
{
if (fgets(Buffer, 128, Pipe.get()) != NULL)
Result += Buffer;
}
return Result;
}
extern "C" KWM_KEY_REMAP(RemapKeys)
{
*Result = -1;
/*
if(*CmdKey && *AltKey && *CtrlKey)
{
}
switch(Keycode)
{
case kVK_ANSI_A:
{
*Result = kVK_ANSI_S;
} break;
}
Change wether a modifier flag should be set or not.
If a modifier is not changed, the value already set for
the event will be used.
*CmdKey = true;
*AltKey = true;
*CtrlKey = true;
*ShiftKey = true;
*/
}
extern "C" KWM_HOTKEY_COMMANDS(KWMHotkeyCommands)
{
bool Result = true;
GetKwmcFilePath();
if(CmdKey && AltKey && CtrlKey)
{
switch(Keycode)
{
// Toggle Focus-Mode
case kVK_ANSI_T:
{
KwmcCommandToExecute = "config focus toggle";
} break;
// Mark Container to split
case kVK_ANSI_M:
{
KwmcCommandToExecute = "window -t mark";
} break;
// Toggle window floating
case kVK_ANSI_W:
{
KwmcCommandToExecute = "window -t float";
} break;
// Reapply node container to window
case kVK_ANSI_R:
{
KwmcCommandToExecute = "window -c refresh";
} break;
// Restart Kwm
case kVK_ANSI_Q:
{
KwmcCommandToExecute = "quit";
} break;
// Use Width/Height ratio to determine split mode
case kVK_ANSI_O:
{
KwmcCommandToExecute = "screen -s optimal";
} break;
// Vertical Split-Mode
case kVK_ANSI_7:
{
KwmcCommandToExecute = "screen -s vertical";
} break;
// Horizontal Split-Mode
case kVK_ANSI_Slash:
{
KwmcCommandToExecute = "screen -s horizontal";
} break;
// Toggle Split-Type of existing container
case kVK_ANSI_S:
{
KwmcCommandToExecute = "window -c split";
} break;
// Resize Panes
case kVK_ANSI_H:
{
KwmcCommandToExecute = "space -m left";
} break;
case kVK_ANSI_L:
{
KwmcCommandToExecute = "space -m right";
} break;
case kVK_ANSI_J:
{
KwmcCommandToExecute = "space -m down";
} break;
case kVK_ANSI_K:
{
KwmcCommandToExecute = "space -m up";
} break;
// Toggle Fullscreen / Parent Container
case kVK_ANSI_F:
{
KwmcCommandToExecute = "window -t fullscreen";
} break;
case kVK_ANSI_P:
{
KwmcCommandToExecute = "window -t parent";
} break;
default:
{
Result = false;
} break;
}
}
else if(CmdKey && AltKey && !CtrlKey)
{
switch(Keycode)
{
// Toggle space floating/tiling
case kVK_ANSI_T:
{
KwmcCommandToExecute = "space -t toggle";
} break;
// Swap focused window with the previous window
case kVK_ANSI_P:
{
KwmcCommandToExecute = "window -s prev";
} break;
// Swap focused window with the next window
case kVK_ANSI_N:
{
KwmcCommandToExecute = "window -s next";
} break;
// Swap focused window with the marked window
case kVK_ANSI_M:
{
KwmcCommandToExecute = "window -s mark";
} break;
// Shift focus to the previous window
case kVK_ANSI_H:
{
KwmcCommandToExecute = "window -f prev";
} break;
// Shift focus to the next window
case kVK_ANSI_L:
{
KwmcCommandToExecute = "window -f next";
} break;
// Rotate window-tree by 180 degrees
case kVK_ANSI_R:
{
KwmcCommandToExecute = "space -r 180";
} break;
// Decrease space gaps
case kVK_ANSI_X:
{
KwmcCommandToExecute = "space -g decrease horizontal";
} break;
case kVK_ANSI_Y:
{
KwmcCommandToExecute = "space -g decrease vertical";
} break;
// Decrease space padding
case kVK_LeftArrow:
{
KwmcCommandToExecute = "space -p decrease left";
} break;
case kVK_RightArrow:
{
KwmcCommandToExecute = "space -p decrease right";
} break;
case kVK_UpArrow:
{
KwmcCommandToExecute = "space -p decrease top";
} break;
case kVK_DownArrow:
{
KwmcCommandToExecute = "space -p decrease bottom";
} break;
default:
{
Result = false;
} break;
}
}
else if(!CmdKey && CtrlKey && AltKey)
{
switch(Keycode)
{
// Send window to previous screen
case kVK_ANSI_P:
{
KwmcCommandToExecute = "screen -m prev";
} break;
// Send window to next screen
case kVK_ANSI_N:
{
KwmcCommandToExecute = "screen -m next";
} break;
// Send window to screen 0
case kVK_ANSI_1:
{
KwmcCommandToExecute = "screen -m 0";
} break;
// Send window to screen 1
case kVK_ANSI_2:
{
KwmcCommandToExecute = "screen -m 1";
} break;
// Send window to screen 2
case kVK_ANSI_3:
{
KwmcCommandToExecute = "screen -m 2";
} break;
// Increase space gaps
case kVK_ANSI_X:
{
KwmcCommandToExecute = "space -g increase horizontal";
} break;
case kVK_ANSI_Y:
{
KwmcCommandToExecute = "space -g increase vertical";
} break;
// Increase space padding
case kVK_LeftArrow:
{
KwmcCommandToExecute = "space -p increase left";
} break;
case kVK_RightArrow:
{
KwmcCommandToExecute = "space -p increase right";
} break;
case kVK_UpArrow:
{
KwmcCommandToExecute = "space -p increase top";
} break;
case kVK_DownArrow:
{
KwmcCommandToExecute = "space -p increase bottom";
} break;
default:
{
Result = false;
};
}
}
else
{
Result = false;
}
if(Result)
{
std::string SysArg = KwmcFilePath + " " + KwmcCommandToExecute;
system(SysArg.c_str());
KwmcCommandToExecute = "";
}
return Result;
}
extern "C" KWM_HOTKEY_COMMANDS(SystemHotkeyCommands)
{
bool Result = true;
if (CmdKey && !CtrlKey && !AltKey)
{
switch(Keycode)
{
default:
{
Result = false;
} break;
}
}
else
{
Result = false;
}
return Result;
}
extern "C" KWM_HOTKEY_COMMANDS(CustomHotkeyCommands)
{
bool Result = true;
GetKwmcFilePath();
if(CmdKey && AltKey && CtrlKey)
{
switch(Keycode)
{
// Open New iTerm Window
case kVK_Return:
{
system("open -na /Applications/iTerm.app");
} break;
/* This demonstrates how a hotkey may do different things
* depending on what the focused window is.
case kVK_ANSI_N:
{
std::string Focused = GetOutputAndExec(KwmcFilePath + " focused");
std::stringstream Stream(Focused);
std::string Owner;
std::getline(Stream, Owner, '-');
Owner.erase(Owner.end()-1);
if(Owner == "iTerm2")
KwmcCommandToExecute = "write This is written inside iTerm";
else if(Owner == "Google Chrome")
KwmcCommandToExecute = "write This is written inside Google Chrome";
else
KwmcCommandToExecute = "write This was written in " + Owner + "!";
} break;
*/
default:
{
Result = false;
} break;
}
}
else
{
Result = false;
}
if(Result && !KwmcCommandToExecute.empty())
{
std::string SysArg = KwmcFilePath + " " + KwmcCommandToExecute;
system(SysArg.c_str());
KwmcCommandToExecute = "";
}
return Result;
}
<|endoftext|>
|
<commit_before>#include "proto\ql2.pb.h"
#include <string>
#include <stdio.h>
#include <stdint.h>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <stdlib.h>
#include <stdexcept>
#include <boost/format.hpp>
#include <vector>
#include <boost/unordered_map.hpp>
// fix for undefined ssize_t from https://code.google.com/p/cpp-btree/issues/detail?id=6
#if defined(_MSC_VER)
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif
#ifndef RETHINK_DB_CONNECTION
#define RETHINK_DB_CONNECTION
namespace com {
namespace rethinkdb {
namespace driver {
//
// definitions of exceptions
//
class connection_exception : public std::runtime_error{
public:
connection_exception() :runtime_error(""){}
connection_exception(const std::string& msg) : runtime_error(("RethinkDB connection exception. " + msg).c_str()){}
};
class runtime_error_exception : public std::runtime_error {
public:
runtime_error_exception() : runtime_error(""){}
runtime_error_exception(const std::string& msg) : runtime_error(("RethinkDB runtime exception. " + msg).c_str()){}
};
class compile_error_exception : public std::runtime_error {
public:
compile_error_exception() :runtime_error(""){}
compile_error_exception(const std::string& msg) : runtime_error(("RethinkDB compile error exception. " + msg).c_str()){}
};
class client_error_exception : public std::runtime_error {
public:
client_error_exception() :runtime_error(""){}
client_error_exception(const std::string& msg) : runtime_error(("RethinkDB client error exception. " + msg).c_str()){}
};
//
// implementation of connection class
//
class connection {
public:
connection(const std::string& host, const std::string& port, const std::string& database, const std::string& auth_key) : resolver_(io_service), socket_(io_service) {
this->host = host;
this->port = port;
this->database = database;
this->auth_key = auth_key;
this->is_connected = false;
this->connect();
}
bool connect() {
if (socket_.is_open() && this->is_connected) return true;
try {
// resolve the host
boost::asio::ip::tcp::resolver::query query(this->host, this->port);
boost::asio::ip::tcp::resolver::iterator iterator = this->resolver_.resolve(query);
boost::asio::connect(this->socket_, iterator);
// prepare stream for writing data
std::ostream request_stream(&(this->request_));
// write magic version number
request_stream.write((char*)&(com::rethinkdb::VersionDummy::V0_2), sizeof (com::rethinkdb::VersionDummy::V0_2));
// write auth_key length
u_int auth_key_length = this->auth_key.length();
request_stream.write((char*)&auth_key_length, sizeof (u_int));
// write auth_key
request_stream.write(this->auth_key.c_str(), auth_key.length());
// send the request
boost::asio::write(this->socket_, this->request_);
// read response until a null character
boost::asio::read_until(this->socket_, this->response_, 0);
// prepare to read a response
std::istream response_stream(&(this->response_));
std::string response;
// read one line of response
std::getline(response_stream, response);
// if it starts with "SUCCESS"
if (response.substr(0, 7) == "SUCCESS") {
this->is_connected = true;
return true;
}
else {
this->is_connected = false;
throw connection_exception("Error while connecting to RethinkDB server: " + response);
}
}
catch (std::exception& e)
{
// exception from boost has been caught
throw connection_exception(std::string(e.what()));
}
}
std::shared_ptr<com::rethinkdb::Response> read_response() {
u_int response_length;
char* reply;
size_t bytes_read;
std::shared_ptr<com::rethinkdb::Response> response(new com::rethinkdb::Response());
try {
try {
// read length of the response
boost::asio::read(this->socket_, boost::asio::buffer(&response_length, sizeof(u_int)));
// read content
reply = new char[response_length];
bytes_read = boost::asio::read(this->socket_, boost::asio::buffer(reply, response_length));
}
catch (std::exception& e) {
throw connection_exception("Unable to read from the socket.");
}
if (bytes_read != response_length) throw connection_exception(boost::str(boost::format("%1% bytes read, when %2% bytes promised.") % bytes_read % response_length));
try {
response->ParseFromArray(reply, response_length);
}
catch (std::exception& e) {
throw connection_exception("Unable to parse the protobuf Response object.");
}
delete[] reply;
}
catch (std::exception& e) {
throw connection_exception(boost::str(boost::format("Read response: %1%") % e.what()));
}
return response;
}
void write_query(const com::rethinkdb::Query& query) {
// prepare output stream
std::ostream request_stream(&request_);
// serialize query
std::string blob = query.SerializeAsString();
// write blob's length in little endian 32 bit unsigned integer
u_int blob_length = blob.length();
request_stream.write((char*)&blob_length, sizeof (u_int));
// write protobuf blob
request_stream.write(blob.c_str(), blob.length());
try {
// send the content of the output stream over the wire
boost::asio::write(this->socket_, this->request_);
}
catch (std::exception& e)
{
throw connection_exception(boost::str(boost::format("Write query: exception: %1%") % e.what()));
}
}
private:
std::string host;
std::string port;
std::string database;
std::string auth_key;
int timeout;
int64_t token;
bool is_connected;
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver_;
boost::asio::ip::tcp::socket socket_;
boost::asio::streambuf request_;
boost::asio::streambuf response_;
};
//
// implementation data structures
//
enum datum_type {
R_NULL,
R_BOOL,
R_NUM, // a double
R_STR,
R_ARRAY,
R_OBJECT
};
class datum {
public:
datum_type type;
datum(datum_type t) : type(t) {};
};
class null_datum : datum {
null_datum() : datum(datum_type::R_NULL) {};
};
class bool_datum : datum {
bool value;
bool_datum() : datum(datum_type::R_BOOL) {};
};
class num_datum : datum {
double value;
num_datum() : datum(datum_type::R_NUM) {};
};
class str_datum : datum {
std::string value;
str_datum() : datum(datum_type::R_STR) {};
};
class array_datum : datum {
std::vector<datum> value;
array_datum() : datum(datum_type::R_ARRAY) {};
};
class object_datum : datum {
boost::unordered_map<std::string, datum> value;
object_datum() : datum(datum_type::R_OBJECT) {};
};
//
// implementation of RQL class
//
class RQL {
public:
RQL(com::rethinkdb::Query::QueryType query_type) : query(com::rethinkdb::Query()) {
this->query.set_type(query_type);
// generate random token
this->query.set_token(rand());
}
RQL() : RQL(com::rethinkdb::Query::QueryType::Query_QueryType_START) {};
RQL* db_create(const std::string& name) {
com::rethinkdb::Term *term;
term = this->query.mutable_query();
term->set_type(com::rethinkdb::Term::TermType::Term_TermType_DB_CREATE);
com::rethinkdb::Term *term_name;
term_name = term->add_args();
term_name->set_type(com::rethinkdb::Term::TermType::Term_TermType_DATUM);
com::rethinkdb::Datum *datum;
datum = term_name->mutable_datum();
datum->set_type(com::rethinkdb::Datum::DatumType::Datum_DatumType_R_STR);
datum->set_r_str(name);
return this;
}
std::vector<datum> run(std::shared_ptr<connection> conn) {
// TODO - optargs?
// write query
conn->write_query(this->query);
// read response
std::shared_ptr<com::rethinkdb::Response> response(conn->read_response());
switch (response->type()) {
case com::rethinkdb::Response::ResponseType::Response_ResponseType_RUNTIME_ERROR:
throw runtime_error_exception("\n\nResponse received:\n" + response->DebugString());
break;
case com::rethinkdb::Response::ResponseType::Response_ResponseType_CLIENT_ERROR:
throw client_error_exception("\n\nResponse received:\n" + response->DebugString());
break;
case com::rethinkdb::Response::ResponseType::Response_ResponseType_COMPILE_ERROR:
throw compile_error_exception("\n\nResponse received:\n" + response->DebugString());
break;
default:
response->PrintDebugString();
// TODO
}
}
private:
com::rethinkdb::Query query;
};
}
}
}
#endif<commit_msg>Messed up<commit_after>#include "proto\ql2.pb.h"
#include <string>
#include <stdio.h>
#include <stdint.h>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <stdlib.h>
#include <stdexcept>
#include <boost/format.hpp>
#include <vector>
#include <boost/unordered_map.hpp>
// fix for undefined ssize_t from https://code.google.com/p/cpp-btree/issues/detail?id=6
#if defined(_MSC_VER)
#include <BaseTsd.h>
typedef SSIZE_T ssize_t;
#endif
#ifndef RETHINK_DB_DRIVER
#define RETHINK_DB_DRIVER
namespace com {
namespace rethinkdb {
namespace driver {
//
// definitions of exceptions
//
class connection_exception : public std::runtime_error{
public:
connection_exception() :runtime_error(""){}
connection_exception(const std::string& msg) : runtime_error(("RethinkDB connection exception. " + msg).c_str()){}
};
class runtime_error_exception : public std::runtime_error {
public:
runtime_error_exception() : runtime_error(""){}
runtime_error_exception(const std::string& msg) : runtime_error(("RethinkDB runtime exception. " + msg).c_str()){}
};
class compile_error_exception : public std::runtime_error {
public:
compile_error_exception() :runtime_error(""){}
compile_error_exception(const std::string& msg) : runtime_error(("RethinkDB compile error exception. " + msg).c_str()){}
};
class client_error_exception : public std::runtime_error {
public:
client_error_exception() :runtime_error(""){}
client_error_exception(const std::string& msg) : runtime_error(("RethinkDB client error exception. " + msg).c_str()){}
};
//
// implementation of connection class
//
class connection {
public:
connection(const std::string& host, const std::string& port, const std::string& database, const std::string& auth_key) : resolver_(io_service), socket_(io_service) {
this->host = host;
this->port = port;
this->database = database;
this->auth_key = auth_key;
this->is_connected = false;
this->connect();
}
bool connect() {
if (socket_.is_open() && this->is_connected) return true;
try {
// resolve the host
boost::asio::ip::tcp::resolver::query query(this->host, this->port);
boost::asio::ip::tcp::resolver::iterator iterator = this->resolver_.resolve(query);
boost::asio::connect(this->socket_, iterator);
// prepare stream for writing data
std::ostream request_stream(&(this->request_));
// write magic version number
request_stream.write((char*)&(com::rethinkdb::VersionDummy::V0_2), sizeof (com::rethinkdb::VersionDummy::V0_2));
// write auth_key length
u_int auth_key_length = this->auth_key.length();
request_stream.write((char*)&auth_key_length, sizeof (u_int));
// write auth_key
request_stream.write(this->auth_key.c_str(), auth_key.length());
// send the request
boost::asio::write(this->socket_, this->request_);
// read response until a null character
boost::asio::read_until(this->socket_, this->response_, 0);
// prepare to read a response
std::istream response_stream(&(this->response_));
std::string response;
// read one line of response
std::getline(response_stream, response);
// if it starts with "SUCCESS"
if (response.substr(0, 7) == "SUCCESS") {
this->is_connected = true;
return true;
}
else {
this->is_connected = false;
throw connection_exception("Error while connecting to RethinkDB server: " + response);
}
}
catch (std::exception& e)
{
// exception from boost has been caught
throw connection_exception(std::string(e.what()));
}
}
std::shared_ptr<com::rethinkdb::Response> read_response() {
u_int response_length;
char* reply;
size_t bytes_read;
std::shared_ptr<com::rethinkdb::Response> response(new com::rethinkdb::Response());
try {
try {
// read length of the response
boost::asio::read(this->socket_, boost::asio::buffer(&response_length, sizeof(u_int)));
// read content
reply = new char[response_length];
bytes_read = boost::asio::read(this->socket_, boost::asio::buffer(reply, response_length));
}
catch (std::exception& e) {
throw connection_exception("Unable to read from the socket.");
}
if (bytes_read != response_length) throw connection_exception(boost::str(boost::format("%1% bytes read, when %2% bytes promised.") % bytes_read % response_length));
try {
response->ParseFromArray(reply, response_length);
}
catch (std::exception& e) {
throw connection_exception("Unable to parse the protobuf Response object.");
}
delete[] reply;
}
catch (std::exception& e) {
throw connection_exception(boost::str(boost::format("Read response: %1%") % e.what()));
}
return response;
}
void write_query(const com::rethinkdb::Query& query) {
// prepare output stream
std::ostream request_stream(&request_);
// serialize query
std::string blob = query.SerializeAsString();
// write blob's length in little endian 32 bit unsigned integer
u_int blob_length = blob.length();
request_stream.write((char*)&blob_length, sizeof (u_int));
// write protobuf blob
request_stream.write(blob.c_str(), blob.length());
try {
// send the content of the output stream over the wire
boost::asio::write(this->socket_, this->request_);
}
catch (std::exception& e)
{
throw connection_exception(boost::str(boost::format("Write query: exception: %1%") % e.what()));
}
}
private:
std::string host;
std::string port;
std::string database;
std::string auth_key;
int timeout;
int64_t token;
bool is_connected;
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver_;
boost::asio::ip::tcp::socket socket_;
boost::asio::streambuf request_;
boost::asio::streambuf response_;
};
//
// implementation data structures
//
class array_datum;
class null_datum;
class bool_datum;
class num_datum;
class str_datum;
class array_datum;
class object_datum;
class datum {
public:
com::rethinkdb::Datum::DatumType type;
datum(com::rethinkdb::Datum::DatumType t) : type(t) {};
std::shared_ptr<array_datum> to_array_datum() {
std::shared_ptr<datum> ptr(this);
return std::static_pointer_cast<array_datum> (ptr);
}
};
class null_datum {
public:
null_datum();
};
class bool_datum : datum {
public:
bool value;
bool_datum(bool v) : datum(com::rethinkdb::Datum::DatumType::Datum_DatumType_R_BOOL), value(v) {};
};
class num_datum : datum {
public:
double value;
num_datum(double v) : datum(com::rethinkdb::Datum::DatumType::Datum_DatumType_R_NUM), value(v) {};
};
class str_datum : datum {
public:
std::string value;
str_datum(std::string v) : datum(com::rethinkdb::Datum::DatumType::Datum_DatumType_R_STR), value(v) {};
};
class array_datum : datum {
public:
std::vector<datum> value;
array_datum() : datum(com::rethinkdb::Datum::DatumType::Datum_DatumType_R_ARRAY) {
value = std::vector<datum>();
};
};
class object_datum : datum {
public:
boost::unordered_map<std::string, datum> value;
object_datum() : datum(com::rethinkdb::Datum::DatumType::Datum_DatumType_R_OBJECT) {
value = boost::unordered_map<std::string, datum>();
};
};
const com::rethinkdb::driver::datum& parse(const com::rethinkdb::Datum& input) {
/*std::shared_ptr<datum> output;
switch (input.type()) {
case com::rethinkdb::Datum::DatumType::Datum_DatumType_R_NULL:
output = std::make_shared<null_datum>(null_datum());
break;
case com::rethinkdb::Datum::DatumType::Datum_DatumType_R_BOOL:
output = std::make_shared<bool_datum>(bool_datum(input.r_bool()));
break;
case com::rethinkdb::Datum::DatumType::Datum_DatumType_R_NUM:
output = std::make_shared<num_datum>(num_datum(input.r_num()));
break;
case com::rethinkdb::Datum::DatumType::Datum_DatumType_R_STR:
output = std::make_shared<str_datum>(str_datum(input.r_str()));
break;
case com::rethinkdb::Datum::DatumType::Datum_DatumType_R_ARRAY:
output = std::make_shared<array_datum>(array_datum());
for (int i = 0, s = input.r_array_size(); i < s; i++) {
//output->to_array_datum()->value.push_back(parse(input.r_array(i)));
//parse(&input.r_array(i));
//output.push_back(t);
}
break;
case com::rethinkdb::Datum::DatumType::Datum_DatumType_R_OBJECT:
// TODO
break;
}
return output;
*/
return datum(com::rethinkdb::Datum::DatumType::Datum_DatumType_R_NULL);
}
//
// implementation of RQL class
//
class RQL {
public:
RQL(com::rethinkdb::Query::QueryType query_type) : query(com::rethinkdb::Query()) {
this->query.set_type(query_type);
// generate random token
this->query.set_token(rand());
}
RQL() : RQL(com::rethinkdb::Query::QueryType::Query_QueryType_START) {};
RQL* db_create(const std::string& name) {
com::rethinkdb::Term *term;
term = this->query.mutable_query();
term->set_type(com::rethinkdb::Term::TermType::Term_TermType_DB_CREATE);
com::rethinkdb::Term *term_name;
term_name = term->add_args();
term_name->set_type(com::rethinkdb::Term::TermType::Term_TermType_DATUM);
com::rethinkdb::Datum *datum;
datum = term_name->mutable_datum();
datum->set_type(com::rethinkdb::Datum::DatumType::Datum_DatumType_R_STR);
datum->set_r_str(name);
return this;
}
std::vector<datum> run(std::shared_ptr<connection> conn) {
// TODO - optargs?
// write query
conn->write_query(this->query);
// read response
std::shared_ptr<com::rethinkdb::Response> response(conn->read_response());
switch (response->type()) {
case com::rethinkdb::Response::ResponseType::Response_ResponseType_RUNTIME_ERROR:
throw runtime_error_exception("\n\nResponse received:\n" + response->DebugString());
break;
case com::rethinkdb::Response::ResponseType::Response_ResponseType_CLIENT_ERROR:
throw client_error_exception("\n\nResponse received:\n" + response->DebugString());
break;
case com::rethinkdb::Response::ResponseType::Response_ResponseType_COMPILE_ERROR:
throw compile_error_exception("\n\nResponse received:\n" + response->DebugString());
break;
}
// if this point is reached, response is fine
response->PrintDebugString();
}
private:
com::rethinkdb::Query query;
};
}
}
}
#endif<|endoftext|>
|
<commit_before>
// Persistent RNN Includes
#include <persistent_rnn_high_level.h>
#include <prnn/detail/matrix/matrix.h>
#include <prnn/detail/matrix/random_operations.h>
#include <prnn/detail/matrix/matrix_operations.h>
#include <prnn/detail/matrix/matrix_transforms.h>
#include <prnn/detail/matrix/matrix_view.h>
#include <prnn/detail/matrix/copy_operations.h>
#include <prnn/detail/matrix/operation.h>
#include <prnn/detail/rnn/recurrent_ops_handle.h>
#include <prnn/detail/rnn/recurrent_ops.h>
#include <prnn/detail/parallel/synchronization.h>
#include <prnn/detail/util/logger.h>
#include <prnn/detail/util/timer.h>
#include <prnn/detail/util/argument_parser.h>
// Standard Library Includes
#include <random>
#include <iostream>
static double getFlopCount(prnn::RecurrentOpsHandle& handle)
{
return 2.0 * handle.layerSize * handle.layerSize * handle.miniBatchSize * handle.timesteps;
}
void benchmarkRnnForward(size_t iterations, size_t layerSize, size_t miniBatchSize,
size_t timesteps, bool usePersistent, const prnn::matrix::Precision& precision) {
auto weights = prnn::matrix::rand({layerSize, layerSize }, precision);
auto activations = prnn::matrix::rand({layerSize, miniBatchSize, timesteps}, precision);
prnn::RecurrentOpsHandle handle(layerSize, miniBatchSize, timesteps,
prnn::RecurrentRectifiedLinear(),
prnn::RECURRENT_FORWARD,
usePersistent);
auto scratch = prnn::rnn::getForwardPropScratch(handle, precision);
// warm up
prnn::rnn::forwardPropRecurrent(prnn::matrix::DynamicView(activations),
prnn::matrix::ConstDynamicView(weights),
prnn::matrix::DynamicView(scratch), handle);
prnn::parallel::synchronize();
prnn::util::Timer timer;
timer.start();
for (size_t i = 0; i < iterations; ++i) {
prnn::rnn::forwardPropRecurrent(prnn::matrix::DynamicView(activations),
prnn::matrix::ConstDynamicView(weights),
prnn::matrix::DynamicView(scratch), handle);
}
prnn::parallel::synchronize();
timer.stop();
double totalFlops = iterations * getFlopCount(handle);
double teraflops = totalFlops / (timer.seconds() * 1.0e12);
double microsecondsPerKernel = timer.seconds() * 1.0e6 / iterations;
std::cout << "RNN Forward Propagation: " << teraflops << " TFLOPS/s\n";
std::cout << "RNN Average Kernel Time: " << microsecondsPerKernel << " us\n";
}
void benchmarkRnnReverse(size_t iterations, size_t layerSize, size_t miniBatchSize,
size_t timesteps, bool usePersistent, const prnn::matrix::Precision& precision)
{
auto weights = prnn::matrix::rand({layerSize, layerSize }, precision);
auto activations = prnn::matrix::rand({layerSize, miniBatchSize, timesteps}, precision);
auto deltas = prnn::matrix::rand({layerSize, miniBatchSize, timesteps}, precision);
prnn::RecurrentOpsHandle handle(layerSize, miniBatchSize, timesteps,
prnn::RecurrentRectifiedLinear(),
prnn::RECURRENT_FORWARD,
usePersistent);
auto scratch = prnn::rnn::getBackPropDeltasScratch(handle, precision);
// warm up
prnn::rnn::backPropDeltasRecurrent(prnn::matrix::DynamicView(deltas),
prnn::matrix::ConstDynamicView(weights),
prnn::matrix::DynamicView(activations),
prnn::matrix::DynamicView(scratch), handle);
prnn::parallel::synchronize();
prnn::util::Timer timer;
timer.start();
for (size_t i = 0; i < iterations; ++i) {
prnn::rnn::backPropDeltasRecurrent(prnn::matrix::DynamicView(deltas),
prnn::matrix::ConstDynamicView(weights),
prnn::matrix::DynamicView(activations),
prnn::matrix::DynamicView(scratch), handle);
}
prnn::parallel::synchronize();
timer.stop();
double totalFlops = iterations * getFlopCount(handle);
double teraflops = totalFlops / (timer.seconds() * 1.0e12);
double microsecondsPerKernel = timer.seconds() * 1.0e6 / iterations;
std::cout << "RNN Back Propagation Deltas: " << teraflops << " TFLOPS/s\n";
std::cout << "RNN Average Kernel Time: " << microsecondsPerKernel << " us\n";
}
void benchmarkRnnGradients(size_t iterations, size_t layerSize, size_t miniBatchSize,
size_t timesteps, bool usePersistent, const prnn::matrix::Precision& precision)
{
auto weights = prnn::matrix::rand({layerSize, layerSize }, precision);
auto activations = prnn::matrix::rand({layerSize, miniBatchSize, timesteps}, precision);
auto deltas = prnn::matrix::rand({layerSize, miniBatchSize, timesteps}, precision);
prnn::RecurrentOpsHandle handle(layerSize, miniBatchSize, timesteps,
prnn::RecurrentRectifiedLinear(),
prnn::RECURRENT_FORWARD,
usePersistent);
auto scratch = prnn::rnn::getBackPropGradientsScratch(handle, precision);
// warm up
prnn::rnn::backPropGradientsRecurrent(
prnn::matrix::DynamicView(weights),
prnn::matrix::ConstDynamicView(activations),
prnn::matrix::ConstDynamicView(deltas),
prnn::matrix::DynamicView(scratch), handle);
prnn::parallel::synchronize();
prnn::util::Timer timer;
timer.start();
for (size_t i = 0; i < iterations; ++i) {
prnn::rnn::backPropGradientsRecurrent(
prnn::matrix::DynamicView(weights),
prnn::matrix::ConstDynamicView(activations),
prnn::matrix::ConstDynamicView(deltas),
prnn::matrix::DynamicView(scratch), handle);
}
prnn::parallel::synchronize();
timer.stop();
double totalFlops = iterations * getFlopCount(handle);
double teraflops = totalFlops / (timer.seconds() * 1.0e12);
double microsecondsPerKernel = timer.seconds() * 1.0e6 / iterations;
std::cout << "RNN Back Propagation Deltas: " << teraflops << " TFLOPS/s\n";
std::cout << "RNN Average Kernel Time: " << microsecondsPerKernel << " us\n";
}
void runBenchmark(size_t iterations, size_t layerSize, size_t miniBatchSize,
size_t timesteps, bool usePersistent, prnn::matrix::Precision& precision)
{
benchmarkRnnForward( iterations, layerSize, miniBatchSize, timesteps, usePersistent, precision);
benchmarkRnnReverse( iterations, layerSize, miniBatchSize, timesteps, usePersistent, precision);
benchmarkRnnGradients(iterations, layerSize, miniBatchSize, timesteps, usePersistent, precision);
}
int main(int argc, char** argv) {
prnn::util::ArgumentParser parser(argc, argv);
prnn::matrix::Precision precision = prnn::matrix::SinglePrecision();
size_t iterations = 20;
size_t layerSize = prnn::rnn::getMaximumSizeRNNForThisGPU(precision);
size_t miniBatcheSize = 2;
size_t timesteps = 64;
bool usePersistent = true;
parser.parse("-i", "--iterations", iterations, iterations, "Iterations to run each recurrent operation.");
parser.parse("-l", "--layer-size", layerSize, layerSize, "The size of the recurrent layer.");
parser.parse("-b", "--mini-batch-size", miniBatcheSize, miniBatcheSize, "The number of utterances per mini-batch.");
parser.parse("-t", "--timesteps", timesteps, timesteps, "The length of each utterance.");
parser.parse("-p", "--no-peristent", usePersistent, usePersistent, "Disable use of persistent kernels.");
parser.parse();
runBenchmark(iterations, layerSize, miniBatcheSize, timesteps, usePersistent, precision);
}
<commit_msg>ENH: benchmark logging.<commit_after>
// Persistent RNN Includes
#include <persistent_rnn_high_level.h>
#include <prnn/detail/matrix/matrix.h>
#include <prnn/detail/matrix/random_operations.h>
#include <prnn/detail/matrix/matrix_operations.h>
#include <prnn/detail/matrix/matrix_transforms.h>
#include <prnn/detail/matrix/matrix_view.h>
#include <prnn/detail/matrix/copy_operations.h>
#include <prnn/detail/matrix/operation.h>
#include <prnn/detail/rnn/recurrent_ops_handle.h>
#include <prnn/detail/rnn/recurrent_ops.h>
#include <prnn/detail/parallel/synchronization.h>
#include <prnn/detail/util/logger.h>
#include <prnn/detail/util/timer.h>
#include <prnn/detail/util/argument_parser.h>
// Standard Library Includes
#include <random>
#include <iostream>
static double getFlopCount(prnn::RecurrentOpsHandle& handle)
{
return 2.0 * handle.layerSize * handle.layerSize * handle.miniBatchSize * handle.timesteps;
}
void benchmarkRnnForward(size_t iterations, size_t layerSize, size_t miniBatchSize,
size_t timesteps, bool usePersistent, const prnn::matrix::Precision& precision) {
auto weights = prnn::matrix::rand({layerSize, layerSize }, precision);
auto activations = prnn::matrix::rand({layerSize, miniBatchSize, timesteps}, precision);
prnn::RecurrentOpsHandle handle(layerSize, miniBatchSize, timesteps,
prnn::RecurrentRectifiedLinear(),
prnn::RECURRENT_FORWARD,
usePersistent);
auto scratch = prnn::rnn::getForwardPropScratch(handle, precision);
// warm up
prnn::rnn::forwardPropRecurrent(prnn::matrix::DynamicView(activations),
prnn::matrix::ConstDynamicView(weights),
prnn::matrix::DynamicView(scratch), handle);
prnn::parallel::synchronize();
prnn::util::Timer timer;
timer.start();
for (size_t i = 0; i < iterations; ++i) {
prnn::rnn::forwardPropRecurrent(prnn::matrix::DynamicView(activations),
prnn::matrix::ConstDynamicView(weights),
prnn::matrix::DynamicView(scratch), handle);
}
prnn::parallel::synchronize();
timer.stop();
double totalFlops = iterations * getFlopCount(handle);
double teraflops = totalFlops / (timer.seconds() * 1.0e12);
double microsecondsPerKernel = timer.seconds() * 1.0e6 / iterations;
std::cout << "RNN Forward Propagation: " << teraflops << " TFLOPS/s\n";
std::cout << "RNN Average Kernel Time: " << microsecondsPerKernel << " us\n";
}
void benchmarkRnnReverse(size_t iterations, size_t layerSize, size_t miniBatchSize,
size_t timesteps, bool usePersistent, const prnn::matrix::Precision& precision)
{
auto weights = prnn::matrix::rand({layerSize, layerSize }, precision);
auto activations = prnn::matrix::rand({layerSize, miniBatchSize, timesteps}, precision);
auto deltas = prnn::matrix::rand({layerSize, miniBatchSize, timesteps}, precision);
prnn::RecurrentOpsHandle handle(layerSize, miniBatchSize, timesteps,
prnn::RecurrentRectifiedLinear(),
prnn::RECURRENT_FORWARD,
usePersistent);
auto scratch = prnn::rnn::getBackPropDeltasScratch(handle, precision);
// warm up
prnn::rnn::backPropDeltasRecurrent(prnn::matrix::DynamicView(deltas),
prnn::matrix::ConstDynamicView(weights),
prnn::matrix::DynamicView(activations),
prnn::matrix::DynamicView(scratch), handle);
prnn::parallel::synchronize();
prnn::util::Timer timer;
timer.start();
for (size_t i = 0; i < iterations; ++i) {
prnn::rnn::backPropDeltasRecurrent(prnn::matrix::DynamicView(deltas),
prnn::matrix::ConstDynamicView(weights),
prnn::matrix::DynamicView(activations),
prnn::matrix::DynamicView(scratch), handle);
}
prnn::parallel::synchronize();
timer.stop();
double totalFlops = iterations * getFlopCount(handle);
double teraflops = totalFlops / (timer.seconds() * 1.0e12);
double microsecondsPerKernel = timer.seconds() * 1.0e6 / iterations;
std::cout << "RNN Back Propagation Deltas: " << teraflops << " TFLOPS/s\n";
std::cout << "RNN Average Kernel Time: " << microsecondsPerKernel << " us\n";
}
void benchmarkRnnGradients(size_t iterations, size_t layerSize, size_t miniBatchSize,
size_t timesteps, bool usePersistent, const prnn::matrix::Precision& precision)
{
auto weights = prnn::matrix::rand({layerSize, layerSize }, precision);
auto activations = prnn::matrix::rand({layerSize, miniBatchSize, timesteps}, precision);
auto deltas = prnn::matrix::rand({layerSize, miniBatchSize, timesteps}, precision);
prnn::RecurrentOpsHandle handle(layerSize, miniBatchSize, timesteps,
prnn::RecurrentRectifiedLinear(),
prnn::RECURRENT_FORWARD,
usePersistent);
auto scratch = prnn::rnn::getBackPropGradientsScratch(handle, precision);
// warm up
prnn::rnn::backPropGradientsRecurrent(
prnn::matrix::DynamicView(weights),
prnn::matrix::ConstDynamicView(activations),
prnn::matrix::ConstDynamicView(deltas),
prnn::matrix::DynamicView(scratch), handle);
prnn::parallel::synchronize();
prnn::util::Timer timer;
timer.start();
for (size_t i = 0; i < iterations; ++i) {
prnn::rnn::backPropGradientsRecurrent(
prnn::matrix::DynamicView(weights),
prnn::matrix::ConstDynamicView(activations),
prnn::matrix::ConstDynamicView(deltas),
prnn::matrix::DynamicView(scratch), handle);
}
prnn::parallel::synchronize();
timer.stop();
double totalFlops = iterations * getFlopCount(handle);
double teraflops = totalFlops / (timer.seconds() * 1.0e12);
double microsecondsPerKernel = timer.seconds() * 1.0e6 / iterations;
std::cout << "RNN Back Propagation Deltas: " << teraflops << " TFLOPS/s\n";
std::cout << "RNN Average Kernel Time: " << microsecondsPerKernel << " us\n";
}
void runBenchmark(size_t iterations, size_t layerSize, size_t miniBatchSize,
size_t timesteps, bool usePersistent, prnn::matrix::Precision& precision)
{
benchmarkRnnForward( iterations, layerSize, miniBatchSize, timesteps, usePersistent, precision);
benchmarkRnnReverse( iterations, layerSize, miniBatchSize, timesteps, usePersistent, precision);
benchmarkRnnGradients(iterations, layerSize, miniBatchSize, timesteps, usePersistent, precision);
}
int main(int argc, char** argv) {
prnn::util::ArgumentParser parser(argc, argv);
prnn::matrix::Precision precision = prnn::matrix::SinglePrecision();
size_t iterations = 20;
size_t layerSize = prnn::rnn::getMaximumSizeRNNForThisGPU(precision);
size_t miniBatcheSize = 2;
size_t timesteps = 64;
bool usePersistent = true;
parser.parse("-i", "--iterations", iterations, iterations, "Iterations to run each recurrent operation.");
parser.parse("-l", "--layer-size", layerSize, layerSize, "The size of the recurrent layer.");
parser.parse("-b", "--mini-batch-size", miniBatcheSize, miniBatcheSize, "The number of utterances per mini-batch.");
parser.parse("-t", "--timesteps", timesteps, timesteps, "The length of each utterance.");
parser.parse("-p", "--no-peristent", usePersistent, usePersistent, "Disable use of persistent kernels.");
parser.parse();
prnn::util::enable_all_logs();
runBenchmark(iterations, layerSize, miniBatcheSize, timesteps, usePersistent, precision);
}
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "ECComponentEditor.h"
#include "ECEditorModule.h"
#include "IAttribute.h"
#include "ECAttributeEditor.h"
#include "IComponent.h"
#include "Transform.h"
#include "AssetReference.h"
#include <QtTreePropertyBrowser>
#include <QtGroupPropertyManager>
#include <QtProperty>
#include "MemoryLeakCheck.h"
namespace ECEditor
{
// static
//! @todo Replace this more practical implementation where new attribute type support would be more pratical.
//! Like somesort of factory that is ownd by ComponentManager.
ECAttributeEditorBase *ECComponentEditor::CreateAttributeEditor(
QtAbstractPropertyBrowser *browser,
ECComponentEditor *editor,
ComponentPtr component,
const QString &name,
const QString &type)
//IAttribute &attribute)
{
ECAttributeEditorBase *attributeEditor = 0;
if(type == "float")
attributeEditor = new ECAttributeEditor<float>(browser, component, name, editor);//&attribute, editor);
else if(type == "int")
attributeEditor = new ECAttributeEditor<int>(browser, component, name, editor);
else if(type == "vector3df")
attributeEditor = new ECAttributeEditor<Vector3df>(browser, component, name, editor);
else if(type == "color")
attributeEditor = new ECAttributeEditor<Color>(browser, component, name, editor);
else if(type == "string")
attributeEditor = new ECAttributeEditor<QString>(browser, component, name, editor);
else if(type == "bool")
attributeEditor = new ECAttributeEditor<bool>(browser, component, name, editor);
else if(type == "qvariant")
attributeEditor = new ECAttributeEditor<QVariant>(browser, component, name, editor);
else if(type == "qvariantlist")
attributeEditor = new ECAttributeEditor<QVariantList>(browser, component, name, editor);
else if(type == "assetreference")
attributeEditor = new ECAttributeEditor<AssetReference>(browser, component, name, editor);
else if(type == "transform")
attributeEditor = new ECAttributeEditor<Transform>(browser, component, name, editor);
/*if(dynamic_cast<const Attribute<float> *>(&attribute))
attributeEditor = new ECAttributeEditor<float>(browser, &attribute, editor);
else if(dynamic_cast<const Attribute<int> *>(&attribute))
attributeEditor = new ECAttributeEditor<int>(browser, &attribute, editor);
else if(dynamic_cast<const Attribute<Vector3df> *>(&attribute))
attributeEditor = new ECAttributeEditor<Vector3df>(browser, &attribute, editor);
else if(dynamic_cast<const Attribute<Color> *>(&attribute))
attributeEditor = new ECAttributeEditor<Color>(browser, &attribute, editor);
else if(dynamic_cast<const Attribute<QString> *>(&attribute))
attributeEditor = new ECAttributeEditor<QString>(browser, &attribute, editor);
else if(dynamic_cast<const Attribute<bool> *>(&attribute))
attributeEditor = new ECAttributeEditor<bool>(browser, &attribute, editor);
else if(dynamic_cast<const Attribute<QVariant> *>(&attribute))
attributeEditor = new ECAttributeEditor<QVariant>(browser, &attribute, editor);
else if(dynamic_cast<const Attribute<QVariantList > *>(&attribute))
attributeEditor = new ECAttributeEditor<QVariantList >(browser, &attribute, editor);
else if(dynamic_cast<const Attribute<AssetReference> *>(&attribute))
attributeEditor = new ECAttributeEditor<AssetReference>(browser, &attribute, editor);
else if(dynamic_cast<const Attribute<Transform> *>(&attribute))
attributeEditor = new ECAttributeEditor<Transform>(browser, &attribute, editor);*/
return attributeEditor;
}
ECComponentEditor::ECComponentEditor(ComponentPtr component, QtAbstractPropertyBrowser *propertyBrowser):
QObject(propertyBrowser),
groupProperty_(0),
groupPropertyManager_(0),
propertyBrowser_(propertyBrowser)
{
assert(component);
typeName_ = component->TypeName();
name_ = component->Name();
assert(propertyBrowser_);
if(!propertyBrowser_)
return;
groupPropertyManager_ = new QtGroupPropertyManager(this);
if(groupPropertyManager_)
{
groupProperty_ = groupPropertyManager_->addProperty();
AddNewComponent(component, true);
CreateAttributeEditors(component);
}
propertyBrowser_->addProperty(groupProperty_);
}
ECComponentEditor::~ECComponentEditor()
{
propertyBrowser_->unsetFactoryForManager(groupPropertyManager_);
SAFE_DELETE(groupProperty_)
SAFE_DELETE(groupPropertyManager_)
while(!attributeEditors_.empty())
{
SAFE_DELETE(attributeEditors_.begin()->second)
attributeEditors_.erase(attributeEditors_.begin());
}
}
void ECComponentEditor::CreateAttributeEditors(ComponentPtr component)
{
AttributeVector attributes = component->GetAttributes();
for(uint i = 0; i < attributes.size(); i++)
{
ECAttributeEditorBase *attributeEditor = 0;
attributeEditor = ECComponentEditor::CreateAttributeEditor(propertyBrowser_,
this,
component,
QString::fromStdString(attributes[i]->GetNameString()),
QString::fromStdString(attributes[i]->TypenameToString()));
if(!attributeEditor)
continue;
attributeEditors_[attributes[i]->GetName()] = attributeEditor;
attributeEditor->UpdateEditorUI();
groupProperty_->setToolTip("Component type is " + component->TypeName());
groupProperty_->addSubProperty(attributeEditor->GetProperty());
connect(attributeEditor, SIGNAL(EditorChanged(const QString &)), this, SLOT(OnEditorChanged(const QString &)));
}
}
void ECComponentEditor::UpdateGroupPropertyText()
{
if(!groupProperty_ || !components_.size())
return;
QString componentName = typeName_;
componentName.replace("EC_", "");
QString groupPropertyName = componentName;
if(!name_.isEmpty())
groupPropertyName += " (" + name_ + ") ";
if(components_.size() > 1)
groupPropertyName += QString(" (%1 components)").arg(components_.size());
groupProperty_->setPropertyName(groupPropertyName);
}
bool ECComponentEditor::ContainProperty(QtProperty *property) const
{
AttributeEditorMap::const_iterator constIter = attributeEditors_.begin();
while(constIter != attributeEditors_.end())
{
if(constIter->second->ContainProperty(property))
return true;
constIter++;
}
return false;
}
void ECComponentEditor::AddNewComponent(ComponentPtr component, bool updateUi)
{
//! Check that component type is same as editor's typename (We only want to add same type of components to editor).
if(component->TypeName() != typeName_)
return;
components_.insert(component);
//! insert new component for each attribute editor.
AttributeEditorMap::iterator iter = attributeEditors_.begin();
while(iter != attributeEditors_.end())
{
IAttribute *attribute = component->GetAttribute(iter->second->GetAttributeName());
if(attribute)
iter->second->AddComponent(component);
iter++;
}
QObject::connect(component.get(), SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)), this, SLOT(AttributeChanged(IAttribute*, AttributeChange::Type)));
UpdateGroupPropertyText();
}
void ECComponentEditor::RemoveComponent(ComponentPtr component)
{
if(!component)
return;
if(component->TypeName() != typeName_)
return;
ComponentSet::iterator iter = components_.begin();
while(iter != components_.end())
{
ComponentPtr componentPtr = (*iter).lock();
if(componentPtr.get() == component.get())
{
AttributeEditorMap::iterator attributeIter = attributeEditors_.begin();
while(attributeIter != attributeEditors_.end())
{
IAttribute *attribute = componentPtr->GetAttribute(attributeIter->second->GetAttributeName());
if(attribute)
attributeIter->second->RemoveComponent(component);//RemoveAttribute(attribute);
attributeIter++;
}
disconnect(componentPtr.get(), SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)), this, SLOT(AttributeChanged(IAttribute*, AttributeChange::Type)));
components_.erase(iter);
break;
}
iter++;
}
UpdateGroupPropertyText();
}
void ECComponentEditor::OnEditorChanged(const QString &name)
{
ECAttributeEditorBase *editor = qobject_cast<ECAttributeEditorBase*>(sender());
if(!editor)
{
ECEditorModule::LogWarning("Fail to convert signal sender to ECAttributeEditorBase.");
return;
}
groupProperty_->addSubProperty(editor->GetProperty());
}
void ECComponentEditor::AttributeChanged(IAttribute* attribute, AttributeChange::Type change)
{
IComponent *component = dynamic_cast<IComponent *>(sender());
if((!component) || (!attribute))
return;
if(component->TypeName() != typeName_)
return;
AttributeEditorMap::iterator iter = attributeEditors_.find(attribute->GetName());
if(iter != attributeEditors_.end())
iter->second->UpdateEditorUI();
}
}
<commit_msg>Fixed an issue that prevent float type of attribute to appear on the ECEditor.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "ECComponentEditor.h"
#include "ECEditorModule.h"
#include "IAttribute.h"
#include "ECAttributeEditor.h"
#include "IComponent.h"
#include "Transform.h"
#include "AssetReference.h"
#include <QtTreePropertyBrowser>
#include <QtGroupPropertyManager>
#include <QtProperty>
#include "MemoryLeakCheck.h"
namespace ECEditor
{
// static
//! @todo Replace this more practical implementation where new attribute type support would be more pratical.
//! Like somesort of factory that is ownd by ComponentManager.
ECAttributeEditorBase *ECComponentEditor::CreateAttributeEditor(
QtAbstractPropertyBrowser *browser,
ECComponentEditor *editor,
ComponentPtr component,
const QString &name,
const QString &type)
//IAttribute &attribute)
{
ECAttributeEditorBase *attributeEditor = 0;
if(type == "real")
attributeEditor = new ECAttributeEditor<float>(browser, component, name, editor);
else if(type == "int")
attributeEditor = new ECAttributeEditor<int>(browser, component, name, editor);
else if(type == "vector3df")
attributeEditor = new ECAttributeEditor<Vector3df>(browser, component, name, editor);
else if(type == "color")
attributeEditor = new ECAttributeEditor<Color>(browser, component, name, editor);
else if(type == "string")
attributeEditor = new ECAttributeEditor<QString>(browser, component, name, editor);
else if(type == "bool")
attributeEditor = new ECAttributeEditor<bool>(browser, component, name, editor);
else if(type == "qvariant")
attributeEditor = new ECAttributeEditor<QVariant>(browser, component, name, editor);
else if(type == "qvariantlist")
attributeEditor = new ECAttributeEditor<QVariantList>(browser, component, name, editor);
else if(type == "assetreference")
attributeEditor = new ECAttributeEditor<AssetReference>(browser, component, name, editor);
else if(type == "transform")
attributeEditor = new ECAttributeEditor<Transform>(browser, component, name, editor);
return attributeEditor;
}
ECComponentEditor::ECComponentEditor(ComponentPtr component, QtAbstractPropertyBrowser *propertyBrowser):
QObject(propertyBrowser),
groupProperty_(0),
groupPropertyManager_(0),
propertyBrowser_(propertyBrowser)
{
assert(component);
typeName_ = component->TypeName();
name_ = component->Name();
assert(propertyBrowser_);
if(!propertyBrowser_)
return;
groupPropertyManager_ = new QtGroupPropertyManager(this);
if(groupPropertyManager_)
{
groupProperty_ = groupPropertyManager_->addProperty();
AddNewComponent(component, true);
CreateAttributeEditors(component);
}
propertyBrowser_->addProperty(groupProperty_);
}
ECComponentEditor::~ECComponentEditor()
{
propertyBrowser_->unsetFactoryForManager(groupPropertyManager_);
SAFE_DELETE(groupProperty_)
SAFE_DELETE(groupPropertyManager_)
while(!attributeEditors_.empty())
{
SAFE_DELETE(attributeEditors_.begin()->second)
attributeEditors_.erase(attributeEditors_.begin());
}
}
void ECComponentEditor::CreateAttributeEditors(ComponentPtr component)
{
AttributeVector attributes = component->GetAttributes();
for(uint i = 0; i < attributes.size(); i++)
{
ECAttributeEditorBase *attributeEditor = 0;
attributeEditor = ECComponentEditor::CreateAttributeEditor(propertyBrowser_,
this,
component,
QString::fromStdString(attributes[i]->GetNameString()),
QString::fromStdString(attributes[i]->TypenameToString()));
if(!attributeEditor)
continue;
attributeEditors_[attributes[i]->GetName()] = attributeEditor;
attributeEditor->UpdateEditorUI();
groupProperty_->setToolTip("Component type is " + component->TypeName());
groupProperty_->addSubProperty(attributeEditor->GetProperty());
connect(attributeEditor, SIGNAL(EditorChanged(const QString &)), this, SLOT(OnEditorChanged(const QString &)));
}
}
void ECComponentEditor::UpdateGroupPropertyText()
{
if(!groupProperty_ || !components_.size())
return;
QString componentName = typeName_;
componentName.replace("EC_", "");
QString groupPropertyName = componentName;
if(!name_.isEmpty())
groupPropertyName += " (" + name_ + ") ";
if(components_.size() > 1)
groupPropertyName += QString(" (%1 components)").arg(components_.size());
groupProperty_->setPropertyName(groupPropertyName);
}
bool ECComponentEditor::ContainProperty(QtProperty *property) const
{
AttributeEditorMap::const_iterator constIter = attributeEditors_.begin();
while(constIter != attributeEditors_.end())
{
if(constIter->second->ContainProperty(property))
return true;
constIter++;
}
return false;
}
void ECComponentEditor::AddNewComponent(ComponentPtr component, bool updateUi)
{
//! Check that component type is same as editor's typename (We only want to add same type of components to editor).
if(component->TypeName() != typeName_)
return;
components_.insert(component);
//! insert new component for each attribute editor.
AttributeEditorMap::iterator iter = attributeEditors_.begin();
while(iter != attributeEditors_.end())
{
IAttribute *attribute = component->GetAttribute(iter->second->GetAttributeName());
if(attribute)
iter->second->AddComponent(component);
iter++;
}
QObject::connect(component.get(), SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)), this, SLOT(AttributeChanged(IAttribute*, AttributeChange::Type)));
UpdateGroupPropertyText();
}
void ECComponentEditor::RemoveComponent(ComponentPtr component)
{
if(!component)
return;
if(component->TypeName() != typeName_)
return;
ComponentSet::iterator iter = components_.begin();
while(iter != components_.end())
{
ComponentPtr componentPtr = (*iter).lock();
if(componentPtr.get() == component.get())
{
AttributeEditorMap::iterator attributeIter = attributeEditors_.begin();
while(attributeIter != attributeEditors_.end())
{
IAttribute *attribute = componentPtr->GetAttribute(attributeIter->second->GetAttributeName());
if(attribute)
attributeIter->second->RemoveComponent(component);//RemoveAttribute(attribute);
attributeIter++;
}
disconnect(componentPtr.get(), SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)), this, SLOT(AttributeChanged(IAttribute*, AttributeChange::Type)));
components_.erase(iter);
break;
}
iter++;
}
UpdateGroupPropertyText();
}
void ECComponentEditor::OnEditorChanged(const QString &name)
{
ECAttributeEditorBase *editor = qobject_cast<ECAttributeEditorBase*>(sender());
if(!editor)
{
ECEditorModule::LogWarning("Fail to convert signal sender to ECAttributeEditorBase.");
return;
}
groupProperty_->addSubProperty(editor->GetProperty());
}
void ECComponentEditor::AttributeChanged(IAttribute* attribute, AttributeChange::Type change)
{
IComponent *component = dynamic_cast<IComponent *>(sender());
if((!component) || (!attribute))
return;
if(component->TypeName() != typeName_)
return;
AttributeEditorMap::iterator iter = attributeEditors_.find(attribute->GetName());
if(iter != attributeEditors_.end())
iter->second->UpdateEditorUI();
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 Stanislas Polu.
// See the LICENSE file.
#include "breach/browser/node/node_thread.h"
#include "breach/browser/node/api/api_bindings.h"
#include "content/public/browser/browser_thread.h"
#include "third_party/node/src/node.h"
#include "third_party/node/src/node_internals.h"
#include "base/command_line.h"
#include "base/time/time.h"
using v8::Isolate;
using v8::HandleScope;
using v8::Local;
using v8::Locker;
using v8::Context;
using v8::Object;
using v8::V8;
using v8::Value;
using v8::Script;
using v8::String;
using v8::RegisterExtension;
using namespace content;
namespace breach {
static NodeThread* s_thread = NULL;
NodeThread*
NodeThread::Get()
{
if(s_thread == NULL) {
s_thread = new NodeThread();
}
return s_thread;
}
NodeThread::NodeThread()
: Thread("node_wrapper_thread")
{
}
NodeThread::~NodeThread()
{
/* All Thread subclasses must call Stop() in the destructor */
Stop();
}
void
NodeThread::Init()
{
message_loop()->PostTask(FROM_HERE,
base::Bind(&NodeThread::RunUvLoop,
base::Unretained(this)));
}
void
NodeThread::Run(
base::MessageLoop* message_loop)
{
/* TODO(spolu): fork execution depending on kBreachRawInit */
/* If not set, launch the default version of the Browser. */
/* If set, pass argc/argv to Node */
/* Extract argc, argv to pass it directly to Node */
const CommandLine* command_line = CommandLine::ForCurrentProcess();
int argc = command_line->argv().size();
char **argv = (char**)malloc(argc * sizeof(char*));
for(int i = 0; i < argc; i ++) {
unsigned len = strlen(command_line->argv()[i].c_str()) + 1;
argv[i] = (char*) malloc(len * sizeof(char));
memcpy(argv[i], command_line->argv()[i].c_str(), len);
}
node::InitSetup(argc, argv);
Isolate* node_isolate = Isolate::GetCurrent();
V8::Initialize();
{
Locker locker(node_isolate);
HandleScope handle_scope(node_isolate);
api_bindings_.reset(new ApiBindings());
RegisterExtension(api_bindings_.get());
const char* names[] = { "api_bindings.js" };
v8::ExtensionConfiguration extensions(1, names);
/* Create the one and only Context. */
context_ = Context::New(node_isolate, &extensions);
Context::Scope context_scope(context_);
node::SetupBindingCache();
process_ = node::SetupProcessObject(argc, argv);
/* Create all the objects, load modules, do everything. */
/* so your next reading stop should be node::Load()! */
node::Load(process_);
Thread::Run(message_loop);
node::EmitExit(process_);
node::RunAtExit();
}
/* Cleanup */
for(int i = 0; i < argc; i++) { free(argv[i]); }
free(argv);
}
void
NodeThread::CleanUp()
{
/* Clean up. Not strictly necessary. */
V8::Dispose();
}
void
NodeThread::RunUvLoop()
{
/* int ret = */ uv_run(uv_default_loop(), UV_RUN_NOWAIT);
/* TODO(spolu): FixMe [/!\ Bad Code Ahead] */
/* If we call with UV_RUN_ONCE then it will hang the thread while there is */
/* no `uv` related events, blocking all Chromium/Breach message delivery. */
/* We therefore post a delayed task to avoid hogging the CPU but not too */
/* far away to avoid any delay in the execution of nodeJS code. This is no */
/* perfect, but it works! */
/* Eventual best solution will be to implement a message_loop based on uv */
/* as it has already been done for node-webkit */
/* Another acceptable solution would be to run the uv run_loop direclty */
/* from here and expose a mechanism for existing content threads to post a */
/* task on that thread. */
message_loop()->PostDelayedTask(FROM_HERE,
base::Bind(&NodeThread::RunUvLoop,
base::Unretained(this)),
base::TimeDelta::FromMicroseconds(100));
}
} // namespace breach
<commit_msg>NodeThread Comment<commit_after>// Copyright (c) 2013 Stanislas Polu.
// See the LICENSE file.
#include "breach/browser/node/node_thread.h"
#include "breach/browser/node/api/api_bindings.h"
#include "content/public/browser/browser_thread.h"
#include "third_party/node/src/node.h"
#include "third_party/node/src/node_internals.h"
#include "base/command_line.h"
#include "base/time/time.h"
using v8::Isolate;
using v8::HandleScope;
using v8::Local;
using v8::Locker;
using v8::Context;
using v8::Object;
using v8::V8;
using v8::Value;
using v8::Script;
using v8::String;
using v8::RegisterExtension;
using namespace content;
namespace breach {
static NodeThread* s_thread = NULL;
NodeThread*
NodeThread::Get()
{
if(s_thread == NULL) {
s_thread = new NodeThread();
}
return s_thread;
}
NodeThread::NodeThread()
: Thread("node_wrapper_thread")
{
}
NodeThread::~NodeThread()
{
/* All Thread subclasses must call Stop() in the destructor */
Stop();
}
void
NodeThread::Init()
{
message_loop()->PostTask(FROM_HERE,
base::Bind(&NodeThread::RunUvLoop,
base::Unretained(this)));
}
void
NodeThread::Run(
base::MessageLoop* message_loop)
{
/* TODO(spolu): fork execution depending on kBreachRawInit */
/* If not set, launch the default version of the Browser. */
/* If set, pass argc/argv to Node */
/* Extract argc, argv to pass it directly to Node */
const CommandLine* command_line = CommandLine::ForCurrentProcess();
int argc = command_line->argv().size();
char **argv = (char**)malloc(argc * sizeof(char*));
for(int i = 0; i < argc; i ++) {
unsigned len = strlen(command_line->argv()[i].c_str()) + 1;
argv[i] = (char*) malloc(len * sizeof(char));
memcpy(argv[i], command_line->argv()[i].c_str(), len);
}
node::InitSetup(argc, argv);
Isolate* node_isolate = Isolate::GetCurrent();
V8::Initialize();
{
Locker locker(node_isolate);
HandleScope handle_scope(node_isolate);
api_bindings_.reset(new ApiBindings());
RegisterExtension(api_bindings_.get());
const char* names[] = { "api_bindings.js" };
v8::ExtensionConfiguration extensions(1, names);
/* Create the one and only Context. */
context_ = Context::New(node_isolate, &extensions);
Context::Scope context_scope(context_);
node::SetupBindingCache();
process_ = node::SetupProcessObject(argc, argv);
/* Create all the objects, load modules, do everything. */
/* so your next reading stop should be node::Load()! */
node::Load(process_);
Thread::Run(message_loop);
node::EmitExit(process_);
node::RunAtExit();
}
/* Cleanup */
for(int i = 0; i < argc; i++) { free(argv[i]); }
free(argv);
}
void
NodeThread::CleanUp()
{
/* Clean up. Not strictly necessary. */
V8::Dispose();
}
void
NodeThread::RunUvLoop()
{
/* int ret = */ uv_run(uv_default_loop(), UV_RUN_NOWAIT);
/* TODO(spolu): FixMe [/!\ Bad Code Ahead] */
/* If we call with UV_RUN_ONCE then it will hang the thread while there is */
/* no `uv` related events, blocking all Chromium/Breach message delivery. */
/* We therefore post a delayed task to avoid hogging the CPU but not too */
/* far away to avoid any delay in the execution of nodeJS code. This is no */
/* perfect, but it works! */
/* An eventually very good solution would be to be able to call the run */
/* loop with UV_RUN_ONCE and be able to generate a dummy request form */
/* the outside when a message needs to get delivered. */
/* Eventual best solution will be to implement a message_loop based on uv */
/* as it has already been done for node-webkit */
/* Another acceptable solution would be to run the uv run_loop direclty */
/* from here and expose a mechanism for existing content threads to post a */
/* task on that thread. */
message_loop()->PostDelayedTask(FROM_HERE,
base::Bind(&NodeThread::RunUvLoop,
base::Unretained(this)),
base::TimeDelta::FromMicroseconds(100));
}
} // namespace breach
<|endoftext|>
|
<commit_before>#ifndef _LANDMARKS_HH_
# define _LANDMARKS_HH_
#include <vector>
#include <map>
#include <cmath>
static const double CONVERSION = (M_PI / 180.0); // Convert to radians
static const unsigned int MAXLANDMARKS = 3000; // Max number of landmarks
static const double MAXERROR = 0.5; // If a landmarks is within this distance of another landmarks, its the same landmarks
static const unsigned int MINOBSERVATIONS = 15; // Number of times a landmark must be observed to be recongnized as a landmark
static const unsigned int LIFE = 40; // Use to reset life counter (counter use to determine whether to discard a landmark or not)
static const float MAX_RANGE = 1.0;
static const unsigned int MAXTRIALS = 1000; // RANSAC: max times to run algorithm
static const unsigned int MAXSAMPLE = 10; // RANSAC: randomly select x points
static const unsigned int MINLINEPOINTS = 30; // RANSAC: if less than x points left, don't bother trying to find a consensus (stop algorithm)
static const double RANSAC_TOLERANCE = 0.05; // RANSAC: if point is within x distance of line, its part of the line
static const unsigned int RANSAC_CONSENSUS = 30; // RANSAC: at leat x votes required to determine if its a line
static const double DEGRESSPERSCAN = 0.5;
class Landmarks
{
public:
class Landmark
{
public:
double pos[2]; // landmarks (x, y) position relative to map
int id; // lanndmarks unique ID
int life; // a life counter to determine whether to discard a landmarl
int totalTimeObserved; // the number of times we have seen the landmark
double range; // last observed range to landmark
double bearing; // last observed bearing to landmark
// RANSAC : Store equation of a line to be reused
double a;
double b;
double rangeError; // distance from robot position to the wall we are using as a landmark (to calculate error)
double bearingError; // bearing from robot position to the wall we are using as a landmark (to calculate error)
public:
Landmark();
~Landmark();
};
public:
Landmarks();
~Landmarks();
Landmarks(double degreePerScan);
int getSLamId(int id) const;
int addSlamId(int landmarkId, int slamId);
int removeBadLandmarks(double laserdata[], double robotPosition[]); // Possibly change array to vector ? Depends of the robot
int removeBadLandmarks(const std::vector<double> & laserdata, const std::vector<double> & robotPosition); // both to be sure
std::vector<Landmark *> updateAndAddLineLandmarks(std::vector<Landmark *> extractedLandmarks); // bad return value
std::vector<Landmark *> updateAndAddLandmarkUsingEKFResults(bool matched[], int id[], double ranges[], double bearings[], double robotPosition[]);
int updateLineLandmark(const Landmark &lm);
std::vector<Landmark *> extractLineLandmarks(double laserdata[], double robotPosition[]);
// matched is an array of boolean
// id is an arary of int
// ranges is an array of double
// bearings is an array of double
int alignLandmarkData(std::vector<Landmark *> &extractedLandmarks, bool *matched, int *id,
double *ranges, double *bearings, std::vector<std::pair<double, double> > &lmrks, std::vector<std::pair<double, double> > &exlmrks);
int addToDB(const Landmark &lm);
int getDBSize() const;
std::vector<Landmark *> getLandmarkDB() const;
private:
Landmark *updateLandmark(bool matched, int id, double distance, double readingNo, double robotPosition[]);
Landmark *udpdateLandmark(Landmark *lm);
void leastSquaresLineEstimate(double laserdata[], double robotPosition[], int selectPoints[], int arraySize, double &a, double &b);
double distanceToLine(double x, double y, double a, double b);
std::vector<Landmark *> extractSpikeLandmarks(double laserdata[], double robotPosition[]);
Landmark *getLandmark(double range, int readingNo, double robotPosition[]);
Landmark *getLineLandmark(double a, double b, double robotPosition[]);
Landmark *getLine(double a, double b);
Landmark *getOrigin();
void getClosestAssociation(Landmark *lm, int &id, int &totalTimeObserved);
int getAssociation(Landmark &lm);
std::vector<Landmark *> removeDouble(std::vector<Landmark *> extractedLandmarks);
double distance(double x1, double y1, double x2, double y2) const;
double distance(const Landmark &lm1, const Landmark &lm2) const;
private:
std::vector<Landmark *> landmarkDB;
int DBSize;
std::vector<std::pair<int, int> > IDtoID;
int EKFLandmarks;
};
#endif
<commit_msg>SLAM: Modification of the header file, degreePerScan was not in the class Landmarks<commit_after>#ifndef _LANDMARKS_HH_
# define _LANDMARKS_HH_
#include <vector>
#include <map>
#include <cmath>
static const double CONVERSION = (M_PI / 180.0); // Convert to radians
static const unsigned int MAXLANDMARKS = 3000; // Max number of landmarks
static const double MAXERROR = 0.5; // If a landmarks is within this distance of another landmarks, its the same landmarks
static const unsigned int MINOBSERVATIONS = 15; // Number of times a landmark must be observed to be recongnized as a landmark
static const unsigned int LIFE = 40; // Use to reset life counter (counter use to determine whether to discard a landmark or not)
static const float MAX_RANGE = 1.0;
static const unsigned int MAXTRIALS = 1000; // RANSAC: max times to run algorithm
static const unsigned int MAXSAMPLE = 10; // RANSAC: randomly select x points
static const unsigned int MINLINEPOINTS = 30; // RANSAC: if less than x points left, don't bother trying to find a consensus (stop algorithm)
static const double RANSAC_TOLERANCE = 0.05; // RANSAC: if point is within x distance of line, its part of the line
static const unsigned int RANSAC_CONSENSUS = 30; // RANSAC: at leat x votes required to determine if its a line
static const double DEGREESPERSCAN = 0.5;
class Landmarks
{
public:
class Landmark
{
public:
double pos[2]; // landmarks (x, y) position relative to map
int id; // lanndmarks unique ID
int life; // a life counter to determine whether to discard a landmarl
int totalTimeObserved; // the number of times we have seen the landmark
double range; // last observed range to landmark
double bearing; // last observed bearing to landmark
// RANSAC : Store equation of a line to be reused
double a;
double b;
double rangeError; // distance from robot position to the wall we are using as a landmark (to calculate error)
double bearingError; // bearing from robot position to the wall we are using as a landmark (to calculate error)
public:
Landmark();
~Landmark();
};
public:
~Landmarks();
Landmarks(double degreePerScan = DEGREESPERSCAN);
int getSLamId(int id) const;
int addSlamId(int landmarkId, int slamId);
int removeBadLandmarks(double laserdata[], double robotPosition[]); // Possibly change array to vector ? Depends of the robot
int removeBadLandmarks(const std::vector<double> & laserdata, const std::vector<double> & robotPosition); // both to be sure
std::vector<Landmark *> updateAndAddLineLandmarks(std::vector<Landmark *> extractedLandmarks); // bad return value
std::vector<Landmark *> updateAndAddLandmarkUsingEKFResults(bool matched[], int id[], double ranges[], double bearings[], double robotPosition[]);
int updateLineLandmark(const Landmark &lm);
std::vector<Landmark *> extractLineLandmarks(double laserdata[], double robotPosition[]);
// matched is an array of boolean
// id is an arary of int
// ranges is an array of double
// bearings is an array of double
int alignLandmarkData(std::vector<Landmark *> &extractedLandmarks, bool *matched, int *id,
double *ranges, double *bearings, std::vector<std::pair<double, double> > &lmrks, std::vector<std::pair<double, double> > &exlmrks);
int addToDB(const Landmark &lm);
int getDBSize() const;
std::vector<Landmark *> getLandmarkDB() const;
private:
Landmark *updateLandmark(bool matched, int id, double distance, double readingNo, double robotPosition[]);
Landmark *udpdateLandmark(Landmark *lm);
void leastSquaresLineEstimate(double laserdata[], double robotPosition[], int selectPoints[], int arraySize, double &a, double &b);
double distanceToLine(double x, double y, double a, double b);
std::vector<Landmark *> extractSpikeLandmarks(double laserdata[], double robotPosition[]);
Landmark *getLandmark(double range, int readingNo, double robotPosition[]);
Landmark *getLineLandmark(double a, double b, double robotPosition[]);
Landmark *getLine(double a, double b);
Landmark *getOrigin();
void getClosestAssociation(Landmark *lm, int &id, int &totalTimeObserved);
int getAssociation(Landmark &lm);
std::vector<Landmark *> removeDouble(std::vector<Landmark *> extractedLandmarks);
double distance(double x1, double y1, double x2, double y2) const;
double distance(const Landmark &lm1, const Landmark &lm2) const;
private: // PRIVATE OTHER CASES
#ifdef UNITTEST
public: // ONLY FOR UNIT TESTS
#endif
double degreePerScan;
std::vector<Landmark *> landmarkDB;
int DBSize;
std::vector<std::pair<int, int> > IDtoID;
int EKFLandmarks;
};
#endif
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "camerabinvideoencoder.h"
#include "camerabinsession.h"
#include "camerabincontainer.h"
#include <QtCore/qdebug.h>
CameraBinVideoEncoder::CameraBinVideoEncoder(CameraBinSession *session)
:QVideoEncoderControl(session), m_session(session)
{
QList<QByteArray> codecCandidates;
#if defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
codecCandidates << "video/h264" << "video/mpeg4" << "video/h263" << "video/theora"
<< "video/mpeg2" << "video/mpeg1" << "video/mjpeg" << "video/VP8" << "video/h261";
m_elementNames["video/h264"] = "dsph264enc";
m_elementNames["video/mpeg4"] = "dspmp4venc";
m_elementNames["video/h263"] = "dsph263enc";
m_elementNames["video/theora"] = "theoraenc";
m_elementNames["video/mpeg2"] = "ffenc_mpeg2video";
m_elementNames["video/mpeg1"] = "ffenc_mpeg1video";
m_elementNames["video/mjpeg"] = "ffenc_mjpeg";
m_elementNames["video/VP8"] = "vp8enc";
m_elementNames["video/h261"] = "ffenc_h261";
m_codecOptions["video/mpeg4"] = QStringList() << "mode" << "keyframe-interval";
#else
codecCandidates << "video/h264" << "video/xvid" << "video/mpeg4"
<< "video/mpeg1" << "video/mpeg2" << "video/theora"
<< "video/VP8" << "video/h261" << "video/mjpeg";
m_elementNames["video/h264"] = "x264enc";
m_elementNames["video/xvid"] = "xvidenc";
m_elementNames["video/mpeg4"] = "ffenc_mpeg4";
m_elementNames["video/mpeg1"] = "ffenc_mpeg1video";
m_elementNames["video/mpeg2"] = "ffenc_mpeg2video";
m_elementNames["video/theora"] = "theoraenc";
m_elementNames["video/mjpeg"] = "ffenc_mjpeg";
m_elementNames["video/VP8"] = "vp8enc";
m_elementNames["video/h261"] = "ffenc_h261";
m_codecOptions["video/h264"] = QStringList() << "quantizer";
m_codecOptions["video/xvid"] = QStringList() << "quantizer" << "profile";
m_codecOptions["video/mpeg4"] = QStringList() << "quantizer";
m_codecOptions["video/mpeg1"] = QStringList() << "quantizer";
m_codecOptions["video/mpeg2"] = QStringList() << "quantizer";
m_codecOptions["video/theora"] = QStringList();
#endif
foreach( const QByteArray& codecName, codecCandidates ) {
QByteArray elementName = m_elementNames[codecName];
GstElementFactory *factory = gst_element_factory_find(elementName.constData());
if (factory) {
m_codecs.append(codecName);
const gchar *descr = gst_element_factory_get_description(factory);
m_codecDescriptions.insert(codecName, QString::fromUtf8(descr));
m_streamTypes.insert(codecName,
CameraBinContainer::supportedStreamTypes(factory, GST_PAD_SRC));
gst_object_unref(GST_OBJECT(factory));
}
}
}
CameraBinVideoEncoder::~CameraBinVideoEncoder()
{
}
QList<QSize> CameraBinVideoEncoder::supportedResolutions(const QVideoEncoderSettings &settings, bool *continuous) const
{
if (continuous)
*continuous = false;
QPair<int,int> rate = rateAsRational(settings.frameRate());
//select the closest supported rational rate to settings.frameRate()
return m_session->supportedResolutions(rate, continuous);
}
QList< qreal > CameraBinVideoEncoder::supportedFrameRates(const QVideoEncoderSettings &settings, bool *continuous) const
{
if (continuous)
*continuous = false;
QList< qreal > res;
QPair<int,int> rate;
foreach(rate, m_session->supportedFrameRates(settings.resolution(), continuous)) {
if (rate.second > 0)
res << qreal(rate.first)/rate.second;
}
return res;
}
QStringList CameraBinVideoEncoder::supportedVideoCodecs() const
{
return m_codecs;
}
QString CameraBinVideoEncoder::videoCodecDescription(const QString &codecName) const
{
return m_codecDescriptions.value(codecName);
}
QStringList CameraBinVideoEncoder::supportedEncodingOptions(const QString &codec) const
{
return m_codecOptions.value(codec);
}
QVariant CameraBinVideoEncoder::encodingOption(const QString &codec, const QString &name) const
{
return m_options[codec].value(name);
}
void CameraBinVideoEncoder::setEncodingOption(
const QString &codec, const QString &name, const QVariant &value)
{
m_options[codec][name] = value;
}
QVideoEncoderSettings CameraBinVideoEncoder::videoSettings() const
{
return m_videoSettings;
}
void CameraBinVideoEncoder::setVideoSettings(const QVideoEncoderSettings &settings)
{
m_videoSettings = settings;
m_userSettings = settings;
emit settingsChanged();
}
void CameraBinVideoEncoder::setActualVideoSettings(const QVideoEncoderSettings &settings)
{
m_videoSettings = settings;
}
void CameraBinVideoEncoder::resetActualSettings()
{
m_videoSettings = m_userSettings;
}
GstElement *CameraBinVideoEncoder::createEncoder()
{
QString codec = m_videoSettings.codec();
QByteArray elementName = m_elementNames.value(codec);
GstElement *encoderElement = gst_element_factory_make( elementName.constData(), "video-encoder");
if (encoderElement) {
if (m_videoSettings.encodingMode() == QtMultimediaKit::ConstantQualityEncoding) {
QtMultimediaKit::EncodingQuality qualityValue = m_videoSettings.quality();
if (elementName == "x264enc") {
//constant quantizer mode
g_object_set(G_OBJECT(encoderElement), "pass", 4, NULL);
int qualityTable[] = {
50, //VeryLow
35, //Low
21, //Normal
15, //High
8 //VeryHigh
};
g_object_set(G_OBJECT(encoderElement), "quantizer", qualityTable[qualityValue], NULL);
} else if (elementName == "xvidenc") {
//constant quantizer mode
g_object_set(G_OBJECT(encoderElement), "pass", 3, NULL);
int qualityTable[] = {
32, //VeryLow
12, //Low
5, //Normal
3, //High
2 //VeryHigh
};
int quant = qualityTable[qualityValue];
g_object_set(G_OBJECT(encoderElement), "quantizer", quant, NULL);
} else if (elementName == "ffenc_mpeg4" ||
elementName == "ffenc_mpeg1video" ||
elementName == "ffenc_mpeg2video" ) {
//constant quantizer mode
g_object_set(G_OBJECT(encoderElement), "pass", 2, NULL);
//quant from 1 to 30, default ~3
double qualityTable[] = {
20, //VeryLow
8.0, //Low
3.0, //Normal
2.5, //High
2.0 //VeryHigh
};
double quant = qualityTable[qualityValue];
g_object_set(G_OBJECT(encoderElement), "quantizer", quant, NULL);
} else if (elementName == "theoraenc") {
int qualityTable[] = {
8, //VeryLow
16, //Low
32, //Normal
45, //High
60 //VeryHigh
};
//quality from 0 to 63
int quality = qualityTable[qualityValue];
g_object_set(G_OBJECT(encoderElement), "quality", quality, NULL);
} else if (elementName == "dsph264enc" ||
elementName == "dspmp4venc" ||
elementName == "dsph263enc") {
//only bitrate parameter is supported
}
} else {
int bitrate = m_videoSettings.bitRate();
if (bitrate > 0) {
g_object_set(G_OBJECT(encoderElement), "bitrate", bitrate, NULL);
}
}
QMap<QString,QVariant> options = m_options.value(codec);
QMapIterator<QString,QVariant> it(options);
while (it.hasNext()) {
it.next();
QString option = it.key();
QVariant value = it.value();
switch (value.type()) {
case QVariant::Int:
g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toInt(), NULL);
break;
case QVariant::Bool:
g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toBool(), NULL);
break;
case QVariant::Double:
g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toDouble(), NULL);
break;
case QVariant::String:
g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toString().toUtf8().constData(), NULL);
break;
default:
qWarning() << "unsupported option type:" << option << value;
break;
}
}
}
return encoderElement;
}
QPair<int,int> CameraBinVideoEncoder::rateAsRational(qreal frameRate) const
{
if (frameRate > 0.001) {
//convert to rational number
QList<int> denumCandidates;
denumCandidates << 1 << 2 << 3 << 5 << 10 << 25 << 30 << 50 << 100 << 1001 << 1000;
qreal error = 1.0;
int num = 1;
int denum = 1;
foreach (int curDenum, denumCandidates) {
int curNum = qRound(frameRate*curDenum);
qreal curError = qAbs(qreal(curNum)/curDenum - frameRate);
if (curError < error) {
error = curError;
num = curNum;
denum = curDenum;
}
if (curError < 1e-8)
break;
}
return QPair<int,int>(num,denum);
}
return QPair<int,int>();
}
QSet<QString> CameraBinVideoEncoder::supportedStreamTypes(const QString &codecName) const
{
return m_streamTypes.value(codecName);
}
<commit_msg>CameraBin backend: Use Mpeg4 video encoder by default on N900.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "camerabinvideoencoder.h"
#include "camerabinsession.h"
#include "camerabincontainer.h"
#include <QtCore/qdebug.h>
CameraBinVideoEncoder::CameraBinVideoEncoder(CameraBinSession *session)
:QVideoEncoderControl(session), m_session(session)
{
QList<QByteArray> codecCandidates;
#if defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
codecCandidates << "video/mpeg4" << "video/h264" << "video/h263" << "video/theora"
<< "video/mpeg2" << "video/mpeg1" << "video/mjpeg" << "video/VP8" << "video/h261";
m_elementNames["video/h264"] = "dsph264enc";
m_elementNames["video/mpeg4"] = "dspmp4venc";
m_elementNames["video/h263"] = "dsph263enc";
m_elementNames["video/theora"] = "theoraenc";
m_elementNames["video/mpeg2"] = "ffenc_mpeg2video";
m_elementNames["video/mpeg1"] = "ffenc_mpeg1video";
m_elementNames["video/mjpeg"] = "ffenc_mjpeg";
m_elementNames["video/VP8"] = "vp8enc";
m_elementNames["video/h261"] = "ffenc_h261";
m_codecOptions["video/mpeg4"] = QStringList() << "mode" << "keyframe-interval";
#else
codecCandidates << "video/h264" << "video/xvid" << "video/mpeg4"
<< "video/mpeg1" << "video/mpeg2" << "video/theora"
<< "video/VP8" << "video/h261" << "video/mjpeg";
m_elementNames["video/h264"] = "x264enc";
m_elementNames["video/xvid"] = "xvidenc";
m_elementNames["video/mpeg4"] = "ffenc_mpeg4";
m_elementNames["video/mpeg1"] = "ffenc_mpeg1video";
m_elementNames["video/mpeg2"] = "ffenc_mpeg2video";
m_elementNames["video/theora"] = "theoraenc";
m_elementNames["video/mjpeg"] = "ffenc_mjpeg";
m_elementNames["video/VP8"] = "vp8enc";
m_elementNames["video/h261"] = "ffenc_h261";
m_codecOptions["video/h264"] = QStringList() << "quantizer";
m_codecOptions["video/xvid"] = QStringList() << "quantizer" << "profile";
m_codecOptions["video/mpeg4"] = QStringList() << "quantizer";
m_codecOptions["video/mpeg1"] = QStringList() << "quantizer";
m_codecOptions["video/mpeg2"] = QStringList() << "quantizer";
m_codecOptions["video/theora"] = QStringList();
#endif
foreach( const QByteArray& codecName, codecCandidates ) {
QByteArray elementName = m_elementNames[codecName];
GstElementFactory *factory = gst_element_factory_find(elementName.constData());
if (factory) {
m_codecs.append(codecName);
const gchar *descr = gst_element_factory_get_description(factory);
m_codecDescriptions.insert(codecName, QString::fromUtf8(descr));
m_streamTypes.insert(codecName,
CameraBinContainer::supportedStreamTypes(factory, GST_PAD_SRC));
gst_object_unref(GST_OBJECT(factory));
}
}
}
CameraBinVideoEncoder::~CameraBinVideoEncoder()
{
}
QList<QSize> CameraBinVideoEncoder::supportedResolutions(const QVideoEncoderSettings &settings, bool *continuous) const
{
if (continuous)
*continuous = false;
QPair<int,int> rate = rateAsRational(settings.frameRate());
//select the closest supported rational rate to settings.frameRate()
return m_session->supportedResolutions(rate, continuous);
}
QList< qreal > CameraBinVideoEncoder::supportedFrameRates(const QVideoEncoderSettings &settings, bool *continuous) const
{
if (continuous)
*continuous = false;
QList< qreal > res;
QPair<int,int> rate;
foreach(rate, m_session->supportedFrameRates(settings.resolution(), continuous)) {
if (rate.second > 0)
res << qreal(rate.first)/rate.second;
}
return res;
}
QStringList CameraBinVideoEncoder::supportedVideoCodecs() const
{
return m_codecs;
}
QString CameraBinVideoEncoder::videoCodecDescription(const QString &codecName) const
{
return m_codecDescriptions.value(codecName);
}
QStringList CameraBinVideoEncoder::supportedEncodingOptions(const QString &codec) const
{
return m_codecOptions.value(codec);
}
QVariant CameraBinVideoEncoder::encodingOption(const QString &codec, const QString &name) const
{
return m_options[codec].value(name);
}
void CameraBinVideoEncoder::setEncodingOption(
const QString &codec, const QString &name, const QVariant &value)
{
m_options[codec][name] = value;
}
QVideoEncoderSettings CameraBinVideoEncoder::videoSettings() const
{
return m_videoSettings;
}
void CameraBinVideoEncoder::setVideoSettings(const QVideoEncoderSettings &settings)
{
m_videoSettings = settings;
m_userSettings = settings;
emit settingsChanged();
}
void CameraBinVideoEncoder::setActualVideoSettings(const QVideoEncoderSettings &settings)
{
m_videoSettings = settings;
}
void CameraBinVideoEncoder::resetActualSettings()
{
m_videoSettings = m_userSettings;
}
GstElement *CameraBinVideoEncoder::createEncoder()
{
QString codec = m_videoSettings.codec();
QByteArray elementName = m_elementNames.value(codec);
GstElement *encoderElement = gst_element_factory_make( elementName.constData(), "video-encoder");
if (encoderElement) {
if (m_videoSettings.encodingMode() == QtMultimediaKit::ConstantQualityEncoding) {
QtMultimediaKit::EncodingQuality qualityValue = m_videoSettings.quality();
if (elementName == "x264enc") {
//constant quantizer mode
g_object_set(G_OBJECT(encoderElement), "pass", 4, NULL);
int qualityTable[] = {
50, //VeryLow
35, //Low
21, //Normal
15, //High
8 //VeryHigh
};
g_object_set(G_OBJECT(encoderElement), "quantizer", qualityTable[qualityValue], NULL);
} else if (elementName == "xvidenc") {
//constant quantizer mode
g_object_set(G_OBJECT(encoderElement), "pass", 3, NULL);
int qualityTable[] = {
32, //VeryLow
12, //Low
5, //Normal
3, //High
2 //VeryHigh
};
int quant = qualityTable[qualityValue];
g_object_set(G_OBJECT(encoderElement), "quantizer", quant, NULL);
} else if (elementName == "ffenc_mpeg4" ||
elementName == "ffenc_mpeg1video" ||
elementName == "ffenc_mpeg2video" ) {
//constant quantizer mode
g_object_set(G_OBJECT(encoderElement), "pass", 2, NULL);
//quant from 1 to 30, default ~3
double qualityTable[] = {
20, //VeryLow
8.0, //Low
3.0, //Normal
2.5, //High
2.0 //VeryHigh
};
double quant = qualityTable[qualityValue];
g_object_set(G_OBJECT(encoderElement), "quantizer", quant, NULL);
} else if (elementName == "theoraenc") {
int qualityTable[] = {
8, //VeryLow
16, //Low
32, //Normal
45, //High
60 //VeryHigh
};
//quality from 0 to 63
int quality = qualityTable[qualityValue];
g_object_set(G_OBJECT(encoderElement), "quality", quality, NULL);
} else if (elementName == "dsph264enc" ||
elementName == "dspmp4venc" ||
elementName == "dsph263enc") {
//only bitrate parameter is supported
}
} else {
int bitrate = m_videoSettings.bitRate();
if (bitrate > 0) {
g_object_set(G_OBJECT(encoderElement), "bitrate", bitrate, NULL);
}
}
QMap<QString,QVariant> options = m_options.value(codec);
QMapIterator<QString,QVariant> it(options);
while (it.hasNext()) {
it.next();
QString option = it.key();
QVariant value = it.value();
switch (value.type()) {
case QVariant::Int:
g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toInt(), NULL);
break;
case QVariant::Bool:
g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toBool(), NULL);
break;
case QVariant::Double:
g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toDouble(), NULL);
break;
case QVariant::String:
g_object_set(G_OBJECT(encoderElement), option.toAscii(), value.toString().toUtf8().constData(), NULL);
break;
default:
qWarning() << "unsupported option type:" << option << value;
break;
}
}
}
return encoderElement;
}
QPair<int,int> CameraBinVideoEncoder::rateAsRational(qreal frameRate) const
{
if (frameRate > 0.001) {
//convert to rational number
QList<int> denumCandidates;
denumCandidates << 1 << 2 << 3 << 5 << 10 << 25 << 30 << 50 << 100 << 1001 << 1000;
qreal error = 1.0;
int num = 1;
int denum = 1;
foreach (int curDenum, denumCandidates) {
int curNum = qRound(frameRate*curDenum);
qreal curError = qAbs(qreal(curNum)/curDenum - frameRate);
if (curError < error) {
error = curError;
num = curNum;
denum = curDenum;
}
if (curError < 1e-8)
break;
}
return QPair<int,int>(num,denum);
}
return QPair<int,int>();
}
QSet<QString> CameraBinVideoEncoder::supportedStreamTypes(const QString &codecName) const
{
return m_streamTypes.value(codecName);
}
<|endoftext|>
|
<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
// own
#include "Importer.h"
// ospcommon
#include "ospcommon/FileName.h"
// scene graph
#include "sg/module/Module.h"
#include "sg/importer/Importer.h"
#include "sg/Renderer.h"
#include <string>
namespace ospray {
namespace importer {
void importOSP(const FileName &fileName, Group *existingGroupToAddTo);
void importRM(const FileName &fileName, Group *existingGroupToAddTo);
Group *import(const std::string &fn, Group *existingGroupToAddTo)
{
FileName fileName = fn;
Group *group = existingGroupToAddTo;
if (!group) group = new Group;
if (fileName.ext() == "osp") {
#ifndef _WIN32
std::shared_ptr<sg::World> world;;
world = sg::loadOSP(fn);
std::shared_ptr<sg::Volume> volumeNode;
for (auto node : world->nodes) {
if (node->toString().find("Volume") != std::string::npos)
volumeNode = std::dynamic_pointer_cast<sg::Volume>(node);
}
if (!volumeNode) {
throw std::runtime_error("#ospray:importer: no volume found "
"in osg file");
}
sg::RenderContext ctx;
std::shared_ptr<sg::Integrator> integrator;
integrator = std::make_shared<sg::Integrator>("scivis");
ctx.integrator = integrator;
integrator->commit();
if (!world) {
std::cout << "#osp:qtv: no world defined. exiting." << std::endl;
exit(1);
}
world->render(ctx);
OSPVolume volume = volumeNode->volume;
Volume* msgVolume = new Volume;
msgVolume->bounds = volumeNode->getBounds();
msgVolume->handle = volumeNode->volume;
group->volume.push_back(msgVolume);
#endif
} else if (fileName.ext() == "bob") {
importRM(fn, group);
} else {
throw std::runtime_error("#ospray:importer: do not know how to import file of type "
+ fileName.ext());
}
return group;
}
} // ::ospray::importer
} // ::ospray
<commit_msg>revert to using old importers until ospray::sg isn't broken<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
// own
#include "Importer.h"
// ospcommon
#include "ospcommon/FileName.h"
// scene graph
#include "sg/module/Module.h"
#include "sg/importer/Importer.h"
#include "sg/Renderer.h"
#include <string>
namespace ospray {
namespace importer {
void importOSP(const FileName &fileName, Group *existingGroupToAddTo);
void importRM(const FileName &fileName, Group *existingGroupToAddTo);
Group *import(const std::string &fn, Group *existingGroupToAddTo)
{
FileName fileName = fn;
Group *group = existingGroupToAddTo;
if (!group) group = new Group;
if (fileName.ext() == "osp") {
importOSP(fileName, group);
#if 0 // NOTE(jda) - using ospray::sg is broken, needs fixed before enabling
//#ifndef _WIN32
std::shared_ptr<sg::World> world;;
world = sg::loadOSP(fn);
std::shared_ptr<sg::Volume> volumeNode;
for (auto node : world->nodes) {
if (node->toString().find("Volume") != std::string::npos)
volumeNode = std::dynamic_pointer_cast<sg::Volume>(node);
}
if (!volumeNode) {
throw std::runtime_error("#ospray:importer: no volume found "
"in osg file");
}
sg::RenderContext ctx;
std::shared_ptr<sg::Integrator> integrator;
integrator = std::make_shared<sg::Integrator>("scivis");
ctx.integrator = integrator;
integrator->commit();
if (!world) {
std::cout << "#osp:qtv: no world defined. exiting." << std::endl;
exit(1);
}
world->render(ctx);
OSPVolume volume = volumeNode->volume;
Volume* msgVolume = new Volume;
msgVolume->bounds = volumeNode->getBounds();
msgVolume->handle = volumeNode->volume;
group->volume.push_back(msgVolume);
#endif
} else if (fileName.ext() == "bob") {
importRM(fn, group);
} else {
throw std::runtime_error("#ospray:importer: do not know how to import file of type "
+ fileName.ext());
}
return group;
}
} // ::ospray::importer
} // ::ospray
<|endoftext|>
|
<commit_before>// #define DEBUG
#include <os>
#include <stdio.h>
#include <assert.h>
#include <class_dev.hpp>
#include <class_service.hpp>
// A private class to handle IRQ
#include "class_irq_handler.hpp"
#include <class_pci_manager.hpp>
bool OS::power = true;
uint32_t OS::_CPU_mhz = 2500;
void OS::start()
{
rsprint(">>> OS class started\n");
disable_PIT();
printf("<OS> UPTIME: %li \n",uptime());
__asm__("cli");
IRQ_handler::init();
Dev::init();
//Everything is ready
Service::start();
__asm__("sti");
halt();
};
void OS::disable_PIT(){
#define PIT_one_shot 0x30
#define PIT_mode_chan 0x43
#define PIT_chan0 0x40
// Enable 1-shot mode
OS::outb(PIT_mode_chan,PIT_one_shot);
// Set a frequency for "first shot"
OS::outb(PIT_chan0,1);
OS::outb(PIT_chan0,0);
debug("<PIT> Switching to 1-shot mode (0x%b) \n",PIT_1shot);
};
extern "C" void halt_loop(){
__asm__ volatile("hlt; jmp halt_loop;");
}
union intstr{
int i;
char part[4];
};
void OS::halt(){
//intstr eof{EOF};
OS::rsprint("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
OS::rsprint(">>> System idle - everything seems OK \n");
//OS::rsprint(eof.part);
while(power){
IRQ_handler::notify();
debug("<OS> Woke up @ t = %li \n",uptime());
}
//Cleanup
//Service::stop();
}
int OS::rsprint(const char* str){
char* ptr=(char*)str;
while(*ptr)
rswrite(*(ptr++));
return ptr-str;
}
/* STEAL: Read byte from I/O address space */
uint8_t OS::inb(int port) {
int ret;
__asm__ volatile ("xorl %eax,%eax");
__asm__ volatile ("inb %%dx,%%al":"=a" (ret):"d"(port));
return ret;
}
/* Write byte to I/O address space */
void OS::outb(int port, uint8_t data) {
__asm__ volatile ("outb %%al,%%dx"::"a" (data), "d"(port));
}
/*
* STEAL: Print to serial port 0x3F8
*/
int OS::rswrite(char c) {
/* Wait for the previous character to be sent */
while ((inb(0x3FD) & 0x20) != 0x20);
/* Send the character */
outb(0x3F8, c);
return 1;
}
<commit_msg>Update class_os.cpp<commit_after>Final test (I hope....)
// #define DEBUG
#include <os>
#include <stdio.h>
#include <assert.h>
#include <class_dev.hpp>
#include <class_service.hpp>
// A private class to handle IRQ
#include "class_irq_handler.hpp"
#include <class_pci_manager.hpp>
bool OS::power = true;
uint32_t OS::_CPU_mhz = 2500;
void OS::start()
{
rsprint(">>> OS class started\n");
disable_PIT();
printf("<OS> UPTIME: %li \n",uptime());
__asm__("cli");
IRQ_handler::init();
Dev::init();
//Everything is ready
Service::start();
__asm__("sti");
halt();
};
void OS::disable_PIT(){
#define PIT_one_shot 0x30
#define PIT_mode_chan 0x43
#define PIT_chan0 0x40
// Enable 1-shot mode
OS::outb(PIT_mode_chan,PIT_one_shot);
// Set a frequency for "first shot"
OS::outb(PIT_chan0,1);
OS::outb(PIT_chan0,0);
debug("<PIT> Switching to 1-shot mode (0x%b) \n",PIT_1shot);
};
extern "C" void halt_loop(){
__asm__ volatile("hlt; jmp halt_loop;");
}
union intstr{
int i;
char part[4];
};
void OS::halt(){
//intstr eof{EOF};
OS::rsprint("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
OS::rsprint(">>> System idle - everything seems OK \n");
//OS::rsprint(eof.part);
while(power){
IRQ_handler::notify();
debug("<OS> Woke up @ t = %li \n",uptime());
}
//Cleanup
//Service::stop();
}
int OS::rsprint(const char* str){
char* ptr=(char*)str;
while(*ptr)
rswrite(*(ptr++));
return ptr-str;
}
/* STEAL: Read byte from I/O address space */
uint8_t OS::inb(int port) {
int ret;
__asm__ volatile ("xorl %eax,%eax");
__asm__ volatile ("inb %%dx,%%al":"=a" (ret):"d"(port));
return ret;
}
/* Write byte to I/O address space */
void OS::outb(int port, uint8_t data) {
__asm__ volatile ("outb %%al,%%dx"::"a" (data), "d"(port));
}
/*
* STEAL: Print to serial port 0x3F8
*/
int OS::rswrite(char c) {
/* Wait for the previous character to be sent */
while ((inb(0x3FD) & 0x20) != 0x20);
/* Send the character */
outb(0x3F8, c);
return 1;
}
<|endoftext|>
|
<commit_before><commit_msg>jit add function start location to assembly output<commit_after><|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.