text
stringlengths
54
60.6k
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <private/qqmljslexer_p.h> #include <private/qqmljsparser_p.h> #include <private/qqmljsast_p.h> #include <private/qv4codegen_p.h> #include <private/qqmlpool_p.h> #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtCore/QSet> #include <QtCore/QStringList> #include <QtCore/QMetaObject> #include <QtCore/QMetaProperty> #include <QtCore/QVariant> #include <QtCore/QJsonObject> #include <QtCore/QJsonArray> #include <QtCore/QJsonDocument> #include <QtCore/QLibraryInfo> #include <iostream> QT_USE_NAMESPACE QStringList g_qmlImportPaths; void printUsage(const QString &appName) { std::cerr << qPrintable(QString::fromLatin1( "Usage: %1 -rootPath qmldir -importPath importPath \n" "Example: %1 -rootPath qmldir -importPath importPath").arg( appName)); } QVariantList findImportsInAst(QQmlJS::AST::UiHeaderItemList *headerItemList, const QByteArray &code, const QString &path) { QVariantList imports; // extract uri and version from the imports (which look like "import Foo.Bar 1.2.3") for (QQmlJS::AST::UiHeaderItemList *headerItemIt = headerItemList; headerItemIt; headerItemIt = headerItemIt->next) { QVariantMap import; QQmlJS::AST::UiImport *importNode = QQmlJS::AST::cast<QQmlJS::AST::UiImport *>(headerItemIt->headerItem); if (!importNode) continue; // handle directory imports if (!importNode->fileName.isEmpty()) { QString name = importNode->fileName.toString(); import[QStringLiteral("name")] = name; import[QStringLiteral("type")] = QStringLiteral("directory"); import[QStringLiteral("path")] = path + QLatin1Char('/') + name; } else { // Walk the id chain ("Foo" -> "Bar" -> etc) QString name; QQmlJS::AST::UiQualifiedId *uri = importNode->importUri; while (uri) { name.append(uri->name); name.append(QLatin1Char('.')); uri = uri->next; } name.chop(1); // remove trailing "." if (!name.isEmpty()) import[QStringLiteral("name")] = name; import[QStringLiteral("type")] = QStringLiteral("module"); import[QStringLiteral("version")] = code.mid(importNode->versionToken.offset, importNode->versionToken.length); } imports.append(import); } return imports; } // Scan a single qml file for import statements QVariantList findQmlImportsInFile(const QString &qmlFilePath) { QFile qmlFile(qmlFilePath); if (!qmlFile.open(QIODevice::ReadOnly)) { std::cerr << "Cannot open input file " << qPrintable(QDir::toNativeSeparators(qmlFile.fileName())) << ':' << qPrintable(qmlFile.errorString()) << std::endl; return QVariantList(); } QByteArray code = qmlFile.readAll(); QQmlJS::Engine engine; QQmlJS::Lexer lexer(&engine); lexer.setCode(QString::fromUtf8(code), /*line = */ 1); QQmlJS::Parser parser(&engine); if (!parser.parse() || !parser.diagnosticMessages().isEmpty()) { // Extract errors from the parser foreach (const QQmlJS::DiagnosticMessage &m, parser.diagnosticMessages()) { std::cerr << qPrintable(QDir::toNativeSeparators(qmlFile.fileName())) << ':' << m.loc.startLine << ':' << qPrintable(m.message) << std::endl; } return QVariantList(); } return findImportsInAst(parser.ast()->headers, code, QFileInfo(qmlFilePath).absolutePath()); } // Scan all qml files in directory for import statements QVariantList findQmlImportsInDirectory(const QString &qmlDir) { QVariantList ret; if (qmlDir.isEmpty()) return ret; QStringList qmlFileNames = QDir(qmlDir).entryList(QStringList(QStringLiteral("*.qml"))); foreach (const QString &qmlFileName, qmlFileNames) { QString qmlFilePath = qmlDir + QLatin1Char('/') + qmlFileName; QVariantList imports = findQmlImportsInFile(qmlFilePath); ret.append(imports); } return ret; } // Read the qmldir file, extract a list of plugins by // parsing the "plugin" lines QString pluginsForModulePath(const QString &modulePath) { QFile qmldirFile(modulePath + QStringLiteral("/qmldir")); if (!qmldirFile.exists()) return QString(); qmldirFile.open(QIODevice::ReadOnly | QIODevice::Text); QString plugins; QByteArray line; do { line = qmldirFile.readLine(); if (line.startsWith("plugin")) { plugins += QString::fromUtf8(line.split(' ').at(1)); plugins += QLatin1Char(' '); } } while (line.length() > 0); return plugins.simplified(); } // Construct a file system path from a module uri and version. // Special case for 1.x: QtQuick.Dialogs 1.x -> QtQuick/Dialogs // Genral casefor y.x: QtQuick.Dialogs y.x -> QtQuick/Dialogs.y QString localPathForModule(const QString &moduleUri, const QString &version) { QString path; foreach (const QString &part, moduleUri.split(QLatin1Char('.'))) path += QLatin1Char('/') + part; if (version.startsWith(QLatin1String("1."))) return path; if (version.contains(QLatin1Char('.'))) path += QLatin1Char('.') + version.split(QLatin1Char('.')).at(0); else path += QLatin1Char('.') + version; return path; } // Search for a given qml import in g_qmlImportPaths QString findPathForImport(const QString&localModulePath) { foreach (const QString &qmlImportPath, g_qmlImportPaths) { QString candidatePath = QDir::cleanPath(qmlImportPath + QLatin1Char('/') + localModulePath); if (QDir(candidatePath).exists()) return candidatePath; } return QString(); } // Find absolute file system paths and plugins for a list of modules. QVariantList findPathsForModuleImports(const QVariantList &imports) { QVariantList done; foreach (QVariant importVariant, imports) { QVariantMap import = qvariant_cast<QVariantMap>(importVariant); if (import[QStringLiteral("type")] == QStringLiteral("module")) { const QString path = findPathForImport(localPathForModule(import[QStringLiteral("name")].toString(), import[QStringLiteral("version")].toString())); import.insert(QStringLiteral("path"), path); const QString plugin = pluginsForModulePath(path); if (!plugin.isEmpty()) import[QStringLiteral("plugin")] = plugin; } if (!import[QStringLiteral("path")].isNull()) done.append(import); } return done; } // Merge two lists of imports, discard duplicates. QVariantList mergeImports(const QVariantList &a, const QVariantList &b) { QVariantList merged = a; foreach (const QVariant &variant, b) { if (!merged.contains(variant)) merged.append(variant); } return merged; } // find Qml Imports Recursively QVariantList findQmlImportsRecursively(const QStringList &qmlDirs) { QVariantList ret; QSet<QString> toVisit = qmlDirs.toSet(); QSet<QString> visited; while (!toVisit.isEmpty()) { QString qmlDir = *toVisit.begin(); toVisit.erase(toVisit.begin()); visited.insert(qmlDir); QVariantList imports = findQmlImportsInDirectory(qmlDir); imports = findPathsForModuleImports(imports); // schedule recursive visit of imports foreach (const QVariant &importVariant, imports) { QVariantMap import = qvariant_cast<QVariantMap>(importVariant); QString path = import[QStringLiteral("path")].toString(); if (!path.isEmpty() && !visited.contains(path)) { toVisit.insert(path); } } ret = mergeImports(ret, imports); } return ret; } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QStringList args = app.arguments(); const QString appName = QFileInfo(app.applicationFilePath()).baseName(); if (args.size() < 2) { printUsage(appName); return 1; } QStringList qmlRootPaths; QStringList qmlImportPaths; int i = 1; while (i < args.count()) { const QString &arg = args.at(i); ++i; if (!arg.startsWith(QLatin1Char('-'))) { qmlRootPaths += arg; } else if (arg == QLatin1String("-rootPath")) { if (i >= args.count()) std::cerr << "-rootPath requires an argument\n"; while (i < args.count()) { const QString arg = args.at(i); if (arg.startsWith(QLatin1Char('-'))) break; ++i; qmlRootPaths += arg; } } else if (arg == QLatin1String("-importPath")) { if (i >= args.count()) std::cerr << "-importPath requires an argument\n"; while (i < args.count()) { const QString arg = args.at(i); if (arg.startsWith(QLatin1Char('-'))) break; ++i; qmlImportPaths += arg; } } else { std::cerr << "Invalid argument: \"" << qPrintable(arg) << "\"\n"; return 1; } } g_qmlImportPaths = qmlImportPaths; // Find the imports! QVariantList imports = findQmlImportsRecursively(qmlRootPaths); // Convert to JSON QByteArray json = QJsonDocument(QJsonArray::fromVariantList(imports)).toJson(); std::cout << json.constData() << std::endl; return 0; } <commit_msg>Make qmlimportscanner report plugin classnames.<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <private/qqmljslexer_p.h> #include <private/qqmljsparser_p.h> #include <private/qqmljsast_p.h> #include <private/qv4codegen_p.h> #include <private/qqmlpool_p.h> #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QFileInfo> #include <QtCore/QSet> #include <QtCore/QStringList> #include <QtCore/QMetaObject> #include <QtCore/QMetaProperty> #include <QtCore/QVariant> #include <QtCore/QJsonObject> #include <QtCore/QJsonArray> #include <QtCore/QJsonDocument> #include <QtCore/QLibraryInfo> #include <iostream> QT_USE_NAMESPACE QStringList g_qmlImportPaths; void printUsage(const QString &appName) { std::cerr << qPrintable(QString::fromLatin1( "Usage: %1 -rootPath qmldir -importPath importPath \n" "Example: %1 -rootPath qmldir -importPath importPath").arg( appName)); } QVariantList findImportsInAst(QQmlJS::AST::UiHeaderItemList *headerItemList, const QByteArray &code, const QString &path) { QVariantList imports; // extract uri and version from the imports (which look like "import Foo.Bar 1.2.3") for (QQmlJS::AST::UiHeaderItemList *headerItemIt = headerItemList; headerItemIt; headerItemIt = headerItemIt->next) { QVariantMap import; QQmlJS::AST::UiImport *importNode = QQmlJS::AST::cast<QQmlJS::AST::UiImport *>(headerItemIt->headerItem); if (!importNode) continue; // handle directory imports if (!importNode->fileName.isEmpty()) { QString name = importNode->fileName.toString(); import[QStringLiteral("name")] = name; import[QStringLiteral("type")] = QStringLiteral("directory"); import[QStringLiteral("path")] = path + QLatin1Char('/') + name; } else { // Walk the id chain ("Foo" -> "Bar" -> etc) QString name; QQmlJS::AST::UiQualifiedId *uri = importNode->importUri; while (uri) { name.append(uri->name); name.append(QLatin1Char('.')); uri = uri->next; } name.chop(1); // remove trailing "." if (!name.isEmpty()) import[QStringLiteral("name")] = name; import[QStringLiteral("type")] = QStringLiteral("module"); import[QStringLiteral("version")] = code.mid(importNode->versionToken.offset, importNode->versionToken.length); } imports.append(import); } return imports; } // Scan a single qml file for import statements QVariantList findQmlImportsInFile(const QString &qmlFilePath) { QFile qmlFile(qmlFilePath); if (!qmlFile.open(QIODevice::ReadOnly)) { std::cerr << "Cannot open input file " << qPrintable(QDir::toNativeSeparators(qmlFile.fileName())) << ':' << qPrintable(qmlFile.errorString()) << std::endl; return QVariantList(); } QByteArray code = qmlFile.readAll(); QQmlJS::Engine engine; QQmlJS::Lexer lexer(&engine); lexer.setCode(QString::fromUtf8(code), /*line = */ 1); QQmlJS::Parser parser(&engine); if (!parser.parse() || !parser.diagnosticMessages().isEmpty()) { // Extract errors from the parser foreach (const QQmlJS::DiagnosticMessage &m, parser.diagnosticMessages()) { std::cerr << qPrintable(QDir::toNativeSeparators(qmlFile.fileName())) << ':' << m.loc.startLine << ':' << qPrintable(m.message) << std::endl; } return QVariantList(); } return findImportsInAst(parser.ast()->headers, code, QFileInfo(qmlFilePath).absolutePath()); } // Scan all qml files in directory for import statements QVariantList findQmlImportsInDirectory(const QString &qmlDir) { QVariantList ret; if (qmlDir.isEmpty()) return ret; QStringList qmlFileNames = QDir(qmlDir).entryList(QStringList(QStringLiteral("*.qml"))); foreach (const QString &qmlFileName, qmlFileNames) { QString qmlFilePath = qmlDir + QLatin1Char('/') + qmlFileName; QVariantList imports = findQmlImportsInFile(qmlFilePath); ret.append(imports); } return ret; } // Read the qmldir file, extract a list of plugins by // parsing the "plugin" and "classname" lines. QVariantMap pluginsForModulePath(const QString &modulePath) { QFile qmldirFile(modulePath + QStringLiteral("/qmldir")); if (!qmldirFile.exists()) return QVariantMap(); qmldirFile.open(QIODevice::ReadOnly | QIODevice::Text); // a qml import may contain several plugins QString plugins; QString classnames; QByteArray line; do { line = qmldirFile.readLine(); if (line.startsWith("plugin")) { plugins += QString::fromUtf8(line.split(' ').at(1)); plugins += QStringLiteral(" "); } else if (line.startsWith("classname")) { classnames += QString::fromUtf8(line.split(' ').at(1)); classnames += QStringLiteral(" "); } } while (line.length() > 0); QVariantMap pluginInfo; pluginInfo[QStringLiteral("plugins")] = plugins.simplified(); pluginInfo[QStringLiteral("classnames")] = classnames.simplified(); return pluginInfo; } // Construct a file system path from a module uri and version. // Special case for 1.x: QtQuick.Dialogs 1.x -> QtQuick/Dialogs // Genral casefor y.x: QtQuick.Dialogs y.x -> QtQuick/Dialogs.y QString localPathForModule(const QString &moduleUri, const QString &version) { QString path; foreach (const QString &part, moduleUri.split(QLatin1Char('.'))) path += QLatin1Char('/') + part; if (version.startsWith(QLatin1String("1."))) return path; if (version.contains(QLatin1Char('.'))) path += QLatin1Char('.') + version.split(QLatin1Char('.')).at(0); else path += QLatin1Char('.') + version; return path; } // Search for a given qml import in g_qmlImportPaths QString findPathForImport(const QString&localModulePath) { foreach (const QString &qmlImportPath, g_qmlImportPaths) { QString candidatePath = QDir::cleanPath(qmlImportPath + QLatin1Char('/') + localModulePath); if (QDir(candidatePath).exists()) return candidatePath; } return QString(); } // Find absolute file system paths and plugins for a list of modules. QVariantList findPathsForModuleImports(const QVariantList &imports) { QVariantList done; foreach (QVariant importVariant, imports) { QVariantMap import = qvariant_cast<QVariantMap>(importVariant); if (import[QStringLiteral("type")] == QStringLiteral("module")) { import[QStringLiteral("path")] = findPathForImport(localPathForModule(import[QStringLiteral("name")].toString(), import[QStringLiteral("version")].toString())); QVariantMap plugininfo = pluginsForModulePath(import[QStringLiteral("path")].toString()); QString plugins = plugininfo[QStringLiteral("plugins")].toString(); QString classnames = plugininfo[QStringLiteral("classnames")].toString(); if (!plugins.isEmpty()) { import[QStringLiteral("plugin")] = plugins; import[QStringLiteral("classname")] = classnames; } } if (!import[QStringLiteral("path")].isNull()) done.append(import); } return done; } // Merge two lists of imports, discard duplicates. QVariantList mergeImports(const QVariantList &a, const QVariantList &b) { QVariantList merged = a; foreach (const QVariant &variant, b) { if (!merged.contains(variant)) merged.append(variant); } return merged; } // find Qml Imports Recursively QVariantList findQmlImportsRecursively(const QStringList &qmlDirs) { QVariantList ret; QSet<QString> toVisit = qmlDirs.toSet(); QSet<QString> visited; while (!toVisit.isEmpty()) { QString qmlDir = *toVisit.begin(); toVisit.erase(toVisit.begin()); visited.insert(qmlDir); QVariantList imports = findQmlImportsInDirectory(qmlDir); imports = findPathsForModuleImports(imports); // schedule recursive visit of imports foreach (const QVariant &importVariant, imports) { QVariantMap import = qvariant_cast<QVariantMap>(importVariant); QString path = import[QStringLiteral("path")].toString(); if (!path.isEmpty() && !visited.contains(path)) { toVisit.insert(path); } } ret = mergeImports(ret, imports); } return ret; } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QStringList args = app.arguments(); const QString appName = QFileInfo(app.applicationFilePath()).baseName(); if (args.size() < 2) { printUsage(appName); return 1; } QStringList qmlRootPaths; QStringList qmlImportPaths; int i = 1; while (i < args.count()) { const QString &arg = args.at(i); ++i; if (!arg.startsWith(QLatin1Char('-'))) { qmlRootPaths += arg; } else if (arg == QLatin1String("-rootPath")) { if (i >= args.count()) std::cerr << "-rootPath requires an argument\n"; while (i < args.count()) { const QString arg = args.at(i); if (arg.startsWith(QLatin1Char('-'))) break; ++i; qmlRootPaths += arg; } } else if (arg == QLatin1String("-importPath")) { if (i >= args.count()) std::cerr << "-importPath requires an argument\n"; while (i < args.count()) { const QString arg = args.at(i); if (arg.startsWith(QLatin1Char('-'))) break; ++i; qmlImportPaths += arg; } } else { std::cerr << "Invalid argument: \"" << qPrintable(arg) << "\"\n"; return 1; } } g_qmlImportPaths = qmlImportPaths; // Find the imports! QVariantList imports = findQmlImportsRecursively(qmlRootPaths); // Convert to JSON QByteArray json = QJsonDocument(QJsonArray::fromVariantList(imports)).toJson(); std::cout << json.constData() << std::endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: parser.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: gh $ $Date: 2001-11-30 15:03:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <stdio.h> #include <stream.hxx> #include <fsys.hxx> #include "iparser.hxx" #include "geninfo.hxx" // // class InformationParser // const char InformationParser::cKeyLevelChars = '\t'; /*****************************************************************************/ InformationParser::InformationParser( BOOL bReplace ) /*****************************************************************************/ : pActStream( NULL ), nErrorCode( 0 ), nErrorLine( 0 ), nActLine( 0 ), bRecover( FALSE ), sOldLine( "" ), sErrorText( "" ), bReplaceVariables( bReplace ), nLevel( 0 ), sUPD( "" ), sVersion( "" ) { } /*****************************************************************************/ InformationParser::~InformationParser() /*****************************************************************************/ { } /*****************************************************************************/ ByteString &InformationParser::ReadLine() /*****************************************************************************/ { ByteString sLine; if ( bRecover ) { bRecover = FALSE; } else { if ( !pActStream->IsEof()) { pActStream->ReadLine( sLine ); ULONG nLen; do { nLen = sLine.Len(); sLine.EraseLeadingChars( 0x09 ); sLine.EraseLeadingChars( ' ' ); } while ( nLen != sLine.Len()); do { nLen = sLine.Len(); sLine.EraseTrailingChars( 0x09 ); sLine.EraseTrailingChars( ' ' ); } while ( nLen != sLine.Len()); if (( sLine.Search( "#" ) == 0 ) || ( !sLine.Len())) { if ( sCurrentComment.Len()) sCurrentComment += "\n"; sCurrentComment += sLine; return ReadLine(); } else { if ( bReplaceVariables ) { while( sLine.SearchAndReplace( "%UPD", sUPD ) != (USHORT)-1 ); while( sLine.SearchAndReplace( "%VERSION", sVersion ) != (USHORT)-1 ); } } } else { if ( nLevel ) { sLine = "}"; fprintf( stdout, "Reached EOF parsing %s. Suplying extra '}'\n",ByteString( sStreamName, gsl_getSystemTextEncoding()).GetBuffer() ); // nErrorCode = IP_UNEXPECTED_EOF; // nErrorLine = nActLine; } else sLine = ""; } sOldLine = sLine; nActLine++; } return sOldLine; } /*****************************************************************************/ GenericInformation *InformationParser::ReadKey( GenericInformationList *pExistingList ) /*****************************************************************************/ { // this method has no error handling yet, but it works very fast. // it is used to create whole informations and sub informations in // a simple data format in memory, readed in a configuration file with // following format: /* key [value] { key [value] key [value] { key [value] ... ... } } key [value] ... ... */ GenericInformation *pInfo = NULL; ByteString sLine( ReadLine()); ByteString sKey; ByteString sValue; ByteString sComment( sCurrentComment ); sCurrentComment = ""; // key separated from value by tab? USHORT nWSPos = sLine.Search( ' ' ); if ( sLine.Search( '\t' ) < nWSPos ) { nWSPos = sLine.Search( '\t' ); sLine.SearchAndReplace( "\t", " " ); } if ( sLine.GetTokenCount( ' ' ) > 1 ) { sKey = sLine.GetToken( 0, ' ' ); sValue = sLine.Copy( sKey.Len() + 1 ); while (( sValue.Search( ' ' ) == 0 ) || ( sValue.Search( '\t' ) == 0 )) { sValue.Erase( 0, 1 ); } } else sKey=sLine; if ( bReplaceVariables && !nLevel ) { sUPD = sKey.Copy( sKey.Len() - 3 ); sVersion = sKey; } if ( ReadLine() == "{" ) { nLevel++; GenericInformationList *pSubList = new GenericInformationList(); while ( ReadLine() != "}" ) { Recover(); ReadKey( pSubList ); } nLevel--; pInfo = new GenericInformation( sKey, sValue, pExistingList, pSubList ); pInfo->SetComment( sComment ); } else { Recover(); if ( !sKey.Equals( "}" ) && !sKey.Equals( "{" ) ) { pInfo = new GenericInformation( sKey, sValue, pExistingList ); pInfo->SetComment( sComment ); } } return pInfo; } /*****************************************************************************/ void InformationParser::Recover() /*****************************************************************************/ { bRecover = TRUE; } /*****************************************************************************/ BOOL InformationParser::Save( SvStream &rOutStream, const GenericInformationList *pSaveList, USHORT nLevel ) /*****************************************************************************/ { USHORT i; ULONG nInfoListCount; ByteString sTmpStr; GenericInformation *pGenericInfo; GenericInformationList *pGenericInfoList; for ( nInfoListCount = 0; nInfoListCount < pSaveList->Count(); nInfoListCount++) { // Key-Value Paare schreiben pGenericInfo = pSaveList->GetObject( nInfoListCount ); sTmpStr = ""; for( ULONG j=0; j<nLevel; j++) sTmpStr += cKeyLevelChars; for ( i = 0; i < pGenericInfo->GetComment().GetTokenCount( '\n' ); i++ ) { sTmpStr += pGenericInfo->GetComment().GetToken( i, '\n' ); sTmpStr += "\n"; for( ULONG j=0; j<nLevel; j++) sTmpStr += cKeyLevelChars; } sTmpStr += pGenericInfo->GetBuffer(); sTmpStr += ' '; sTmpStr += pGenericInfo->GetValue(); if ( !rOutStream.WriteLine( sTmpStr ) ) return FALSE; // wenn vorhanden, bearbeite recursive die Sublisten if (( pGenericInfoList = pGenericInfo->GetSubList() ) != 0) { // oeffnende Klammer sTmpStr = ""; for( i=0; i<nLevel; i++) sTmpStr += cKeyLevelChars; sTmpStr += '{'; if ( !rOutStream.WriteLine( sTmpStr ) ) return FALSE; // recursiv die sublist abarbeiten if ( !Save( rOutStream, pGenericInfoList, nLevel+1 ) ) return FALSE; // schliessende Klammer sTmpStr = ""; for( i=0; i<nLevel; i++) sTmpStr += cKeyLevelChars; sTmpStr += '}'; if ( !rOutStream.WriteLine( sTmpStr ) ) return FALSE; } } return TRUE; } /*****************************************************************************/ GenericInformationList *InformationParser::Execute( SvStream &rSourceStream, GenericInformationList *pExistingList ) /*****************************************************************************/ { GenericInformationList *pList; if ( pExistingList ) pList = pExistingList; else pList = new GenericInformationList(); pActStream = &rSourceStream; // read all infos out of current file while( !rSourceStream.IsEof()) { nLevel = 0; ReadKey( pList ); } return pList; } /*****************************************************************************/ GenericInformationList *InformationParser::Execute( SvMemoryStream &rSourceStream, GenericInformationList *pExistingList ) /*****************************************************************************/ { sStreamName = UniString( "Memory", gsl_getSystemTextEncoding()); return Execute( (SvStream &)rSourceStream, pExistingList ); } /*****************************************************************************/ GenericInformationList *InformationParser::Execute( SvFileStream &rSourceStream, GenericInformationList *pExistingList ) /*****************************************************************************/ { if ( !rSourceStream.IsOpen()) return NULL; sStreamName = rSourceStream.GetFileName(); return Execute( (SvStream &)rSourceStream, pExistingList ); } /*****************************************************************************/ GenericInformationList *InformationParser::Execute( UniString &rSourceFile, GenericInformationList *pExistingList ) /*****************************************************************************/ { DirEntry aDirEntry( rSourceFile ); if ( !aDirEntry.Exists()) return NULL; GenericInformationList *pList; if ( pExistingList ) pList = pExistingList; else pList = new GenericInformationList(); // reset status nErrorCode = 0; nErrorLine = 0; nActLine = 0; SvFileStream aActStream; aActStream.Open( rSourceFile, STREAM_READ ); if( aActStream.GetError()) return NULL; pActStream = &aActStream; if ( !Execute( aActStream, pList )) { delete pList; pList = NULL; } // close the stream aActStream.Close(); pActStream = NULL; if ( !nErrorCode ) return pList; return NULL; } /*****************************************************************************/ GenericInformationList *InformationParser::Execute( Dir &rDir, GenericInformationList *pExistingList ) /*****************************************************************************/ { GenericInformationList *pList; if ( pExistingList ) pList = pExistingList; else pList = new GenericInformationList(); for ( USHORT i = 0; i < rDir.Count(); i++ ) { // execute this dir UniString sNextFile( rDir[i].GetFull()); GenericInformationList *pSubList = Execute( sNextFile ); if ( !pSubList ) { // any errors ? delete pList; return NULL; } // create new info and insert it into list ByteString sFileKey( rDir[i].GetName(), RTL_TEXTENCODING_UTF8 ); GenericInformation *pInfo = new GenericInformation( sFileKey, ByteString( "" ), pList, pSubList ); } return pList; } /*****************************************************************************/ BOOL InformationParser::Save( SvFileStream &rSourceStream, const GenericInformationList *pSaveList ) /*****************************************************************************/ { if ( !rSourceStream.IsOpen() || !Save( (SvStream &)rSourceStream, pSaveList, 0 )) return FALSE; return TRUE; } /*****************************************************************************/ BOOL InformationParser::Save( SvMemoryStream &rSourceStream, const GenericInformationList *pSaveList ) /*****************************************************************************/ { return Save( (SvStream &)rSourceStream, pSaveList, 0 ); } /*****************************************************************************/ BOOL InformationParser::Save( const UniString &rSourceFile, const GenericInformationList *pSaveList ) /*****************************************************************************/ { SvFileStream *pOutFile = new SvFileStream( rSourceFile, STREAM_STD_WRITE | STREAM_TRUNC ); if ( !Save( *pOutFile, pSaveList )) { delete pOutFile; return FALSE; } delete pOutFile; return TRUE; } /*****************************************************************************/ USHORT InformationParser::GetErrorCode() /*****************************************************************************/ { return nErrorCode; } /*****************************************************************************/ ByteString &InformationParser::GetErrorText() /*****************************************************************************/ { // sErrorText = pActStream->GetFileName(); sErrorText = ByteString( sStreamName, gsl_getSystemTextEncoding()); sErrorText += ByteString( " (" ); sErrorText += ByteString( nErrorLine ); sErrorText += ByteString( "): " ); switch ( nErrorCode ) { case IP_NO_ERROR: sErrorText += ByteString( "Keine Fehler aufgetereten" ); break; case IP_UNEXPECTED_EOF: sErrorText += ByteString( "Ungltiges Dateiende!" ); break; } return sErrorText; } <commit_msg>print error when unable to save file<commit_after>/************************************************************************* * * $RCSfile: parser.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: gh $ $Date: 2001-12-14 16:31:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <stdio.h> #include <stream.hxx> #include <fsys.hxx> #include "iparser.hxx" #include "geninfo.hxx" // // class InformationParser // const char InformationParser::cKeyLevelChars = '\t'; /*****************************************************************************/ InformationParser::InformationParser( BOOL bReplace ) /*****************************************************************************/ : pActStream( NULL ), nErrorCode( 0 ), nErrorLine( 0 ), nActLine( 0 ), bRecover( FALSE ), sOldLine( "" ), sErrorText( "" ), bReplaceVariables( bReplace ), nLevel( 0 ), sUPD( "" ), sVersion( "" ) { } /*****************************************************************************/ InformationParser::~InformationParser() /*****************************************************************************/ { } /*****************************************************************************/ ByteString &InformationParser::ReadLine() /*****************************************************************************/ { ByteString sLine; if ( bRecover ) { bRecover = FALSE; } else { if ( !pActStream->IsEof()) { pActStream->ReadLine( sLine ); ULONG nLen; do { nLen = sLine.Len(); sLine.EraseLeadingChars( 0x09 ); sLine.EraseLeadingChars( ' ' ); } while ( nLen != sLine.Len()); do { nLen = sLine.Len(); sLine.EraseTrailingChars( 0x09 ); sLine.EraseTrailingChars( ' ' ); } while ( nLen != sLine.Len()); if (( sLine.Search( "#" ) == 0 ) || ( !sLine.Len())) { if ( sCurrentComment.Len()) sCurrentComment += "\n"; sCurrentComment += sLine; return ReadLine(); } else { if ( bReplaceVariables ) { while( sLine.SearchAndReplace( "%UPD", sUPD ) != (USHORT)-1 ); while( sLine.SearchAndReplace( "%VERSION", sVersion ) != (USHORT)-1 ); } } } else { if ( nLevel ) { sLine = "}"; fprintf( stdout, "Reached EOF parsing %s. Suplying extra '}'\n",ByteString( sStreamName, gsl_getSystemTextEncoding()).GetBuffer() ); // nErrorCode = IP_UNEXPECTED_EOF; // nErrorLine = nActLine; } else sLine = ""; } sOldLine = sLine; nActLine++; } return sOldLine; } /*****************************************************************************/ GenericInformation *InformationParser::ReadKey( GenericInformationList *pExistingList ) /*****************************************************************************/ { // this method has no error handling yet, but it works very fast. // it is used to create whole informations and sub informations in // a simple data format in memory, readed in a configuration file with // following format: /* key [value] { key [value] key [value] { key [value] ... ... } } key [value] ... ... */ GenericInformation *pInfo = NULL; ByteString sLine( ReadLine()); ByteString sKey; ByteString sValue; ByteString sComment( sCurrentComment ); sCurrentComment = ""; // key separated from value by tab? USHORT nWSPos = sLine.Search( ' ' ); if ( sLine.Search( '\t' ) < nWSPos ) { nWSPos = sLine.Search( '\t' ); sLine.SearchAndReplace( "\t", " " ); } if ( sLine.GetTokenCount( ' ' ) > 1 ) { sKey = sLine.GetToken( 0, ' ' ); sValue = sLine.Copy( sKey.Len() + 1 ); while (( sValue.Search( ' ' ) == 0 ) || ( sValue.Search( '\t' ) == 0 )) { sValue.Erase( 0, 1 ); } } else sKey=sLine; if ( bReplaceVariables && !nLevel ) { sUPD = sKey.Copy( sKey.Len() - 3 ); sVersion = sKey; } if ( ReadLine() == "{" ) { nLevel++; GenericInformationList *pSubList = new GenericInformationList(); while ( ReadLine() != "}" ) { Recover(); ReadKey( pSubList ); } nLevel--; pInfo = new GenericInformation( sKey, sValue, pExistingList, pSubList ); pInfo->SetComment( sComment ); } else { Recover(); if ( !sKey.Equals( "}" ) && !sKey.Equals( "{" ) ) { pInfo = new GenericInformation( sKey, sValue, pExistingList ); pInfo->SetComment( sComment ); } } return pInfo; } /*****************************************************************************/ void InformationParser::Recover() /*****************************************************************************/ { bRecover = TRUE; } /*****************************************************************************/ BOOL InformationParser::Save( SvStream &rOutStream, const GenericInformationList *pSaveList, USHORT nLevel ) /*****************************************************************************/ { USHORT i; ULONG nInfoListCount; ByteString sTmpStr; GenericInformation *pGenericInfo; GenericInformationList *pGenericInfoList; for ( nInfoListCount = 0; nInfoListCount < pSaveList->Count(); nInfoListCount++) { // Key-Value Paare schreiben pGenericInfo = pSaveList->GetObject( nInfoListCount ); sTmpStr = ""; for( ULONG j=0; j<nLevel; j++) sTmpStr += cKeyLevelChars; for ( i = 0; i < pGenericInfo->GetComment().GetTokenCount( '\n' ); i++ ) { sTmpStr += pGenericInfo->GetComment().GetToken( i, '\n' ); sTmpStr += "\n"; for( ULONG j=0; j<nLevel; j++) sTmpStr += cKeyLevelChars; } sTmpStr += pGenericInfo->GetBuffer(); sTmpStr += ' '; sTmpStr += pGenericInfo->GetValue(); if ( !rOutStream.WriteLine( sTmpStr ) ) return FALSE; // wenn vorhanden, bearbeite recursive die Sublisten if (( pGenericInfoList = pGenericInfo->GetSubList() ) != 0) { // oeffnende Klammer sTmpStr = ""; for( i=0; i<nLevel; i++) sTmpStr += cKeyLevelChars; sTmpStr += '{'; if ( !rOutStream.WriteLine( sTmpStr ) ) return FALSE; // recursiv die sublist abarbeiten if ( !Save( rOutStream, pGenericInfoList, nLevel+1 ) ) return FALSE; // schliessende Klammer sTmpStr = ""; for( i=0; i<nLevel; i++) sTmpStr += cKeyLevelChars; sTmpStr += '}'; if ( !rOutStream.WriteLine( sTmpStr ) ) return FALSE; } } return TRUE; } /*****************************************************************************/ GenericInformationList *InformationParser::Execute( SvStream &rSourceStream, GenericInformationList *pExistingList ) /*****************************************************************************/ { GenericInformationList *pList; if ( pExistingList ) pList = pExistingList; else pList = new GenericInformationList(); pActStream = &rSourceStream; // read all infos out of current file while( !rSourceStream.IsEof()) { nLevel = 0; ReadKey( pList ); } return pList; } /*****************************************************************************/ GenericInformationList *InformationParser::Execute( SvMemoryStream &rSourceStream, GenericInformationList *pExistingList ) /*****************************************************************************/ { sStreamName = UniString( "Memory", gsl_getSystemTextEncoding()); return Execute( (SvStream &)rSourceStream, pExistingList ); } /*****************************************************************************/ GenericInformationList *InformationParser::Execute( SvFileStream &rSourceStream, GenericInformationList *pExistingList ) /*****************************************************************************/ { if ( !rSourceStream.IsOpen()) return NULL; sStreamName = rSourceStream.GetFileName(); return Execute( (SvStream &)rSourceStream, pExistingList ); } /*****************************************************************************/ GenericInformationList *InformationParser::Execute( UniString &rSourceFile, GenericInformationList *pExistingList ) /*****************************************************************************/ { DirEntry aDirEntry( rSourceFile ); if ( !aDirEntry.Exists()) return NULL; GenericInformationList *pList; if ( pExistingList ) pList = pExistingList; else pList = new GenericInformationList(); // reset status nErrorCode = 0; nErrorLine = 0; nActLine = 0; SvFileStream aActStream; aActStream.Open( rSourceFile, STREAM_READ ); if( aActStream.GetError()) return NULL; pActStream = &aActStream; if ( !Execute( aActStream, pList )) { delete pList; pList = NULL; } // close the stream aActStream.Close(); pActStream = NULL; if ( !nErrorCode ) return pList; return NULL; } /*****************************************************************************/ GenericInformationList *InformationParser::Execute( Dir &rDir, GenericInformationList *pExistingList ) /*****************************************************************************/ { GenericInformationList *pList; if ( pExistingList ) pList = pExistingList; else pList = new GenericInformationList(); for ( USHORT i = 0; i < rDir.Count(); i++ ) { // execute this dir UniString sNextFile( rDir[i].GetFull()); GenericInformationList *pSubList = Execute( sNextFile ); if ( !pSubList ) { // any errors ? delete pList; return NULL; } // create new info and insert it into list ByteString sFileKey( rDir[i].GetName(), RTL_TEXTENCODING_UTF8 ); GenericInformation *pInfo = new GenericInformation( sFileKey, ByteString( "" ), pList, pSubList ); } return pList; } /*****************************************************************************/ BOOL InformationParser::Save( SvFileStream &rSourceStream, const GenericInformationList *pSaveList ) /*****************************************************************************/ { if ( !rSourceStream.IsOpen() || !Save( (SvStream &)rSourceStream, pSaveList, 0 )) { printf( "ERROR saving file \"%s\"\n",ByteString( rSourceStream.GetFileName(), gsl_getSystemTextEncoding()).GetBuffer() ); return FALSE; } return TRUE; } /*****************************************************************************/ BOOL InformationParser::Save( SvMemoryStream &rSourceStream, const GenericInformationList *pSaveList ) /*****************************************************************************/ { return Save( (SvStream &)rSourceStream, pSaveList, 0 ); } /*****************************************************************************/ BOOL InformationParser::Save( const UniString &rSourceFile, const GenericInformationList *pSaveList ) /*****************************************************************************/ { SvFileStream *pOutFile = new SvFileStream( rSourceFile, STREAM_STD_WRITE | STREAM_TRUNC ); if ( !Save( *pOutFile, pSaveList )) { delete pOutFile; return FALSE; } delete pOutFile; return TRUE; } /*****************************************************************************/ USHORT InformationParser::GetErrorCode() /*****************************************************************************/ { return nErrorCode; } /*****************************************************************************/ ByteString &InformationParser::GetErrorText() /*****************************************************************************/ { // sErrorText = pActStream->GetFileName(); sErrorText = ByteString( sStreamName, gsl_getSystemTextEncoding()); sErrorText += ByteString( " (" ); sErrorText += ByteString( nErrorLine ); sErrorText += ByteString( "): " ); switch ( nErrorCode ) { case IP_NO_ERROR: sErrorText += ByteString( "Keine Fehler aufgetereten" ); break; case IP_UNEXPECTED_EOF: sErrorText += ByteString( "Ungltiges Dateiende!" ); break; } return sErrorText; } <|endoftext|>
<commit_before>/* * BackwardChainer.cc * * Copyright (C) 2014-2017 OpenCog Foundation * * Authors: Misgana Bayetta <[email protected]> October 2014 * William Ma <https://github.com/williampma> * Nil Geisweiller 2016-2017 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <random> #include <boost/range/algorithm/lower_bound.hpp> #include <opencog/util/random.h> #include <opencog/atomutils/FindUtils.h> #include <opencog/atomutils/Substitutor.h> #include <opencog/atomutils/Unify.h> #include <opencog/atomutils/TypeUtils.h> #include <opencog/atoms/pattern/PatternLink.h> #include <opencog/atoms/pattern/BindLink.h> #include <opencog/query/BindLinkAPI.h> #include "BackwardChainer.h" #include "BackwardChainerPMCB.h" #include "UnifyPMCB.h" #include "BCLogger.h" using namespace opencog; BackwardChainer::BackwardChainer(AtomSpace& as, const Handle& rbs, const Handle& target, const Handle& vardecl, const Handle& focus_set, // TODO: // support // focus_set const BITNodeFitness& fitness) : _fcs_maximum_size(2000), _as(as), _configReader(as, rbs), _bit(as, target, vardecl, fitness), _iteration(0), _last_expansion_andbit(nullptr), _rules(_configReader.get_rules()) { } UREConfigReader& BackwardChainer::get_config() { return _configReader; } const UREConfigReader& BackwardChainer::get_config() const { return _configReader; } void BackwardChainer::do_chain() { while (not termination()) { do_step(); } } void BackwardChainer::do_step() { bc_logger().debug("Iteration %d", _iteration); _iteration++; expand_bit(); fulfill_bit(); reduce_bit(); } bool BackwardChainer::termination() { return _configReader.get_maximum_iterations() <= _iteration; } Handle BackwardChainer::get_results() const { HandleSeq results(_results.begin(), _results.end()); return _as.add_link(SET_LINK, results); } void BackwardChainer::expand_bit() { // This is kinda of hack before meta rules are fully supported by // the Rule class. size_t rules_size = _rules.size(); _rules.expand_meta_rules(_as); // If the rule set has changed we need to reset the exhausted // flags. if (rules_size != _rules.size()) { _bit.reset_exhausted_flags(); bc_logger().debug() << "The rule set has gone from " << rules_size << " rules to " << _rules.size() << ". All exhausted flags have been reset."; } // Reset _last_expansion_fcs _last_expansion_andbit = nullptr; if (_bit.empty()) { _last_expansion_andbit = _bit.init(); } else { // Select an FCS (i.e. and-BIT) and expand it AndBIT* andbit = select_expansion_andbit(); LAZY_BC_LOG_DEBUG << "Selected and-BIT for expansion:" << std::endl << andbit->to_string(); expand_bit(*andbit); } } void BackwardChainer::expand_bit(AndBIT& andbit) { // Select leaf BITNode* bitleaf = andbit.select_leaf(); if (bitleaf) { LAZY_BC_LOG_DEBUG << "Selected BIT-node for expansion:" << std::endl << bitleaf->to_string(); } else { bc_logger().debug() << "All BIT-nodes of this and-BIT are exhausted " << "(or possibly fulfilled). Abort expansion."; andbit.exhausted = true; return; } // Build the leaf vardecl from fcs Handle vardecl = andbit.fcs.is_defined() ? filter_vardecl(BindLinkCast(andbit.fcs)->get_vardecl(), bitleaf->body) : Handle::UNDEFINED; // Select a valid rule Rule rule = select_rule(*bitleaf, vardecl); // Add the rule in the _bit.bit_as to make comparing atoms easier // as well as logging more consistent. rule.add(_bit.bit_as); if (not rule.is_valid()) { bc_logger().debug("No valid rule for the selected BIT-node, abort expansion"); return; } LAZY_BC_LOG_DEBUG << "Selected rule for BIT expansion:" << std::endl << rule.to_string(); _last_expansion_andbit = _bit.expand(andbit, *bitleaf, rule); } void BackwardChainer::fulfill_bit() { if (_bit.empty()) { bc_logger().warn("Cannot fulfill an empty BIT!"); return; } // Select an and-BIT for fulfillment const AndBIT* andbit = select_fulfillment_andbit(); if (andbit == nullptr) { bc_logger().debug() << "Cannot fulfill an empty and-BIT. " << "Abort BIT fulfillment"; return; } LAZY_BC_LOG_DEBUG << "Selected and-BIT for fulfillment:" << std::endl << oc_to_string(andbit->fcs); fulfill_fcs(andbit->fcs); } void BackwardChainer::fulfill_fcs(const Handle& fcs) { Handle hresult = bindlink(&_as, fcs); const HandleSeq& results = hresult->getOutgoingSet(); LAZY_BC_LOG_DEBUG << "Results:" << std::endl << results; _results.insert(results.begin(), results.end()); } AndBIT* BackwardChainer::select_expansion_andbit() { // Calculate distribution. For now it only uses the complexity // factor. Ultimately it should estimate the probability that // selecting an andbit for expansion is gonna contribute to the // inference. std::vector<double> weights; for (const AndBIT& andbit : _bit.andbits) weights.push_back(operator()(andbit)); std::discrete_distribution<size_t> dist(weights.begin(), weights.end()); return &rand_element(_bit.andbits, dist); } const AndBIT* BackwardChainer::select_fulfillment_andbit() const { return _last_expansion_andbit; } void BackwardChainer::reduce_bit() { // TODO: reset exhausted flags related to the removed and-BITs. // Remove and-BITs above a certain size. auto complex_lt = [&](const AndBIT& andbit, size_t max_size) { return andbit.fcs->size() < max_size; }; auto it = boost::lower_bound(_bit.andbits, _fcs_maximum_size, complex_lt); size_t previous_size = _bit.andbits.size(); _bit.erase(it, _bit.andbits.end()); if (size_t removed_andbits = previous_size - _bit.andbits.size()) { LAZY_BC_LOG_DEBUG << "Removed " << removed_andbits << " overly complex and-BITs from the BIT"; } } Rule BackwardChainer::select_rule(BITNode& target, const Handle& vardecl) { // The rule is randomly selected amongst the valid ones, with // probability of selection being proportional to its weight. const RuleSet valid_rules = get_valid_rules(target, vardecl); if (valid_rules.empty()) { target.exhausted = true; return Rule(); } // Log all valid rules and their weights if (bc_logger().is_debug_enabled()) { std::stringstream ss; ss << "The following rules are valid:"; for (const Rule& r : valid_rules) ss << std::endl << r.get_name(); LAZY_BC_LOG_DEBUG << ss.str(); } return select_rule(valid_rules); } Rule BackwardChainer::select_rule(const RuleSet& rules) { // Build weight vector to do weighted random selection std::vector<double> weights; for (const Rule& rule : rules) weights.push_back(rule.get_weight()); // No rule exhaustion, sample one according to the distribution std::discrete_distribution<size_t> dist(weights.begin(), weights.end()); return rand_element(rules, dist); } RuleSet BackwardChainer::get_valid_rules(const BITNode& target, const Handle& vardecl) { // Generate all valid rules RuleSet valid_rules; for (const Rule& rule : _rules) { // For now ignore meta rules as they are forwardly applied in // expand_bit() if (rule.is_meta()) continue; RuleSet unified_rules = rule.unify_target(target.body, vardecl); // Insert only rules with positive probability of success RuleSet pos_rules; for (const Rule& rule : unified_rules) { double p = (_bit.is_in(rule, target) ? 0.0 : 1.0) * rule.get_weight(); if (p > 0) pos_rules.insert(rule); } valid_rules.insert(pos_rules.begin(), pos_rules.end()); } return valid_rules; } double BackwardChainer::complexity_factor(const AndBIT& andbit) const { return exp(-_configReader.get_complexity_penalty() * andbit.fcs->size()); } double BackwardChainer::operator()(const AndBIT& andbit) const { return (andbit.exhausted ? 0.0 : 1.0) * complexity_factor(andbit); } <commit_msg>Dump the intermediary results in a temporary atomspace<commit_after>/* * BackwardChainer.cc * * Copyright (C) 2014-2017 OpenCog Foundation * * Authors: Misgana Bayetta <[email protected]> October 2014 * William Ma <https://github.com/williampma> * Nil Geisweiller 2016-2017 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <random> #include <boost/range/algorithm/lower_bound.hpp> #include <opencog/util/random.h> #include <opencog/atomutils/FindUtils.h> #include <opencog/atomutils/Substitutor.h> #include <opencog/atomutils/Unify.h> #include <opencog/atomutils/TypeUtils.h> #include <opencog/atoms/pattern/PatternLink.h> #include <opencog/atoms/pattern/BindLink.h> #include <opencog/query/BindLinkAPI.h> #include "BackwardChainer.h" #include "BackwardChainerPMCB.h" #include "UnifyPMCB.h" #include "BCLogger.h" using namespace opencog; BackwardChainer::BackwardChainer(AtomSpace& as, const Handle& rbs, const Handle& target, const Handle& vardecl, const Handle& focus_set, // TODO: // support // focus_set const BITNodeFitness& fitness) : _fcs_maximum_size(2000), _as(as), _configReader(as, rbs), _bit(as, target, vardecl, fitness), _iteration(0), _last_expansion_andbit(nullptr), _rules(_configReader.get_rules()) { } UREConfigReader& BackwardChainer::get_config() { return _configReader; } const UREConfigReader& BackwardChainer::get_config() const { return _configReader; } void BackwardChainer::do_chain() { while (not termination()) { do_step(); } } void BackwardChainer::do_step() { bc_logger().debug("Iteration %d", _iteration); _iteration++; expand_bit(); fulfill_bit(); reduce_bit(); } bool BackwardChainer::termination() { return _configReader.get_maximum_iterations() <= _iteration; } Handle BackwardChainer::get_results() const { HandleSeq results(_results.begin(), _results.end()); return _as.add_link(SET_LINK, results); } void BackwardChainer::expand_bit() { // This is kinda of hack before meta rules are fully supported by // the Rule class. size_t rules_size = _rules.size(); _rules.expand_meta_rules(_as); // If the rule set has changed we need to reset the exhausted // flags. if (rules_size != _rules.size()) { _bit.reset_exhausted_flags(); bc_logger().debug() << "The rule set has gone from " << rules_size << " rules to " << _rules.size() << ". All exhausted flags have been reset."; } // Reset _last_expansion_fcs _last_expansion_andbit = nullptr; if (_bit.empty()) { _last_expansion_andbit = _bit.init(); } else { // Select an FCS (i.e. and-BIT) and expand it AndBIT* andbit = select_expansion_andbit(); LAZY_BC_LOG_DEBUG << "Selected and-BIT for expansion:" << std::endl << andbit->to_string(); expand_bit(*andbit); } } void BackwardChainer::expand_bit(AndBIT& andbit) { // Select leaf BITNode* bitleaf = andbit.select_leaf(); if (bitleaf) { LAZY_BC_LOG_DEBUG << "Selected BIT-node for expansion:" << std::endl << bitleaf->to_string(); } else { bc_logger().debug() << "All BIT-nodes of this and-BIT are exhausted " << "(or possibly fulfilled). Abort expansion."; andbit.exhausted = true; return; } // Build the leaf vardecl from fcs Handle vardecl = andbit.fcs.is_defined() ? filter_vardecl(BindLinkCast(andbit.fcs)->get_vardecl(), bitleaf->body) : Handle::UNDEFINED; // Select a valid rule Rule rule = select_rule(*bitleaf, vardecl); // Add the rule in the _bit.bit_as to make comparing atoms easier // as well as logging more consistent. rule.add(_bit.bit_as); if (not rule.is_valid()) { bc_logger().debug("No valid rule for the selected BIT-node, abort expansion"); return; } LAZY_BC_LOG_DEBUG << "Selected rule for BIT expansion:" << std::endl << rule.to_string(); _last_expansion_andbit = _bit.expand(andbit, *bitleaf, rule); } void BackwardChainer::fulfill_bit() { if (_bit.empty()) { bc_logger().warn("Cannot fulfill an empty BIT!"); return; } // Select an and-BIT for fulfillment const AndBIT* andbit = select_fulfillment_andbit(); if (andbit == nullptr) { bc_logger().debug() << "Cannot fulfill an empty and-BIT. " << "Abort BIT fulfillment"; return; } LAZY_BC_LOG_DEBUG << "Selected and-BIT for fulfillment:" << std::endl << oc_to_string(andbit->fcs); fulfill_fcs(andbit->fcs); } void BackwardChainer::fulfill_fcs(const Handle& fcs) { // Temporary atomspace to not pollute _as with intermediary // results AtomSpace tmp_as(&_as); // Run the FCS and add the results in _as Handle hresult = bindlink(&tmp_as, fcs); HandleSeq results; for (const Handle& result : hresult->getOutgoingSet()) results.push_back(_as.add_atom(result)); LAZY_BC_LOG_DEBUG << "Results:" << std::endl << results; _results.insert(results.begin(), results.end()); } AndBIT* BackwardChainer::select_expansion_andbit() { // Calculate distribution. For now it only uses the complexity // factor. Ultimately it should estimate the probability that // selecting an andbit for expansion is gonna contribute to the // inference. std::vector<double> weights; for (const AndBIT& andbit : _bit.andbits) weights.push_back(operator()(andbit)); std::discrete_distribution<size_t> dist(weights.begin(), weights.end()); return &rand_element(_bit.andbits, dist); } const AndBIT* BackwardChainer::select_fulfillment_andbit() const { return _last_expansion_andbit; } void BackwardChainer::reduce_bit() { // TODO: reset exhausted flags related to the removed and-BITs. // Remove and-BITs above a certain size. auto complex_lt = [&](const AndBIT& andbit, size_t max_size) { return andbit.fcs->size() < max_size; }; auto it = boost::lower_bound(_bit.andbits, _fcs_maximum_size, complex_lt); size_t previous_size = _bit.andbits.size(); _bit.erase(it, _bit.andbits.end()); if (size_t removed_andbits = previous_size - _bit.andbits.size()) { LAZY_BC_LOG_DEBUG << "Removed " << removed_andbits << " overly complex and-BITs from the BIT"; } } Rule BackwardChainer::select_rule(BITNode& target, const Handle& vardecl) { // The rule is randomly selected amongst the valid ones, with // probability of selection being proportional to its weight. const RuleSet valid_rules = get_valid_rules(target, vardecl); if (valid_rules.empty()) { target.exhausted = true; return Rule(); } // Log all valid rules and their weights if (bc_logger().is_debug_enabled()) { std::stringstream ss; ss << "The following rules are valid:"; for (const Rule& r : valid_rules) ss << std::endl << r.get_name(); LAZY_BC_LOG_DEBUG << ss.str(); } return select_rule(valid_rules); } Rule BackwardChainer::select_rule(const RuleSet& rules) { // Build weight vector to do weighted random selection std::vector<double> weights; for (const Rule& rule : rules) weights.push_back(rule.get_weight()); // No rule exhaustion, sample one according to the distribution std::discrete_distribution<size_t> dist(weights.begin(), weights.end()); return rand_element(rules, dist); } RuleSet BackwardChainer::get_valid_rules(const BITNode& target, const Handle& vardecl) { // Generate all valid rules RuleSet valid_rules; for (const Rule& rule : _rules) { // For now ignore meta rules as they are forwardly applied in // expand_bit() if (rule.is_meta()) continue; RuleSet unified_rules = rule.unify_target(target.body, vardecl); // Insert only rules with positive probability of success RuleSet pos_rules; for (const Rule& rule : unified_rules) { double p = (_bit.is_in(rule, target) ? 0.0 : 1.0) * rule.get_weight(); if (p > 0) pos_rules.insert(rule); } valid_rules.insert(pos_rules.begin(), pos_rules.end()); } return valid_rules; } double BackwardChainer::complexity_factor(const AndBIT& andbit) const { return exp(-_configReader.get_complexity_penalty() * andbit.fcs->size()); } double BackwardChainer::operator()(const AndBIT& andbit) const { return (andbit.exhausted ? 0.0 : 1.0) * complexity_factor(andbit); } <|endoftext|>
<commit_before>//===--- ConditionVariable.cpp - ConditionVariable Tests ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/Threading/ConditionVariable.h" #include "gtest/gtest.h" #include <chrono> #include <vector> #include "ThreadingHelpers.h" #include "LockingHelpers.h" using namespace swift; template <typename Body> std::chrono::duration<double> measureDuration(Body body) { auto start = std::chrono::steady_clock::now(); body(); return std::chrono::steady_clock::now() - start; } // ----------------------------------------------------------------------------- // Check we can lock, unlock, lock and unlock an unlocked condition variable TEST(ConditionVariableTest, BasicLockable) { ConditionVariable cond; basicLockable(cond); } // Test ScopedLock and ScopedUnlock TEST(ConditionVariableTest, ScopedLockThreaded) { ConditionVariable cond; scopedLockThreaded<ConditionVariable::ScopedLock>(cond); } TEST(ConditionVariableTest, ScopedUnlockUnderScopedLockThreaded) { ConditionVariable cond; scopedUnlockUnderScopedLockThreaded<ConditionVariable::ScopedLock, ConditionVariable::ScopedUnlock>(cond); } // Test withLock() TEST(ConditionVariableTest, CriticalSectionThreaded) { ConditionVariable cond; criticalSectionThreaded(cond); } // Check that timeouts work TEST(ConditionVariableTest, Timeout) { using namespace std::chrono_literals; ConditionVariable cond; auto duration = measureDuration([&] { ConditionVariable::ScopedLock lock(cond); bool ret = cond.wait(0.01s); ASSERT_FALSE(ret); }); ASSERT_GE(duration.count(), 0.01); duration = measureDuration([&] { ConditionVariable::ScopedLock lock(cond); bool ret = cond.wait(0.1s); ASSERT_FALSE(ret); }); ASSERT_GE(duration.count(), 0.1); duration = measureDuration([&] { ConditionVariable::ScopedLock lock(cond); bool ret = cond.wait(1s); ASSERT_FALSE(ret); }); ASSERT_GE(duration.count(), 1.0); auto deadline = std::chrono::system_clock::now() + 0.5s; duration = measureDuration([&] { ConditionVariable::ScopedLock lock(cond); bool ret = cond.waitUntil(deadline); ASSERT_FALSE(ret); }); ASSERT_GE(duration.count(), 0.5); } #if !SWIFT_THREADING_NONE // Check that signal() wakes exactly one waiter TEST(ConditionVariableTest, Signal) { ConditionVariable cond; int ready = 0, done = 0; std::vector<std::thread> threads; const int thread_count = 10; for (int i = 0; i < thread_count; ++i) { threads.push_back(std::thread([&] { cond.lock(); ++ready; cond.wait(); ++done; cond.unlock(); })); } // Wait for all threads to be ready cond.withLock([&] { int tries = 1000; while (ready < thread_count && tries--) { ConditionVariable::ScopedUnlock unlock(cond); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }); ASSERT_EQ(ready, thread_count); // Signal the condition variable and check that done increments by one // each time for (int i = 0; i < thread_count; ++i) { cond.signal(); cond.withLock([&] { int tries = 500; while (done == i && tries--) { ConditionVariable::ScopedUnlock unlock(cond); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }); ASSERT_EQ(done, i + 1); } ASSERT_EQ(done, thread_count); for (auto &thread : threads) { thread.join(); } } // Check that broadcast() wakes all waiters TEST(ConditionVariableTest, Broadcast) { ConditionVariable cond; int ready = 0, done = 0; std::vector<std::thread> threads; const int thread_count = 10; for (int i = 0; i < thread_count; ++i) { threads.push_back(std::thread([&] { cond.lock(); ++ready; cond.wait(); ++done; cond.unlock(); })); } // Wait for all threads to be ready cond.withLock([&] { int tries = 1000; while (ready < thread_count && tries--) { ConditionVariable::ScopedUnlock unlock(cond); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }); ASSERT_EQ(ready, thread_count); // Broadcast and wait cond.broadcast(); cond.withLock([&] { int tries = 1000; while (done < thread_count && tries--) { ConditionVariable::ScopedUnlock unlock(cond); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }); ASSERT_EQ(done, thread_count); for (auto &thread : threads) { thread.join(); } } #endif <commit_msg>[Threading][Tests] Don't test timeouts on threading=none.<commit_after>//===--- ConditionVariable.cpp - ConditionVariable Tests ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/Threading/ConditionVariable.h" #include "gtest/gtest.h" #include <chrono> #include <vector> #include "ThreadingHelpers.h" #include "LockingHelpers.h" using namespace swift; template <typename Body> std::chrono::duration<double> measureDuration(Body body) { auto start = std::chrono::steady_clock::now(); body(); return std::chrono::steady_clock::now() - start; } // ----------------------------------------------------------------------------- // Check we can lock, unlock, lock and unlock an unlocked condition variable TEST(ConditionVariableTest, BasicLockable) { ConditionVariable cond; basicLockable(cond); } // Test ScopedLock and ScopedUnlock TEST(ConditionVariableTest, ScopedLockThreaded) { ConditionVariable cond; scopedLockThreaded<ConditionVariable::ScopedLock>(cond); } TEST(ConditionVariableTest, ScopedUnlockUnderScopedLockThreaded) { ConditionVariable cond; scopedUnlockUnderScopedLockThreaded<ConditionVariable::ScopedLock, ConditionVariable::ScopedUnlock>(cond); } // Test withLock() TEST(ConditionVariableTest, CriticalSectionThreaded) { ConditionVariable cond; criticalSectionThreaded(cond); } #if !SWIFT_THREADING_NONE // Check that timeouts work TEST(ConditionVariableTest, Timeout) { using namespace std::chrono_literals; ConditionVariable cond; auto duration = measureDuration([&] { ConditionVariable::ScopedLock lock(cond); bool ret = cond.wait(0.01s); ASSERT_FALSE(ret); }); ASSERT_GE(duration.count(), 0.01); duration = measureDuration([&] { ConditionVariable::ScopedLock lock(cond); bool ret = cond.wait(0.1s); ASSERT_FALSE(ret); }); ASSERT_GE(duration.count(), 0.1); duration = measureDuration([&] { ConditionVariable::ScopedLock lock(cond); bool ret = cond.wait(1s); ASSERT_FALSE(ret); }); ASSERT_GE(duration.count(), 1.0); auto deadline = std::chrono::system_clock::now() + 0.5s; duration = measureDuration([&] { ConditionVariable::ScopedLock lock(cond); bool ret = cond.waitUntil(deadline); ASSERT_FALSE(ret); }); ASSERT_GE(duration.count(), 0.5); } // Check that signal() wakes exactly one waiter TEST(ConditionVariableTest, Signal) { ConditionVariable cond; int ready = 0, done = 0; std::vector<std::thread> threads; const int thread_count = 10; for (int i = 0; i < thread_count; ++i) { threads.push_back(std::thread([&] { cond.lock(); ++ready; cond.wait(); ++done; cond.unlock(); })); } // Wait for all threads to be ready cond.withLock([&] { int tries = 1000; while (ready < thread_count && tries--) { ConditionVariable::ScopedUnlock unlock(cond); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }); ASSERT_EQ(ready, thread_count); // Signal the condition variable and check that done increments by one // each time for (int i = 0; i < thread_count; ++i) { cond.signal(); cond.withLock([&] { int tries = 500; while (done == i && tries--) { ConditionVariable::ScopedUnlock unlock(cond); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }); ASSERT_EQ(done, i + 1); } ASSERT_EQ(done, thread_count); for (auto &thread : threads) { thread.join(); } } // Check that broadcast() wakes all waiters TEST(ConditionVariableTest, Broadcast) { ConditionVariable cond; int ready = 0, done = 0; std::vector<std::thread> threads; const int thread_count = 10; for (int i = 0; i < thread_count; ++i) { threads.push_back(std::thread([&] { cond.lock(); ++ready; cond.wait(); ++done; cond.unlock(); })); } // Wait for all threads to be ready cond.withLock([&] { int tries = 1000; while (ready < thread_count && tries--) { ConditionVariable::ScopedUnlock unlock(cond); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }); ASSERT_EQ(ready, thread_count); // Broadcast and wait cond.broadcast(); cond.withLock([&] { int tries = 1000; while (done < thread_count && tries--) { ConditionVariable::ScopedUnlock unlock(cond); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }); ASSERT_EQ(done, thread_count); for (auto &thread : threads) { thread.join(); } } #endif <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2015, Stuart W Baker * 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. * * 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. * * \file Lpc17xx40xxEEPROMEmulation.cxx * This file implements Lpc compatible EEPROM emulation in FLASH. * * @author Stuart W. Baker * @date 15 June 2015 */ #include "Lpc17xx40xxEEPROMEmulation.hxx" #include <cstring> #include "iap.h" #include "chip.h" // We can't put a weak definition of a constant, because GCC, due to a bug, // will inline the definition that appears here even if it is overridden at link // time. // // const size_t __attribute__((weak)) EEPROMEmulation::SECTOR_SIZE = 0x8000; const size_t EEPROMEmulation::BLOCK_SIZE = 16; const size_t EEPROMEmulation::BYTES_PER_BLOCK = 8; static uint8_t get_first_sector() { unsigned estart = (unsigned)(&__eeprom_start); if (estart < 0x10000) { return estart / 0x1000; } else { return 16 - 2 + estart / 0x8000; // estart==0x10000 -> sector==16. } } /** Constructor. * @param name device name * @param file_size maximum file size that we can grow to. */ LpcEEPROMEmulation::LpcEEPROMEmulation(const char *name, size_t file_size) : EEPROMEmulation(name, file_size), firstSector_(get_first_sector()) { /* IAP cannot access RAM below 0x10000200) */ HASSERT(((uintptr_t)scratch) >= 0x10000200); unsigned eend = (unsigned)(&__eeprom_end); unsigned estart = (unsigned)(&__eeprom_start); if (eend <= 0x10000) { HASSERT(SECTOR_SIZE == 0x1000); } else if (estart >= 0x10000) { HASSERT(SECTOR_SIZE == 0x8000); } else { DIE("LPC17xx cannot have the EEPROM range cross the boundary of " "address of 0x10000"); } HASSERT(estart % SECTOR_SIZE == 0); HASSERT(eend % SECTOR_SIZE == 0); mount(); } inline const uint32_t *LpcEEPROMEmulation::get_block( unsigned sector, unsigned offset) { return (uint32_t*)(&__eeprom_start + sector * EEPROMEmulation::SECTOR_SIZE + offset * EEPROMEmulation::BLOCK_SIZE); } /** * Computes the pointer to load the data stored in a specific block from. * @param sector sector number [0..sectorCount_ - 1] * @param offset block index within sector, [0..rawBlockCount_ - 1] * @return pointer to the beginning of the data in the block. Must be alive until the next call to this function. */ const uint32_t* LpcEEPROMEmulation::block(unsigned sector, unsigned offset) { return get_block(sector, offset); } /** Simple hardware abstraction for FLASH erase API. * @param sector Number of sector [0.. sectorCount_ - 1] to erase */ void LpcEEPROMEmulation::flash_erase(unsigned sector) { HASSERT(sector < sectorCount_); unsigned s = sector + firstSector_; portENTER_CRITICAL(); Chip_IAP_PreSectorForReadWrite(s, s); Chip_IAP_EraseSector(s, s); portEXIT_CRITICAL(); } /** Simple hardware abstraction for FLASH program API. * @param sector the sector to write to [0..sectorCount_ - 1] * @param start_block the block index to start writing to [0..rawBlockCount_ - * 1] * @param data a pointer to the data to be programmed * @param byte_count the number of bytes to be programmed. * Must be a multiple of BLOCK_SIZE */ void LpcEEPROMEmulation::flash_program( unsigned relative_sector, unsigned start_block, uint32_t *data, uint32_t byte_count) { HASSERT(relative_sector < sectorCount_); HASSERT((byte_count % BLOCK_SIZE) == 0); HASSERT(start_block + (byte_count / BLOCK_SIZE) < rawBlockCount_); auto* address = get_block(relative_sector, start_block); /* make sure we have the correct frequency */ SystemCoreClockUpdate(); uint32_t start_address = (uintptr_t)address & ~(WRITE_SIZE - 1); uint32_t sector = firstSector_ + relative_sector; HASSERT(((uintptr_t)address + byte_count) <= (start_address + WRITE_SIZE)); memset(scratch, 0xFF, sizeof(scratch)); memcpy(scratch + ((uintptr_t)address - start_address), data, byte_count); portENTER_CRITICAL(); Chip_IAP_PreSectorForReadWrite(sector, sector); Chip_IAP_CopyRamToFlash(start_address, (uint32_t*)scratch, WRITE_SIZE); portEXIT_CRITICAL(); } <commit_msg>Lpc17xx40xx eeprom emulation hassert bug (#664)<commit_after>/** \copyright * Copyright (c) 2015, Stuart W Baker * 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. * * 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. * * \file Lpc17xx40xxEEPROMEmulation.cxx * This file implements Lpc compatible EEPROM emulation in FLASH. * * @author Stuart W. Baker * @date 15 June 2015 */ #include "Lpc17xx40xxEEPROMEmulation.hxx" #include <cstring> #include "iap.h" #include "chip.h" // We can't put a weak definition of a constant, because GCC, due to a bug, // will inline the definition that appears here even if it is overridden at link // time. // // const size_t __attribute__((weak)) EEPROMEmulation::SECTOR_SIZE = 0x8000; const size_t EEPROMEmulation::BLOCK_SIZE = 16; const size_t EEPROMEmulation::BYTES_PER_BLOCK = 8; static uint8_t get_first_sector() { unsigned estart = (unsigned)(&__eeprom_start); if (estart < 0x10000) { return estart / 0x1000; } else { return 16 - 2 + estart / 0x8000; // estart==0x10000 -> sector==16. } } /** Constructor. * @param name device name * @param file_size maximum file size that we can grow to. */ LpcEEPROMEmulation::LpcEEPROMEmulation(const char *name, size_t file_size) : EEPROMEmulation(name, file_size), firstSector_(get_first_sector()) { /* IAP cannot access RAM below 0x10000200) */ HASSERT(((uintptr_t)scratch) >= 0x10000200); unsigned eend = (unsigned)(&__eeprom_end); unsigned estart = (unsigned)(&__eeprom_start); if (eend <= 0x10000) { HASSERT(SECTOR_SIZE == 0x1000); } else if (estart >= 0x10000) { HASSERT(SECTOR_SIZE == 0x8000); } else { DIE("LPC17xx cannot have the EEPROM range cross the boundary of " "address of 0x10000"); } HASSERT(estart % SECTOR_SIZE == 0); HASSERT(eend % SECTOR_SIZE == 0); mount(); } inline const uint32_t *LpcEEPROMEmulation::get_block( unsigned sector, unsigned offset) { return (uint32_t*)(&__eeprom_start + sector * EEPROMEmulation::SECTOR_SIZE + offset * EEPROMEmulation::BLOCK_SIZE); } /** * Computes the pointer to load the data stored in a specific block from. * @param sector sector number [0..sectorCount_ - 1] * @param offset block index within sector, [0..rawBlockCount_ - 1] * @return pointer to the beginning of the data in the block. Must be alive until the next call to this function. */ const uint32_t* LpcEEPROMEmulation::block(unsigned sector, unsigned offset) { return get_block(sector, offset); } /** Simple hardware abstraction for FLASH erase API. * @param sector Number of sector [0.. sectorCount_ - 1] to erase */ void LpcEEPROMEmulation::flash_erase(unsigned sector) { HASSERT(sector < sectorCount_); unsigned s = sector + firstSector_; portENTER_CRITICAL(); Chip_IAP_PreSectorForReadWrite(s, s); Chip_IAP_EraseSector(s, s); portEXIT_CRITICAL(); } /** Simple hardware abstraction for FLASH program API. * @param sector the sector to write to [0..sectorCount_ - 1] * @param start_block the block index to start writing to [0..rawBlockCount_ - * 1] * @param data a pointer to the data to be programmed * @param byte_count the number of bytes to be programmed. * Must be a multiple of BLOCK_SIZE */ void LpcEEPROMEmulation::flash_program( unsigned relative_sector, unsigned start_block, uint32_t *data, uint32_t byte_count) { HASSERT(relative_sector < sectorCount_); HASSERT((byte_count % BLOCK_SIZE) == 0); HASSERT(start_block + (byte_count / BLOCK_SIZE) <= rawBlockCount_); auto* address = get_block(relative_sector, start_block); /* make sure we have the correct frequency */ SystemCoreClockUpdate(); uint32_t start_address = (uintptr_t)address & ~(WRITE_SIZE - 1); uint32_t sector = firstSector_ + relative_sector; HASSERT(((uintptr_t)address + byte_count) <= (start_address + WRITE_SIZE)); memset(scratch, 0xFF, sizeof(scratch)); memcpy(scratch + ((uintptr_t)address - start_address), data, byte_count); portENTER_CRITICAL(); Chip_IAP_PreSectorForReadWrite(sector, sector); Chip_IAP_CopyRamToFlash(start_address, (uint32_t*)scratch, WRITE_SIZE); portEXIT_CRITICAL(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2011, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the University of Oxford 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 "utility/oskar_Device_curand_state.h" #include "utility/oskar_device_curand_state_init.h" #include <cstdlib> #include <cstdio> #include <cuda_runtime_api.h> #include <curand_kernel.h> oskar_Device_curand_state::oskar_Device_curand_state(int num_states) { int err = cudaMalloc((void**)&(this->state), num_states * sizeof(curandState)); this->num_states = num_states; if (err != CUDA_SUCCESS) throw "Error allocating memory oskar_Device_state::curand_state."; } oskar_Device_curand_state::~oskar_Device_curand_state() { if (state != NULL) cudaFree(state); } int oskar_Device_curand_state::init(int seed, int offset, int use_device_offset) { return oskar_device_curand_state_init(this->state, this->num_states, seed, offset, use_device_offset); } <commit_msg>Fixed include.<commit_after>/* * Copyright (c) 2011, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the University of Oxford 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 "utility/oskar_Device_curand_state.h" #include "utility/oskar_device_curand_state_init.h" #include <cstdlib> #include <cstdio> #include <cuda.h> #include <curand_kernel.h> oskar_Device_curand_state::oskar_Device_curand_state(int num_states) { int err = cudaMalloc((void**)&(this->state), num_states * sizeof(curandState)); this->num_states = num_states; if (err != CUDA_SUCCESS) throw "Error allocating memory oskar_Device_state::curand_state."; } oskar_Device_curand_state::~oskar_Device_curand_state() { if (state != NULL) cudaFree(state); } int oskar_Device_curand_state::init(int seed, int offset, int use_device_offset) { return oskar_device_curand_state_init(this->state, this->num_states, seed, offset, use_device_offset); } <|endoftext|>
<commit_before>//===- SearchableTableEmitter.cpp - Generate efficiently searchable tables -==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits a generic array initialized by specified fields, // together with companion index tables and lookup functions (binary search, // currently). // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Format.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include <algorithm> #include <sstream> #include <string> #include <vector> using namespace llvm; #define DEBUG_TYPE "searchable-table-emitter" namespace { class SearchableTableEmitter { RecordKeeper &Records; public: SearchableTableEmitter(RecordKeeper &R) : Records(R) {} void run(raw_ostream &OS); private: typedef std::pair<Init *, int> SearchTableEntry; int getAsInt(BitsInit *B) { return cast<IntInit>(B->convertInitializerTo(IntRecTy::get()))->getValue(); } int getInt(Record *R, StringRef Field) { return getAsInt(R->getValueAsBitsInit(Field)); } std::string primaryRepresentation(Init *I) { if (StringInit *SI = dyn_cast<StringInit>(I)) return SI->getAsString(); else if (BitsInit *BI = dyn_cast<BitsInit>(I)) return "0x" + utohexstr(getAsInt(BI)); else if (BitInit *BI = dyn_cast<BitInit>(I)) return BI->getValue() ? "true" : "false"; else if (CodeInit *CI = dyn_cast<CodeInit>(I)) { return CI->getValue(); } PrintFatalError(SMLoc(), "invalid field type, expected: string, bits, bit or code"); } std::string searchRepresentation(Init *I) { std::string PrimaryRep = primaryRepresentation(I); if (!isa<StringInit>(I)) return PrimaryRep; return StringRef(PrimaryRep).upper(); } std::string searchableFieldType(Init *I) { if (isa<StringInit>(I)) return "const char *"; else if (BitsInit *BI = dyn_cast<BitsInit>(I)) { unsigned NumBits = BI->getNumBits(); if (NumBits <= 8) NumBits = 8; else if (NumBits <= 16) NumBits = 16; else if (NumBits <= 32) NumBits = 32; else if (NumBits <= 64) NumBits = 64; else PrintFatalError(SMLoc(), "bitfield too large to search"); return "uint" + utostr(NumBits) + "_t"; } PrintFatalError(SMLoc(), "Unknown type to search by"); } void emitMapping(Record *MappingDesc, raw_ostream &OS); void emitMappingEnum(std::vector<Record *> &Items, Record *InstanceClass, raw_ostream &OS); void emitPrimaryTable(StringRef Name, std::vector<std::string> &FieldNames, std::vector<std::string> &SearchFieldNames, std::vector<std::vector<SearchTableEntry>> &SearchTables, std::vector<Record *> &Items, raw_ostream &OS); void emitSearchTable(StringRef Name, StringRef Field, std::vector<SearchTableEntry> &SearchTable, raw_ostream &OS); void emitLookupDeclaration(StringRef Name, StringRef Field, Init *I, raw_ostream &OS); void emitLookupFunction(StringRef Name, StringRef Field, Init *I, raw_ostream &OS); }; } // End anonymous namespace. /// Emit an enum providing symbolic access to some preferred field from /// C++. void SearchableTableEmitter::emitMappingEnum(std::vector<Record *> &Items, Record *InstanceClass, raw_ostream &OS) { std::string EnumNameField = InstanceClass->getValueAsString("EnumNameField"); std::string EnumValueField; if (!InstanceClass->isValueUnset("EnumValueField")) EnumValueField = InstanceClass->getValueAsString("EnumValueField"); OS << "enum " << InstanceClass->getName() << "Values {\n"; for (auto Item : Items) { OS << " " << Item->getValueAsString(EnumNameField); if (EnumValueField != StringRef()) OS << " = " << getInt(Item, EnumValueField); OS << ",\n"; } OS << "};\n\n"; } void SearchableTableEmitter::emitPrimaryTable( StringRef Name, std::vector<std::string> &FieldNames, std::vector<std::string> &SearchFieldNames, std::vector<std::vector<SearchTableEntry>> &SearchTables, std::vector<Record *> &Items, raw_ostream &OS) { OS << "const " << Name << " " << Name << "sList[] = {\n"; for (auto Item : Items) { OS << " { "; for (unsigned i = 0; i < FieldNames.size(); ++i) { OS << primaryRepresentation(Item->getValueInit(FieldNames[i])); if (i != FieldNames.size() - 1) OS << ", "; } OS << "},\n"; } OS << "};\n\n"; } void SearchableTableEmitter::emitSearchTable( StringRef Name, StringRef Field, std::vector<SearchTableEntry> &SearchTable, raw_ostream &OS) { OS << "const std::pair<" << searchableFieldType(SearchTable[0].first) << ", int> " << Name << "sBy" << Field << "[] = {\n"; if (isa<BitsInit>(SearchTable[0].first)) { std::stable_sort(SearchTable.begin(), SearchTable.end(), [this](const SearchTableEntry &LHS, const SearchTableEntry &RHS) { return getAsInt(cast<BitsInit>(LHS.first)) < getAsInt(cast<BitsInit>(RHS.first)); }); } else { std::stable_sort(SearchTable.begin(), SearchTable.end(), [this](const SearchTableEntry &LHS, const SearchTableEntry &RHS) { return searchRepresentation(LHS.first) < searchRepresentation(RHS.first); }); } for (auto Entry : SearchTable) { OS << " { " << searchRepresentation(Entry.first) << ", " << Entry.second << " },\n"; } OS << "};\n\n"; } void SearchableTableEmitter::emitLookupFunction(StringRef Name, StringRef Field, Init *I, raw_ostream &OS) { bool IsIntegral = isa<BitsInit>(I); std::string FieldType = searchableFieldType(I); std::string PairType = "std::pair<" + FieldType + ", int>"; // const SysRegs *lookupSysRegByName(const char *Name) { OS << "const " << Name << " *" << "lookup" << Name << "By" << Field; OS << "(" << (IsIntegral ? FieldType : "StringRef") << " " << Field << ") {\n"; if (IsIntegral) { OS << " auto CanonicalVal = " << Field << ";\n"; OS << " " << PairType << " Val = {CanonicalVal, 0};\n"; } else { // Make sure the result is null terminated because it's going via "char *". OS << " std::string CanonicalVal = " << Field << ".upper();\n"; OS << " " << PairType << " Val = {CanonicalVal.data(), 0};\n"; } OS << " ArrayRef<" << PairType << "> Table(" << Name << "sBy" << Field << ");\n"; OS << " auto Idx = std::lower_bound(Table.begin(), Table.end(), Val"; if (IsIntegral) OS << ");\n"; else { OS << ",\n "; OS << "[](const " << PairType << " &LHS, const " << PairType << " &RHS) {\n"; OS << " return StringRef(LHS.first) < StringRef(RHS.first);\n"; OS << " });\n\n"; } OS << " if (Idx == Table.end() || CanonicalVal != Idx->first)\n"; OS << " return nullptr;\n"; OS << " return &" << Name << "sList[Idx->second];\n"; OS << "}\n\n"; } void SearchableTableEmitter::emitLookupDeclaration(StringRef Name, StringRef Field, Init *I, raw_ostream &OS) { bool IsIntegral = isa<BitsInit>(I); std::string FieldType = searchableFieldType(I); OS << "const " << Name << " *" << "lookup" << Name << "By" << Field; OS << "(" << (IsIntegral ? FieldType : "StringRef") << " " << Field << ");\n\n"; } void SearchableTableEmitter::emitMapping(Record *InstanceClass, raw_ostream &OS) { std::string TableName = InstanceClass->getName(); std::vector<Record *> Items = Records.getAllDerivedDefinitions(TableName); // Gather all the records we're going to need for this particular mapping. std::vector<std::vector<SearchTableEntry>> SearchTables; std::vector<std::string> SearchFieldNames; std::vector<std::string> FieldNames; for (const RecordVal &Field : InstanceClass->getValues()) { std::string FieldName = Field.getName(); // Skip uninteresting fields: either built-in, special to us, or injected // template parameters (if they contain a ':'). if (FieldName.find(':') != std::string::npos || FieldName == "NAME" || FieldName == "SearchableFields" || FieldName == "EnumNameField" || FieldName == "EnumValueField") continue; FieldNames.push_back(FieldName); } for (auto *Field : *InstanceClass->getValueAsListInit("SearchableFields")) { SearchTables.emplace_back(); SearchFieldNames.push_back(Field->getAsUnquotedString()); } int Idx = 0; for (Record *Item : Items) { for (unsigned i = 0; i < SearchFieldNames.size(); ++i) { Init *SearchVal = Item->getValueInit(SearchFieldNames[i]); SearchTables[i].emplace_back(SearchVal, Idx); } ++Idx; } OS << "#ifdef GET_" << StringRef(TableName).upper() << "_DECL\n"; OS << "#undef GET_" << StringRef(TableName).upper() << "_DECL\n"; // Next emit the enum containing the top-level names for use in C++ code if // requested if (!InstanceClass->isValueUnset("EnumNameField")) { emitMappingEnum(Items, InstanceClass, OS); } // And the declarations for the functions that will perform lookup. for (unsigned i = 0; i < SearchFieldNames.size(); ++i) emitLookupDeclaration(TableName, SearchFieldNames[i], SearchTables[i][0].first, OS); OS << "#endif\n\n"; OS << "#ifdef GET_" << StringRef(TableName).upper() << "_IMPL\n"; OS << "#undef GET_" << StringRef(TableName).upper() << "_IMPL\n"; // The primary data table contains all the fields defined for this map. emitPrimaryTable(TableName, FieldNames, SearchFieldNames, SearchTables, Items, OS); // Indexes are sorted "{ Thing, PrimaryIdx }" arrays, so that a binary // search can be performed by "Thing". for (unsigned i = 0; i < SearchTables.size(); ++i) { emitSearchTable(TableName, SearchFieldNames[i], SearchTables[i], OS); emitLookupFunction(TableName, SearchFieldNames[i], SearchTables[i][0].first, OS); } OS << "#endif\n"; } void SearchableTableEmitter::run(raw_ostream &OS) { // Tables are defined to be the direct descendents of "SearchableEntry". Record *SearchableTable = Records.getClass("SearchableTable"); for (auto &NameRec : Records.getClasses()) { Record *Class = NameRec.second.get(); if (Class->getSuperClasses().size() != 1 || !Class->isSubClassOf(SearchableTable)) continue; emitMapping(Class, OS); } } namespace llvm { void EmitSearchableTables(RecordKeeper &RK, raw_ostream &OS) { SearchableTableEmitter(RK).run(OS); } } // End llvm namespace. <commit_msg>TableGen: avoid string copy.<commit_after>//===- SearchableTableEmitter.cpp - Generate efficiently searchable tables -==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits a generic array initialized by specified fields, // together with companion index tables and lookup functions (binary search, // currently). // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Format.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/SourceMgr.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include <algorithm> #include <sstream> #include <string> #include <vector> using namespace llvm; #define DEBUG_TYPE "searchable-table-emitter" namespace { class SearchableTableEmitter { RecordKeeper &Records; public: SearchableTableEmitter(RecordKeeper &R) : Records(R) {} void run(raw_ostream &OS); private: typedef std::pair<Init *, int> SearchTableEntry; int getAsInt(BitsInit *B) { return cast<IntInit>(B->convertInitializerTo(IntRecTy::get()))->getValue(); } int getInt(Record *R, StringRef Field) { return getAsInt(R->getValueAsBitsInit(Field)); } std::string primaryRepresentation(Init *I) { if (StringInit *SI = dyn_cast<StringInit>(I)) return SI->getAsString(); else if (BitsInit *BI = dyn_cast<BitsInit>(I)) return "0x" + utohexstr(getAsInt(BI)); else if (BitInit *BI = dyn_cast<BitInit>(I)) return BI->getValue() ? "true" : "false"; else if (CodeInit *CI = dyn_cast<CodeInit>(I)) { return CI->getValue(); } PrintFatalError(SMLoc(), "invalid field type, expected: string, bits, bit or code"); } std::string searchRepresentation(Init *I) { std::string PrimaryRep = primaryRepresentation(I); if (!isa<StringInit>(I)) return PrimaryRep; return StringRef(PrimaryRep).upper(); } std::string searchableFieldType(Init *I) { if (isa<StringInit>(I)) return "const char *"; else if (BitsInit *BI = dyn_cast<BitsInit>(I)) { unsigned NumBits = BI->getNumBits(); if (NumBits <= 8) NumBits = 8; else if (NumBits <= 16) NumBits = 16; else if (NumBits <= 32) NumBits = 32; else if (NumBits <= 64) NumBits = 64; else PrintFatalError(SMLoc(), "bitfield too large to search"); return "uint" + utostr(NumBits) + "_t"; } PrintFatalError(SMLoc(), "Unknown type to search by"); } void emitMapping(Record *MappingDesc, raw_ostream &OS); void emitMappingEnum(std::vector<Record *> &Items, Record *InstanceClass, raw_ostream &OS); void emitPrimaryTable(StringRef Name, std::vector<std::string> &FieldNames, std::vector<std::string> &SearchFieldNames, std::vector<std::vector<SearchTableEntry>> &SearchTables, std::vector<Record *> &Items, raw_ostream &OS); void emitSearchTable(StringRef Name, StringRef Field, std::vector<SearchTableEntry> &SearchTable, raw_ostream &OS); void emitLookupDeclaration(StringRef Name, StringRef Field, Init *I, raw_ostream &OS); void emitLookupFunction(StringRef Name, StringRef Field, Init *I, raw_ostream &OS); }; } // End anonymous namespace. /// Emit an enum providing symbolic access to some preferred field from /// C++. void SearchableTableEmitter::emitMappingEnum(std::vector<Record *> &Items, Record *InstanceClass, raw_ostream &OS) { std::string EnumNameField = InstanceClass->getValueAsString("EnumNameField"); std::string EnumValueField; if (!InstanceClass->isValueUnset("EnumValueField")) EnumValueField = InstanceClass->getValueAsString("EnumValueField"); OS << "enum " << InstanceClass->getName() << "Values {\n"; for (auto Item : Items) { OS << " " << Item->getValueAsString(EnumNameField); if (EnumValueField != StringRef()) OS << " = " << getInt(Item, EnumValueField); OS << ",\n"; } OS << "};\n\n"; } void SearchableTableEmitter::emitPrimaryTable( StringRef Name, std::vector<std::string> &FieldNames, std::vector<std::string> &SearchFieldNames, std::vector<std::vector<SearchTableEntry>> &SearchTables, std::vector<Record *> &Items, raw_ostream &OS) { OS << "const " << Name << " " << Name << "sList[] = {\n"; for (auto Item : Items) { OS << " { "; for (unsigned i = 0; i < FieldNames.size(); ++i) { OS << primaryRepresentation(Item->getValueInit(FieldNames[i])); if (i != FieldNames.size() - 1) OS << ", "; } OS << "},\n"; } OS << "};\n\n"; } void SearchableTableEmitter::emitSearchTable( StringRef Name, StringRef Field, std::vector<SearchTableEntry> &SearchTable, raw_ostream &OS) { OS << "const std::pair<" << searchableFieldType(SearchTable[0].first) << ", int> " << Name << "sBy" << Field << "[] = {\n"; if (isa<BitsInit>(SearchTable[0].first)) { std::stable_sort(SearchTable.begin(), SearchTable.end(), [this](const SearchTableEntry &LHS, const SearchTableEntry &RHS) { return getAsInt(cast<BitsInit>(LHS.first)) < getAsInt(cast<BitsInit>(RHS.first)); }); } else { std::stable_sort(SearchTable.begin(), SearchTable.end(), [this](const SearchTableEntry &LHS, const SearchTableEntry &RHS) { return searchRepresentation(LHS.first) < searchRepresentation(RHS.first); }); } for (auto Entry : SearchTable) { OS << " { " << searchRepresentation(Entry.first) << ", " << Entry.second << " },\n"; } OS << "};\n\n"; } void SearchableTableEmitter::emitLookupFunction(StringRef Name, StringRef Field, Init *I, raw_ostream &OS) { bool IsIntegral = isa<BitsInit>(I); std::string FieldType = searchableFieldType(I); std::string PairType = "std::pair<" + FieldType + ", int>"; // const SysRegs *lookupSysRegByName(const char *Name) { OS << "const " << Name << " *" << "lookup" << Name << "By" << Field; OS << "(" << (IsIntegral ? FieldType : "StringRef") << " " << Field << ") {\n"; if (IsIntegral) { OS << " auto CanonicalVal = " << Field << ";\n"; OS << " " << PairType << " Val = {CanonicalVal, 0};\n"; } else { // Make sure the result is null terminated because it's going via "char *". OS << " std::string CanonicalVal = " << Field << ".upper();\n"; OS << " " << PairType << " Val = {CanonicalVal.data(), 0};\n"; } OS << " ArrayRef<" << PairType << "> Table(" << Name << "sBy" << Field << ");\n"; OS << " auto Idx = std::lower_bound(Table.begin(), Table.end(), Val"; if (IsIntegral) OS << ");\n"; else { OS << ",\n "; OS << "[](const " << PairType << " &LHS, const " << PairType << " &RHS) {\n"; OS << " return StringRef(LHS.first) < StringRef(RHS.first);\n"; OS << " });\n\n"; } OS << " if (Idx == Table.end() || CanonicalVal != Idx->first)\n"; OS << " return nullptr;\n"; OS << " return &" << Name << "sList[Idx->second];\n"; OS << "}\n\n"; } void SearchableTableEmitter::emitLookupDeclaration(StringRef Name, StringRef Field, Init *I, raw_ostream &OS) { bool IsIntegral = isa<BitsInit>(I); std::string FieldType = searchableFieldType(I); OS << "const " << Name << " *" << "lookup" << Name << "By" << Field; OS << "(" << (IsIntegral ? FieldType : "StringRef") << " " << Field << ");\n\n"; } void SearchableTableEmitter::emitMapping(Record *InstanceClass, raw_ostream &OS) { const std::string &TableName = InstanceClass->getName(); std::vector<Record *> Items = Records.getAllDerivedDefinitions(TableName); // Gather all the records we're going to need for this particular mapping. std::vector<std::vector<SearchTableEntry>> SearchTables; std::vector<std::string> SearchFieldNames; std::vector<std::string> FieldNames; for (const RecordVal &Field : InstanceClass->getValues()) { std::string FieldName = Field.getName(); // Skip uninteresting fields: either built-in, special to us, or injected // template parameters (if they contain a ':'). if (FieldName.find(':') != std::string::npos || FieldName == "NAME" || FieldName == "SearchableFields" || FieldName == "EnumNameField" || FieldName == "EnumValueField") continue; FieldNames.push_back(FieldName); } for (auto *Field : *InstanceClass->getValueAsListInit("SearchableFields")) { SearchTables.emplace_back(); SearchFieldNames.push_back(Field->getAsUnquotedString()); } int Idx = 0; for (Record *Item : Items) { for (unsigned i = 0; i < SearchFieldNames.size(); ++i) { Init *SearchVal = Item->getValueInit(SearchFieldNames[i]); SearchTables[i].emplace_back(SearchVal, Idx); } ++Idx; } OS << "#ifdef GET_" << StringRef(TableName).upper() << "_DECL\n"; OS << "#undef GET_" << StringRef(TableName).upper() << "_DECL\n"; // Next emit the enum containing the top-level names for use in C++ code if // requested if (!InstanceClass->isValueUnset("EnumNameField")) { emitMappingEnum(Items, InstanceClass, OS); } // And the declarations for the functions that will perform lookup. for (unsigned i = 0; i < SearchFieldNames.size(); ++i) emitLookupDeclaration(TableName, SearchFieldNames[i], SearchTables[i][0].first, OS); OS << "#endif\n\n"; OS << "#ifdef GET_" << StringRef(TableName).upper() << "_IMPL\n"; OS << "#undef GET_" << StringRef(TableName).upper() << "_IMPL\n"; // The primary data table contains all the fields defined for this map. emitPrimaryTable(TableName, FieldNames, SearchFieldNames, SearchTables, Items, OS); // Indexes are sorted "{ Thing, PrimaryIdx }" arrays, so that a binary // search can be performed by "Thing". for (unsigned i = 0; i < SearchTables.size(); ++i) { emitSearchTable(TableName, SearchFieldNames[i], SearchTables[i], OS); emitLookupFunction(TableName, SearchFieldNames[i], SearchTables[i][0].first, OS); } OS << "#endif\n"; } void SearchableTableEmitter::run(raw_ostream &OS) { // Tables are defined to be the direct descendents of "SearchableEntry". Record *SearchableTable = Records.getClass("SearchableTable"); for (auto &NameRec : Records.getClasses()) { Record *Class = NameRec.second.get(); if (Class->getSuperClasses().size() != 1 || !Class->isSubClassOf(SearchableTable)) continue; emitMapping(Class, OS); } } namespace llvm { void EmitSearchableTables(RecordKeeper &RK, raw_ostream &OS) { SearchableTableEmitter(RK).run(OS); } } // End llvm namespace. <|endoftext|>
<commit_before>#include "../../h/stdafx.h" #include "TextInput.h" #include "../..//Win32/Win32Window.h" #include "../../h/Win32Callbacks.h" #include <Commctrl.h> using std::wstring; using std::wstring_view; namespace Onyx32::Gui::Controls { const std::wstring TextInput::Class = L"EDIT"; const int TextInput::Styles = WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL; ITextInput* TextInput::Create(IWindow* parent, uint64_t controlId, std::wstring_view text, unsigned int width, unsigned int height, unsigned int xPos, unsigned int yPos) { auto control = new TextInput(text, width, height, xPos, yPos, controlId); Win32ChildWindowCreationArgs args( 0, TextInput::Class, text, TextInput::Styles, xPos, yPos, width, height, parent->GetHwnd(), (HMENU)controlId, control, DefCtrlProc ); ; if (control->_wndHandle = CreateChildWindow(args)) { control->_state = ControlState::Initialized; control->_isVisible = true; return control; } delete control; return nullptr; } TextInput::TextInput( std::wstring_view text, const UINT width, const UINT height, const UINT xPos, const UINT yPos, const uint64_t controlId) : BaseControl(controlId, ControlState::Uninitialized, width, height, xPos, yPos, nullptr, nullptr), _text(text) { } TextInput::~TextInput() { } void TextInput::Initialize() { } const wstring TextInput::GetText() { //WCHAR* ptr = new WCHAR[100]; //GetWindowText( // hwndEdit, // ptr, // 100); return _text; } void TextInput::SetText(wstring_view str) { _text = str; SetWindowText(_wndHandle, _text.c_str()); } LRESULT TextInput::Process(unsigned int message, WPARAM wParam, LPARAM lParam) { switch (message) { default: return DefSubclassProc(_wndHandle, message, wParam, lParam); } return DefSubclassProc(_wndHandle, message, wParam, lParam); } }<commit_msg>Minor changes<commit_after>#include "../../h/stdafx.h" #include "TextInput.h" #include "../..//Win32/Win32Window.h" #include "../../h/Win32Callbacks.h" #include <Commctrl.h> using std::wstring; using std::wstring_view; namespace Onyx32::Gui::Controls { const std::wstring TextInput::Class = L"EDIT"; const int TextInput::Styles = WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL; ITextInput* TextInput::Create(IWindow* parent, uint64_t controlId, std::wstring_view text, unsigned int width, unsigned int height, unsigned int xPos, unsigned int yPos) { auto control = new TextInput(text, width, height, xPos, yPos, controlId); Win32ChildWindowCreationArgs args( 0, TextInput::Class, text, TextInput::Styles, xPos, yPos, width, height, parent->GetHwnd(), (HMENU)controlId, control, DefCtrlProc ); ; if (control->_wndHandle = CreateChildWindow(args)) { control->_state = ControlState::Initialized; control->_isVisible = true; return control; } delete control; return nullptr; } TextInput::TextInput( std::wstring_view text, const unsigned int width, const unsigned int height, const unsigned int xPos, const unsigned int yPos, const uint64_t controlId) : BaseControl(controlId, ControlState::Uninitialized, width, height, xPos, yPos, nullptr, nullptr), _text(text) { } TextInput::~TextInput() { } void TextInput::Initialize() { } const wstring TextInput::GetText() { //WCHAR* ptr = new WCHAR[100]; //GetWindowText( // hwndEdit, // ptr, // 100); return _text; } void TextInput::SetText(wstring_view str) { _text = str; SetWindowText(_wndHandle, _text.c_str()); } LRESULT TextInput::Process(unsigned int message, WPARAM wParam, LPARAM lParam) { switch (message) { default: return DefSubclassProc(_wndHandle, message, wParam, lParam); } return DefSubclassProc(_wndHandle, message, wParam, lParam); } }<|endoftext|>
<commit_before>/* <x0/FileInfoService.cpp> * * This file is part of the x0 web server project and is released under LGPL-3. * http://www.xzero.ws/ * * (c) 2009-2010 Christian Parpart <[email protected]> */ #include <x0/io/FileInfoService.h> #include <x0/strutils.h> #include <x0/sysconfig.h> #include <boost/tokenizer.hpp> #if defined(HAVE_SYS_INOTIFY_H) #undef HAVE_SYS_INOTIFY_H #endif namespace x0 { FileInfoService::FileInfoService(struct ::ev_loop *loop, const Config *config) : loop_(loop), #if defined(HAVE_SYS_INOTIFY_H) handle_(-1), inotify_(loop_), inotifies_(), #endif config_(config), cache_() { #if defined(HAVE_SYS_INOTIFY_H) handle_ = inotify_init(); if (handle_ != -1) { if (fcntl(handle_, F_SETFL, fcntl(handle_, F_GETFL) | O_NONBLOCK) < 0) fprintf(stderr, "Error setting nonblock/cloexec flags on inotify handle\n"); if (fcntl(handle_, F_SETFD, fcntl(handle_, F_GETFD) | FD_CLOEXEC) < 0) fprintf(stderr, "Error setting cloexec flags on inotify handle\n"); inotify_.set<FileInfoService, &FileInfoService::onFileChanged>(this); inotify_.start(handle_, ev::READ); } else { fprintf(stderr, "Error initializing inotify: %s\n", strerror(errno)); } #endif } FileInfoService::~FileInfoService() { #if defined(HAVE_SYS_INOTIFY_H) if (handle_ != -1) { ::close(handle_); } #endif } FileInfoPtr FileInfoService::query(const std::string& _filename) { std::string filename(_filename[_filename.size() - 1] == '/' ? _filename.substr(0, _filename.size() - 1) : _filename); auto i = cache_.find(filename); if (i != cache_.end()) { FileInfoPtr fi = i->second; if (fi->inotifyId_ > 0 || fi->cachedAt() + config_->cacheTTL_ > ev_now(loop_)) { FILEINFO_DEBUG("query.cached(%s)\n", filename.c_str()); return fi; } FILEINFO_DEBUG("query.expired(%s)\n", filename.c_str()); #if defined(HAVE_SYS_INOTIFY_H) inotifies_.erase(inotifies_.find(fi->inotifyId_)); #endif cache_.erase(i); } if (FileInfoPtr fi = FileInfoPtr(new FileInfo(*this, filename))) { fi->mimetype_ = get_mimetype(filename); fi->etag_ = make_etag(*fi); #if defined(HAVE_SYS_INOTIFY_H) int rv = handle_ != -1 && ::inotify_add_watch(handle_, filename.c_str(), /*IN_ONESHOT |*/ IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_UNMOUNT | IN_DELETE_SELF | IN_MOVE_SELF ); FILEINFO_DEBUG("query(%s).new -> %d\n", filename.c_str(), rv); if (rv != -1) { fi->inotifyId_ = rv; inotifies_[rv] = fi; } cache_[filename] = fi; #else FILEINFO_DEBUG("query(%s)!\n", filename.c_str()); cache_[filename] = fi; #endif return fi; } FILEINFO_DEBUG("query(%s) failed (%s)\n", filename.c_str(), strerror(errno)); // either ::stat() or caching failed. return FileInfoPtr(); } #if defined(HAVE_SYS_INOTIFY_H) void FileInfoService::onFileChanged(ev::io& w, int revents) { FILEINFO_DEBUG("onFileChanged()\n"); char buf[sizeof(inotify_event) * 256]; ssize_t rv = ::read(handle_, &buf, sizeof(buf)); FILEINFO_DEBUG("read returned: %ld (%% %ld, %ld)\n", rv, sizeof(inotify_event), rv / sizeof(inotify_event)); if (rv > 0) { const char *i = buf; const char *e = i + rv; inotify_event *ev = (inotify_event *)i; for (; i < e && ev->wd != 0; i += sizeof(*ev) + ev->len, ev = (inotify_event *)i) { FILEINFO_DEBUG("traverse: (wd:%d, mask:0x%04x, cookie:%d)\n", ev->wd, ev->mask, ev->cookie); auto wi = inotifies_.find(ev->wd); if (wi == inotifies_.end()) { FILEINFO_DEBUG("-skipping\n"); continue; } auto k = cache_.find(wi->second->filename()); FILEINFO_DEBUG("invalidate: %s\n", k->first.c_str()); // onInvalidate(k->first, k->second); cache_.erase(k); inotifies_.erase(wi); int rv = inotify_rm_watch(handle_, ev->wd); if (rv < 0) { FILEINFO_DEBUG("error removing inotify watch (%d, %s): %s\n", ev->wd, ev->name, strerror(errno)); } else { FILEINFO_DEBUG("inotify_rm_watch: %d (ok)\n", rv); } } } } #endif void FileInfoService::Config::loadMimetypes(const std::string& filename) { typedef boost::tokenizer<boost::char_separator<char> > tokenizer; std::string input(x0::read_file(filename)); tokenizer lines(input, boost::char_separator<char>("\n")); mimetypes.clear(); for (auto line: lines) { line = x0::trim(line); tokenizer columns(line, boost::char_separator<char>(" \t")); tokenizer::iterator ci = columns.begin(), ce = columns.end(); std::string mime = ci != ce ? *ci++ : std::string(); if (!mime.empty() && mime[0] != '#') { for (; ci != ce; ++ci) { mimetypes[*ci] = mime; } } } } std::string FileInfoService::get_mimetype(const std::string& filename) const { std::size_t ndot = filename.find_last_of("."); std::size_t nslash = filename.find_last_of("/"); if (ndot != std::string::npos && ndot > nslash) { std::string ext(filename.substr(ndot + 1)); while (ext.size()) { auto i = config_->mimetypes.find(ext); if (i != config_->mimetypes.end()) { //DEBUG("filename(%s), ext(%s), use mimetype: %s", filename.c_str(), ext.c_str(), i->second.c_str()); return i->second; } if (ext[ext.size() - 1] != '~') break; ext.resize(ext.size() - 1); } } //DEBUG("file(%s) use default mimetype", filename.c_str()); return config_->defaultMimetype; } } // namespace x0 <commit_msg>FileInfoService: re-enable inotify-support<commit_after>/* <x0/FileInfoService.cpp> * * This file is part of the x0 web server project and is released under LGPL-3. * http://www.xzero.ws/ * * (c) 2009-2010 Christian Parpart <[email protected]> */ #include <x0/io/FileInfoService.h> #include <x0/strutils.h> #include <x0/sysconfig.h> #include <boost/tokenizer.hpp> namespace x0 { FileInfoService::FileInfoService(struct ::ev_loop *loop, const Config *config) : loop_(loop), #if defined(HAVE_SYS_INOTIFY_H) handle_(-1), inotify_(loop_), inotifies_(), #endif config_(config), cache_() { #if defined(HAVE_SYS_INOTIFY_H) handle_ = inotify_init(); if (handle_ != -1) { if (fcntl(handle_, F_SETFL, fcntl(handle_, F_GETFL) | O_NONBLOCK) < 0) fprintf(stderr, "Error setting nonblock/cloexec flags on inotify handle\n"); if (fcntl(handle_, F_SETFD, fcntl(handle_, F_GETFD) | FD_CLOEXEC) < 0) fprintf(stderr, "Error setting cloexec flags on inotify handle\n"); inotify_.set<FileInfoService, &FileInfoService::onFileChanged>(this); inotify_.start(handle_, ev::READ); } else { fprintf(stderr, "Error initializing inotify: %s\n", strerror(errno)); } #endif } FileInfoService::~FileInfoService() { #if defined(HAVE_SYS_INOTIFY_H) if (handle_ != -1) { ::close(handle_); } #endif } FileInfoPtr FileInfoService::query(const std::string& _filename) { std::string filename(_filename[_filename.size() - 1] == '/' ? _filename.substr(0, _filename.size() - 1) : _filename); auto i = cache_.find(filename); if (i != cache_.end()) { FileInfoPtr fi = i->second; if (fi->inotifyId_ > 0 || fi->cachedAt() + config_->cacheTTL_ > ev_now(loop_)) { FILEINFO_DEBUG("query.cached(%s)\n", filename.c_str()); return fi; } FILEINFO_DEBUG("query.expired(%s)\n", filename.c_str()); #if defined(HAVE_SYS_INOTIFY_H) inotifies_.erase(inotifies_.find(fi->inotifyId_)); #endif cache_.erase(i); } if (FileInfoPtr fi = FileInfoPtr(new FileInfo(*this, filename))) { fi->mimetype_ = get_mimetype(filename); fi->etag_ = make_etag(*fi); #if defined(HAVE_SYS_INOTIFY_H) int rv = handle_ != -1 && ::inotify_add_watch(handle_, filename.c_str(), /*IN_ONESHOT |*/ IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_UNMOUNT | IN_DELETE_SELF | IN_MOVE_SELF ); FILEINFO_DEBUG("query(%s).new -> %d\n", filename.c_str(), rv); if (rv != -1) { fi->inotifyId_ = rv; inotifies_[rv] = fi; } cache_[filename] = fi; #else FILEINFO_DEBUG("query(%s)!\n", filename.c_str()); cache_[filename] = fi; #endif return fi; } FILEINFO_DEBUG("query(%s) failed (%s)\n", filename.c_str(), strerror(errno)); // either ::stat() or caching failed. return FileInfoPtr(); } #if defined(HAVE_SYS_INOTIFY_H) void FileInfoService::onFileChanged(ev::io& w, int revents) { FILEINFO_DEBUG("onFileChanged()\n"); char buf[sizeof(inotify_event) * 256]; ssize_t rv = ::read(handle_, &buf, sizeof(buf)); FILEINFO_DEBUG("read returned: %ld (%% %ld, %ld)\n", rv, sizeof(inotify_event), rv / sizeof(inotify_event)); if (rv > 0) { const char *i = buf; const char *e = i + rv; inotify_event *ev = (inotify_event *)i; for (; i < e && ev->wd != 0; i += sizeof(*ev) + ev->len, ev = (inotify_event *)i) { FILEINFO_DEBUG("traverse: (wd:%d, mask:0x%04x, cookie:%d)\n", ev->wd, ev->mask, ev->cookie); auto wi = inotifies_.find(ev->wd); if (wi == inotifies_.end()) { FILEINFO_DEBUG("-skipping\n"); continue; } auto k = cache_.find(wi->second->filename()); FILEINFO_DEBUG("invalidate: %s\n", k->first.c_str()); // onInvalidate(k->first, k->second); cache_.erase(k); inotifies_.erase(wi); int rv = inotify_rm_watch(handle_, ev->wd); if (rv < 0) { FILEINFO_DEBUG("error removing inotify watch (%d, %s): %s\n", ev->wd, ev->name, strerror(errno)); } else { FILEINFO_DEBUG("inotify_rm_watch: %d (ok)\n", rv); } } } } #endif void FileInfoService::Config::loadMimetypes(const std::string& filename) { typedef boost::tokenizer<boost::char_separator<char> > tokenizer; std::string input(x0::read_file(filename)); tokenizer lines(input, boost::char_separator<char>("\n")); mimetypes.clear(); for (auto line: lines) { line = x0::trim(line); tokenizer columns(line, boost::char_separator<char>(" \t")); tokenizer::iterator ci = columns.begin(), ce = columns.end(); std::string mime = ci != ce ? *ci++ : std::string(); if (!mime.empty() && mime[0] != '#') { for (; ci != ce; ++ci) { mimetypes[*ci] = mime; } } } } std::string FileInfoService::get_mimetype(const std::string& filename) const { std::size_t ndot = filename.find_last_of("."); std::size_t nslash = filename.find_last_of("/"); if (ndot != std::string::npos && ndot > nslash) { std::string ext(filename.substr(ndot + 1)); while (ext.size()) { auto i = config_->mimetypes.find(ext); if (i != config_->mimetypes.end()) { //DEBUG("filename(%s), ext(%s), use mimetype: %s", filename.c_str(), ext.c_str(), i->second.c_str()); return i->second; } if (ext[ext.size() - 1] != '~') break; ext.resize(ext.size() - 1); } } //DEBUG("file(%s) use default mimetype", filename.c_str()); return config_->defaultMimetype; } } // namespace x0 <|endoftext|>
<commit_before>//===- unittests/libclang/LibclangTest.cpp --- libclang tests -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang-c/Index.h" #include "gtest/gtest.h" TEST(libclang, clang_parseTranslationUnit2_InvalidArgs) { EXPECT_EQ(CXError_InvalidArguments, clang_parseTranslationUnit2(nullptr, nullptr, nullptr, 0, nullptr, 0, 0, nullptr)); } TEST(libclang, clang_createTranslationUnit_InvalidArgs) { EXPECT_EQ(nullptr, clang_createTranslationUnit(nullptr, nullptr)); } TEST(libclang, clang_createTranslationUnit2_InvalidArgs) { EXPECT_EQ(CXError_InvalidArguments, clang_createTranslationUnit2(nullptr, nullptr, nullptr)); CXTranslationUnit TU = reinterpret_cast<CXTranslationUnit>(1); EXPECT_EQ(CXError_InvalidArguments, clang_createTranslationUnit2(nullptr, nullptr, &TU)); EXPECT_EQ(nullptr, TU); } namespace { struct TestVFO { const char *Contents; CXVirtualFileOverlay VFO; TestVFO(const char *Contents) : Contents(Contents) { VFO = clang_VirtualFileOverlay_create(0); } void map(const char *VPath, const char *RPath) { CXErrorCode Err = clang_VirtualFileOverlay_addFileMapping(VFO, VPath, RPath); EXPECT_EQ(Err, CXError_Success); } void mapError(const char *VPath, const char *RPath, CXErrorCode ExpErr) { CXErrorCode Err = clang_VirtualFileOverlay_addFileMapping(VFO, VPath, RPath); EXPECT_EQ(Err, ExpErr); } ~TestVFO() { if (Contents) { char *BufPtr; unsigned BufSize; clang_VirtualFileOverlay_writeToBuffer(VFO, 0, &BufPtr, &BufSize); std::string BufStr(BufPtr, BufSize); EXPECT_STREQ(Contents, BufStr.c_str()); free(BufPtr); } clang_VirtualFileOverlay_dispose(VFO); } }; } TEST(libclang, VirtualFileOverlay_Basic) { const char *contents = "{\n" " 'version': 0,\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/virtual\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo.h\",\n" " 'external-contents': \"/real/foo.h\"\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/path/virtual/foo.h", "/real/foo.h"); } TEST(libclang, VirtualFileOverlay_Unicode) { const char *contents = "{\n" " 'version': 0,\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/\\u266B\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"\\u2602.h\",\n" " 'external-contents': \"/real/\\u2602.h\"\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/path/♫/☂.h", "/real/☂.h"); } TEST(libclang, VirtualFileOverlay_InvalidArgs) { TestVFO T(nullptr); T.mapError("/path/./virtual/../foo.h", "/real/foo.h", CXError_InvalidArguments); } TEST(libclang, VirtualFileOverlay_RemapDirectories) { const char *contents = "{\n" " 'version': 0,\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/another/dir\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo2.h\",\n" " 'external-contents': \"/real/foo2.h\"\n" " }\n" " ]\n" " },\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/virtual/dir\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo1.h\",\n" " 'external-contents': \"/real/foo1.h\"\n" " },\n" " {\n" " 'type': 'file',\n" " 'name': \"foo3.h\",\n" " 'external-contents': \"/real/foo3.h\"\n" " },\n" " {\n" " 'type': 'directory',\n" " 'name': \"in/subdir\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo4.h\",\n" " 'external-contents': \"/real/foo4.h\"\n" " }\n" " ]\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/path/virtual/dir/foo1.h", "/real/foo1.h"); T.map("/another/dir/foo2.h", "/real/foo2.h"); T.map("/path/virtual/dir/foo3.h", "/real/foo3.h"); T.map("/path/virtual/dir/in/subdir/foo4.h", "/real/foo4.h"); } TEST(libclang, VirtualFileOverlay_CaseInsensitive) { const char *contents = "{\n" " 'version': 0,\n" " 'case-sensitive': 'false',\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/virtual\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo.h\",\n" " 'external-contents': \"/real/foo.h\"\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/path/virtual/foo.h", "/real/foo.h"); clang_VirtualFileOverlay_setCaseSensitivity(T.VFO, false); } TEST(libclang, VirtualFileOverlay_SharedPrefix) { const char *contents = "{\n" " 'version': 0,\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/foo\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"bar\",\n" " 'external-contents': \"/real/bar\"\n" " },\n" " {\n" " 'type': 'file',\n" " 'name': \"bar.h\",\n" " 'external-contents': \"/real/bar.h\"\n" " }\n" " ]\n" " },\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/foobar\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"baz.h\",\n" " 'external-contents': \"/real/baz.h\"\n" " }\n" " ]\n" " },\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foobarbaz.h\",\n" " 'external-contents': \"/real/foobarbaz.h\"\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/path/foo/bar.h", "/real/bar.h"); T.map("/path/foo/bar", "/real/bar"); T.map("/path/foobar/baz.h", "/real/baz.h"); T.map("/path/foobarbaz.h", "/real/foobarbaz.h"); } TEST(libclang, VirtualFileOverlay_AdjacentDirectory) { const char *contents = "{\n" " 'version': 0,\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/dir1\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo.h\",\n" " 'external-contents': \"/real/foo.h\"\n" " },\n" " {\n" " 'type': 'directory',\n" " 'name': \"subdir\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"bar.h\",\n" " 'external-contents': \"/real/bar.h\"\n" " }\n" " ]\n" " }\n" " ]\n" " },\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/dir2\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"baz.h\",\n" " 'external-contents': \"/real/baz.h\"\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/path/dir1/foo.h", "/real/foo.h"); T.map("/path/dir1/subdir/bar.h", "/real/bar.h"); T.map("/path/dir2/baz.h", "/real/baz.h"); } TEST(libclang, VirtualFileOverlay_TopLevel) { const char *contents = "{\n" " 'version': 0,\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo.h\",\n" " 'external-contents': \"/real/foo.h\"\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/foo.h", "/real/foo.h"); } TEST(libclang, ModuleMapDescriptor) { const char *Contents = "framework module TestFrame {\n" " umbrella header \"TestFrame.h\"\n" "\n" " export *\n" " module * { export * }\n" "}\n"; CXModuleMapDescriptor MMD = clang_ModuleMapDescriptor_create(0); clang_ModuleMapDescriptor_setFrameworkModuleName(MMD, "TestFrame"); clang_ModuleMapDescriptor_setUmbrellaHeader(MMD, "TestFrame.h"); char *BufPtr; unsigned BufSize; clang_ModuleMapDescriptor_writeToBuffer(MMD, 0, &BufPtr, &BufSize); std::string BufStr(BufPtr, BufSize); EXPECT_STREQ(Contents, BufStr.c_str()); free(BufPtr); clang_ModuleMapDescriptor_dispose(MMD); } <commit_msg>Add reparse test for libclang<commit_after>//===- unittests/libclang/LibclangTest.cpp --- libclang tests -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang-c/Index.h" #include "gtest/gtest.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <fstream> #include <set> #define DEBUG_TYPE "libclang-test" TEST(libclang, clang_parseTranslationUnit2_InvalidArgs) { EXPECT_EQ(CXError_InvalidArguments, clang_parseTranslationUnit2(nullptr, nullptr, nullptr, 0, nullptr, 0, 0, nullptr)); } TEST(libclang, clang_createTranslationUnit_InvalidArgs) { EXPECT_EQ(nullptr, clang_createTranslationUnit(nullptr, nullptr)); } TEST(libclang, clang_createTranslationUnit2_InvalidArgs) { EXPECT_EQ(CXError_InvalidArguments, clang_createTranslationUnit2(nullptr, nullptr, nullptr)); CXTranslationUnit TU = reinterpret_cast<CXTranslationUnit>(1); EXPECT_EQ(CXError_InvalidArguments, clang_createTranslationUnit2(nullptr, nullptr, &TU)); EXPECT_EQ(nullptr, TU); } namespace { struct TestVFO { const char *Contents; CXVirtualFileOverlay VFO; TestVFO(const char *Contents) : Contents(Contents) { VFO = clang_VirtualFileOverlay_create(0); } void map(const char *VPath, const char *RPath) { CXErrorCode Err = clang_VirtualFileOverlay_addFileMapping(VFO, VPath, RPath); EXPECT_EQ(Err, CXError_Success); } void mapError(const char *VPath, const char *RPath, CXErrorCode ExpErr) { CXErrorCode Err = clang_VirtualFileOverlay_addFileMapping(VFO, VPath, RPath); EXPECT_EQ(Err, ExpErr); } ~TestVFO() { if (Contents) { char *BufPtr; unsigned BufSize; clang_VirtualFileOverlay_writeToBuffer(VFO, 0, &BufPtr, &BufSize); std::string BufStr(BufPtr, BufSize); EXPECT_STREQ(Contents, BufStr.c_str()); free(BufPtr); } clang_VirtualFileOverlay_dispose(VFO); } }; } TEST(libclang, VirtualFileOverlay_Basic) { const char *contents = "{\n" " 'version': 0,\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/virtual\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo.h\",\n" " 'external-contents': \"/real/foo.h\"\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/path/virtual/foo.h", "/real/foo.h"); } TEST(libclang, VirtualFileOverlay_Unicode) { const char *contents = "{\n" " 'version': 0,\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/\\u266B\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"\\u2602.h\",\n" " 'external-contents': \"/real/\\u2602.h\"\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/path/♫/☂.h", "/real/☂.h"); } TEST(libclang, VirtualFileOverlay_InvalidArgs) { TestVFO T(nullptr); T.mapError("/path/./virtual/../foo.h", "/real/foo.h", CXError_InvalidArguments); } TEST(libclang, VirtualFileOverlay_RemapDirectories) { const char *contents = "{\n" " 'version': 0,\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/another/dir\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo2.h\",\n" " 'external-contents': \"/real/foo2.h\"\n" " }\n" " ]\n" " },\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/virtual/dir\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo1.h\",\n" " 'external-contents': \"/real/foo1.h\"\n" " },\n" " {\n" " 'type': 'file',\n" " 'name': \"foo3.h\",\n" " 'external-contents': \"/real/foo3.h\"\n" " },\n" " {\n" " 'type': 'directory',\n" " 'name': \"in/subdir\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo4.h\",\n" " 'external-contents': \"/real/foo4.h\"\n" " }\n" " ]\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/path/virtual/dir/foo1.h", "/real/foo1.h"); T.map("/another/dir/foo2.h", "/real/foo2.h"); T.map("/path/virtual/dir/foo3.h", "/real/foo3.h"); T.map("/path/virtual/dir/in/subdir/foo4.h", "/real/foo4.h"); } TEST(libclang, VirtualFileOverlay_CaseInsensitive) { const char *contents = "{\n" " 'version': 0,\n" " 'case-sensitive': 'false',\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/virtual\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo.h\",\n" " 'external-contents': \"/real/foo.h\"\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/path/virtual/foo.h", "/real/foo.h"); clang_VirtualFileOverlay_setCaseSensitivity(T.VFO, false); } TEST(libclang, VirtualFileOverlay_SharedPrefix) { const char *contents = "{\n" " 'version': 0,\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/foo\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"bar\",\n" " 'external-contents': \"/real/bar\"\n" " },\n" " {\n" " 'type': 'file',\n" " 'name': \"bar.h\",\n" " 'external-contents': \"/real/bar.h\"\n" " }\n" " ]\n" " },\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/foobar\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"baz.h\",\n" " 'external-contents': \"/real/baz.h\"\n" " }\n" " ]\n" " },\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foobarbaz.h\",\n" " 'external-contents': \"/real/foobarbaz.h\"\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/path/foo/bar.h", "/real/bar.h"); T.map("/path/foo/bar", "/real/bar"); T.map("/path/foobar/baz.h", "/real/baz.h"); T.map("/path/foobarbaz.h", "/real/foobarbaz.h"); } TEST(libclang, VirtualFileOverlay_AdjacentDirectory) { const char *contents = "{\n" " 'version': 0,\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/dir1\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo.h\",\n" " 'external-contents': \"/real/foo.h\"\n" " },\n" " {\n" " 'type': 'directory',\n" " 'name': \"subdir\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"bar.h\",\n" " 'external-contents': \"/real/bar.h\"\n" " }\n" " ]\n" " }\n" " ]\n" " },\n" " {\n" " 'type': 'directory',\n" " 'name': \"/path/dir2\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"baz.h\",\n" " 'external-contents': \"/real/baz.h\"\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/path/dir1/foo.h", "/real/foo.h"); T.map("/path/dir1/subdir/bar.h", "/real/bar.h"); T.map("/path/dir2/baz.h", "/real/baz.h"); } TEST(libclang, VirtualFileOverlay_TopLevel) { const char *contents = "{\n" " 'version': 0,\n" " 'roots': [\n" " {\n" " 'type': 'directory',\n" " 'name': \"/\",\n" " 'contents': [\n" " {\n" " 'type': 'file',\n" " 'name': \"foo.h\",\n" " 'external-contents': \"/real/foo.h\"\n" " }\n" " ]\n" " }\n" " ]\n" "}\n"; TestVFO T(contents); T.map("/foo.h", "/real/foo.h"); } TEST(libclang, ModuleMapDescriptor) { const char *Contents = "framework module TestFrame {\n" " umbrella header \"TestFrame.h\"\n" "\n" " export *\n" " module * { export * }\n" "}\n"; CXModuleMapDescriptor MMD = clang_ModuleMapDescriptor_create(0); clang_ModuleMapDescriptor_setFrameworkModuleName(MMD, "TestFrame"); clang_ModuleMapDescriptor_setUmbrellaHeader(MMD, "TestFrame.h"); char *BufPtr; unsigned BufSize; clang_ModuleMapDescriptor_writeToBuffer(MMD, 0, &BufPtr, &BufSize); std::string BufStr(BufPtr, BufSize); EXPECT_STREQ(Contents, BufStr.c_str()); free(BufPtr); clang_ModuleMapDescriptor_dispose(MMD); } class LibclangReparseTest : public ::testing::Test { std::string TestDir; std::set<std::string> Files; public: CXIndex Index; CXTranslationUnit ClangTU; unsigned TUFlags; void SetUp() { llvm::SmallString<256> Dir; ASSERT_FALSE(llvm::sys::fs::createUniqueDirectory("libclang-test", Dir)); TestDir = Dir.str(); TUFlags = CXTranslationUnit_DetailedPreprocessingRecord | clang_defaultEditingTranslationUnitOptions(); Index = clang_createIndex(0, 0); } void TearDown() { clang_disposeTranslationUnit(ClangTU); clang_disposeIndex(Index); for (const std::string &Path : Files) llvm::sys::fs::remove(Path); llvm::sys::fs::remove(TestDir); } void WriteFile(std::string &Filename, const std::string &Contents) { if (!llvm::sys::path::is_absolute(Filename)) { llvm::SmallString<256> Path(TestDir); llvm::sys::path::append(Path, Filename); Filename = Path.str(); Files.insert(Filename); } std::ofstream OS(Filename); OS << Contents; } void DisplayDiagnostics() { uint NumDiagnostics = clang_getNumDiagnostics(ClangTU); for (uint i = 0; i < NumDiagnostics; ++i) { auto Diag = clang_getDiagnostic(ClangTU, i); DEBUG(llvm::dbgs() << clang_getCString(clang_formatDiagnostic( Diag, clang_defaultDiagnosticDisplayOptions())) << "\n"); clang_disposeDiagnostic(Diag); } } bool ReparseTU(uint num_unsaved_files, CXUnsavedFile* unsaved_files) { if (clang_reparseTranslationUnit(ClangTU, num_unsaved_files, unsaved_files, clang_defaultReparseOptions(ClangTU))) { DEBUG(llvm::dbgs() << "Reparse failed\n"); return false; } DisplayDiagnostics(); return true; } }; TEST_F(LibclangReparseTest, Reparse) { const char *HeaderTop = "#ifndef H\n#define H\nstruct Foo { int bar;"; const char *HeaderBottom = "\n};\n#endif\n"; const char *CppFile = "#include \"HeaderFile.h\"\nint main() {" " Foo foo; foo.bar = 7; foo.baz = 8; }\n"; std::string HeaderName = "HeaderFile.h"; std::string CppName = "CppFile.cpp"; WriteFile(CppName, CppFile); WriteFile(HeaderName, std::string(HeaderTop) + HeaderBottom); ClangTU = clang_parseTranslationUnit(Index, CppName.c_str(), nullptr, 0, nullptr, 0, TUFlags); EXPECT_EQ(1U, clang_getNumDiagnostics(ClangTU)); DisplayDiagnostics(); // Immedaitely reparse. ASSERT_TRUE(ReparseTU(0, nullptr /* No unsaved files. */)); EXPECT_EQ(1U, clang_getNumDiagnostics(ClangTU)); std::string NewHeaderContents = std::string(HeaderTop) + "int baz;" + HeaderBottom; WriteFile(HeaderName, NewHeaderContents); // Reparse after fix. ASSERT_TRUE(ReparseTU(0, nullptr /* No unsaved files. */)); EXPECT_EQ(0U, clang_getNumDiagnostics(ClangTU)); } <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2010 Klaus Post Copyright (C) 2014-2015 Pedro Côrte-Real Copyright (C) 2017 Roman Lebedev This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 */ #include "decompressors/SamsungV0Decompressor.h" #include "common/Common.h" // for uint32_t, uint16_t, int32_t #include "common/Point.h" // for iPoint2D #include "common/RawImage.h" // for RawImage, RawImageData #include "decoders/RawDecoderException.h" // for ThrowRDE #include "io/BitPumpMSB32.h" // for BitPumpMSB32 #include "io/ByteStream.h" // for ByteStream #include <algorithm> // for max #include <cassert> // for assert #include <iterator> // for advance, begin, end, next #include <vector> // for vector namespace rawspeed { SamsungV0Decompressor::SamsungV0Decompressor(const RawImage& image, const ByteStream& bso, const ByteStream& bsr) : AbstractSamsungDecompressor(image) { if (mRaw->getCpp() != 1 || mRaw->getDataType() != TYPE_USHORT16 || mRaw->getBpp() != 2) ThrowRDE("Unexpected component count / data type"); const uint32_t width = mRaw->dim.x; const uint32_t height = mRaw->dim.y; if (width == 0 || height == 0 || width < 16 || width > 5546 || height > 3714) ThrowRDE("Unexpected image dimensions found: (%u; %u)", width, height); computeStripes(bso.peekStream(height, 4), bsr); } // FIXME: this is very close to IiqDecoder::computeSripes() void SamsungV0Decompressor::computeStripes(ByteStream bso, ByteStream bsr) { const uint32_t height = mRaw->dim.y; std::vector<uint32_t> offsets; offsets.reserve(1 + height); for (uint32_t y = 0; y < height; y++) offsets.emplace_back(bso.getU32()); offsets.emplace_back(bsr.getSize()); stripes.reserve(height); auto offset_iterator = std::begin(offsets); bsr.skipBytes(*offset_iterator); auto next_offset_iterator = std::next(offset_iterator); while (next_offset_iterator < std::end(offsets)) { if (*offset_iterator >= *next_offset_iterator) ThrowRDE("Line offsets are out of sequence or slice is empty."); const auto size = *next_offset_iterator - *offset_iterator; assert(size > 0); stripes.emplace_back(bsr.getStream(size)); std::advance(offset_iterator, 1); std::advance(next_offset_iterator, 1); } assert(stripes.size() == height); } void SamsungV0Decompressor::decompress() const { for (int y = 0; y < mRaw->dim.y; y++) decompressStrip(y, stripes[y]); // Swap red and blue pixels to get the final CFA pattern for (int y = 0; y < mRaw->dim.y - 1; y += 2) { auto* topline = reinterpret_cast<uint16_t*>(mRaw->getData(0, y)); auto* bottomline = reinterpret_cast<uint16_t*>(mRaw->getData(0, y + 1)); for (int x = 0; x < mRaw->dim.x - 1; x += 2) { uint16_t temp = topline[1]; topline[1] = bottomline[0]; bottomline[0] = temp; topline += 2; bottomline += 2; } } } int32_t SamsungV0Decompressor::calcAdj(BitPumpMSB32* bits, int b) { int32_t adj = 0; if (b) adj = (static_cast<int32_t>(bits->getBits(b)) << (32 - b) >> (32 - b)); return adj; } void SamsungV0Decompressor::decompressStrip(uint32_t y, const ByteStream& bs) const { const uint32_t width = mRaw->dim.x; assert(width > 0); BitPumpMSB32 bits(bs); std::array<int, 4> len; for (int& i : len) i = y < 2 ? 7 : 4; auto* img = reinterpret_cast<uint16_t*>(mRaw->getData(0, y)); const auto* const past_last = reinterpret_cast<uint16_t*>(mRaw->getData(width - 1, y) + mRaw->getBpp()); uint16_t* img_up = reinterpret_cast<uint16_t*>( mRaw->getData(0, std::max(0, static_cast<int>(y) - 1))); uint16_t* img_up2 = reinterpret_cast<uint16_t*>( mRaw->getData(0, std::max(0, static_cast<int>(y) - 2))); // Image is arranged in groups of 16 pixels horizontally for (uint32_t x = 0; x < width; x += 16) { bits.fill(); bool dir = !!bits.getBitsNoFill(1); std::array<int, 4> op; for (int& i : op) i = bits.getBitsNoFill(2); for (int i = 0; i < 4; i++) { assert(op[i] >= 0 && op[i] <= 3); switch (op[i]) { case 3: len[i] = bits.getBits(4); break; case 2: len[i]--; break; case 1: len[i]++; break; default: // FIXME: it can be zero too. break; } if (len[i] < 0) ThrowRDE("Bit length less than 0."); if (len[i] > 16) ThrowRDE("Bit Length more than 16."); } if (dir) { // Upward prediction if (y < 2) ThrowRDE("Upward prediction for the first two rows. Raw corrupt"); if (x + 16 >= width) ThrowRDE("Upward prediction for the last block of pixels. Raw corrupt"); // First we decode even pixels for (int c = 0; c < 16; c += 2) { int b = len[c >> 3]; int32_t adj = calcAdj(&bits, b); img[c] = adj + img_up[c]; } // Now we decode odd pixels // Why on earth upward prediction only looks up 1 line above // is beyond me, it will hurt compression a deal. for (int c = 1; c < 16; c += 2) { int b = len[2 | (c >> 3)]; int32_t adj = calcAdj(&bits, b); img[c] = adj + img_up2[c]; } } else { // Left to right prediction // First we decode even pixels int pred_left = x != 0 ? img[-2] : 128; for (int c = 0; c < 16; c += 2) { int b = len[c >> 3]; int32_t adj = calcAdj(&bits, b); if (img + c < past_last) img[c] = adj + pred_left; } // Now we decode odd pixels pred_left = x != 0 ? img[-1] : 128; for (int c = 1; c < 16; c += 2) { int b = len[2 | (c >> 3)]; int32_t adj = calcAdj(&bits, b); if (img + c < past_last) img[c] = adj + pred_left; } } img += 16; img_up += 16; img_up2 += 16; } } } // namespace rawspeed <commit_msg>SamsungV0Decompressor::decompress(): migrate to getU16DataAsUncroppedArray2DRef()<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2010 Klaus Post Copyright (C) 2014-2015 Pedro Côrte-Real Copyright (C) 2017 Roman Lebedev This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 */ #include "decompressors/SamsungV0Decompressor.h" #include "common/Common.h" // for uint32_t, uint16_t, int32_t #include "common/Point.h" // for iPoint2D #include "common/RawImage.h" // for RawImage, RawImageData #include "decoders/RawDecoderException.h" // for ThrowRDE #include "io/BitPumpMSB32.h" // for BitPumpMSB32 #include "io/ByteStream.h" // for ByteStream #include <algorithm> // for max #include <cassert> // for assert #include <iterator> // for advance, begin, end, next #include <vector> // for vector namespace rawspeed { SamsungV0Decompressor::SamsungV0Decompressor(const RawImage& image, const ByteStream& bso, const ByteStream& bsr) : AbstractSamsungDecompressor(image) { if (mRaw->getCpp() != 1 || mRaw->getDataType() != TYPE_USHORT16 || mRaw->getBpp() != 2) ThrowRDE("Unexpected component count / data type"); const uint32_t width = mRaw->dim.x; const uint32_t height = mRaw->dim.y; if (width == 0 || height == 0 || width < 16 || width > 5546 || height > 3714) ThrowRDE("Unexpected image dimensions found: (%u; %u)", width, height); computeStripes(bso.peekStream(height, 4), bsr); } // FIXME: this is very close to IiqDecoder::computeSripes() void SamsungV0Decompressor::computeStripes(ByteStream bso, ByteStream bsr) { const uint32_t height = mRaw->dim.y; std::vector<uint32_t> offsets; offsets.reserve(1 + height); for (uint32_t y = 0; y < height; y++) offsets.emplace_back(bso.getU32()); offsets.emplace_back(bsr.getSize()); stripes.reserve(height); auto offset_iterator = std::begin(offsets); bsr.skipBytes(*offset_iterator); auto next_offset_iterator = std::next(offset_iterator); while (next_offset_iterator < std::end(offsets)) { if (*offset_iterator >= *next_offset_iterator) ThrowRDE("Line offsets are out of sequence or slice is empty."); const auto size = *next_offset_iterator - *offset_iterator; assert(size > 0); stripes.emplace_back(bsr.getStream(size)); std::advance(offset_iterator, 1); std::advance(next_offset_iterator, 1); } assert(stripes.size() == height); } void SamsungV0Decompressor::decompress() const { for (int y = 0; y < mRaw->dim.y; y++) decompressStrip(y, stripes[y]); // Swap red and blue pixels to get the final CFA pattern const Array2DRef<uint16_t> out(mRaw->getU16DataAsUncroppedArray2DRef()); for (int row = 0; row < out.height - 1; row += 2) { for (int col = 0; col < out.width - 1; col += 2) std::swap(out(row, col + 1), out(row + 1, col)); } } int32_t SamsungV0Decompressor::calcAdj(BitPumpMSB32* bits, int b) { int32_t adj = 0; if (b) adj = (static_cast<int32_t>(bits->getBits(b)) << (32 - b) >> (32 - b)); return adj; } void SamsungV0Decompressor::decompressStrip(uint32_t y, const ByteStream& bs) const { const uint32_t width = mRaw->dim.x; assert(width > 0); BitPumpMSB32 bits(bs); std::array<int, 4> len; for (int& i : len) i = y < 2 ? 7 : 4; auto* img = reinterpret_cast<uint16_t*>(mRaw->getData(0, y)); const auto* const past_last = reinterpret_cast<uint16_t*>(mRaw->getData(width - 1, y) + mRaw->getBpp()); uint16_t* img_up = reinterpret_cast<uint16_t*>( mRaw->getData(0, std::max(0, static_cast<int>(y) - 1))); uint16_t* img_up2 = reinterpret_cast<uint16_t*>( mRaw->getData(0, std::max(0, static_cast<int>(y) - 2))); // Image is arranged in groups of 16 pixels horizontally for (uint32_t x = 0; x < width; x += 16) { bits.fill(); bool dir = !!bits.getBitsNoFill(1); std::array<int, 4> op; for (int& i : op) i = bits.getBitsNoFill(2); for (int i = 0; i < 4; i++) { assert(op[i] >= 0 && op[i] <= 3); switch (op[i]) { case 3: len[i] = bits.getBits(4); break; case 2: len[i]--; break; case 1: len[i]++; break; default: // FIXME: it can be zero too. break; } if (len[i] < 0) ThrowRDE("Bit length less than 0."); if (len[i] > 16) ThrowRDE("Bit Length more than 16."); } if (dir) { // Upward prediction if (y < 2) ThrowRDE("Upward prediction for the first two rows. Raw corrupt"); if (x + 16 >= width) ThrowRDE("Upward prediction for the last block of pixels. Raw corrupt"); // First we decode even pixels for (int c = 0; c < 16; c += 2) { int b = len[c >> 3]; int32_t adj = calcAdj(&bits, b); img[c] = adj + img_up[c]; } // Now we decode odd pixels // Why on earth upward prediction only looks up 1 line above // is beyond me, it will hurt compression a deal. for (int c = 1; c < 16; c += 2) { int b = len[2 | (c >> 3)]; int32_t adj = calcAdj(&bits, b); img[c] = adj + img_up2[c]; } } else { // Left to right prediction // First we decode even pixels int pred_left = x != 0 ? img[-2] : 128; for (int c = 0; c < 16; c += 2) { int b = len[c >> 3]; int32_t adj = calcAdj(&bits, b); if (img + c < past_last) img[c] = adj + pred_left; } // Now we decode odd pixels pred_left = x != 0 ? img[-1] : 128; for (int c = 1; c < 16; c += 2) { int b = len[2 | (c >> 3)]; int32_t adj = calcAdj(&bits, b); if (img + c < past_last) img[c] = adj + pred_left; } } img += 16; img_up += 16; img_up2 += 16; } } } // namespace rawspeed <|endoftext|>
<commit_before>#include <Rcpp.h> using namespace Rcpp; // used to keep track when we sort our distances struct pair_dist { double d; int i; int j; }; // custom comparator for sorting pair-distances // (C++11 would let us use a lambda instead, but...) struct pair_dist_cmp { bool operator() (pair_dist a, pair_dist b) { return a.d < b.d; } }; // [[Rcpp::export]] IntegerVector naive_cluster(NumericVector D, int M, int K, double threshold=1.0) { IntegerVector result(M * K); std::vector<pair_dist> dst(D.size()); std::map<int, std::set<int> > clusters; if (M * (M - 1) / 2 * K * K != D.size()) { stop("The length of D is not consistent with M and K"); } // initialization std::iota(result.begin(), result.end(), 0); for (int i = 0; i < K * M; ++i) { clusters[i].insert(i); } int d = 0; // runs along D for (int i = 0; i < (M - 1) * K; ++i) { // brute force: we'll just write down which index in D // corresponds to which pair of topics. D is assumed to go rowwise // along a block-lower-triangular matrix whose (I, J) block is the // K x K matrix of distances between topics in models I and J. And // blocks are omitted. // 1.1:2.1 1.1:2.2 ... 1.1:M.K // 1.2:2.1 1.1:2.1 ... 1.2:M.K // ... // 2.1:3.1 ... // ... // (M - 1).1:M.1 ... (M - 1):M.K // where a.b:c.d = distance from topic a in model b to topic c in // model d. for (int j = i / K + K; j < M * K; ++j) { dst[d].d = D[d]; // copying D like space is cheap or something dst[d].i = i; // a.b coded as (a - 1) * K + (b - 1) dst[d].j = j; d += 1; } } pair_dist_cmp pdc; std::sort(dst.begin(), dst.end(), pdc); int r1, r2; std::set<int> sect; bool allow; for (std::vector<pair_dist>::iterator d = dst.begin(); d != dst.end(); ++d) { if (d->d > threshold) { // then we're done break; } // topic pair's positions in the sequence of all topics d->i = d->i; d->j = d->j; // guaranteed to be > d->i if (d->i >= d->j) { stop("Something's wrong: d->i >= d->j"); } #ifdef __NAIVE_CLUSTER_LOG__ Rcout << "Consider: " << d->i << " (" << d->i / K << " "; Rcout << d->i % K << ") "; Rcout << d->j << " (" << d->j / K << " "; Rcout << d->j % K << ")"; #endif r1 = result[d->i]; r2 = result[d->j]; std::set<int> &c1 = clusters[r1]; std::set<int> &c2 = clusters[r2]; if (c1.size() == M || c2.size() == M) { // if either cluster is full, merge is impossible #ifdef __NAIVE_CLUSTER_LOG__ Rcout << "...cluster full." << std::endl; #endif continue; } // Check whether the two clusters share topics from the same model sect.clear(); allow = true; #ifdef __NAIVE_CLUSTER_LOG__ Rcout << " c1:"; #endif for (std::set<int>::iterator t = c1.begin(); t != c1.end(); ++t) { #ifdef __NAIVE_CLUSTER_LOG__ Rcout << " " << *t / K; #endif sect.insert(*t / K); } #ifdef __NAIVE_CLUSTER_LOG__ Rcout << " c2:"; #endif for (std::set<int>::iterator t = c2.begin(); t != c2.end() && allow; ++t) { // if same model: cluster disallowed #ifdef __NAIVE_CLUSTER_LOG__ Rcout << " " << *t / K; #endif allow = (sect.count(*t / K) == 0); } if (!allow) { #ifdef __NAIVE_CLUSTER_LOG__ Rcout << "...disallowed." << std::endl; #endif continue; } #ifdef __NAIVE_CLUSTER_LOG__ Rcout << "...merge." << std::endl; #endif // otherwise: merge for (std::set<int>::iterator t = c2.begin(); t != c2.end(); ++t) { c1.insert(*t); result[*t] = r1; } clusters.erase(r2); // also deletes the associated set object } return result; } <commit_msg>fixed crash: counting is hard<commit_after>#include <Rcpp.h> using namespace Rcpp; // used to keep track when we sort our distances struct pair_dist { double d; int i; int j; }; // custom comparator for sorting pair-distances // (C++11 would let us use a lambda instead, but...) struct pair_dist_cmp { bool operator() (pair_dist a, pair_dist b) { return a.d < b.d; } }; // [[Rcpp::export]] IntegerVector naive_cluster(NumericVector D, int M, int K, double threshold=1.0) { IntegerVector result(M * K); std::vector<pair_dist> dst(D.size()); std::map<int, std::set<int> > clusters; if (M * (M - 1) / 2 * K * K != D.size()) { stop("The length of D is not consistent with M and K"); } // initialization std::iota(result.begin(), result.end(), 0); for (int i = 0; i < K * M; ++i) { clusters[i].insert(i); } int d = 0; // runs along D for (int i = 0; i < (M - 1) * K; ++i) { // brute force: we'll just write down which index in D // corresponds to which pair of topics. D is assumed to go rowwise // along a block-upper-triangular matrix whose (I, J) block is the // K x K matrix of distances between topics in models I and J. And // zero blocks are omitted: // 1.1:2.1 1.1:2.2 ... 1.1:M.K // 1.2:2.1 1.1:2.1 ... 1.2:M.K // ... // 2.1:3.1 ... // ... // (M - 1).1:M.1 ... (M - 1):M.K // where a.b:c.d = distance from topic a in model b to topic c in // model d. for (int j = (1 + i / K) * K; j < M * K; ++j) { if (d >= dst.size()) { stop("Something's wrong: initialization counted past D"); } dst[d].d = D[d]; // copying D like space is cheap or something dst[d].i = i; // a.b coded as (a - 1) * K + (b - 1) dst[d].j = j; d += 1; } } pair_dist_cmp pdc; std::sort(dst.begin(), dst.end(), pdc); int r1, r2; std::set<int> sect; bool allow; for (std::vector<pair_dist>::iterator d = dst.begin(); d != dst.end(); ++d) { if (d->d > threshold) { // then we're done break; } // topic pair's positions in the sequence of all topics d->i = d->i; d->j = d->j; // guaranteed to be > d->i if (d->i >= d->j) { stop("Something's wrong: d->i >= d->j"); } #ifdef __NAIVE_CLUSTER_LOG__ Rcout << "Consider: " << d->i << " (" << d->i / K << " "; Rcout << d->i % K << ") "; Rcout << d->j << " (" << d->j / K << " "; Rcout << d->j % K << ")"; #endif r1 = result[d->i]; r2 = result[d->j]; std::set<int> &c1 = clusters[r1]; std::set<int> &c2 = clusters[r2]; if (c1.size() == M || c2.size() == M) { // if either cluster is full, merge is impossible #ifdef __NAIVE_CLUSTER_LOG__ Rcout << "...cluster full." << std::endl; #endif continue; } // Check whether the two clusters share topics from the same model sect.clear(); allow = true; #ifdef __NAIVE_CLUSTER_LOG__ Rcout << " c1:"; #endif for (std::set<int>::iterator t = c1.begin(); t != c1.end(); ++t) { #ifdef __NAIVE_CLUSTER_LOG__ Rcout << " " << *t / K; #endif sect.insert(*t / K); } #ifdef __NAIVE_CLUSTER_LOG__ Rcout << " c2:"; #endif for (std::set<int>::iterator t = c2.begin(); t != c2.end() && allow; ++t) { // if same model: cluster disallowed #ifdef __NAIVE_CLUSTER_LOG__ Rcout << " " << *t / K; #endif allow = (sect.count(*t / K) == 0); } if (!allow) { #ifdef __NAIVE_CLUSTER_LOG__ Rcout << "...disallowed." << std::endl; #endif continue; } #ifdef __NAIVE_CLUSTER_LOG__ Rcout << "...merge." << std::endl; #endif // otherwise: merge for (std::set<int>::iterator t = c2.begin(); t != c2.end(); ++t) { c1.insert(*t); result[*t] = r1; } clusters.erase(r2); // also deletes the associated set object } return result; } <|endoftext|>
<commit_before>#include <cpr/cpr.h> #include <utils.h> #include "command.h" #include "../CmdHandler.h" #include "../option.h" #include "../skills.h" #include "../strfmt.h" #define NP 0 #define SC 1 #define VH 2 #define MAX_URL 128 /* full name of the command */ CMDNAME("cml"); /* description of the command */ CMDDESCR("interact with crystalmathlabs trackers"); /* command usage synopsis */ CMDUSAGE("$cml [-s|-v] [-nu] [-t SKILL] [RSN]"); static const char *CML_HOST = "https://crystalmathlabs.com"; static const char *CML_USER = "/tracker/track.php?player="; static const char *CML_SCALC = "/tracker/suppliescalc.php"; static const char *CML_VHS = "/tracker/virtualhiscores.php?page=timeplayed"; static const char *CML_UPDATE = "/tracker/api.php?type=update&player="; static const char *CML_CTOP = "/tracker/api.php?type=currenttop&count=5&skill="; static int updatecml(char *rsn, char *err); static int read_current_top(char *out, int id); /* cml: interact with crystalmathlabs trackers */ int CmdHandler::cml(char *out, struct command *c) { int usenick, update, page, id, status; char buf[RSN_BUF]; char err[RSN_BUF]; int opt; static struct l_option long_opts[] = { { "help", NO_ARG, 'h' }, { "nick", NO_ARG, 'n' }, { "supplies-calc", NO_ARG, 's' }, { "current-top", REQ_ARG, 't' }, { "update", NO_ARG, 'u' }, { "virtual-hiscores", NO_ARG, 'v' }, { 0, 0, 0 } }; opt_init(); usenick = update = 0; page = NP; id = -1; status = EXIT_SUCCESS; while ((opt = l_getopt_long(c->argc, c->argv, "nst:uv", long_opts)) != EOF) { switch (opt) { case 'h': HELPMSG(out, CMDNAME, CMDUSAGE, CMDDESCR); return EXIT_SUCCESS; case 'n': usenick = 1; break; case 's': page = SC; break; case 't': if (strcmp(l_optarg, "ehp") == 0) { id = 99; break; } if ((id = skill_id(l_optarg)) == -1) { _sprintf(out, MAX_MSG, "%s: invalid skill " "name: %s", c->argv[0], l_optarg); return EXIT_FAILURE; } break; case 'u': update = 1; break; case 'v': page = VH; break; case '?': _sprintf(out, MAX_MSG, "%s", l_opterr()); return EXIT_FAILURE; default: return EXIT_FAILURE; } } if (l_optind == c->argc) { if (page) { if (update || usenick || id != -1) { _sprintf(out, MAX_MSG, "%s: cannot use other " "options with %s", c->argv[0], page == SC ? "-s" : "-v"); status = EXIT_FAILURE; } else { _sprintf(out, MAX_MSG, "[CML] %s%s", CML_HOST, page == SC ? CML_SCALC : CML_VHS); } } else if (id != -1) { status = read_current_top(out, id); } else if (update) { _sprintf(out, MAX_MSG, "%s: must provide RSN to update", c->argv[0]); status = EXIT_FAILURE; } else if (usenick) { _sprintf(out, MAX_MSG, "%s: no Twitch nick given", c->argv[0]); status = EXIT_FAILURE; } else { _sprintf(out, MAX_MSG, "[CML] %s", CML_HOST); } return status; } else if (l_optind != c->argc - 1 || page || id != -1) { USAGEMSG(out, CMDNAME, CMDUSAGE); return EXIT_FAILURE; } /* get the rsn of the queried player */ if (!getrsn(buf, RSN_BUF, c->argv[l_optind], c->nick, usenick)) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], buf); return EXIT_FAILURE; } if (update) { if (updatecml(buf, err) == 1) { _sprintf(out, MAX_MSG, "@%s, %s's CML tracker has " "been updated", c->nick, buf); } else { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], err); status = EXIT_FAILURE; } } else { _sprintf(out, MAX_MSG, "[CML] %s%s%s", CML_HOST, CML_USER, buf); } return status; } /* updatecml: update the cml tracker of player rsn */ static int updatecml(char *rsn, char *err) { int i; char url[MAX_URL]; cpr::Response resp; _sprintf(url, MAX_URL, "%s%s%s", CML_HOST, CML_UPDATE, rsn); resp = cpr::Get(cpr::Url(url), cpr::Header{{ "Connection", "close" }}); switch ((i = atoi(resp.text.c_str()))) { case 1: /* success */ break; case 2: _sprintf(err, RSN_BUF, "'%s' could not be found " "on the hiscores", rsn); break; case 3: _sprintf(err, RSN_BUF, "'%s' has had a negative " "XP gain", rsn); break; case 4: _sprintf(err, RSN_BUF, "unknown error, try again"); break; case 5: _sprintf(err, RSN_BUF, "'%s' has been updated within " "the last 30s", rsn); break; case 6: _sprintf(err, RSN_BUF, "'%s' is an invalid RSN", rsn); break; default: _sprintf(err, RSN_BUF, "could not reach CML API, try again"); break; } return i; } /* current_top: get 5 current top players for skill id */ static int read_current_top(char *out, int id) { cpr::Response resp; int i; char *nick, *score, *s, *orig; char url[MAX_URL]; char text[MAX_URL]; _sprintf(url, MAX_URL, "%s%s%d", CML_HOST, CML_CTOP, id); resp = cpr::Get(cpr::Url(url), cpr::Header{{ "Connection", "close" }}); strcpy(text, resp.text.c_str()); if (strcmp(text, "-3") == 0 || strcmp(text, "-4") == 0) { _sprintf(out, MAX_MSG, "%s: could not reach CML API, try again", CMDNAME); return EXIT_FAILURE; } i = 0; nick = text; orig = out; _sprintf(out, MAX_MSG, "[CML] Current top players in %s: ", id == 99 ? "EHP" : skill_name(id).c_str()); out += strlen(out); while ((score = strchr(nick, ','))) { ++i; *score++ = '\0'; if ((s = strchr(score, '\n'))) *s = '\0'; _sprintf(out, MAX_MSG - 50 * i, "%d. %s (+", i, nick); out += strlen(out); if (id == 99) { strcat(out, score); } else { fmtnum(out, 24, score); strcat(out, " xp"); } strcat(out, ")"); if (i != 5) { nick = s + 1; strcat(out, ", "); } out += strlen(out); } if (i != 5) { _sprintf(orig, MAX_MSG, "%s: could not read current top", CMDNAME); return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>cml: change page to char *<commit_after>#include <cpr/cpr.h> #include <utils.h> #include "command.h" #include "../CmdHandler.h" #include "../option.h" #include "../skills.h" #include "../strfmt.h" #define MAX_URL 128 /* full name of the command */ CMDNAME("cml"); /* description of the command */ CMDDESCR("interact with crystalmathlabs trackers"); /* command usage synopsis */ CMDUSAGE("$cml [-s|-v] [-nu] [-t SKILL] [RSN]"); static const char *CML_HOST = "https://crystalmathlabs.com"; static const char *CML_USER = "/tracker/track.php?player="; static const char *CML_SCALC = "/tracker/suppliescalc.php"; static const char *CML_VHS = "/tracker/virtualhiscores.php?page=timeplayed"; static const char *CML_UPDATE = "/tracker/api.php?type=update&player="; static const char *CML_CTOP = "/tracker/api.php?type=currenttop&count=5&skill="; static int updatecml(char *rsn, char *err); static int read_current_top(char *out, int id); /* cml: interact with crystalmathlabs trackers */ int CmdHandler::cml(char *out, struct command *c) { int usenick, update, id, status; const char *page; char buf[RSN_BUF]; char err[RSN_BUF]; int opt; static struct l_option long_opts[] = { { "help", NO_ARG, 'h' }, { "nick", NO_ARG, 'n' }, { "supplies-calc", NO_ARG, 's' }, { "current-top", REQ_ARG, 't' }, { "update", NO_ARG, 'u' }, { "virtual-hiscores", NO_ARG, 'v' }, { 0, 0, 0 } }; opt_init(); usenick = update = 0; page = NULL; id = -1; status = EXIT_SUCCESS; while ((opt = l_getopt_long(c->argc, c->argv, "nst:uv", long_opts)) != EOF) { switch (opt) { case 'h': HELPMSG(out, CMDNAME, CMDUSAGE, CMDDESCR); return EXIT_SUCCESS; case 'n': usenick = 1; break; case 's': page = CML_SCALC; break; case 't': if (strcmp(l_optarg, "ehp") == 0) { id = 99; break; } if ((id = skill_id(l_optarg)) == -1) { _sprintf(out, MAX_MSG, "%s: invalid skill " "name: %s", c->argv[0], l_optarg); return EXIT_FAILURE; } break; case 'u': update = 1; break; case 'v': page = CML_VHS; break; case '?': _sprintf(out, MAX_MSG, "%s", l_opterr()); return EXIT_FAILURE; default: return EXIT_FAILURE; } } if (l_optind == c->argc) { if (page) { if (update || usenick || id != -1) { _sprintf(out, MAX_MSG, "%s: cannot use other " "options with %s", c->argv[0], page == CML_VHS ? "-v" : "-s"); status = EXIT_FAILURE; } else { _sprintf(out, MAX_MSG, "[CML] %s%s", CML_HOST, page); } } else if (id != -1) { status = read_current_top(out, id); } else if (update) { _sprintf(out, MAX_MSG, "%s: must provide RSN to update", c->argv[0]); status = EXIT_FAILURE; } else if (usenick) { _sprintf(out, MAX_MSG, "%s: no Twitch nick given", c->argv[0]); status = EXIT_FAILURE; } else { _sprintf(out, MAX_MSG, "[CML] %s", CML_HOST); } return status; } else if (l_optind != c->argc - 1 || page || id != -1) { USAGEMSG(out, CMDNAME, CMDUSAGE); return EXIT_FAILURE; } /* get the rsn of the queried player */ if (!getrsn(buf, RSN_BUF, c->argv[l_optind], c->nick, usenick)) { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], buf); return EXIT_FAILURE; } if (update) { if (updatecml(buf, err) == 1) { _sprintf(out, MAX_MSG, "@%s, %s's CML tracker has " "been updated", c->nick, buf); } else { _sprintf(out, MAX_MSG, "%s: %s", c->argv[0], err); status = EXIT_FAILURE; } } else { _sprintf(out, MAX_MSG, "[CML] %s%s%s", CML_HOST, CML_USER, buf); } return status; } /* updatecml: update the cml tracker of player rsn */ static int updatecml(char *rsn, char *err) { int i; char url[MAX_URL]; cpr::Response resp; _sprintf(url, MAX_URL, "%s%s%s", CML_HOST, CML_UPDATE, rsn); resp = cpr::Get(cpr::Url(url), cpr::Header{{ "Connection", "close" }}); switch ((i = atoi(resp.text.c_str()))) { case 1: /* success */ break; case 2: _sprintf(err, RSN_BUF, "'%s' could not be found " "on the hiscores", rsn); break; case 3: _sprintf(err, RSN_BUF, "'%s' has had a negative " "XP gain", rsn); break; case 4: _sprintf(err, RSN_BUF, "unknown error, try again"); break; case 5: _sprintf(err, RSN_BUF, "'%s' has been updated within " "the last 30s", rsn); break; case 6: _sprintf(err, RSN_BUF, "'%s' is an invalid RSN", rsn); break; default: _sprintf(err, RSN_BUF, "could not reach CML API, try again"); break; } return i; } /* current_top: get 5 current top players for skill id */ static int read_current_top(char *out, int id) { cpr::Response resp; int i; char *nick, *score, *s, *orig; char url[MAX_URL]; char text[MAX_URL]; _sprintf(url, MAX_URL, "%s%s%d", CML_HOST, CML_CTOP, id); resp = cpr::Get(cpr::Url(url), cpr::Header{{ "Connection", "close" }}); strcpy(text, resp.text.c_str()); if (strcmp(text, "-3") == 0 || strcmp(text, "-4") == 0) { _sprintf(out, MAX_MSG, "%s: could not reach CML API, try again", CMDNAME); return EXIT_FAILURE; } i = 0; nick = text; orig = out; _sprintf(out, MAX_MSG, "[CML] Current top players in %s: ", id == 99 ? "EHP" : skill_name(id).c_str()); out += strlen(out); while ((score = strchr(nick, ','))) { ++i; *score++ = '\0'; if ((s = strchr(score, '\n'))) *s = '\0'; _sprintf(out, MAX_MSG - 50 * i, "%d. %s (+", i, nick); out += strlen(out); if (id == 99) { strcat(out, score); } else { fmtnum(out, 24, score); strcat(out, " xp"); } strcat(out, ")"); if (i != 5) { nick = s + 1; strcat(out, ", "); } out += strlen(out); } if (i != 5) { _sprintf(orig, MAX_MSG, "%s: could not read current top", CMDNAME); return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "codegen.h" #include <map> #include <llvm/Constants.h> #include <llvm/DerivedTypes.h> #include <llvm/Function.h> #include <llvm/Transforms/Utils/Cloning.h> #include <llvm/ADT/ValueMap.h> #include <llvm/LLVMContext.h> #include <llvm/Module.h> #include <llvm/Analysis/Verifier.h> #include <llvm/Support/IRBuilder.h> #include <llvm/PassManager.h> #include <llvm/LinkAllPasses.h> #include "node.h" #include "parser.h" using namespace llvm; llvm::Value *ErrorV(const char *str) { std::cerr << "Error: " << str << std::endl; return 0; } static llvm::Module *mod; static llvm::IRBuilder<> builder(llvm::getGlobalContext()); static std::map<std::string, llvm::Value *> named_values; namespace llvm { struct UnresolvedType; } static std::map<int, llvm::UnresolvedType *> unresolved_type_map; namespace llvm { struct UnresolvedType : public Type { int x; UnresolvedType(int x) : Type(mod->getContext(), NumTypeIDs), x(x) {} static const UnresolvedType *get(int x) { UnresolvedType *ret = unresolved_type_map[x]; if (!ret) { ret = unresolved_type_map[x] = new UnresolvedType(x); } return ret; } virtual TypeID getTypeID() const { return NumTypeIDs; } static inline bool classof(const Type *b) { return b->getTypeID() == NumTypeIDs; } }; } llvm::Function *generate_identity() { using namespace llvm; std::vector<const Type *> func_ident_args; func_ident_args.push_back(UnresolvedType::get(0)); FunctionType *func_ident_type = FunctionType::get(UnresolvedType::get(0), func_ident_args, false); Function *func_ident = Function::Create(func_ident_type, GlobalValue::InternalLinkage, "ι"); BasicBlock *block_ident = BasicBlock::Create(mod->getContext(), "entry", func_ident, 0); llvm::IRBuilder<> builder_ident(llvm::getGlobalContext()); builder_ident.SetInsertPoint(block_ident); builder_ident.CreateRet(func_ident->arg_begin()); return func_ident; } llvm::Value *NAssign::codeGen() { NApply *decl = llvm::dyn_cast<NApply>(&l); if (!decl) { return ErrorV("Expected NApply on the left"); } NIdentifier *ident = llvm::dyn_cast<NIdentifier>(&decl->rhs); if (!ident) { return ErrorV("Identifier expected"); } llvm::Value *decl_type = decl->lhs.codeGen(); llvm::Value *ident_val = ident->codeGen(); if (!decl_type || ident_val || !llvm::isa<llvm::UndefValue>(decl_type)) { return ErrorV("Invalid declaration"); } llvm::Value *R = r.codeGen(); if (R == 0) return NULL; if (decl_type->getType() != R->getType()) { return ErrorV("Types don't match"); } named_values[ident->name] = R; return R; } static bool is_resolved(llvm::Function *F) { std::vector<const llvm::Type*> ArgTypes; for (llvm::Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) { if (llvm::isa<llvm::UnresolvedType>(I->getType())) { return false; } } const llvm::Type *ret_type = F->getFunctionType()->getReturnType(); if (llvm::isa<llvm::UnresolvedType>(ret_type)) { return false; } return true; } static llvm::Function *replace_unresolved(llvm::Function *F, int index, const llvm::Type *type, bool put_in_module) { using namespace llvm; std::vector<const Type*> ArgTypes; for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) { const UnresolvedType *t; if ((t = llvm::dyn_cast<UnresolvedType>(I->getType())) && t->x == index) { ArgTypes.push_back(type); } else { ArgTypes.push_back(I->getType()); } } // Create a new function type... const Type *ret_type = F->getFunctionType()->getReturnType(); if (llvm::isa<UnresolvedType>(ret_type) && llvm::cast<UnresolvedType>(ret_type)->x == index) { ret_type = type; } FunctionType *FTy = FunctionType::get(ret_type, ArgTypes, F->getFunctionType()->isVarArg()); // Create the new function... Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName(), put_in_module ? mod : NULL); ValueMap<const Value *, Value *> vmap; Function::arg_iterator DestI = NewF->arg_begin(); for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) { DestI->setName(I->getName()); vmap[I] = DestI++; } SmallVectorImpl<ReturnInst *> ri(0); CloneFunctionInto(NewF, F, vmap, false, ri); return NewF; } llvm::Value *NApply::codeGen() { using namespace llvm; llvm::Value *func = lhs.codeGen(); llvm::Value *apply = rhs.codeGen(); if (!func) { return ErrorV("Error in NApply"); } if (llvm::dyn_cast<llvm::Function>(apply)) { return ErrorV("Non-value arguments to NApply not supported yet"); } llvm::Function *func_func; if (!(func_func = llvm::dyn_cast<llvm::Function>(func))) { return ErrorV("Non-function left arguments to NApply not supported yet"); } if (!is_resolved(func_func)) { func_func = replace_unresolved(func_func, 0, apply->getType(), true); } return builder.CreateCall(func_func, apply); } llvm::Value *NInteger::codeGen() { return builder.getInt64(value); } llvm::Value *NIdentifier::codeGen() { if (name == "int") { return llvm::UndefValue::get(builder.getInt64Ty()); } else { return named_values[name]; } } llvm::Value *NTuple::codeGen() { std::vector<llvm::Constant *> values; std::vector<const llvm::Type *> types; for (size_t i = 0; i < l.size(); ++i) { llvm::Value *val = l[i]->codeGen(); if (!val) { return ErrorV("Bad Tuple"); } if (!llvm::isa<llvm::Constant>(val)) { return ErrorV("Tuple elements must be constants"); } values.push_back(llvm::cast<llvm::Constant>(val)); types.push_back(val->getType()); } Constant *tuple = llvm::ConstantStruct::get(llvm::StructType::get(mod->getContext(), types, false), values); GlobalVariable* gvar = new GlobalVariable(*mod, tuple->getType(), true, GlobalValue::PrivateLinkage, 0, "struct"); gvar->setInitializer(tuple); return gvar; } llvm::Value *NArray::codeGen() { std::vector<llvm::Constant *> values; std::vector<const llvm::Type *> types; for (size_t i = 0; i < l.size(); ++i) { llvm::Value *val = l[i]->codeGen(); if (!val) { return ErrorV("Bad Tuple"); } if (!llvm::isa<llvm::Constant>(val)) { return ErrorV("Tuple elements must be constants"); } values.push_back(llvm::cast<llvm::Constant>(val)); types.push_back(val->getType()); } Constant *array = llvm::ConstantArray::get(llvm::ArrayType::get(types[0], values.size()), values); GlobalVariable* gvar = new GlobalVariable(*mod, array->getType(), true, GlobalValue::PrivateLinkage, 0, "array"); gvar->setInitializer(array); return gvar; } llvm::Value *NBinaryOperator::codeGen() { llvm::Value *L = lhs.codeGen(); llvm::Value *R = rhs.codeGen(); if (L == 0 || R == 0) return NULL; switch (op) { case TPLUS: std::cerr << "TPLUS" << std::endl; return builder.CreateAdd(L, R, "addtmp"); case TMINUS: std::cerr << "TMINUS" << std::endl; return builder.CreateSub(L, R, "subtmp"); case TMUL: std::cerr << "TMUL" << std::endl; return builder.CreateMul(L, R, "multmp"); default: return ErrorV("invalid binary operator"); } return NULL; } static void print_value(llvm::Function *printf, llvm::Value *val) { using namespace llvm; static Value *format_int = builder.CreateGlobalStringPtr("%d"); static Value *format_str = builder.CreateGlobalStringPtr("%s"); static Value *format_newline = builder.CreateGlobalStringPtr("\n"); static Value *struct_beg = builder.CreateGlobalStringPtr("("); static Value *struct_del = builder.CreateGlobalStringPtr(", "); static Value *struct_end = builder.CreateGlobalStringPtr(")"); static Value *array_beg = builder.CreateGlobalStringPtr("["); static Value *array_end = builder.CreateGlobalStringPtr("]"); if (val->getType()->isIntegerTy()) { builder.CreateCall2(printf, format_int, val); } else if (val->getType()->isPointerTy()) { if (builder.CreateLoad(val)->getType()->isStructTy()) { size_t size = cast<StructType>(builder.CreateLoad(val)->getType())->getNumElements(); builder.CreateCall(printf, struct_beg); for (size_t i = 0; i < size; ++i) { builder.CreateCall2(printf, format_int, builder.CreateLoad(builder.CreateStructGEP(val, i))); if (i != size - 1) builder.CreateCall(printf, struct_del); } builder.CreateCall(printf, struct_end); } else if (builder.CreateLoad(val)->getType()->isArrayTy()) { size_t size = cast<ArrayType>(builder.CreateLoad(val)->getType())->getNumElements(); builder.CreateCall(printf, array_beg); for (size_t i = 0; i < size; ++i) { builder.CreateCall2(printf, format_int, builder.CreateLoad(builder.CreateStructGEP(val, i))); if (i != size - 1) builder.CreateCall(printf, struct_del); } builder.CreateCall(printf, array_end); } } else { return; } builder.CreateCall(printf, format_newline); } void generate_code(ExpressionList *exprs) { using namespace llvm; mod = new Module("main", getGlobalContext()); // char * PointerType* char_ptr = PointerType::get(IntegerType::get(mod->getContext(), 8), 0); // char ** PointerType* char_ptr_ptr = PointerType::get(char_ptr, 0); // main std::vector<const Type *> func_main_args; func_main_args.push_back(IntegerType::get(mod->getContext(), 32)); func_main_args.push_back(char_ptr_ptr); FunctionType* func_main_type = FunctionType::get(IntegerType::get(mod->getContext(), 32), func_main_args, false); Function *func_main = Function::Create(func_main_type, GlobalValue::ExternalLinkage, "main", mod); // printf std::vector<const Type *> func_printf_args; func_printf_args.push_back(char_ptr); FunctionType *func_printf_type = FunctionType::get(IntegerType::get(mod->getContext(), 32), func_printf_args, true); Function *func_printf = Function::Create(func_printf_type, GlobalValue::ExternalLinkage, "printf", mod); // main block BasicBlock *bblock = BasicBlock::Create(mod->getContext(), "entry", func_main, 0); builder.SetInsertPoint(bblock); // globals named_values["ι"] = generate_identity(); Value *last = NULL; for (size_t i = 0; i < exprs->size(); ++i) { last = (*exprs)[i]->codeGen(); if (!isa<NAssign>((*exprs)[i]) && last) { print_value(func_printf, last); } } builder.CreateRet(builder.getInt32(0)); std::cerr << "Code is generated." << std::endl; PassManager pm; pm.add(createPrintModulePass(&outs())); pm.run(*mod); } <commit_msg>pascal style arrays<commit_after>#include "codegen.h" #include <map> #include <llvm/Constants.h> #include <llvm/DerivedTypes.h> #include <llvm/Function.h> #include <llvm/Transforms/Utils/Cloning.h> #include <llvm/ADT/ValueMap.h> #include <llvm/LLVMContext.h> #include <llvm/Module.h> #include <llvm/Analysis/Verifier.h> #include <llvm/Support/IRBuilder.h> #include <llvm/PassManager.h> #include <llvm/LinkAllPasses.h> #include "node.h" #include "parser.h" using namespace llvm; llvm::Value *ErrorV(const char *str) { std::cerr << "Error: " << str << std::endl; return 0; } static llvm::Module *mod; static llvm::IRBuilder<> builder(llvm::getGlobalContext()); static std::map<std::string, llvm::Value *> named_values; namespace llvm { struct UnresolvedType; } static std::map<int, llvm::UnresolvedType *> unresolved_type_map; namespace llvm { struct UnresolvedType : public Type { int x; UnresolvedType(int x) : Type(mod->getContext(), NumTypeIDs), x(x) {} static const UnresolvedType *get(int x) { UnresolvedType *ret = unresolved_type_map[x]; if (!ret) { ret = unresolved_type_map[x] = new UnresolvedType(x); } return ret; } virtual TypeID getTypeID() const { return NumTypeIDs; } static inline bool classof(const Type *b) { return b->getTypeID() == NumTypeIDs; } }; } llvm::Function *generate_identity() { using namespace llvm; std::vector<const Type *> func_ident_args; func_ident_args.push_back(UnresolvedType::get(0)); FunctionType *func_ident_type = FunctionType::get(UnresolvedType::get(0), func_ident_args, false); Function *func_ident = Function::Create(func_ident_type, GlobalValue::InternalLinkage, "ι"); BasicBlock *block_ident = BasicBlock::Create(mod->getContext(), "entry", func_ident, 0); llvm::IRBuilder<> builder_ident(llvm::getGlobalContext()); builder_ident.SetInsertPoint(block_ident); builder_ident.CreateRet(func_ident->arg_begin()); return func_ident; } llvm::Value *NAssign::codeGen() { NApply *decl = llvm::dyn_cast<NApply>(&l); if (!decl) { return ErrorV("Expected NApply on the left"); } NIdentifier *ident = llvm::dyn_cast<NIdentifier>(&decl->rhs); if (!ident) { return ErrorV("Identifier expected"); } llvm::Value *decl_type = decl->lhs.codeGen(); llvm::Value *ident_val = ident->codeGen(); if (!decl_type || ident_val || !llvm::isa<llvm::UndefValue>(decl_type)) { return ErrorV("Invalid declaration"); } llvm::Value *R = r.codeGen(); if (R == 0) return NULL; if (decl_type->getType() != R->getType()) { return ErrorV("Types don't match"); } named_values[ident->name] = R; return R; } static bool is_resolved(llvm::Function *F) { std::vector<const llvm::Type*> ArgTypes; for (llvm::Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) { if (llvm::isa<llvm::UnresolvedType>(I->getType())) { return false; } } const llvm::Type *ret_type = F->getFunctionType()->getReturnType(); if (llvm::isa<llvm::UnresolvedType>(ret_type)) { return false; } return true; } static llvm::Function *replace_unresolved(llvm::Function *F, int index, const llvm::Type *type, bool put_in_module) { using namespace llvm; std::vector<const Type*> ArgTypes; for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) { const UnresolvedType *t; if ((t = llvm::dyn_cast<UnresolvedType>(I->getType())) && t->x == index) { ArgTypes.push_back(type); } else { ArgTypes.push_back(I->getType()); } } // Create a new function type... const Type *ret_type = F->getFunctionType()->getReturnType(); if (llvm::isa<UnresolvedType>(ret_type) && llvm::cast<UnresolvedType>(ret_type)->x == index) { ret_type = type; } FunctionType *FTy = FunctionType::get(ret_type, ArgTypes, F->getFunctionType()->isVarArg()); // Create the new function... Function *NewF = Function::Create(FTy, F->getLinkage(), F->getName(), put_in_module ? mod : NULL); ValueMap<const Value *, Value *> vmap; Function::arg_iterator DestI = NewF->arg_begin(); for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) { DestI->setName(I->getName()); vmap[I] = DestI++; } SmallVectorImpl<ReturnInst *> ri(0); CloneFunctionInto(NewF, F, vmap, false, ri); return NewF; } llvm::Value *NApply::codeGen() { using namespace llvm; llvm::Value *func = lhs.codeGen(); llvm::Value *apply = rhs.codeGen(); if (!func) { return ErrorV("Error in NApply"); } if (llvm::dyn_cast<llvm::Function>(apply)) { return ErrorV("Non-value arguments to NApply not supported yet"); } llvm::Function *func_func; if (!(func_func = llvm::dyn_cast<llvm::Function>(func))) { return ErrorV("Non-function left arguments to NApply not supported yet"); } if (!is_resolved(func_func)) { func_func = replace_unresolved(func_func, 0, apply->getType(), true); } return builder.CreateCall(func_func, apply); } llvm::Value *NInteger::codeGen() { return builder.getInt64(value); } llvm::Value *NIdentifier::codeGen() { if (name == "int") { return llvm::UndefValue::get(builder.getInt64Ty()); } else { return named_values[name]; } } llvm::Value *NTuple::codeGen() { std::vector<llvm::Constant *> values; std::vector<const llvm::Type *> types; for (size_t i = 0; i < l.size(); ++i) { llvm::Value *val = l[i]->codeGen(); if (!val) { return ErrorV("Bad Tuple"); } if (!llvm::isa<llvm::Constant>(val)) { return ErrorV("Tuple elements must be constants"); } values.push_back(llvm::cast<llvm::Constant>(val)); types.push_back(val->getType()); } Constant *tuple = llvm::ConstantStruct::get(llvm::StructType::get(mod->getContext(), types, false), values); GlobalVariable* gvar = new GlobalVariable(*mod, tuple->getType(), true, GlobalValue::PrivateLinkage, 0, "struct"); gvar->setInitializer(tuple); return gvar; } llvm::Value *NArray::codeGen() { std::vector<llvm::Constant *> values; const llvm::Type *type = NULL; for (size_t i = 0; i < l.size(); ++i) { llvm::Value *val = l[i]->codeGen(); if (!val) { return ErrorV("Bad Tuple"); } if (!llvm::isa<llvm::Constant>(val)) return ErrorV("Tuple elements must be constants"); values.push_back(llvm::cast<llvm::Constant>(val)); if (i == 0) type = val->getType(); else if (val->getType() != type) return ErrorV("Types of array elements must be the same"); } std::vector<const llvm::Type *> types; const Type *size = builder.getInt64Ty(); const ArrayType *array = llvm::ArrayType::get(type, values.size()); types.push_back(size); types.push_back(array); const Type *array_real = llvm::StructType::get(mod->getContext(), types, false); Constant *alloca_size = ConstantExpr::getSizeOf(array_real); types[1] = llvm::ArrayType::get(type, 0); const Type *array_type = llvm::StructType::get(mod->getContext(), types, false); Value *mem = builder.CreateAlloca(builder.getInt8Ty(), alloca_size); Value *ret = builder.CreateBitCast(mem, PointerType::getUnqual(array_type)); builder.CreateStore(builder.getInt64(values.size()), builder.CreateStructGEP(ret, 0)); builder.CreateStore(ConstantArray::get(array, values), builder.CreateBitCast(builder.CreateStructGEP(ret, 1), PointerType::getUnqual(array))); return ret; } llvm::Value *NBinaryOperator::codeGen() { llvm::Value *L = lhs.codeGen(); llvm::Value *R = rhs.codeGen(); if (L == 0 || R == 0) return NULL; switch (op) { case TPLUS: std::cerr << "TPLUS" << std::endl; return builder.CreateAdd(L, R, "addtmp"); case TMINUS: std::cerr << "TMINUS" << std::endl; return builder.CreateSub(L, R, "subtmp"); case TMUL: std::cerr << "TMUL" << std::endl; return builder.CreateMul(L, R, "multmp"); default: return ErrorV("invalid binary operator"); } return NULL; } static void print_value(llvm::Function *printf, llvm::Value *val) { using namespace llvm; static Value *format_int = builder.CreateGlobalStringPtr("%d"); static Value *format_str = builder.CreateGlobalStringPtr("%s"); static Value *format_newline = builder.CreateGlobalStringPtr("\n"); static Value *struct_beg = builder.CreateGlobalStringPtr("("); static Value *struct_del = builder.CreateGlobalStringPtr(", "); static Value *struct_end = builder.CreateGlobalStringPtr(")"); static Value *array_beg = builder.CreateGlobalStringPtr("["); static Value *array_end = builder.CreateGlobalStringPtr("]"); if (val->getType()->isIntegerTy()) { builder.CreateCall2(printf, format_int, val); } else if (val->getType()->isPointerTy()) { if (builder.CreateLoad(val)->getType()->isStructTy() && cast<StructType>(builder.CreateLoad(val)->getType())->getNumElements() == 2 && isa<ArrayType>(builder.CreateLoad(builder.CreateStructGEP(val, 1))->getType()) && cast<ArrayType>(builder.CreateLoad(builder.CreateStructGEP(val, 1))->getType())->getNumElements() == 0) { Value *array_size = builder.CreateLoad(builder.CreateStructGEP(val, 0)); Value *array_data = builder.CreateStructGEP(val, 1); builder.CreateCall(printf, array_beg); for (size_t i = 0; i < 2; ++i) { builder.CreateCall2(printf, format_int, builder.CreateLoad(builder.CreateStructGEP(array_data, i))); if (i != 2 - 1) builder.CreateCall(printf, struct_del); } builder.CreateCall(printf, array_end); } else if (builder.CreateLoad(val)->getType()->isStructTy()) { size_t size = cast<StructType>(builder.CreateLoad(val)->getType())->getNumElements(); builder.CreateCall(printf, struct_beg); for (size_t i = 0; i < size; ++i) { builder.CreateCall2(printf, format_int, builder.CreateLoad(builder.CreateStructGEP(val, i))); if (i != size - 1) builder.CreateCall(printf, struct_del); } builder.CreateCall(printf, struct_end); } } else { return; } builder.CreateCall(printf, format_newline); } void generate_code(ExpressionList *exprs) { using namespace llvm; mod = new Module("main", getGlobalContext()); // char * PointerType* char_ptr = PointerType::get(IntegerType::get(mod->getContext(), 8), 0); // char ** PointerType* char_ptr_ptr = PointerType::get(char_ptr, 0); // main std::vector<const Type *> func_main_args; func_main_args.push_back(IntegerType::get(mod->getContext(), 32)); func_main_args.push_back(char_ptr_ptr); FunctionType* func_main_type = FunctionType::get(IntegerType::get(mod->getContext(), 32), func_main_args, false); Function *func_main = Function::Create(func_main_type, GlobalValue::ExternalLinkage, "main", mod); // printf std::vector<const Type *> func_printf_args; func_printf_args.push_back(char_ptr); FunctionType *func_printf_type = FunctionType::get(IntegerType::get(mod->getContext(), 32), func_printf_args, true); Function *func_printf = Function::Create(func_printf_type, GlobalValue::ExternalLinkage, "printf", mod); // main block BasicBlock *bblock = BasicBlock::Create(mod->getContext(), "entry", func_main, 0); builder.SetInsertPoint(bblock); // globals named_values["ι"] = generate_identity(); Value *last = NULL; for (size_t i = 0; i < exprs->size(); ++i) { last = (*exprs)[i]->codeGen(); if (!isa<NAssign>((*exprs)[i]) && last) { print_value(func_printf, last); } } builder.CreateRet(builder.getInt32(0)); std::cerr << "Code is generated." << std::endl; PassManager pm; pm.add(createPrintModulePass(&outs())); pm.run(*mod); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: itkWrapPadImageTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium 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. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 <iostream> #include "itkImage.h" #include "itkImage.h" #include "itkImageRegionIterator.h" #include "itkWrapPadImageFilter.h" #include "itkFileOutputWindow.h" // // Check that val represents the correct pixel value. This routine // allows the pad region to extend to twice the size of the input. // int VerifyPixel(int row, int col, int val) { int nextVal; if (row < 0) row += 8; if (row < 0) row += 8; if (row > 7) row -= 8; if (row > 7) row -= 8; if (col < 0) col += 12; if (col < 0) col += 12; if (col > 11) col -= 12; if (col > 11) col -= 12; nextVal = 8*col+row; return (val == nextVal); } int main() { itk::FileOutputWindow::Pointer fow = itk::FileOutputWindow::New(); fow->SetInstance(fow); // typedefs to simplify the syntax typedef itk::Image<short, 2> SimpleImage; SimpleImage::Pointer simpleImage = SimpleImage::New(); std::cout << "Simple image spacing: " << simpleImage->GetSpacing()[0] << ", " << simpleImage->GetSpacing()[1] << std::endl; // typedefs to simplify the syntax typedef itk::Image<short, 2> ShortImage; // Test the creation of an image with native type ShortImage::Pointer if2 = ShortImage::New(); // fill in an image ShortImage::IndexType index = {{0, 0}}; ShortImage::SizeType size = {{8, 12}}; ShortImage::RegionType region; int row, column; region.SetSize( size ); region.SetIndex( index ); if2->SetLargestPossibleRegion( region ); if2->SetBufferedRegion( region ); if2->Allocate(); itk::ImageRegionIterator<ShortImage> iterator(if2, region); short i=0; for (; !iterator.IsAtEnd(); ++iterator, ++i) { iterator.Set( i ); } // Create a filter itk::WrapPadImageFilter< ShortImage, ShortImage >::Pointer wrapPad; wrapPad = itk::WrapPadImageFilter< ShortImage, ShortImage >::New(); wrapPad->SetInput( if2 ); unsigned int upperfactors[2] = { 0, 0}; unsigned int lowerfactors[2] = { 0, 0}; wrapPad->PadLowerBound(lowerfactors); wrapPad->PadUpperBound(upperfactors); wrapPad->UpdateLargestPossibleRegion(); std::cout << wrapPad << std::endl; std::cout << "Input spacing: " << if2->GetSpacing()[0] << ", " << if2->GetSpacing()[1] << std::endl; std::cout << "Output spacing: " << wrapPad->GetOutput()->GetSpacing()[0] << ", " << wrapPad->GetOutput()->GetSpacing()[1] << std::endl; ShortImage::RegionType requestedRegion; bool passed; // CASE 1 lowerfactors[0] = 1; lowerfactors[1] = 3; upperfactors[0] = 2; upperfactors[1] = 4; wrapPad->PadLowerBound(lowerfactors); wrapPad->PadUpperBound(upperfactors); wrapPad->UpdateLargestPossibleRegion(); requestedRegion = wrapPad->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn1(wrapPad->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != (0 - (long) lowerfactors[0])) || (index[1] != (0 - (long) lowerfactors[1])) || (size[0] != (8 + lowerfactors[0] + upperfactors[0])) || (size[1] != (12 + lowerfactors[1] + upperfactors[1]))) { passed = false; } else { for (; !iteratorIn1.IsAtEnd(); ++iteratorIn1) { row = iteratorIn1.GetIndex()[0]; column = iteratorIn1.GetIndex()[1]; if (!VerifyPixel(row, column, iteratorIn1.Get())) { std::cout << "Error: (" << row << ", " << column << "), got " << iteratorIn1.Get() << std::endl; passed = false; } } } if (passed) { std::cout << "wrapPadImageFilter case 1 passed." << std::endl; } else { std::cout << "wrapPadImageFilter case 1 failed." << std::endl; return EXIT_FAILURE; } // CASE 2 lowerfactors[0] = 10; upperfactors[1] = 15; wrapPad->PadLowerBound(0, lowerfactors[0]); wrapPad->PadUpperBound(1, upperfactors[1]); if ((wrapPad->GetPadUpperBound(0) != upperfactors[0]) || (wrapPad->GetPadUpperBound()[1] != upperfactors[1]) || (wrapPad->GetPadLowerBound()[0] != lowerfactors[0]) || (wrapPad->GetPadLowerBound(1) != lowerfactors[1])) { passed = false; } else { wrapPad->UpdateLargestPossibleRegion(); requestedRegion = wrapPad->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn2(wrapPad->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != (0 - (long) lowerfactors[0])) || (index[1] != (0 - (long) lowerfactors[1])) || (size[0] != (8 + lowerfactors[0] + upperfactors[0])) || (size[1] != (12 + lowerfactors[1] + upperfactors[1]))) { passed = false; } else { for (; !iteratorIn2.IsAtEnd(); ++iteratorIn2) { row = iteratorIn2.GetIndex()[0]; column = iteratorIn2.GetIndex()[1]; if (!VerifyPixel(row, column, iteratorIn2.Get())) { std::cout << "Error: (" << row << ", " << column << "), got " << iteratorIn2.Get() << std::endl; passed = false; } } } } if (passed) { std::cout << "wrapPadImageFilter case 2 passed." << std::endl; } else { std::cout << "wrapPadImageFilter case 2 failed." << std::endl; return EXIT_FAILURE; } // CASE 3 lowerfactors[1] = 16; upperfactors[0] = 9; wrapPad->PadLowerBound(1, lowerfactors[1]); wrapPad->PadUpperBound(0, upperfactors[0]); if ((wrapPad->GetPadUpperBound(0) != upperfactors[0]) || (wrapPad->GetPadUpperBound()[1] != upperfactors[1]) || (wrapPad->GetPadLowerBound()[0] != lowerfactors[0]) || (wrapPad->GetPadLowerBound(1) != lowerfactors[1])) { passed = false; } else { wrapPad->UpdateLargestPossibleRegion(); requestedRegion = wrapPad->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn3(wrapPad->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != (0 - (long) lowerfactors[0])) || (index[1] != (0 - (long) lowerfactors[1])) || (size[0] != (8 + lowerfactors[0] + upperfactors[0])) || (size[1] != (12 + lowerfactors[1] + upperfactors[1]))) { passed = false; } else { for (; !iteratorIn3.IsAtEnd(); ++iteratorIn3) { row = iteratorIn3.GetIndex()[0]; column = iteratorIn3.GetIndex()[1]; if (!VerifyPixel(row, column, iteratorIn3.Get())) { std::cout << "Error: (" << row << ", " << column << "), got " << iteratorIn3.Get() << std::endl; passed = false; } } } } if (passed) { std::cout << "wrapPadImageFilter case 3 passed." << std::endl; } else { std::cout << "wrapPadImageFilter case 3 failed." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>ERR: Code walk through changes.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: itkWrapPadImageTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium 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. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 <iostream> #include "itkImage.h" #include "itkImage.h" #include "itkImageRegionIterator.h" #include "itkWrapPadImageFilter.h" #include "itkFileOutputWindow.h" // // Check that val represents the correct pixel value. This routine // allows the pad region to extend to twice the size of the input. // int VerifyPixel(int row, int col, int val) { int nextVal; if (row < 0) row += 8; if (row < 0) row += 8; if (row > 7) row -= 8; if (row > 7) row -= 8; if (col < 0) col += 12; if (col < 0) col += 12; if (col > 11) col -= 12; if (col > 11) col -= 12; nextVal = 8*col+row; return (val == nextVal); } int main() { itk::FileOutputWindow::Pointer fow = itk::FileOutputWindow::New(); fow->SetInstance(fow); // typedefs to simplify the syntax typedef itk::Image<short, 2> SimpleImage; SimpleImage::Pointer simpleImage = SimpleImage::New(); std::cout << "Simple image spacing: " << simpleImage->GetSpacing()[0] << ", " << simpleImage->GetSpacing()[1] << std::endl; // typedefs to simplify the syntax typedef itk::Image<short, 2> ShortImage; // Test the creation of an image with native type ShortImage::Pointer if2 = ShortImage::New(); // fill in an image ShortImage::IndexType index = {{0, 0}}; ShortImage::SizeType size = {{8, 12}}; ShortImage::RegionType region; int row, column; region.SetSize( size ); region.SetIndex( index ); if2->SetLargestPossibleRegion( region ); if2->SetBufferedRegion( region ); if2->Allocate(); itk::ImageRegionIterator<ShortImage> iterator(if2, region); short i=0; for (; !iterator.IsAtEnd(); ++iterator, ++i) { iterator.Set( i ); } // Create a filter itk::WrapPadImageFilter< ShortImage, ShortImage >::Pointer wrapPad; wrapPad = itk::WrapPadImageFilter< ShortImage, ShortImage >::New(); wrapPad->SetInput( if2 ); unsigned int upperfactors[2] = { 0, 0}; unsigned int lowerfactors[2] = { 0, 0}; wrapPad->SetPadLowerBound(lowerfactors); wrapPad->SetPadUpperBound(upperfactors); wrapPad->UpdateLargestPossibleRegion(); std::cout << wrapPad << std::endl; std::cout << "Input spacing: " << if2->GetSpacing()[0] << ", " << if2->GetSpacing()[1] << std::endl; std::cout << "Output spacing: " << wrapPad->GetOutput()->GetSpacing()[0] << ", " << wrapPad->GetOutput()->GetSpacing()[1] << std::endl; ShortImage::RegionType requestedRegion; bool passed; // CASE 1 lowerfactors[0] = 1; lowerfactors[1] = 3; upperfactors[0] = 2; upperfactors[1] = 4; wrapPad->SetPadLowerBound(lowerfactors); wrapPad->SetPadUpperBound(upperfactors); wrapPad->UpdateLargestPossibleRegion(); requestedRegion = wrapPad->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn1(wrapPad->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != (0 - (long) lowerfactors[0])) || (index[1] != (0 - (long) lowerfactors[1])) || (size[0] != (8 + lowerfactors[0] + upperfactors[0])) || (size[1] != (12 + lowerfactors[1] + upperfactors[1]))) { passed = false; } else { for (; !iteratorIn1.IsAtEnd(); ++iteratorIn1) { row = iteratorIn1.GetIndex()[0]; column = iteratorIn1.GetIndex()[1]; if (!VerifyPixel(row, column, iteratorIn1.Get())) { std::cout << "Error: (" << row << ", " << column << "), got " << iteratorIn1.Get() << std::endl; passed = false; } } } if (passed) { std::cout << "wrapPadImageFilter case 1 passed." << std::endl; } else { std::cout << "wrapPadImageFilter case 1 failed." << std::endl; return EXIT_FAILURE; } // CASE 2 lowerfactors[0] = 10; upperfactors[1] = 15; wrapPad->SetPadLowerBound(lowerfactors); wrapPad->SetPadUpperBound(upperfactors); if ((wrapPad->GetPadUpperBound()[0] != upperfactors[0]) || (wrapPad->GetPadUpperBound()[1] != upperfactors[1]) || (wrapPad->GetPadLowerBound()[0] != lowerfactors[0]) || (wrapPad->GetPadLowerBound()[1] != lowerfactors[1])) { passed = false; } else { wrapPad->UpdateLargestPossibleRegion(); requestedRegion = wrapPad->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn2(wrapPad->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != (0 - (long) lowerfactors[0])) || (index[1] != (0 - (long) lowerfactors[1])) || (size[0] != (8 + lowerfactors[0] + upperfactors[0])) || (size[1] != (12 + lowerfactors[1] + upperfactors[1]))) { passed = false; } else { for (; !iteratorIn2.IsAtEnd(); ++iteratorIn2) { row = iteratorIn2.GetIndex()[0]; column = iteratorIn2.GetIndex()[1]; if (!VerifyPixel(row, column, iteratorIn2.Get())) { std::cout << "Error: (" << row << ", " << column << "), got " << iteratorIn2.Get() << std::endl; passed = false; } } } } if (passed) { std::cout << "wrapPadImageFilter case 2 passed." << std::endl; } else { std::cout << "wrapPadImageFilter case 2 failed." << std::endl; return EXIT_FAILURE; } // CASE 3 lowerfactors[1] = 16; upperfactors[0] = 9; wrapPad->SetPadLowerBound(lowerfactors); wrapPad->SetPadUpperBound(upperfactors); if ((wrapPad->GetPadUpperBound()[0] != upperfactors[0]) || (wrapPad->GetPadUpperBound()[1] != upperfactors[1]) || (wrapPad->GetPadLowerBound()[0] != lowerfactors[0]) || (wrapPad->GetPadLowerBound()[1] != lowerfactors[1])) { passed = false; } else { wrapPad->UpdateLargestPossibleRegion(); requestedRegion = wrapPad->GetOutput()->GetRequestedRegion(); itk::ImageRegionIterator<ShortImage> iteratorIn3(wrapPad->GetOutput(), requestedRegion); passed = true; size = requestedRegion.GetSize(); index = requestedRegion.GetIndex(); if ((index[0] != (0 - (long) lowerfactors[0])) || (index[1] != (0 - (long) lowerfactors[1])) || (size[0] != (8 + lowerfactors[0] + upperfactors[0])) || (size[1] != (12 + lowerfactors[1] + upperfactors[1]))) { passed = false; } else { for (; !iteratorIn3.IsAtEnd(); ++iteratorIn3) { row = iteratorIn3.GetIndex()[0]; column = iteratorIn3.GetIndex()[1]; if (!VerifyPixel(row, column, iteratorIn3.Get())) { std::cout << "Error: (" << row << ", " << column << "), got " << iteratorIn3.Get() << std::endl; passed = false; } } } } if (passed) { std::cout << "wrapPadImageFilter case 3 passed." << std::endl; } else { std::cout << "wrapPadImageFilter case 3 failed." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <string> #include <vector> #include <iostream> #include <stdlib.h> #include <cstdio> #include <sys/wait.h> #include <sys/stat.h> using namespace std; class command{ protected: vector<string> commandlist; bool commandPass; string commandType; bool allCount; string nextConnector; public: command(){} command(vector<string> c){ commandlist = c; commandType = ";"; allCount = true; nextConnector = ";" } command(vector<string> c, string t){ commandlist = c; commandType = t; allCount = true; nextConnector = ";" } bool getPass(){ return commandPass; } string getType(){ return commandType; } void runCommand(vector<string> com){ char* argv[1024]; for(unsigned int i = 0; i < com.size(); i++){ argv[i] = (char*)com.at(i).c_str(); } argv[com.size()] = NULL; pid_t pid; int status; pid = fork(); if (pid == 0){ prevCommandPass = true; execvp(argv[0], argv); perror("execvp failed: "); exit(-1); } else{ if (waitpid(pid, &status, 0) == -1){ perror("Wait: "); } if (WIFEXITED(status) && WEXITSTATUS(status) != 0){ prevCommandPass = false; } } } void runAllCommands(){ vector<string> commandsublist; unsigned int i = 0; unsigned int j = 0; while (i < commandlist.size()){ j = 0; if (checkCommandRun()){ while (!checkBreaker(i)){ //Exit check if (commandlist.at(i) == "exit"){ cout << "Forced Exit." << endl; forceExit = true; _Exit(0); } // Comment check if (commandlist.at(i) == "#" || checkComment(commandlist.at(i))){ runCommand(commandsublist); return; } if (commandlist.at(i) == "[" || commandlist.at(i) == "test"){ i++; commandsublist.push_back(commandlist.at(i); if (commandlist.at(i) == "-e" || commandlist.at(i) == "-f" || commandlist.at(i) == "d"){ i++; commandsublist.push_back(commandlist.at(i)); } else{ i++; } } //Adds command to the list commandsublist.push_back(commandlist.at(i)); i++; j++; if (i == commandlist.size()){ runCommand(commandsublist); return; } } if (commandsublist.size() > 0){ runCommand(commandsublist); commandsublist.clear(); } if (checkBreaker(i)){ if (nextConnector == "||"){ if (allCount == true){ prevCommandPass = true; } else{ if (prevCommandPass == false){ allCount = false; } else{ allCount = true; } } } else if (nextConnector == "&&"){ if (allCount == true){ if (prevCommandPass == false){ allCount = false; } } else{ allCount = false; prevCommandPass = false; } } else if (nextConnector == ";"){ if (prevCommandPass == true){ allCount = true; } else{ allCount = false; } } if (commandlist.at(i) == "|"){ nextConnector = "||"; } else if (commandlist.at(i) == "&"){ nextConnector = "&&"; } else if (commandlist.at(i) == ";"){ nextConnector = ";"; } i++; } i++; } else{ i++; } } } // Checks if there is a '#' at the front of the string bool checkComment(string str){ if (str.at(0) == '#'){ return true; } return false; } // Checks if the string is a breaker bool checkBreaker(int i){ if ( (unsigned)i < commandlist.size() + 1){ if (commandlist.at(i) == "|" && commandlist.at(i + 1) == "|"){ return true; } else if (commandlist.at(i) == "&" && commandlist.at(i + 1) == "&"){ return true; } else if (commandlist.at(i) == ";"){ return true; } else{ return false; } } else if( (unsigned)i == commandlist.size() + 1){ if(commandlist.at(i) == ";"){ return true; } return false; } else{ return false; } } // Checks if the next command should be run bool checkCommandRun(){ if (nextConnector == "||"){ if(allCount == true){ return false; } else{ return true; } } else if (nextConnector == "&&"){ if(allCount == true){ return true; } return false; } else if (nextConnector == ";"){ return true; } return false; } bool checkTest(vector<string> temp){ if (temp.at(0) == "-e"){ return fileExists(temp.at(1)); } else if (temp.at(0) == "-f"){ return regFileExists(temp.at(1)); } else if (temp.at(0) == "-d"){ return dirExists(temp.at(1)); } else{ return fileExists(temp.at(1)); } } bool fileExists(string& path){ struct stat buffer; return (stat(file, &buffer) == 0); } bool dirExists(string& path){ struct stat buffer; if (stat(path, &buffer) == 0 && S_ISDIR(buffer.st_mode)){ return true; } return false; } bool regFileExists(string& path){ struct stat buffer; if (stat(path, &buffer) == 0 && S_ISREG(buffer.st_mode)){ return true; } return false; } void execute(bool prevCommand){ if (prevCommand){ if (commandType == "&&"){ runAllCommands(); if (allCount){ commandPass = true; } else{ commandPass = false; } } else if (commandType == "||"){ commandPass = true; } else if (commandType == ";"){ runAllCommands(); commandPass = true; } else{ if (commandType == "&&"){ commandPass = false; } else if (commandType == "||"){ runAllCommands(); if (allCount){ commandPass = true; } else{ commandPass = false; } } else if (commandType == ";"){ runAllCommands(); commandPass = true; } } } }; <commit_msg>Finished test commands<commit_after>#include <string> #include <vector> #include <iostream> #include <stdlib.h> #include <cstdio> #include <sys/wait.h> #include <sys/stat.h> using namespace std; class command{ protected: vector<string> commandlist; bool commandPass; string commandType; bool allCount; string nextConnector; public: command(){} command(vector<string> c){ commandlist = c; commandType = ";"; allCount = true; nextConnector = ";" } command(vector<string> c, string t){ commandlist = c; commandType = t; allCount = true; nextConnector = ";" } bool getPass(){ return commandPass; } string getType(){ return commandType; } void runCommand(vector<string> com){ char* argv[1024]; for(unsigned int i = 0; i < com.size(); i++){ argv[i] = (char*)com.at(i).c_str(); } argv[com.size()] = NULL; pid_t pid; int status; pid = fork(); if (pid == 0){ prevCommandPass = true; execvp(argv[0], argv); perror("execvp failed: "); exit(-1); } else{ if (waitpid(pid, &status, 0) == -1){ perror("Wait: "); } if (WIFEXITED(status) && WEXITSTATUS(status) != 0){ prevCommandPass = false; } } } void runAllCommands(){ vector<string> commandsublist; unsigned int i = 0; unsigned int j = 0; while (i < commandlist.size()){ j = 0; if (checkCommandRun()){ while (!checkBreaker(i)){ //Exit check if (commandlist.at(i) == "exit"){ cout << "Forced Exit." << endl; forceExit = true; _Exit(0); } // Comment check if (commandlist.at(i) == "#" || checkComment(commandlist.at(i))){ runCommand(commandsublist); return; } if (commandlist.at(i) == "["){ i++; commandsublist.push_back(commandlist.at(i); if (commandlist.at(i) == "-e" || commandlist.at(i) == "-f" || commandlist.at(i) == "d"){ i++; commandsublist.push_back(commandlist.at(i)); } else{ i++; } if (commandlist.at(i) == "]"){ i++; checkTest(commandsublist); commandsublist.clear(); } else{ cout << "Error: Missing close bracket." << endl; _exit(1); } break; } if (commandlist.at(i) == "test"){ i++; commandsublist.push_back(commandlist.at(i)); if (commandlist.at(i) == "-e" || commandlist.at(i) == "-f" || commandlist.at(i) == "d"){ i++; commandsublist.push_back(commandlist.at(i)); } else{ i++; } checkTest(commandsublist); commandsublist.clear(); break; } //Adds command to the list commandsublist.push_back(commandlist.at(i)); i++; j++; if (i == commandlist.size()){ runCommand(commandsublist); return; } } if (commandsublist.size() > 0){ runCommand(commandsublist); commandsublist.clear(); } if (checkBreaker(i)){ if (nextConnector == "||"){ if (allCount == true){ prevCommandPass = true; } else{ if (prevCommandPass == false){ allCount = false; } else{ allCount = true; } } } else if (nextConnector == "&&"){ if (allCount == true){ if (prevCommandPass == false){ allCount = false; } } else{ allCount = false; prevCommandPass = false; } } else if (nextConnector == ";"){ if (prevCommandPass == true){ allCount = true; } else{ allCount = false; } } if (commandlist.at(i) == "|"){ nextConnector = "||"; } else if (commandlist.at(i) == "&"){ nextConnector = "&&"; } else if (commandlist.at(i) == ";"){ nextConnector = ";"; } i++; } i++; } else{ i++; } } } // Checks if there is a '#' at the front of the string bool checkComment(string str){ if (str.at(0) == '#'){ return true; } return false; } // Checks if the string is a breaker bool checkBreaker(int i){ if ( (unsigned)i < commandlist.size() + 1){ if (commandlist.at(i) == "|" && commandlist.at(i + 1) == "|"){ return true; } else if (commandlist.at(i) == "&" && commandlist.at(i + 1) == "&"){ return true; } else if (commandlist.at(i) == ";"){ return true; } else{ return false; } } else if( (unsigned)i == commandlist.size() + 1){ if(commandlist.at(i) == ";"){ return true; } return false; } else{ return false; } } // Checks if the next command should be run bool checkCommandRun(){ if (nextConnector == "||"){ if(allCount == true){ return false; } else{ return true; } } else if (nextConnector == "&&"){ if(allCount == true){ return true; } return false; } else if (nextConnector == ";"){ return true; } return false; } bool checkTest(vector<string> temp){ if (temp.at(0) == "-e"){ return fileExists(temp.at(1)); } else if (temp.at(0) == "-f"){ return regFileExists(temp.at(1)); } else if (temp.at(0) == "-d"){ return dirExists(temp.at(1)); } else{ return fileExists(temp.at(1)); } } bool fileExists(string& path){ struct stat buffer; return (stat(file, &buffer) == 0); } bool dirExists(string& path){ struct stat buffer; if (stat(path, &buffer) == 0 && S_ISDIR(buffer.st_mode)){ return true; } return false; } bool regFileExists(string& path){ struct stat buffer; if (stat(path, &buffer) == 0 && S_ISREG(buffer.st_mode)){ return true; } return false; } void execute(bool prevCommand){ if (prevCommand){ if (commandType == "&&"){ runAllCommands(); if (allCount){ commandPass = true; } else{ commandPass = false; } } else if (commandType == "||"){ commandPass = true; } else if (commandType == ";"){ runAllCommands(); commandPass = true; } else{ if (commandType == "&&"){ commandPass = false; } else if (commandType == "||"){ runAllCommands(); if (allCount){ commandPass = true; } else{ commandPass = false; } } else if (commandType == ";"){ runAllCommands(); commandPass = true; } } } }; <|endoftext|>
<commit_before><commit_msg>Add build Block cut tree<commit_after><|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // FILE: SpectralInterface.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: Interface for the Spectral LMM5 // // COPYRIGHT: University of California, San Francisco, 2009 // // LICENSE: This file is distributed under the "Lesser GPL" (LGPL) license. // License text is included with the source distribution. // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // AUTHOR: Nico Stuurman ([email protected]), 2/7/2008 // #include "SpectralLMM5Interface.h" #include "SpectralLMM5.h" #include <sstream> #include <iomanip> #ifdef WIN32 #include <winsock.h> #else #include <netinet/in.h> #endif SpectralLMM5Interface::SpectralLMM5Interface(std::string port, MM::PortType portType) : laserLinesDetected_ (false), nrLines_ (5) { port_ = port; portType_ = portType; initialized_ = true; } SpectralLMM5Interface::~SpectralLMM5Interface(){}; /* * The Spectral LMM5 has a silly difference between USB and serial communication: * Commands can be sent straight to USB. Commands to the serial port need to converted in some kind of weird ASCI: The command "0x1A0xFF0x000x12<CR>" becomes "1AFF0012<CR>". Presumably, the same weird conversion takes place on the way back. We handle this translation in this function */ int SpectralLMM5Interface::ExecuteCommand(MM::Device& device, MM::Core& core, unsigned char* buf, unsigned long bufLen, unsigned char* answer, unsigned long answerLen, unsigned long& read) { int ret; if (portType_ == MM::SerialPort) { std::string serialCommand; char tmp[3]; tmp[2] = 0; for (unsigned long i=0; i<bufLen; i++) { sprintf(tmp, "%.2x", buf[i]); serialCommand += tmp; } ret = core.SetSerialCommand(&device, port_.c_str(), serialCommand.c_str(), "\r"); } else // check for USB port { ret = core.WriteToSerial(&device, port_.c_str(), buf, bufLen); } if (ret != DEVICE_OK) return ret; if (portType_ == MM::SerialPort) { char strAnswer[128]; read = 0; ret = core.GetSerialAnswer(&device, port_.c_str(), 128, strAnswer, "\r"); if (ret != DEVICE_OK) return ret; // 'translate' back into numbers: std::string tmp = strAnswer; for (unsigned int i=0; i < tmp.length()/2; i++) { char * end; long j = strtol(tmp.substr(i*2,2).c_str(), &end, 16); answer[i] = (unsigned char) j; read++; } } else if (portType_ == MM::HIDPort) { // The USB port will attempt to read up to answerLen characters ret = core.ReadFromSerial(&device, port_.c_str(), answer, answerLen, read); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } int SpectralLMM5Interface::DetectLaserLines(MM::Device& device, MM::Core& core) { if (laserLinesDetected_) return DEVICE_OK; const unsigned long bufLen = 1; unsigned char buf[bufLen]; buf[0]=0x08; const unsigned long answerLen = 11; unsigned char answer[answerLen]; unsigned long read; int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; if (read < 8) { return ERR_UNEXPECTED_ANSWER; } uint16_t* lineP = (uint16_t*) (answer + 1); nrLines_ = (read-1)/2; printf("NrLines: %d\n", nrLines_); char outputPort = 'A'; for (int i=0; i<nrLines_; i++) { laserLines_[i].lineNr = i; laserLines_[i].waveLength = ntohs(*(lineP+i)) / 10; if (*(lineP+i) == 0) { laserLines_[i].present = false; } else { laserLines_[i].present = true; std::ostringstream os; if (laserLines_[i].waveLength > 100) { os << laserLines_[i].waveLength << "nm-" << i + 1; } else { outputPort++; os << "output-port " << outputPort; } laserLines_[i].name = os.str(); } } laserLinesDetected_ = true; return DEVICE_OK; } int SpectralLMM5Interface::SetTransmission(MM::Device& device, MM::Core& core, long laserLine, double transmission) { const unsigned long bufLen = 4; unsigned char buf[bufLen]; buf[0]=0x04; buf[1]=(unsigned char) laserLine; int16_t tr = (int16_t) (10*transmission); tr = htons(tr); memcpy(buf+2, &tr, 2); const unsigned long answerLen = 1; unsigned char answer[answerLen]; unsigned long read; int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; // See if the controller acknowledged our command if (answer[0] != 0x04) return ERR_UNEXPECTED_ANSWER; return DEVICE_OK; } int SpectralLMM5Interface::GetTransmission(MM::Device& device, MM::Core& core, long laserLine, double& transmission) { const unsigned long bufLen = 2; unsigned char buf[bufLen]; buf[0]=0x05; buf[1]= (unsigned char) laserLine; const unsigned long answerLen = 3; unsigned char answer[answerLen]; unsigned long read; int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; if (read < 3) { return ERR_UNEXPECTED_ANSWER; } // See if the controller acknowledged our command if (answer[0] != 0x05) { return ERR_UNEXPECTED_ANSWER; } int16_t tr = 0; memcpy(&tr, answer + 1, 2); tr = ntohs(tr); transmission = tr/10; std::ostringstream os; os << "Transmission for line" << laserLine << " is: " << transmission; printf("%s tr: %d\n", os.str().c_str(), tr); return DEVICE_OK; } int SpectralLMM5Interface::SetShutterState(MM::Device& device, MM::Core& core, int state) { const unsigned long bufLen = 2; unsigned char buf[bufLen]; buf[0]=0x01; buf[1]=(unsigned char) state; const unsigned long answerLen = 1; unsigned char answer[answerLen]; unsigned long read; int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; // See if the controller acknowledged our command if (answer[0] != 0x01) return ERR_UNEXPECTED_ANSWER; return DEVICE_OK; } int SpectralLMM5Interface::GetShutterState(MM::Device& device, MM::Core& core, int& state) { const unsigned long bufLen = 1; unsigned char buf[bufLen]; buf[0]=0x02; const unsigned long answerLen = 4; unsigned char answer[answerLen]; unsigned long read; int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; if (read < 2) { return ERR_UNEXPECTED_ANSWER; } // See if the controller acknowledged our command if (answer[0] != 0x02) return ERR_UNEXPECTED_ANSWER; state = (int) answer[1]; return DEVICE_OK; } int SpectralLMM5Interface::SetExposureConfig(MM::Device& device, MM::Core& core, std::string config) { unsigned char* buf; int length = (int) config.size()/2; unsigned long bufLen = length +1; unsigned long read = 0; buf = (unsigned char*) malloc(bufLen); buf[0]=0x21; for (int i=0; i<length; i++) { char * end; long j = strtol(config.substr(i*2,2).c_str(), &end, 16); buf[i+1] = (unsigned char) j; } const unsigned long answerLen = 1; unsigned char answer[answerLen]; printf ("Set Exposure confign \n"); int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; // See if the controller acknowledged our command if (answer[0] != 0x21) return ERR_UNEXPECTED_ANSWER; return DEVICE_OK; } int SpectralLMM5Interface::GetExposureConfig(MM::Device& device, MM::Core& core, std::string& config) { const unsigned long bufLen = 1; unsigned char buf[bufLen]; buf[0]=0x027; const unsigned long answerLen = 70; unsigned char answer[answerLen]; unsigned long read; printf ("Detecting Exposure Config: \n"); int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; // See if the controller acknowledged our command if (answer[0] != 0x27) return ERR_UNEXPECTED_ANSWER; config = ""; for (unsigned int i=1; i < read; i++) config += buf[i]; return DEVICE_OK; } int SpectralLMM5Interface::SetTriggerOutConfig(MM::Device& device, MM::Core& core, unsigned char * config) { const unsigned long bufLen = 5; unsigned char buf[bufLen]; unsigned long read = 0; buf[0]=0x23; memcpy(buf + 1, config, 4); const unsigned long answerLen = 10; unsigned char answer[answerLen]; printf ("Set Trigger Out \n"); int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; // See if the controller acknowledged our command if (answer[0] != 0x23) return ERR_UNEXPECTED_ANSWER; return DEVICE_OK; } int SpectralLMM5Interface::GetTriggerOutConfig(MM::Device& device, MM::Core& core, unsigned char * config) { const unsigned long bufLen = 1; unsigned char buf[bufLen]; buf[0] = 0x26; const unsigned long answerLen = 10; unsigned char answer[answerLen]; unsigned long read; printf ("Detecting Trigger out Config: \n"); int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; // See if the controller acknowledged our command if (answer[0] != 0x26) return ERR_UNEXPECTED_ANSWER; memcpy(config, answer + 1, 4); return DEVICE_OK; } int SpectralLMM5Interface::GetFirmwareVersion(MM::Device& device, MM::Core& core, std::string& version) { version.clear(); const unsigned long bufLen = 1; unsigned char buf[bufLen]; buf[0] = 0x14; const unsigned long answerLen = 256; unsigned char answer[answerLen]; unsigned long read; int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; if (answer[0] != 0x14) return ERR_UNEXPECTED_ANSWER; // The observed firmware version is a two-byte word. Make it variable-length, just in case. std::ostringstream hex_oss; hex_oss << "0x"; for (unsigned long i = 1; i < read; i++) { unsigned char byte = answer[i]; hex_oss << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned int>(byte); } version = hex_oss.str(); return DEVICE_OK; }<commit_msg>SpectralLMM5: Read two bytes for firmware version.<commit_after>/////////////////////////////////////////////////////////////////////////////// // FILE: SpectralInterface.cpp // PROJECT: Micro-Manager // SUBSYSTEM: DeviceAdapters //----------------------------------------------------------------------------- // DESCRIPTION: Interface for the Spectral LMM5 // // COPYRIGHT: University of California, San Francisco, 2009 // // LICENSE: This file is distributed under the "Lesser GPL" (LGPL) license. // License text is included with the source distribution. // // This file 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. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // AUTHOR: Nico Stuurman ([email protected]), 2/7/2008 // #include "SpectralLMM5Interface.h" #include "SpectralLMM5.h" #include <sstream> #include <iomanip> #ifdef WIN32 #include <winsock.h> #else #include <netinet/in.h> #endif SpectralLMM5Interface::SpectralLMM5Interface(std::string port, MM::PortType portType) : laserLinesDetected_ (false), nrLines_ (5) { port_ = port; portType_ = portType; initialized_ = true; } SpectralLMM5Interface::~SpectralLMM5Interface(){}; /* * The LMM5 USB HID commands are a sequence of binary bytes with no terminator. * The serial commands are the same bytes formatted as an ASCII hex string, two * characters per byte, and terminated with a CR; e.g.: * USB: "\x1a\xff\x00\x12" (4 bytes) * RS-232: "1AFF0012\r" (9 bytes) * The opposite transformation takes place for the reply. * * This function abstracts these differences. Note that the exact answerLen is * important for USB HID: reading excess bytes can result in garbage being * appended to the reply (at least on Windows). */ int SpectralLMM5Interface::ExecuteCommand(MM::Device& device, MM::Core& core, unsigned char* buf, unsigned long bufLen, unsigned char* answer, unsigned long answerLen, unsigned long& read) { int ret; if (portType_ == MM::SerialPort) { std::string serialCommand; char tmp[3]; tmp[2] = 0; for (unsigned long i=0; i<bufLen; i++) { sprintf(tmp, "%.2x", buf[i]); serialCommand += tmp; } ret = core.SetSerialCommand(&device, port_.c_str(), serialCommand.c_str(), "\r"); } else // check for USB port { ret = core.WriteToSerial(&device, port_.c_str(), buf, bufLen); } if (ret != DEVICE_OK) return ret; if (portType_ == MM::SerialPort) { char strAnswer[128]; read = 0; ret = core.GetSerialAnswer(&device, port_.c_str(), 128, strAnswer, "\r"); if (ret != DEVICE_OK) return ret; // 'translate' back into numbers: std::string tmp = strAnswer; for (unsigned int i=0; i < tmp.length()/2; i++) { char * end; long j = strtol(tmp.substr(i*2,2).c_str(), &end, 16); answer[i] = (unsigned char) j; read++; } } else if (portType_ == MM::HIDPort) { // The USB port will attempt to read up to answerLen characters ret = core.ReadFromSerial(&device, port_.c_str(), answer, answerLen, read); if (ret != DEVICE_OK) return ret; } return DEVICE_OK; } int SpectralLMM5Interface::DetectLaserLines(MM::Device& device, MM::Core& core) { if (laserLinesDetected_) return DEVICE_OK; const unsigned long bufLen = 1; unsigned char buf[bufLen]; buf[0]=0x08; const unsigned long answerLen = 11; unsigned char answer[answerLen]; unsigned long read; int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; if (read < 8) { return ERR_UNEXPECTED_ANSWER; } uint16_t* lineP = (uint16_t*) (answer + 1); nrLines_ = (read-1)/2; printf("NrLines: %d\n", nrLines_); char outputPort = 'A'; for (int i=0; i<nrLines_; i++) { laserLines_[i].lineNr = i; laserLines_[i].waveLength = ntohs(*(lineP+i)) / 10; if (*(lineP+i) == 0) { laserLines_[i].present = false; } else { laserLines_[i].present = true; std::ostringstream os; if (laserLines_[i].waveLength > 100) { os << laserLines_[i].waveLength << "nm-" << i + 1; } else { outputPort++; os << "output-port " << outputPort; } laserLines_[i].name = os.str(); } } laserLinesDetected_ = true; return DEVICE_OK; } int SpectralLMM5Interface::SetTransmission(MM::Device& device, MM::Core& core, long laserLine, double transmission) { const unsigned long bufLen = 4; unsigned char buf[bufLen]; buf[0]=0x04; buf[1]=(unsigned char) laserLine; int16_t tr = (int16_t) (10*transmission); tr = htons(tr); memcpy(buf+2, &tr, 2); const unsigned long answerLen = 1; unsigned char answer[answerLen]; unsigned long read; int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; // See if the controller acknowledged our command if (answer[0] != 0x04) return ERR_UNEXPECTED_ANSWER; return DEVICE_OK; } int SpectralLMM5Interface::GetTransmission(MM::Device& device, MM::Core& core, long laserLine, double& transmission) { const unsigned long bufLen = 2; unsigned char buf[bufLen]; buf[0]=0x05; buf[1]= (unsigned char) laserLine; const unsigned long answerLen = 3; unsigned char answer[answerLen]; unsigned long read; int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; if (read < 3) { return ERR_UNEXPECTED_ANSWER; } // See if the controller acknowledged our command if (answer[0] != 0x05) { return ERR_UNEXPECTED_ANSWER; } int16_t tr = 0; memcpy(&tr, answer + 1, 2); tr = ntohs(tr); transmission = tr/10; std::ostringstream os; os << "Transmission for line" << laserLine << " is: " << transmission; printf("%s tr: %d\n", os.str().c_str(), tr); return DEVICE_OK; } int SpectralLMM5Interface::SetShutterState(MM::Device& device, MM::Core& core, int state) { const unsigned long bufLen = 2; unsigned char buf[bufLen]; buf[0]=0x01; buf[1]=(unsigned char) state; const unsigned long answerLen = 1; unsigned char answer[answerLen]; unsigned long read; int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; // See if the controller acknowledged our command if (answer[0] != 0x01) return ERR_UNEXPECTED_ANSWER; return DEVICE_OK; } int SpectralLMM5Interface::GetShutterState(MM::Device& device, MM::Core& core, int& state) { const unsigned long bufLen = 1; unsigned char buf[bufLen]; buf[0]=0x02; const unsigned long answerLen = 4; unsigned char answer[answerLen]; unsigned long read; int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; if (read < 2) { return ERR_UNEXPECTED_ANSWER; } // See if the controller acknowledged our command if (answer[0] != 0x02) return ERR_UNEXPECTED_ANSWER; state = (int) answer[1]; return DEVICE_OK; } int SpectralLMM5Interface::SetExposureConfig(MM::Device& device, MM::Core& core, std::string config) { unsigned char* buf; int length = (int) config.size()/2; unsigned long bufLen = length +1; unsigned long read = 0; buf = (unsigned char*) malloc(bufLen); buf[0]=0x21; for (int i=0; i<length; i++) { char * end; long j = strtol(config.substr(i*2,2).c_str(), &end, 16); buf[i+1] = (unsigned char) j; } const unsigned long answerLen = 1; unsigned char answer[answerLen]; printf ("Set Exposure confign \n"); int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; // See if the controller acknowledged our command if (answer[0] != 0x21) return ERR_UNEXPECTED_ANSWER; return DEVICE_OK; } int SpectralLMM5Interface::GetExposureConfig(MM::Device& device, MM::Core& core, std::string& config) { const unsigned long bufLen = 1; unsigned char buf[bufLen]; buf[0]=0x027; const unsigned long answerLen = 70; unsigned char answer[answerLen]; unsigned long read; printf ("Detecting Exposure Config: \n"); int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; // See if the controller acknowledged our command if (answer[0] != 0x27) return ERR_UNEXPECTED_ANSWER; config = ""; for (unsigned int i=1; i < read; i++) config += buf[i]; return DEVICE_OK; } int SpectralLMM5Interface::SetTriggerOutConfig(MM::Device& device, MM::Core& core, unsigned char * config) { const unsigned long bufLen = 5; unsigned char buf[bufLen]; unsigned long read = 0; buf[0]=0x23; memcpy(buf + 1, config, 4); const unsigned long answerLen = 10; unsigned char answer[answerLen]; printf ("Set Trigger Out \n"); int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; // See if the controller acknowledged our command if (answer[0] != 0x23) return ERR_UNEXPECTED_ANSWER; return DEVICE_OK; } int SpectralLMM5Interface::GetTriggerOutConfig(MM::Device& device, MM::Core& core, unsigned char * config) { const unsigned long bufLen = 1; unsigned char buf[bufLen]; buf[0] = 0x26; const unsigned long answerLen = 10; unsigned char answer[answerLen]; unsigned long read; printf ("Detecting Trigger out Config: \n"); int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; // See if the controller acknowledged our command if (answer[0] != 0x26) return ERR_UNEXPECTED_ANSWER; memcpy(config, answer + 1, 4); return DEVICE_OK; } int SpectralLMM5Interface::GetFirmwareVersion(MM::Device& device, MM::Core& core, std::string& version) { version.clear(); const unsigned long bufLen = 1; unsigned char buf[bufLen]; buf[0] = 0x14; const unsigned long answerLen = 3; unsigned char answer[answerLen]; unsigned long read; int ret = ExecuteCommand(device, core, buf, bufLen, answer, answerLen, read); if (ret != DEVICE_OK) return ret; if (answer[0] != 0x14 || read < answerLen) return ERR_UNEXPECTED_ANSWER; // The firmware version is a two-byte word. std::ostringstream hex_oss; hex_oss << "0x"; for (unsigned long i = 1; i < read; i++) { unsigned char byte = answer[i]; hex_oss << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned int>(byte); } version = hex_oss.str(); return DEVICE_OK; } <|endoftext|>
<commit_before>#include "propagation.h" #include <lightstep_carrier.pb.h> #include <algorithm> #include <cctype> #include <cstdint> #include <functional> #include <iomanip> #include <ios> #include <sstream> namespace lightstep { #define PREFIX_TRACER_STATE "ot-tracer-" // Note: these constants are a convention of the OpenTracing basictracers. const opentracing::string_view PrefixBaggage = "ot-baggage-"; const int FieldCount = 3; const opentracing::string_view FieldNameTraceID = PREFIX_TRACER_STATE "traceid"; const opentracing::string_view FieldNameSpanID = PREFIX_TRACER_STATE "spanid"; const opentracing::string_view FieldNameSampled = PREFIX_TRACER_STATE "sampled"; #undef PREFIX_TRACER_STATE //------------------------------------------------------------------------------ // Uint64ToHex //------------------------------------------------------------------------------ static std::string Uint64ToHex(uint64_t u) { std::stringstream ss; ss << std::setfill('0') << std::setw(16) << std::hex << u; return ss.str(); } //------------------------------------------------------------------------------ // HexToUint64 //------------------------------------------------------------------------------ static uint64_t HexToUint64(const std::string& s) { std::stringstream ss(s); uint64_t x; ss >> std::setw(16) >> std::hex >> x; return x; } //------------------------------------------------------------------------------ // InjectSpanContext //------------------------------------------------------------------------------ static opentracing::expected<void> InjectSpanContext( BinaryCarrier& carrier, uint64_t trace_id, uint64_t span_id, const std::unordered_map<std::string, std::string>& baggage) noexcept try { carrier.Clear(); auto basic = carrier.mutable_basic_ctx(); basic->set_trace_id(trace_id); basic->set_span_id(span_id); basic->set_sampled(true); auto mutable_baggage = basic->mutable_baggage_items(); for (auto& baggage_item : baggage) { (*mutable_baggage)[baggage_item.first] = baggage_item.second; } return {}; } catch (const std::bad_alloc&) { return opentracing::make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } opentracing::expected<void> InjectSpanContext( std::ostream& carrier, uint64_t trace_id, uint64_t span_id, const std::unordered_map<std::string, std::string>& baggage) { BinaryCarrier binary_carrier; auto result = InjectSpanContext(binary_carrier, trace_id, span_id, baggage); if (!result) { return result; } if (!binary_carrier.SerializeToOstream(&carrier)) { return opentracing::make_unexpected( std::make_error_code(std::io_errc::stream)); } // Flush so that when we call carrier.good, we'll get an accurate view of the // error state. carrier.flush(); if (!carrier.good()) { return opentracing::make_unexpected( std::make_error_code(std::io_errc::stream)); } return {}; } opentracing::expected<void> InjectSpanContext( const opentracing::TextMapWriter& carrier, uint64_t trace_id, uint64_t span_id, const std::unordered_map<std::string, std::string>& baggage) { std::string trace_id_hex, span_id_hex, baggage_key; try { trace_id_hex = Uint64ToHex(trace_id); span_id_hex = Uint64ToHex(span_id); baggage_key = PrefixBaggage; } catch (const std::bad_alloc&) { return opentracing::make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } auto result = carrier.Set(FieldNameTraceID, trace_id_hex); if (!result) { return result; } result = carrier.Set(FieldNameSpanID, span_id_hex); if (!result) { return result; } result = carrier.Set(FieldNameSampled, "true"); if (!result) { return result; } for (const auto& baggage_item : baggage) { try { baggage_key.replace(std::begin(baggage_key) + PrefixBaggage.size(), std::end(baggage_key), baggage_item.first); } catch (const std::bad_alloc&) { return opentracing::make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } result = carrier.Set(baggage_key, baggage_item.second); if (!result) { return result; } } return {}; } //------------------------------------------------------------------------------ // ExtractSpanContext //------------------------------------------------------------------------------ static opentracing::expected<bool> ExtractSpanContext( const BinaryCarrier& carrier, uint64_t& trace_id, uint64_t& span_id, std::unordered_map<std::string, std::string>& baggage) noexcept try { auto& basic = carrier.basic_ctx(); trace_id = basic.trace_id(); span_id = basic.span_id(); for (const auto& entry : basic.baggage_items()) { baggage.emplace(entry.first, entry.second); } return true; } catch (const std::bad_alloc&) { return opentracing::make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } opentracing::expected<bool> ExtractSpanContext( std::istream& carrier, uint64_t& trace_id, uint64_t& span_id, std::unordered_map<std::string, std::string>& baggage) try { // istream::peek returns EOF if it's in an error state, so check for an error // state first before checking for an empty stream. if (!carrier.good()) { return opentracing::make_unexpected( std::make_error_code(std::io_errc::stream)); } // Check for the case when no span is encoded. if (carrier.peek() == EOF) { return false; } BinaryCarrier binary_carrier; if (!binary_carrier.ParseFromIstream(&carrier)) { return false; } return ExtractSpanContext(binary_carrier, trace_id, span_id, baggage); } catch (const std::bad_alloc&) { return opentracing::make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } template <class KeyCompare> static opentracing::expected<bool> ExtractSpanContext( const opentracing::TextMapReader& carrier, uint64_t& trace_id, uint64_t& span_id, std::unordered_map<std::string, std::string>& baggage, KeyCompare key_compare) { int count = 0; auto result = carrier.ForeachKey( [&](opentracing::string_view key, opentracing::string_view value) -> opentracing::expected<void> { try { if (key_compare(key, FieldNameTraceID)) { trace_id = HexToUint64(value); count++; } else if (key_compare(key, FieldNameSpanID)) { span_id = HexToUint64(value); count++; } else if (key_compare(key, FieldNameSampled)) { // Ignored count++; } else if (key.length() > PrefixBaggage.size() && key_compare(opentracing::string_view{key.data(), PrefixBaggage.size()}, PrefixBaggage)) { baggage.emplace(std::string{std::begin(key) + PrefixBaggage.size(), std::end(key)}, value); } return {}; } catch (const std::bad_alloc&) { return opentracing::make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } }); if (!result) { return opentracing::make_unexpected(result.error()); } if (count == 0) { return false; } if (count > 0 && count != FieldCount) { return opentracing::make_unexpected( opentracing::span_context_corrupted_error); } return true; } opentracing::expected<bool> ExtractSpanContext( const opentracing::TextMapReader& carrier, uint64_t& trace_id, uint64_t& span_id, std::unordered_map<std::string, std::string>& baggage) { return ExtractSpanContext(carrier, trace_id, span_id, baggage, std::equal_to<opentracing::string_view>()); } // HTTP header field names are case insensitive, so we need to ignore case when // comparing against the OpenTracing field names. // // See https://stackoverflow.com/a/5259004/4447365 opentracing::expected<bool> ExtractSpanContext( const opentracing::HTTPHeadersReader& carrier, uint64_t& trace_id, uint64_t& span_id, std::unordered_map<std::string, std::string>& baggage) { auto iequals = [](opentracing::string_view lhs, opentracing::string_view rhs) { return lhs.length() == rhs.length() && std::equal(std::begin(lhs), std::end(lhs), std::begin(rhs), [](char a, char b) { return std::tolower(a) == std::tolower(b); }); }; return ExtractSpanContext(carrier, trace_id, span_id, baggage, iequals); } } // namespace lightstep <commit_msg>s/std::io_errc::stream/std::errc::io_error/<commit_after>#include "propagation.h" #include <lightstep_carrier.pb.h> #include <algorithm> #include <cctype> #include <cstdint> #include <functional> #include <iomanip> #include <ios> #include <sstream> namespace lightstep { #define PREFIX_TRACER_STATE "ot-tracer-" // Note: these constants are a convention of the OpenTracing basictracers. const opentracing::string_view PrefixBaggage = "ot-baggage-"; const int FieldCount = 3; const opentracing::string_view FieldNameTraceID = PREFIX_TRACER_STATE "traceid"; const opentracing::string_view FieldNameSpanID = PREFIX_TRACER_STATE "spanid"; const opentracing::string_view FieldNameSampled = PREFIX_TRACER_STATE "sampled"; #undef PREFIX_TRACER_STATE //------------------------------------------------------------------------------ // Uint64ToHex //------------------------------------------------------------------------------ static std::string Uint64ToHex(uint64_t u) { std::stringstream ss; ss << std::setfill('0') << std::setw(16) << std::hex << u; return ss.str(); } //------------------------------------------------------------------------------ // HexToUint64 //------------------------------------------------------------------------------ static uint64_t HexToUint64(const std::string& s) { std::stringstream ss(s); uint64_t x; ss >> std::setw(16) >> std::hex >> x; return x; } //------------------------------------------------------------------------------ // InjectSpanContext //------------------------------------------------------------------------------ static opentracing::expected<void> InjectSpanContext( BinaryCarrier& carrier, uint64_t trace_id, uint64_t span_id, const std::unordered_map<std::string, std::string>& baggage) noexcept try { carrier.Clear(); auto basic = carrier.mutable_basic_ctx(); basic->set_trace_id(trace_id); basic->set_span_id(span_id); basic->set_sampled(true); auto mutable_baggage = basic->mutable_baggage_items(); for (auto& baggage_item : baggage) { (*mutable_baggage)[baggage_item.first] = baggage_item.second; } return {}; } catch (const std::bad_alloc&) { return opentracing::make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } opentracing::expected<void> InjectSpanContext( std::ostream& carrier, uint64_t trace_id, uint64_t span_id, const std::unordered_map<std::string, std::string>& baggage) { BinaryCarrier binary_carrier; auto result = InjectSpanContext(binary_carrier, trace_id, span_id, baggage); if (!result) { return result; } if (!binary_carrier.SerializeToOstream(&carrier)) { return opentracing::make_unexpected( std::make_error_code(std::errc::io_error)); } // Flush so that when we call carrier.good, we'll get an accurate view of the // error state. carrier.flush(); if (!carrier.good()) { return opentracing::make_unexpected( std::make_error_code(std::errc::io_error)); } return {}; } opentracing::expected<void> InjectSpanContext( const opentracing::TextMapWriter& carrier, uint64_t trace_id, uint64_t span_id, const std::unordered_map<std::string, std::string>& baggage) { std::string trace_id_hex, span_id_hex, baggage_key; try { trace_id_hex = Uint64ToHex(trace_id); span_id_hex = Uint64ToHex(span_id); baggage_key = PrefixBaggage; } catch (const std::bad_alloc&) { return opentracing::make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } auto result = carrier.Set(FieldNameTraceID, trace_id_hex); if (!result) { return result; } result = carrier.Set(FieldNameSpanID, span_id_hex); if (!result) { return result; } result = carrier.Set(FieldNameSampled, "true"); if (!result) { return result; } for (const auto& baggage_item : baggage) { try { baggage_key.replace(std::begin(baggage_key) + PrefixBaggage.size(), std::end(baggage_key), baggage_item.first); } catch (const std::bad_alloc&) { return opentracing::make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } result = carrier.Set(baggage_key, baggage_item.second); if (!result) { return result; } } return {}; } //------------------------------------------------------------------------------ // ExtractSpanContext //------------------------------------------------------------------------------ static opentracing::expected<bool> ExtractSpanContext( const BinaryCarrier& carrier, uint64_t& trace_id, uint64_t& span_id, std::unordered_map<std::string, std::string>& baggage) noexcept try { auto& basic = carrier.basic_ctx(); trace_id = basic.trace_id(); span_id = basic.span_id(); for (const auto& entry : basic.baggage_items()) { baggage.emplace(entry.first, entry.second); } return true; } catch (const std::bad_alloc&) { return opentracing::make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } opentracing::expected<bool> ExtractSpanContext( std::istream& carrier, uint64_t& trace_id, uint64_t& span_id, std::unordered_map<std::string, std::string>& baggage) try { // istream::peek returns EOF if it's in an error state, so check for an error // state first before checking for an empty stream. if (!carrier.good()) { return opentracing::make_unexpected( std::make_error_code(std::errc::io_error)); } // Check for the case when no span is encoded. if (carrier.peek() == EOF) { return false; } BinaryCarrier binary_carrier; if (!binary_carrier.ParseFromIstream(&carrier)) { return false; } return ExtractSpanContext(binary_carrier, trace_id, span_id, baggage); } catch (const std::bad_alloc&) { return opentracing::make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } template <class KeyCompare> static opentracing::expected<bool> ExtractSpanContext( const opentracing::TextMapReader& carrier, uint64_t& trace_id, uint64_t& span_id, std::unordered_map<std::string, std::string>& baggage, KeyCompare key_compare) { int count = 0; auto result = carrier.ForeachKey( [&](opentracing::string_view key, opentracing::string_view value) -> opentracing::expected<void> { try { if (key_compare(key, FieldNameTraceID)) { trace_id = HexToUint64(value); count++; } else if (key_compare(key, FieldNameSpanID)) { span_id = HexToUint64(value); count++; } else if (key_compare(key, FieldNameSampled)) { // Ignored count++; } else if (key.length() > PrefixBaggage.size() && key_compare(opentracing::string_view{key.data(), PrefixBaggage.size()}, PrefixBaggage)) { baggage.emplace(std::string{std::begin(key) + PrefixBaggage.size(), std::end(key)}, value); } return {}; } catch (const std::bad_alloc&) { return opentracing::make_unexpected( std::make_error_code(std::errc::not_enough_memory)); } }); if (!result) { return opentracing::make_unexpected(result.error()); } if (count == 0) { return false; } if (count > 0 && count != FieldCount) { return opentracing::make_unexpected( opentracing::span_context_corrupted_error); } return true; } opentracing::expected<bool> ExtractSpanContext( const opentracing::TextMapReader& carrier, uint64_t& trace_id, uint64_t& span_id, std::unordered_map<std::string, std::string>& baggage) { return ExtractSpanContext(carrier, trace_id, span_id, baggage, std::equal_to<opentracing::string_view>()); } // HTTP header field names are case insensitive, so we need to ignore case when // comparing against the OpenTracing field names. // // See https://stackoverflow.com/a/5259004/4447365 opentracing::expected<bool> ExtractSpanContext( const opentracing::HTTPHeadersReader& carrier, uint64_t& trace_id, uint64_t& span_id, std::unordered_map<std::string, std::string>& baggage) { auto iequals = [](opentracing::string_view lhs, opentracing::string_view rhs) { return lhs.length() == rhs.length() && std::equal(std::begin(lhs), std::end(lhs), std::begin(rhs), [](char a, char b) { return std::tolower(a) == std::tolower(b); }); }; return ExtractSpanContext(carrier, trace_id, span_id, baggage, iequals); } } // namespace lightstep <|endoftext|>
<commit_before>#include <libmesh/libmesh.h> #include <libmesh/replicated_mesh.h> #include <libmesh/elem.h> #include <libmesh/mesh_generation.h> #include <libmesh/mesh_modification.h> #include <libmesh/boundary_info.h> #include "test_comm.h" #include "libmesh_cppunit.h" using namespace libMesh; class AllTriTest : public CppUnit::TestCase { /** * The goal of this test is to verify proper operation of the Mesh Extruder * with the optional object callback for setting custom subdomain IDs. * We pass a custom object for generating subdomains based on the old element * ID and the current layer and assert the proper values. */ public: LIBMESH_CPPUNIT_TEST_SUITE( AllTriTest ); // 2D tests #if LIBMESH_DIM > 1 CPPUNIT_TEST( testAllTriTri ); CPPUNIT_TEST( testAllTriQuad ); CPPUNIT_TEST( testAllTriQuad8 ); CPPUNIT_TEST( testAllTriQuad9 ); #endif // 3D tests #if LIBMESH_DIM > 2 CPPUNIT_TEST( testAllTriPrism6 ); CPPUNIT_TEST( testAllTriPrism18 ); #endif CPPUNIT_TEST_SUITE_END(); protected: // Helper function called by the test implementations, saves a few lines of code. void test_helper_2D(ElemType elem_type, dof_id_type n_elem_expected, std::size_t n_boundary_conds_expected) { ReplicatedMesh mesh(*TestCommWorld, /*dim=*/2); // Build a 2x1 TRI3 mesh and ask to split it into triangles. // Should be a no-op MeshTools::Generation::build_square(mesh, /*nx=*/2, /*ny=*/1, /*xmin=*/0., /*xmax=*/1., /*ymin=*/0., /*ymax=*/1., elem_type); MeshTools::Modification::all_tri(mesh); // Make sure that the expected number of elements is found. CPPUNIT_ASSERT_EQUAL(n_elem_expected, mesh.n_elem()); // Make sure the expected number of BCs is found. CPPUNIT_ASSERT_EQUAL(n_boundary_conds_expected, mesh.get_boundary_info().n_boundary_conds()); } // Helper function called by the test implementations in 3D, saves a few lines of code. void test_helper_3D(ElemType elem_type, dof_id_type n_elem_expected, std::size_t n_boundary_conds_expected) { ReplicatedMesh mesh(*TestCommWorld, /*dim=*/3); // Build a 2x1 TRI3 mesh and ask to split it into triangles. // Should be a no-op MeshTools::Generation::build_cube(mesh, /*nx=*/1, /*ny=*/1, /*nz=*/1, /*xmin=*/0., /*xmax=*/1., /*ymin=*/0., /*ymax=*/1., /*zmin=*/0., /*zmax=*/1., elem_type); MeshTools::Modification::all_tri(mesh); // Make sure that the expected number of elements is found. CPPUNIT_ASSERT_EQUAL(n_elem_expected, mesh.n_elem()); // Make sure the expected number of BCs is found. CPPUNIT_ASSERT_EQUAL(n_boundary_conds_expected, mesh.get_boundary_info().n_boundary_conds()); } public: void setUp() {} void tearDown() {} // 4 TRIs no-op void testAllTriTri() { LOG_UNIT_TEST; test_helper_2D(TRI3, /*nelem=*/4, /*nbcs=*/6); } // 2 quads split into 4 TRIs. void testAllTriQuad() { LOG_UNIT_TEST; test_helper_2D(QUAD4, /*nelem=*/4, /*nbcs=*/6); } // 2 QUAD8s split into 4 TRIs. void testAllTriQuad8() { LOG_UNIT_TEST; test_helper_2D(QUAD8, /*nelem=*/4, /*nbcs=*/6); } // 2 QUAD9s split into 4 TRIs. void testAllTriQuad9() { LOG_UNIT_TEST; test_helper_2D(QUAD9, /*nelem=*/4, /*nbcs=*/6); } // 2 PRISM6s split into 6 TETs with 2 boundary faces per side. void testAllTriPrism6() { LOG_UNIT_TEST; test_helper_3D(PRISM6, /*nelem=*/6, /*nbcs=*/12); } // 2 PRISM6s split into 6 TETs with 2 boundary faces per side. void testAllTriPrism18() { LOG_UNIT_TEST; test_helper_3D(PRISM18, /*nelem=*/6, /*nbcs=*/12); } }; CPPUNIT_TEST_SUITE_REGISTRATION( AllTriTest ); <commit_msg>Test all_tri() with PRISM20+21<commit_after>#include <libmesh/libmesh.h> #include <libmesh/replicated_mesh.h> #include <libmesh/elem.h> #include <libmesh/mesh_generation.h> #include <libmesh/mesh_modification.h> #include <libmesh/boundary_info.h> #include "test_comm.h" #include "libmesh_cppunit.h" using namespace libMesh; class AllTriTest : public CppUnit::TestCase { /** * The goal of this test is to verify proper operation of the Mesh Extruder * with the optional object callback for setting custom subdomain IDs. * We pass a custom object for generating subdomains based on the old element * ID and the current layer and assert the proper values. */ public: LIBMESH_CPPUNIT_TEST_SUITE( AllTriTest ); // 2D tests #if LIBMESH_DIM > 1 CPPUNIT_TEST( testAllTriTri ); CPPUNIT_TEST( testAllTriQuad ); CPPUNIT_TEST( testAllTriQuad8 ); CPPUNIT_TEST( testAllTriQuad9 ); #endif // 3D tests #if LIBMESH_DIM > 2 CPPUNIT_TEST( testAllTriPrism6 ); CPPUNIT_TEST( testAllTriPrism18 ); CPPUNIT_TEST( testAllTriPrism20 ); CPPUNIT_TEST( testAllTriPrism21 ); #endif CPPUNIT_TEST_SUITE_END(); protected: // Helper function called by the test implementations, saves a few lines of code. void test_helper_2D(ElemType elem_type, dof_id_type n_elem_expected, std::size_t n_boundary_conds_expected) { ReplicatedMesh mesh(*TestCommWorld, /*dim=*/2); // Build a 2x1 TRI3 mesh and ask to split it into triangles. // Should be a no-op MeshTools::Generation::build_square(mesh, /*nx=*/2, /*ny=*/1, /*xmin=*/0., /*xmax=*/1., /*ymin=*/0., /*ymax=*/1., elem_type); MeshTools::Modification::all_tri(mesh); // Make sure that the expected number of elements is found. CPPUNIT_ASSERT_EQUAL(n_elem_expected, mesh.n_elem()); // Make sure the expected number of BCs is found. CPPUNIT_ASSERT_EQUAL(n_boundary_conds_expected, mesh.get_boundary_info().n_boundary_conds()); } // Helper function called by the test implementations in 3D, saves a few lines of code. void test_helper_3D(ElemType elem_type, dof_id_type n_elem_expected, std::size_t n_boundary_conds_expected) { ReplicatedMesh mesh(*TestCommWorld, /*dim=*/3); // Build a 2x1 TRI3 mesh and ask to split it into triangles. // Should be a no-op MeshTools::Generation::build_cube(mesh, /*nx=*/1, /*ny=*/1, /*nz=*/1, /*xmin=*/0., /*xmax=*/1., /*ymin=*/0., /*ymax=*/1., /*zmin=*/0., /*zmax=*/1., elem_type); MeshTools::Modification::all_tri(mesh); // Make sure that the expected number of elements is found. CPPUNIT_ASSERT_EQUAL(n_elem_expected, mesh.n_elem()); // Make sure the expected number of BCs is found. CPPUNIT_ASSERT_EQUAL(n_boundary_conds_expected, mesh.get_boundary_info().n_boundary_conds()); } public: void setUp() {} void tearDown() {} // 4 TRIs no-op void testAllTriTri() { LOG_UNIT_TEST; test_helper_2D(TRI3, /*nelem=*/4, /*nbcs=*/6); } // 2 quads split into 4 TRIs. void testAllTriQuad() { LOG_UNIT_TEST; test_helper_2D(QUAD4, /*nelem=*/4, /*nbcs=*/6); } // 2 QUAD8s split into 4 TRIs. void testAllTriQuad8() { LOG_UNIT_TEST; test_helper_2D(QUAD8, /*nelem=*/4, /*nbcs=*/6); } // 2 QUAD9s split into 4 TRIs. void testAllTriQuad9() { LOG_UNIT_TEST; test_helper_2D(QUAD9, /*nelem=*/4, /*nbcs=*/6); } // 2 PRISMs split into 6 TETs with 2 boundary faces per side. void testAllTriPrism6() { LOG_UNIT_TEST; test_helper_3D(PRISM6, /*nelem=*/6, /*nbcs=*/12); } void testAllTriPrism18() { LOG_UNIT_TEST; test_helper_3D(PRISM18, /*nelem=*/6, /*nbcs=*/12); } void testAllTriPrism20() { LOG_UNIT_TEST; test_helper_3D(PRISM20, /*nelem=*/6, /*nbcs=*/12); } void testAllTriPrism21() { LOG_UNIT_TEST; test_helper_3D(PRISM21, /*nelem=*/6, /*nbcs=*/12); } }; CPPUNIT_TEST_SUITE_REGISTRATION( AllTriTest ); <|endoftext|>
<commit_before>#include <stdlib.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include <stdio.h> #include <new> #include "phashmap.h" #include "kbench.h" #include "time.h" #define SIZE 1000000 #define NUMEL 100000000 int size; int main(int argc, char *argv[]){ if (argc > 1) size = atoi(argv[1]); else size = SIZE; testInsert(); return 0; } void testInsert(){ printf("Testing live data... \nTesting insertion... "); fflush(stdout); FILE *paths; paths = fopen("test.data", "r") ; //paths = fopen("/home/kevin/Library.pla","r"); if (paths == NULL){ printf("File open failure\n"); return; } int n =NUMEL; clock_t a=clock(); //phashmap map ((char *) "hash.table", size); phashmap *map = new phashmap((char *) "hash.table", size, 10000, 2/3); char ** list = (char **) calloc(n, sizeof(char*)); char f[300]; int count = 0; while (fscanf(paths, "%s", f) != EOF){ list[count] = (char *)calloc(300, sizeof(char)); strcpy(list[count],f); count++; } clock_t begin=clock(); while (count > 0){ //char *z; //z = (char*) calloc(300,sizeof(char)); char* z = new char[300]; sprintf(z, "%d", NUMEL-count+1); //strcpy(z,f); map->put(list[count-1],z); //map.put(z,n); n--; count--; //if(n%1000==0) {printf("."); fflush(stdout);} } fclose(paths); printf("PASSED\n"); clock_t end=clock(); free(list); testGet(*map); printf("Insertion Time: %f\n", diffclock(end, begin)); printf("Alloc Time: %f\n", diffclock(begin,a)); //delete map; map = NULL; //free (map); } void testGet(phashmap map){ clock_t begin=clock(); FILE *oth; printf("Testing retrieval... "); fflush(stdout); oth = fopen("test.data", "r"); //oth = fopen("/home/kevin/Library.pla","r"); if (oth == NULL){ printf("File open failure\n"); return; } int n =NUMEL; char f[300]; while (fscanf(oth, "%s", f) != EOF){ //printf("Checking %s... ", f); if (atoi(map.get(f)) != n){ printf("FAILED\n"); printf("%s,%s,%d\n",f,map.get(f), n); return; } else{ //printf("Found\n"); } n--; } //delete [] f; fclose(oth); printf("PASSED\n"); clock_t end=clock(); testRemove2(map); printf("Retrieval time: %f\n", diffclock(end, begin)); } void testRemove(phashmap map){ clock_t beg=clock(); FILE *oth; printf("Testing removal... "); fflush(stdout); oth = fopen("test.data", "r"); //oth = fopen("/home/kevin/Library.pla","r"); if (oth == NULL){ printf("File open failure\n"); return; } int n =NUMEL; char f[300]; int start = map.getSize(); while (fscanf(oth, "%s", f) != EOF){ //printf("Removing %s... ", f); //map.remove(f); if (n%1==0) {map.remove(f); /*printf(".");fflush(stdout);*/} /* if (map.get(f) != n){ printf("FAILED\n"); printf("%s,%d,%d\n",f,map.get(f), n); return; } else{ printf("Removed\n"); }*/ n--; } fclose(oth); printf("PASSED\n"); clock_t end=clock(); printf("Inserted: %d\nRemoved: %d\n", start, start-map.getSize()); printf("Removal Time: %f\n", diffclock(end,beg)); } void testRemove2(phashmap map){ FILE *oth; printf("Testing removal... "); fflush(stdout); oth = fopen("test.data", "r"); //oth = fopen("/home/kevin/Library.pla","r"); if (oth == NULL){ printf("File open failure\n"); return; } int n =NUMEL; char ** list = (char **) calloc(map.getSize(), sizeof(char*)); char f[300]; int count = 0; while (fscanf(oth, "%s", f) != EOF){ list[count] = (char *)calloc(300, sizeof(char)); strcpy(list[count],f); count++; } clock_t beg=clock(); //for (int x =count-1; x>=0 ; x--){ for (int x = 0; x < count; x++){ //map.remove(list[count-x]); //free(list[count-x]); map.remove(list[x]); free(list[x]); } //for(int i = count-1; i>=0; i--){ // free(list[i]); //} free(list); fclose(oth); printf("PASSED\n"); clock_t end=clock(); printf("Inserted: %d\nRemoved: %d\n",count, count-map.getSize()); printf("Removal Time: %f\n", diffclock(end,beg)); } double diffclock(clock_t clock1, clock_t clock2){ double clock_ts=clock1-clock2; double diffms=(clock_ts*1000)/CLOCKS_PER_SEC; return diffms; } <commit_msg> modified: kbench.cxx<commit_after>#include <stdlib.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include <stdio.h> #include <new> #include "phashmap.h" #include "kbench.h" #include "time.h" #define SIZE 1000000 #define NUMEL 100000000 int size; int main(int argc, char *argv[]){ if (argc > 1) size = atoi(argv[1]); else size = SIZE; testInsert(); return 0; } void testInsert(){ printf("Testing live data... \nTesting insertion... "); fflush(stdout); FILE *paths; paths = fopen("test.data", "r") ; if (paths == NULL){ printf("File open failure\n"); return; } int n =NUMEL; clock_t a=clock(); phashmap *map = new phashmap((char *) "hash.table", size, 10000, 2/3); char ** list = (char **) calloc(n, sizeof(char*)); char f[300]; int count = 0; while (fscanf(paths, "%s", f) != EOF){ list[count] = (char *)calloc(300, sizeof(char)); strcpy(list[count],f); count++; } clock_t begin=clock(); while (count > 0){ //char *z; //z = (char*) calloc(300,sizeof(char)); char* z = new char[300]; sprintf(z, "%d", NUMEL-count+1); //strcpy(z,f); map->put(list[count-1],z); //map.put(z,n); n--; count--; //if(n%1000==0) {printf("."); fflush(stdout);} } fclose(paths); printf("PASSED\n"); clock_t end=clock(); free(list); testGet(*map); printf("Insertion Time: %f\n", diffclock(end, begin)); printf("Alloc Time: %f\n", diffclock(begin,a)); //delete map; map = NULL; //free (map); } void testGet(phashmap map){ clock_t begin=clock(); FILE *oth; printf("Testing retrieval... "); fflush(stdout); oth = fopen("test.data", "r"); //oth = fopen("/home/kevin/Library.pla","r"); if (oth == NULL){ printf("File open failure\n"); return; } int n =NUMEL; char f[300]; while (fscanf(oth, "%s", f) != EOF){ //printf("Checking %s... ", f); if (atoi(map.get(f)) != n){ printf("FAILED\n"); printf("%s,%s,%d\n",f,map.get(f), n); return; } else{ //printf("Found\n"); } n--; } //delete [] f; fclose(oth); printf("PASSED\n"); clock_t end=clock(); testRemove2(map); printf("Retrieval time: %f\n", diffclock(end, begin)); } void testRemove(phashmap map){ clock_t beg=clock(); FILE *oth; printf("Testing removal... "); fflush(stdout); oth = fopen("test.data", "r"); //oth = fopen("/home/kevin/Library.pla","r"); if (oth == NULL){ printf("File open failure\n"); return; } int n =NUMEL; char f[300]; int start = map.getSize(); while (fscanf(oth, "%s", f) != EOF){ //printf("Removing %s... ", f); //map.remove(f); if (n%1==0) {map.remove(f); /*printf(".");fflush(stdout);*/} /* if (map.get(f) != n){ printf("FAILED\n"); printf("%s,%d,%d\n",f,map.get(f), n); return; } else{ printf("Removed\n"); }*/ n--; } fclose(oth); printf("PASSED\n"); clock_t end=clock(); printf("Inserted: %d\nRemoved: %d\n", start, start-map.getSize()); printf("Removal Time: %f\n", diffclock(end,beg)); } void testRemove2(phashmap map){ FILE *oth; printf("Testing removal... "); fflush(stdout); oth = fopen("test.data", "r"); //oth = fopen("/home/kevin/Library.pla","r"); if (oth == NULL){ printf("File open failure\n"); return; } int n =NUMEL; char ** list = (char **) calloc(map.getSize(), sizeof(char*)); char f[300]; int count = 0; while (fscanf(oth, "%s", f) != EOF){ list[count] = (char *)calloc(300, sizeof(char)); strcpy(list[count],f); count++; } clock_t beg=clock(); //for (int x =count-1; x>=0 ; x--){ for (int x = 0; x < count; x++){ //map.remove(list[count-x]); //free(list[count-x]); map.remove(list[x]); free(list[x]); } //for(int i = count-1; i>=0; i--){ // free(list[i]); //} free(list); fclose(oth); printf("PASSED\n"); clock_t end=clock(); printf("Inserted: %d\nRemoved: %d\n",count, count-map.getSize()); printf("Removal Time: %f\n", diffclock(end,beg)); } double diffclock(clock_t clock1, clock_t clock2){ double clock_ts=clock1-clock2; double diffms=(clock_ts*1000)/CLOCKS_PER_SEC; return diffms; } <|endoftext|>
<commit_before>//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // fpcmp is a tool that basically works like the 'cmp' tool, except that it can // tolerate errors due to floating point noise, with the -r option. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/System/MappedFile.h" #include <iostream> #include <cmath> using namespace llvm; namespace { cl::opt<std::string> File1(cl::Positional, cl::desc("<input file #1>"), cl::Required); cl::opt<std::string> File2(cl::Positional, cl::desc("<input file #2>"), cl::Required); cl::opt<double> RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0)); cl::opt<double> AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0)); } static bool isNumberChar(char C) { switch (C) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case '+': case '-': case 'e': case 'E': return true; default: return false; } } static char *BackupNumber(char *Pos, char *FirstChar) { // If we didn't stop in the middle of a number, don't backup. if (!isNumberChar(*Pos)) return Pos; // Otherwise, return to the start of the number. while (Pos > FirstChar && isNumberChar(Pos[-1])) --Pos; return Pos; } static void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) { char *F1NumEnd, *F2NumEnd; double V1 = 0.0, V2 = 0.0; // If we stop on numbers, compare their difference. if (isNumberChar(*F1P) && isNumberChar(*F2P)) { V1 = strtod(F1P, &F1NumEnd); V2 = strtod(F2P, &F2NumEnd); } else { // Otherwise, the diff failed. F1NumEnd = F1P; F2NumEnd = F2P; } if (F1NumEnd == F1P || F2NumEnd == F2P) { std::cerr << "Comparison failed, not a numeric difference.\n"; exit(1); } // Check to see if these are inside the absolute tolerance if (AbsTolerance < std::abs(V1-V2)) { // Nope, check the relative tolerance... double Diff; if (V2) Diff = std::abs(V1/V2 - 1.0); else if (V1) Diff = std::abs(V2/V1 - 1.0); else Diff = 0; // Both zero. if (Diff > RelTolerance) { std::cerr << "Compared: " << V1 << " and " << V2 << ": diff = " << Diff << "\n"; std::cerr << "Out of tolerance: rel/abs: " << RelTolerance << "/" << AbsTolerance << "\n"; exit(1); } } // Otherwise, advance our read pointers to the end of the numbers. F1P = F1NumEnd; F2P = F2NumEnd; } // PadFileIfNeeded - If the files are not identical, we will have to be doing // numeric comparisons in here. There are bad cases involved where we (i.e., // strtod) might run off the beginning or end of the file if it starts or ends // with a number. Because of this, if needed, we pad the file so that it starts // and ends with a null character. static void PadFileIfNeeded(char *&FileStart, char *&FileEnd, char *&FP) { if (isNumberChar(FileStart[0]) || isNumberChar(FileEnd[-1])) { unsigned FileLen = FileEnd-FileStart; char *NewFile = new char[FileLen+2]; NewFile[0] = 0; // Add null padding NewFile[FileLen+1] = 0; // Add null padding memcpy(NewFile+1, FileStart, FileLen); FP = NewFile+(FP-FileStart)+1; FileStart = NewFile+1; FileEnd = FileStart+FileLen; } } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); try { // map in the files into memory sys::Path F1Path(File1); sys::Path F2Path(File2); sys::MappedFile F1 ( F1Path ); sys::MappedFile F2 ( F2Path ); F1.map(); F2.map(); // Okay, now that we opened the files, scan them for the first difference. char *File1Start = F1.charBase(); char *File2Start = F2.charBase(); char *File1End = File1Start+F1.size(); char *File2End = File2Start+F2.size(); char *F1P = File1Start; char *F2P = File2Start; // Scan for the end of file or first difference. while (F1P < File1End && F2P < File2End && *F1P == *F2P) ++F1P, ++F2P; // Common case: identifical files. if (F1P == File1End && F2P == File2End) return 0; // If the files need padding, do so now. PadFileIfNeeded(File1Start, File1End, F1P); PadFileIfNeeded(File2Start, File2End, F2P); while (1) { // Scan for the end of file or next difference. while (F1P < File1End && F2P < File2End && *F1P == *F2P) ++F1P, ++F2P; if (F1P >= File1End || F2P >= File2End) break; // Okay, we must have found a difference. Backup to the start of the // current number each stream is at so that we can compare from the // beginning. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); } // Okay, we reached the end of file. If both files are at the end, we // succeeded. bool F1AtEnd = F1P >= File1End; bool F2AtEnd = F2P >= File2End; if (F1AtEnd & F2AtEnd) return 0; // Else, we might have run off the end due to a number: backup and retry. if (F1AtEnd && isNumberChar(F1P[-1])) --F1P; if (F2AtEnd && isNumberChar(F2P[-1])) --F2P; F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); // If we found the end, we succeeded. if (F1P >= File1End && F2P >= File2End) return 0; } catch (const std::string& msg) { std::cerr << argv[0] << ": error: " << msg << "\n"; return 2; } return 1; } <commit_msg>The meat of this utility has been moved to FileUtilities, where it can be used by other tools.<commit_after>//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // fpcmp is a tool that basically works like the 'cmp' tool, except that it can // tolerate errors due to floating point noise, with the -r and -a options. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileUtilities.h" #include <iostream> #include <cmath> using namespace llvm; namespace { cl::opt<std::string> File1(cl::Positional, cl::desc("<input file #1>"), cl::Required); cl::opt<std::string> File2(cl::Positional, cl::desc("<input file #2>"), cl::Required); cl::opt<double> RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0)); cl::opt<double> AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0)); } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); std::string ErrorMsg; int DF = DiffFilesWithTolerance(File1, File2, AbsTolerance, RelTolerance, &ErrorMsg); if (!ErrorMsg.empty()) std::cerr << argv[0] << ": " << ErrorMsg << "\n"; return DF; } <|endoftext|>
<commit_before>#pragma once #include <set> #include "lib/picojson.h" #include "definitions.hpp" #include "util.hpp" namespace processwarp { namespace Convert { /** * Convert process-id from JSON. * @param json JSON. * @return process-id. */ inline vpid_t json2vpid(const picojson::value& json) { return json.get<vpid_t>(); } /** * Convert JSON to bool. * @param json Source JSON. * @return A converted integer. */ inline bool json2bool(const picojson::value& json) { return json.get<std::string>() == "T"; } /** * Convert JSON to integer. * @param json Source JSON. * @return A converted integer. */ template<class T> T json2int(const picojson::value& json) { return Util::hex_str2num<T>(json.get<std::string>()); } /** * Convert a thread-id from JSON. * @param json Source JSON. * @return A thread-id. */ inline vtid_t json2vtid(const picojson::value& json) { return json2int<vtid_t>(json); } /** * Convert a virtual address from JSON. * @param json Source JSON. * @return A virtual address. */ inline vaddr_t json2vaddr(const picojson::value& json) { return json2int<vaddr_t>(json); } /** * Convert a instruction code from JSON. * @param json Source JSON. * @return A instruction code. */ inline instruction_t json2code(const picojson::value& json) { return json2int<instruction_t>(json); } /** * Convert a device-id from JSON * @param json Source JSON. * @return A device-id. */ inline dev_id_t json2devid(const picojson::value& json) { return json.get<dev_id_t>(); } /** * Convert process-id to JSON. * @param pid Source process-id. * @return Process-id as JSON. */ inline picojson::value vpid2json(const vpid_t& pid) { return picojson::value(pid); } /** * Convert bool to JSON. * @param b Source boolean. * @return Boolean as JSON. */ inline picojson::value bool2json(bool b) { return picojson::value(std::string(b ? "T" : "F")); } /** * Convert integer to JSON. * @param num Source integer. * @return Integer as JSON. */ template<class T> picojson::value int2json(T num) { return picojson::value(Util::num2hex_str<T>(num)); } /** * Convert thread-id to JSON. * @param tid Source thread-id. * @return Thread-id as JSON. */ inline picojson::value vtid2json(const vtid_t& tid) { return int2json<vtid_t>(tid); } /** * Convert virtual address to JSON. * @param addr Source virtual address. * @return Virtual address as JSON. */ inline picojson::value vaddr2json(vaddr_t addr) { return int2json<vaddr_t>(addr); } /** * Convert instruction code to JSON. * @param code Source instruction code. * @return Instruction code as JSON. */ inline picojson::value code2json(instruction_t code) { return int2json<instruction_t>(code); } /** * Convert device-id to JSON. * @param dev_id Source device-id. * @return Device-id as JSON. */ inline picojson::value devid2json(const dev_id_t& dev_id) { return picojson::value(dev_id); } /** * Convert process-id to string. * @param pid process-id. * @return process-id as string. */ inline const std::string& vpid2str(const vpid_t& pid) { return pid; } /** * Convert thread-id to string. * @param tid thread-id. * @return thread-id as string. */ inline std::string vtid2str(const vtid_t& tid) { return Util::num2hex_str<vtid_t>(tid); } /** * Convert virtual-address to string. * @param addr Virtual-address. * @return Virtual-address as string. */ inline std::string vaddr2str(const vaddr_t& addr) { return Util::num2hex_str<vaddr_t>(addr); } /** * Convert device-id to string. * @param dev_id Source device-id. * @return Converted value as string. */ inline std::string devid2str(const dev_id_t& dev_id) { return dev_id; } /** * Convert process-id to string. * @param str Source string value. * @return Converted value as vpid_t. */ inline vpid_t str2vpid(const std::string& str) { return str; } /** * Convert thread-id from string. * @param str string. * @param thread-id. */ inline vtid_t str2vtid(const std::string& str) { return Util::hex_str2num<vtid_t>(str); } /** * Convert virtual-address from string. * @param str string. * @param Virtual-address. */ inline vaddr_t str2vaddr(const std::string& str) { return Util::hex_str2num<vaddr_t>(str); } /** * Convert device-id to string. * @param str Source string value. * @param Converted value as dev_id_t. */ inline dev_id_t str2devid(const std::string& str) { return str; } } } <commit_msg>update Convert<commit_after>#pragma once #include <set> #include "lib/picojson.h" #include "definitions.hpp" #include "util.hpp" namespace processwarp { namespace Convert { /** * Convert integer to string. * @param num A source integer. * @return A integer as string. */ template<class T> std::string int2str(T num) { return Util::num2hex_str<T>(num); } /** * Convert process-id to string. * @param pid process-id. * @return process-id as string. */ inline const std::string& vpid2str(const vpid_t& pid) { return pid; } /** * Convert thread-id to string. * @param tid thread-id. * @return thread-id as string. */ inline std::string vtid2str(const vtid_t& tid) { return int2str<vtid_t>(tid); } /** * Convert virtual-address to string. * @param addr Virtual-address. * @return Virtual-address as string. */ inline std::string vaddr2str(const vaddr_t& addr) { return int2str<vaddr_t>(addr); } /** * Convert device-id to string. * @param dev_id Source device-id. * @return Converted value as string. */ inline std::string devid2str(const dev_id_t& dev_id) { return dev_id; } /** * Convert string to integer. * @param json A source string. * @return A converted integer. */ template<class T> T str2int(const std::string& str) { return Util::hex_str2num<T>(str); } /** * Convert process-id to string. * @param str Source string value. * @return Converted value as vpid_t. */ inline vpid_t str2vpid(const std::string& str) { return str; } /** * Convert thread-id from string. * @param str string. * @param thread-id. */ inline vtid_t str2vtid(const std::string& str) { return str2int<vtid_t>(str); } /** * Convert virtual-address from string. * @param str string. * @param Virtual-address. */ inline vaddr_t str2vaddr(const std::string& str) { return str2int<vaddr_t>(str); } /** * Convert device-id to string. * @param str Source string value. * @param Converted value as dev_id_t. */ inline dev_id_t str2devid(const std::string& str) { return str; } /** * Convert process-id from JSON. * @param json JSON. * @return process-id. */ inline vpid_t json2vpid(const picojson::value& json) { return str2vpid(json.get<std::string>()); } /** * Convert JSON to bool. * @param json Source JSON. * @return A converted integer. */ inline bool json2bool(const picojson::value& json) { return json.get<std::string>() == "T"; } /** * Convert JSON to integer. * @param json Source JSON. * @return A converted integer. */ template<class T> T json2int(const picojson::value& json) { return str2int<T>(json.get<std::string>()); } /** * Convert a thread-id from JSON. * @param json Source JSON. * @return A thread-id. */ inline vtid_t json2vtid(const picojson::value& json) { return str2vtid(json.get<std::string>()); } /** * Convert a virtual address from JSON. * @param json Source JSON. * @return A virtual address. */ inline vaddr_t json2vaddr(const picojson::value& json) { return str2vaddr(json.get<std::string>()); } /** * Convert a vector of virtual address from JSON. * @param json Source JSON. * @return A vector of virtual address. */ inline std::vector<vaddr_t> json2vaddr_vector(const picojson::value& json) { std::vector<vaddr_t> av; for (auto& it : json.get<picojson::array>()) { av.push_back(json2vaddr(it)); } return av; } /** * Convert a instruction code from JSON. * @param json Source JSON. * @return A instruction code. */ inline instruction_t json2code(const picojson::value& json) { return str2int<instruction_t>(json.get<std::string>()); } /** * Convert a device-id from JSON * @param json Source JSON. * @return A device-id. */ inline dev_id_t json2devid(const picojson::value& json) { return str2devid(json.get<std::string>()); } /** * Convert process-id to JSON. * @param pid Source process-id. * @return Process-id as JSON. */ inline picojson::value vpid2json(const vpid_t& pid) { return picojson::value(vpid2str(pid)); } /** * Convert bool to JSON. * @param b Source boolean. * @return Boolean as JSON. */ inline picojson::value bool2json(bool b) { return picojson::value(std::string(b ? "T" : "F")); } /** * Convert integer to JSON. * @param num Source integer. * @return Integer as JSON. */ template<class T> picojson::value int2json(T num) { return picojson::value(int2str<T>(num)); } /** * Convert thread-id to JSON. * @param tid Source thread-id. * @return Thread-id as JSON. */ inline picojson::value vtid2json(const vtid_t& tid) { return picojson::value(vtid2str(tid)); } /** * Convert virtual address to JSON. * @param addr Source virtual address. * @return Virtual address as JSON. */ inline picojson::value vaddr2json(vaddr_t addr) { return int2json<vaddr_t>(addr); } /** * Convert vector of virtual address to JSON. * @param addr Source vector of virtual address. * @return Virtual address as JSON. */ inline picojson::value vaddr_vector2json(const std::vector<vaddr_t> av) { picojson::array json; for (auto& it : av) { json.push_back(vaddr2json(it)); } return picojson::value(json); } /** * Convert instruction code to JSON. * @param code Source instruction code. * @return Instruction code as JSON. */ inline picojson::value code2json(instruction_t code) { return picojson::value(int2str<instruction_t>(code)); } /** * Convert device-id to JSON. * @param dev_id Source device-id. * @return Device-id as JSON. */ inline picojson::value devid2json(const dev_id_t& dev_id) { return picojson::value(devid2str(dev_id)); } } } <|endoftext|>
<commit_before>/* tests/test-rank-md.C * Time-stamp: <08 Aug 14 07:40:04 [email protected]> * ----------------------------------------------------- * * ========LICENCE======== * This file is part of the library LinBox. * * LinBox 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 * ========LICENCE======== */ /*! @file tests/test-rank-md.C * @ingroup tests * @brief no doc * @test no doc. */ #include <givaro/modular.h> #include "test-rank.h" int main (int argc, char **argv) { // commentator().setMaxDetailLevel( 100000 ); // commentator().setMaxDepth( 100000 ); bool pass = true; static size_t n = 20; //static integer q = 65519U; //static integer q = 1000003U; static integer q = 67108859; // = prevprime(maxCardinality()) static int iterations = 1; static double sparsity = 0.05; static Argument args[] = { { 'n', "-n N", "Set dimension of test matrices to NxN.", TYPE_INT, &n }, { 'q', "-q Q", "Operate over the \"field\" GF(Q) [1].", TYPE_INTEGER, &q }, { 'i', "-i I", "Perform each test for I iterations.", TYPE_INT, &iterations }, { 's', "-s S", "Sparse matrices with density S.", TYPE_DOUBLE, &sparsity }, END_OF_ARGUMENTS }; parseArguments (argc, argv, args); srand ((unsigned)time (NULL)); // srand48 ((unsigned)time (NULL)); commentator().start("Givaro::Modular<double> sparse rank test suite", "rank"); commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (3); commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_NORMAL); Givaro::Modular<double> G (q); pass = pass && testSparseRank(G,n,n+1,(size_t)iterations,sparsity); pass = pass && testSparseRank(G,LINBOX_USE_BLACKBOX_THRESHOLD+n,LINBOX_USE_BLACKBOX_THRESHOLD+n-1,(size_t)iterations,sparsity); commentator().stop("Givaro::Modular<double> SPArse rank test suite"); return pass ? 0 : -1; } // Local Variables: // mode: C++ // tab-width: 8 // indent-tabs-mode: nil // c-basic-offset: 8 // End: // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s <commit_msg>config first<commit_after>/* tests/test-rank-md.C * Time-stamp: <08 Aug 14 07:40:04 [email protected]> * ----------------------------------------------------- * * ========LICENCE======== * This file is part of the library LinBox. * * LinBox 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 * ========LICENCE======== */ /*! @file tests/test-rank-md.C * @ingroup tests * @brief no doc * @test no doc. */ #include "linbox/linbox-config.h" #include <givaro/modular.h> #include "test-rank.h" int main (int argc, char **argv) { // commentator().setMaxDetailLevel( 100000 ); // commentator().setMaxDepth( 100000 ); bool pass = true; static size_t n = 20; //static integer q = 65519U; //static integer q = 1000003U; static integer q = 67108859; // = prevprime(maxCardinality()) static int iterations = 1; static double sparsity = 0.05; static Argument args[] = { { 'n', "-n N", "Set dimension of test matrices to NxN.", TYPE_INT, &n }, { 'q', "-q Q", "Operate over the \"field\" GF(Q) [1].", TYPE_INTEGER, &q }, { 'i', "-i I", "Perform each test for I iterations.", TYPE_INT, &iterations }, { 's', "-s S", "Sparse matrices with density S.", TYPE_DOUBLE, &sparsity }, END_OF_ARGUMENTS }; parseArguments (argc, argv, args); srand ((unsigned)time (NULL)); // srand48 ((unsigned)time (NULL)); commentator().start("Givaro::Modular<double> sparse rank test suite", "rank"); commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (3); commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_NORMAL); Givaro::Modular<double> G (q); pass = pass && testSparseRank(G,n,n+1,(size_t)iterations,sparsity); pass = pass && testSparseRank(G,LINBOX_USE_BLACKBOX_THRESHOLD+n,LINBOX_USE_BLACKBOX_THRESHOLD+n-1,(size_t)iterations,sparsity); commentator().stop("Givaro::Modular<double> SPArse rank test suite"); return pass ? 0 : -1; } // Local Variables: // mode: C++ // tab-width: 8 // indent-tabs-mode: nil // c-basic-offset: 8 // End: // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // // 'Limit Example' RooStats tutorial macro #101 // author: Kyle Cranmer // date June. 2009 // // This tutorial shows an example of creating a simple // model for a number counting experiment with uncertainty // on both the background rate and signal efficeincy. We then // use a Confidence Interval Calculator to set a limit on the signal. // // ///////////////////////////////////////////////////////////////////////// #ifndef __CINT__ #include "RooGlobalFunc.h" #endif #include "RooProfileLL.h" #include "RooAbsPdf.h" #include "RooStats/HypoTestResult.h" #include "RooRealVar.h" #include "RooPlot.h" #include "RooDataSet.h" #include "RooTreeDataStore.h" #include "TTree.h" #include "TCanvas.h" #include "TLine.h" #include "TStopwatch.h" #include "RooStats/ProfileLikelihoodCalculator.h" #include "RooStats/MCMCCalculator.h" #include "RooStats/UniformProposal.h" #include "RooStats/FeldmanCousins.h" #include "RooStats/NumberCountingPdfFactory.h" #include "RooStats/ConfInterval.h" #include "RooStats/PointSetInterval.h" #include "RooStats/LikelihoodInterval.h" #include "RooStats/LikelihoodIntervalPlot.h" #include "RooStats/RooStatsUtils.h" // use this order for safety on library loading using namespace RooFit ; using namespace RooStats ; void rs101_limitexample() { ///////////////////////////////////////// // An example of setting a limit in a number counting experiment with uncertainty on background and signal ///////////////////////////////////////// // to time the macro TStopwatch t; t.Start(); ///////////////////////////////////////// // The Model building stage ///////////////////////////////////////// RooWorkspace* wspace = new RooWorkspace(); wspace->factory("Poisson::countingModel(obs[150,0,300], sum(s[50,0,120]*ratioSigEff[1.,0,2.],b[100,0,300]*ratioBkgEff[1.,0.,2.]))"); // counting model wspace->factory("Gaussian::sigConstraint(ratioSigEff,1,0.05)"); // 5% signal efficiency uncertainty wspace->factory("Gaussian::bkgConstraint(ratioBkgEff,1,0.1)"); // 10% background efficiency uncertainty wspace->factory("PROD::modelWithConstraints(countingModel,sigConstraint,bkgConstraint)"); // product of terms wspace->Print(); RooAbsPdf* modelWithConstraints = wspace->pdf("modelWithConstraints"); // get the model RooRealVar* obs = wspace->var("obs"); // get the observable RooRealVar* s = wspace->var("s"); // get the signal we care about RooRealVar* b = wspace->var("b"); // get the background and set it to a constant. Uncertainty included in ratioBkgEff b->setConstant(); RooRealVar* ratioSigEff = wspace->var("ratioSigEff"); // get uncertaint parameter to constrain RooRealVar* ratioBkgEff = wspace->var("ratioBkgEff"); // get uncertaint parameter to constrain RooArgSet constrainedParams(*ratioSigEff, *ratioBkgEff); // need to constrain these in the fit (should change default behavior) // Create an example dataset with 160 observed events obs->setVal(160.); RooDataSet* data = new RooDataSet("exampleData", "exampleData", RooArgSet(*obs)); data->add(*obs); RooArgSet all(*s, *ratioBkgEff, *ratioSigEff); // not necessary modelWithConstraints->fitTo(*data, RooFit::Constrain(RooArgSet(*ratioSigEff, *ratioBkgEff))); // Now let's make some confidence intervals for s, our parameter of interest RooArgSet paramOfInterest(*s); // First, let's use a Calculator based on the Profile Likelihood Ratio ProfileLikelihoodCalculator plc(*data, *modelWithConstraints, paramOfInterest); plc.SetTestSize(.1); ConfInterval* lrint = plc.GetInterval(); // that was easy. // Second, use a Calculator based on the Feldman Cousins technique FeldmanCousins fc; fc.SetPdf(*modelWithConstraints); fc.SetData(*data); fc.SetParameters( paramOfInterest ); fc.UseAdaptiveSampling(true); fc.FluctuateNumDataEntries(false); // number counting analysis: dataset always has 1 entry with N events observed fc.SetNBins(100); // number of points to test per parameter fc.SetTestSize(.1); // fc.SaveBeltToFile(true); // optional ConfInterval* fcint = NULL; fcint = fc.GetInterval(); // that was easy. // Third, use a Calculator based on Markov Chain monte carlo UniformProposal up; MCMCCalculator mc; mc.SetPdf(*modelWithConstraints); mc.SetData(*data); mc.SetParameters(paramOfInterest); mc.SetProposalFunction(up); mc.SetNumIters(100000); // steps in the chain mc.SetTestSize(.1); // 90% CL mc.SetNumBins(50); // used in posterior histogram mc.SetNumBurnInSteps(40); // ignore first steps in chain due to "burn in" ConfInterval* mcmcint = NULL; mcmcint = mc.GetInterval(); // Let's make a plot TCanvas* dataCanvas = new TCanvas("dataCanvas"); dataCanvas->Divide(2,1); dataCanvas->cd(1); LikelihoodIntervalPlot plotInt((LikelihoodInterval*)lrint); plotInt.SetTitle("Profile Likelihood Ratio and Posterior for S"); plotInt.Draw(); // draw posterior TH1* posterior = ((MCMCInterval*)mcmcint)->GetPosteriorHist(); posterior->Scale(1/posterior->GetBinContent(posterior->GetMaximumBin())); // scale so highest bin has y=1. posterior->Draw("same"); // Get Lower and Upper limits from Profile Calculator cout << "Profile lower limit on s = " << ((LikelihoodInterval*) lrint)->LowerLimit(*s) << endl; cout << "Profile upper limit on s = " << ((LikelihoodInterval*) lrint)->UpperLimit(*s) << endl; // Get Lower and Upper limits from FeldmanCousins with profile construction if (fcint != NULL) { double fcul = ((PointSetInterval*) fcint)->UpperLimit(*s); double fcll = ((PointSetInterval*) fcint)->LowerLimit(*s); cout << "FC lower limit on s = " << fcll << endl; cout << "FC upper limit on s = " << fcul << endl; TLine* fcllLine = new TLine(fcll, 0, fcll, 1); TLine* fculLine = new TLine(fcul, 0, fcul, 1); fcllLine->SetLineColor(kRed); fculLine->SetLineColor(kRed); fcllLine->Draw("same"); fculLine->Draw("same"); dataCanvas->Update(); } // Get Lower and Upper limits from MCMC double mcul = ((MCMCInterval*) mcmcint)->UpperLimit(*s); double mcll = ((MCMCInterval*) mcmcint)->LowerLimit(*s); cout << "MCMC lower limit on s = " << mcll << endl; cout << "MCMC upper limit on s = " << mcul << endl; TLine* mcllLine = new TLine(mcll, 0, mcll, 1); TLine* mculLine = new TLine(mcul, 0, mcul, 1); mcllLine->SetLineColor(kMagenta); mculLine->SetLineColor(kMagenta); mcllLine->Draw("same"); mculLine->Draw("same"); dataCanvas->Update(); // 3-d plot of the parameter points dataCanvas->cd(2); // also plot the points in the markov chain TTree& chain = ((RooTreeDataStore*) ((MCMCInterval*)mcmcint)->GetChain()->GetAsConstDataSet())->tree(); chain.SetMarkerStyle(6); chain.SetMarkerColor(kRed); chain.Draw("s:ratioSigEff:ratioBkgEff","w","box"); // 3-d box proporional to posterior // the points used in the profile construction TTree& parameterScan = ((RooTreeDataStore*) fc.GetPointsToScan()->store())->tree(); parameterScan.SetMarkerStyle(24); parameterScan.Draw("s:ratioSigEff:ratioBkgEff","","same"); delete wspace; delete lrint; if (fcint != NULL) delete fcint; delete data; /// print timing info t.Stop(); t.Print(); } <commit_msg>new attempt to fic tutorial<commit_after>///////////////////////////////////////////////////////////////////////// // // 'Limit Example' RooStats tutorial macro #101 // author: Kyle Cranmer // date June. 2009 // // This tutorial shows an example of creating a simple // model for a number counting experiment with uncertainty // on both the background rate and signal efficeincy. We then // use a Confidence Interval Calculator to set a limit on the signal. // // ///////////////////////////////////////////////////////////////////////// #ifndef __CINT__ #include "RooGlobalFunc.h" #endif #include "RooProfileLL.h" #include "RooAbsPdf.h" #include "RooStats/HypoTestResult.h" #include "RooRealVar.h" #include "RooPlot.h" #include "RooDataSet.h" #include "RooTreeDataStore.h" #include "TTree.h" #include "TCanvas.h" #include "TLine.h" #include "TStopwatch.h" #include "RooStats/ProfileLikelihoodCalculator.h" #include "RooStats/MCMCCalculator.h" #include "RooStats/UniformProposal.h" #include "RooStats/FeldmanCousins.h" #include "RooStats/NumberCountingPdfFactory.h" #include "RooStats/ConfInterval.h" #include "RooStats/PointSetInterval.h" #include "RooStats/LikelihoodInterval.h" #include "RooStats/LikelihoodIntervalPlot.h" #include "RooStats/RooStatsUtils.h" // use this order for safety on library loading using namespace RooFit ; using namespace RooStats ; void rs101_limitexample() { ///////////////////////////////////////// // An example of setting a limit in a number counting experiment with uncertainty on background and signal ///////////////////////////////////////// // to time the macro TStopwatch t; t.Start(); ///////////////////////////////////////// // The Model building stage ///////////////////////////////////////// RooWorkspace* wspace = new RooWorkspace(); wspace->factory("Poisson::countingModel(obs[150,0,300], sum(s[50,0,120]*ratioSigEff[1.,0,2.],b[100,0,300]*ratioBkgEff[1.,0.,2.]))"); // counting model wspace->factory("Gaussian::sigConstraint(ratioSigEff,1,0.05)"); // 5% signal efficiency uncertainty wspace->factory("Gaussian::bkgConstraint(ratioBkgEff,1,0.1)"); // 10% background efficiency uncertainty wspace->factory("PROD::modelWithConstraints(countingModel,sigConstraint,bkgConstraint)"); // product of terms wspace->Print(); RooAbsPdf* modelWithConstraints = wspace->pdf("modelWithConstraints"); // get the model RooRealVar* obs = wspace->var("obs"); // get the observable RooRealVar* s = wspace->var("s"); // get the signal we care about RooRealVar* b = wspace->var("b"); // get the background and set it to a constant. Uncertainty included in ratioBkgEff b->setConstant(); RooRealVar* ratioSigEff = wspace->var("ratioSigEff"); // get uncertaint parameter to constrain RooRealVar* ratioBkgEff = wspace->var("ratioBkgEff"); // get uncertaint parameter to constrain RooArgSet constrainedParams(*ratioSigEff, *ratioBkgEff); // need to constrain these in the fit (should change default behavior) // Create an example dataset with 160 observed events obs->setVal(160.); RooDataSet* data = new RooDataSet("exampleData", "exampleData", RooArgSet(*obs)); data->add(*obs); RooArgSet all(*s, *ratioBkgEff, *ratioSigEff); // not necessary modelWithConstraints->fitTo(*data, RooFit::Constrain(RooArgSet(*ratioSigEff, *ratioBkgEff))); // Now let's make some confidence intervals for s, our parameter of interest RooArgSet paramOfInterest(*s); // First, let's use a Calculator based on the Profile Likelihood Ratio ProfileLikelihoodCalculator plc(*data, *modelWithConstraints, paramOfInterest); plc.SetTestSize(.1); ConfInterval* lrint = plc.GetInterval(); // that was easy. // Second, use a Calculator based on the Feldman Cousins technique FeldmanCousins fc; fc.SetPdf(*modelWithConstraints); fc.SetData(*data); fc.SetParameters( paramOfInterest ); fc.UseAdaptiveSampling(true); fc.FluctuateNumDataEntries(false); // number counting analysis: dataset always has 1 entry with N events observed fc.SetNBins(100); // number of points to test per parameter fc.SetTestSize(.1); // fc.SaveBeltToFile(true); // optional ConfInterval* fcint = NULL; fcint = fc.GetInterval(); // that was easy. // Third, use a Calculator based on Markov Chain monte carlo UniformProposal up; MCMCCalculator mc; mc.SetPdf(*modelWithConstraints); mc.SetData(*data); mc.SetParameters(paramOfInterest); mc.SetProposalFunction(up); mc.SetNumIters(100000); // steps in the chain mc.SetTestSize(.1); // 90% CL mc.SetNumBins(50); // used in posterior histogram mc.SetNumBurnInSteps(40); // ignore first steps in chain due to "burn in" ConfInterval* mcmcint = NULL; mcmcint = mc.GetInterval(); // Let's make a plot TCanvas* dataCanvas = new TCanvas("dataCanvas"); dataCanvas->Divide(2,1); dataCanvas->cd(1); LikelihoodIntervalPlot plotInt((LikelihoodInterval*)lrint); plotInt.SetTitle("Profile Likelihood Ratio and Posterior for S"); plotInt.Draw(); // draw posterior TH1* posterior = ((MCMCInterval*)mcmcint)->GetPosteriorHist(); posterior->Scale(1/posterior->GetBinContent(posterior->GetMaximumBin())); // scale so highest bin has y=1. posterior->Draw("same"); // Get Lower and Upper limits from Profile Calculator cout << "Profile lower limit on s = " << ((LikelihoodInterval*) lrint)->LowerLimit(*s) << endl; cout << "Profile upper limit on s = " << ((LikelihoodInterval*) lrint)->UpperLimit(*s) << endl; // Get Lower and Upper limits from FeldmanCousins with profile construction if (fcint != NULL) { double fcul = ((PointSetInterval*) fcint)->UpperLimit(*s); double fcll = ((PointSetInterval*) fcint)->LowerLimit(*s); cout << "FC lower limit on s = " << fcll << endl; cout << "FC upper limit on s = " << fcul << endl; TLine* fcllLine = new TLine(fcll, 0, fcll, 1); TLine* fculLine = new TLine(fcul, 0, fcul, 1); fcllLine->SetLineColor(kRed); fculLine->SetLineColor(kRed); fcllLine->Draw("same"); fculLine->Draw("same"); dataCanvas->Update(); } // Get Lower and Upper limits from MCMC double mcul = ((MCMCInterval*) mcmcint)->UpperLimit(*s); double mcll = ((MCMCInterval*) mcmcint)->LowerLimit(*s); cout << "MCMC lower limit on s = " << mcll << endl; cout << "MCMC upper limit on s = " << mcul << endl; TLine* mcllLine = new TLine(mcll, 0, mcll, 1); TLine* mculLine = new TLine(mcul, 0, mcul, 1); mcllLine->SetLineColor(kMagenta); mculLine->SetLineColor(kMagenta); mcllLine->Draw("same"); mculLine->Draw("same"); dataCanvas->Update(); // 3-d plot of the parameter points dataCanvas->cd(2); // also plot the points in the markov chain TTree& chain = ((RooTreeDataStore*) ((MCMCInterval*)mcmcint)->GetChainAsDataSet()->store())->tree(); chain.SetMarkerStyle(6); chain.SetMarkerColor(kRed); chain.Draw("s:ratioSigEff:ratioBkgEff","w","box"); // 3-d box proporional to posterior // the points used in the profile construction TTree& parameterScan = ((RooTreeDataStore*) fc.GetPointsToScan()->store())->tree(); parameterScan.SetMarkerStyle(24); parameterScan.Draw("s:ratioSigEff:ratioBkgEff","","same"); delete wspace; delete lrint; if (fcint != NULL) delete fcint; delete data; /// print timing info t.Stop(); t.Print(); } // int main() { // rs101_limitexample(); // } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <cstring> #include <vector> #include <iostream> #include "genome.h" using namespace std; int main(int argc, const char **argv) { if(argc != 4) { cout<<"usage: " << endl; cout<<" " << argv[0] << " RPKM2TPM <in-gtf-file> <out-gtf-file>"<<endl; cout<<" " << argv[0] << " FPKM2TPM <in-gtf-file> <out-gtf-file>"<<endl; cout<<" " << argv[0] << " format <in-gtf-file> <out-gtf-file>"<<endl; return 0; } if(string(argv[1]) == "FPKM2TPM") { genome gm(argv[2]); gm.assign_TPM_by_FPKM(); gm.write(argv[3]); } if(string(argv[1]) == "RPKM2TPM") { genome gm(argv[2]); gm.assign_TPM_by_RPKM(); gm.write(argv[3]); } if(string(argv[1]) == "format") { genome gm(argv[2]); gm.write(argv[3]); } return 0; } <commit_msg>add filter<commit_after>#include <cstdio> #include <cstdlib> #include <cstring> #include <vector> #include <iostream> #include "genome.h" using namespace std; int main(int argc, const char **argv) { if(argc != 4) { cout<<"usage: " << endl; cout<<" " << argv[0] << " RPKM2TPM <in-gtf-file> <out-gtf-file>"<<endl; cout<<" " << argv[0] << " FPKM2TPM <in-gtf-file> <out-gtf-file>"<<endl; cout<<" " << argv[0] << " format <in-gtf-file> <out-gtf-file>"<<endl; cout<<" " << argv[0] << " filter <min-transcript-coverage> <in-gtf-file> <out-gtf-file>"<<endl; return 0; } if(string(argv[1]) == "FPKM2TPM") { genome gm(argv[2]); gm.assign_TPM_by_FPKM(); gm.write(argv[3]); } if(string(argv[1]) == "RPKM2TPM") { genome gm(argv[2]); gm.assign_TPM_by_RPKM(); gm.write(argv[3]); } if(string(argv[1]) == "format") { genome gm(argv[2]); gm.write(argv[3]); } if(string(argv[1]) == "filter") { double c = atof(argv[2]); genome gm(argv[3]); gm.filter_low_coverage_transcripts(c); gm.write(argv[4]); } return 0; } <|endoftext|>
<commit_before>#define MS_CLASS "RTC::RtpCodecMime" // #define MS_LOG_DEV #include "RTC/RtpDictionaries.hpp" #include "Utils.hpp" #include "MediaSoupError.hpp" #include "Logger.hpp" namespace RTC { /* Class variables. */ std::unordered_map<std::string, RtpCodecMime::Type> RtpCodecMime::string2Type = { { "audio", RtpCodecMime::Type::AUDIO }, { "video", RtpCodecMime::Type::VIDEO } }; std::map<RtpCodecMime::Type, std::string> RtpCodecMime::type2String = { { RtpCodecMime::Type::AUDIO, "audio" }, { RtpCodecMime::Type::VIDEO, "video" } }; std::unordered_map<std::string, RtpCodecMime::Subtype> RtpCodecMime::string2Subtype = { // Audio codecs: { "opus", RtpCodecMime::Subtype::OPUS }, { "pcma", RtpCodecMime::Subtype::PCMA }, { "pcmu", RtpCodecMime::Subtype::PCMU }, { "isac", RtpCodecMime::Subtype::ISAC }, { "g722", RtpCodecMime::Subtype::G722 }, { "ilbc", RtpCodecMime::Subtype::ILBC }, // Video codecs: { "vp8", RtpCodecMime::Subtype::VP8 }, { "vp9", RtpCodecMime::Subtype::VP9 }, { "h264", RtpCodecMime::Subtype::H264 }, { "h265", RtpCodecMime::Subtype::H265 }, // Complementary codecs: { "cn", RtpCodecMime::Subtype::CN }, { "telephone-event", RtpCodecMime::Subtype::TELEPHONE_EVENT }, // Feature codecs: { "rtx", RtpCodecMime::Subtype::RTX }, { "ulpfec", RtpCodecMime::Subtype::ULPFEC }, { "flexfec", RtpCodecMime::Subtype::FLEXFEC }, { "red", RtpCodecMime::Subtype::RED } }; std::map<RtpCodecMime::Subtype, std::string> RtpCodecMime::subtype2String = { // Audio codecs: { RtpCodecMime::Subtype::OPUS, "opus" }, { RtpCodecMime::Subtype::PCMA, "PCMA" }, { RtpCodecMime::Subtype::PCMU, "PCMU" }, { RtpCodecMime::Subtype::ISAC, "ISAC" }, { RtpCodecMime::Subtype::G722, "G722" }, { RtpCodecMime::Subtype::ILBC, "iLBC" }, // Video codecs: { RtpCodecMime::Subtype::VP8, "VP8" }, { RtpCodecMime::Subtype::VP9, "VP9" }, { RtpCodecMime::Subtype::H264, "H264" }, { RtpCodecMime::Subtype::H265, "H265" }, // Complementary codecs: { RtpCodecMime::Subtype::CN, "CN" }, { RtpCodecMime::Subtype::TELEPHONE_EVENT, "telephone-event" }, // Feature codecs: { RtpCodecMime::Subtype::RTX, "rtx" }, { RtpCodecMime::Subtype::ULPFEC, "ulpfec" }, { RtpCodecMime::Subtype::FLEXFEC, "flexfec" }, { RtpCodecMime::Subtype::RED, "red" } }; /* Instance methods. */ void RtpCodecMime::SetName(std::string& name) { MS_TRACE(); auto slash_pos = name.find('/'); if (slash_pos == std::string::npos || slash_pos == 0 || slash_pos == name.length() - 1) MS_THROW_ERROR("wrong codec MIME"); std::string type = name.substr(0, slash_pos); std::string subtype = name.substr(slash_pos + 1); // Force lowcase names. Utils::String::ToLowerCase(type); Utils::String::ToLowerCase(subtype); // Set MIME type. { auto it = RtpCodecMime::string2Type.find(type); if (it != RtpCodecMime::string2Type.end()) this->type = it->second; else MS_THROW_ERROR("unknown codec MIME type"); } // Set MIME subtype. { auto it = RtpCodecMime::string2Subtype.find(subtype); if (it != RtpCodecMime::string2Subtype.end()) this->subtype = it->second; else MS_THROW_ERROR("unknown codec MIME subtype"); } // Set name. this->name = type2String[this->type] + "/" + subtype2String[this->subtype]; } } <commit_msg>Add SILK audio codec<commit_after>#define MS_CLASS "RTC::RtpCodecMime" // #define MS_LOG_DEV #include "RTC/RtpDictionaries.hpp" #include "Utils.hpp" #include "MediaSoupError.hpp" #include "Logger.hpp" namespace RTC { /* Class variables. */ std::unordered_map<std::string, RtpCodecMime::Type> RtpCodecMime::string2Type = { { "audio", RtpCodecMime::Type::AUDIO }, { "video", RtpCodecMime::Type::VIDEO } }; std::map<RtpCodecMime::Type, std::string> RtpCodecMime::type2String = { { RtpCodecMime::Type::AUDIO, "audio" }, { RtpCodecMime::Type::VIDEO, "video" } }; std::unordered_map<std::string, RtpCodecMime::Subtype> RtpCodecMime::string2Subtype = { // Audio codecs: { "opus", RtpCodecMime::Subtype::OPUS }, { "pcma", RtpCodecMime::Subtype::PCMA }, { "pcmu", RtpCodecMime::Subtype::PCMU }, { "isac", RtpCodecMime::Subtype::ISAC }, { "g722", RtpCodecMime::Subtype::G722 }, { "ilbc", RtpCodecMime::Subtype::ILBC }, { "silk", RtpCodecMime::Subtype::SILK }, // Video codecs: { "vp8", RtpCodecMime::Subtype::VP8 }, { "vp9", RtpCodecMime::Subtype::VP9 }, { "h264", RtpCodecMime::Subtype::H264 }, { "h265", RtpCodecMime::Subtype::H265 }, // Complementary codecs: { "cn", RtpCodecMime::Subtype::CN }, { "telephone-event", RtpCodecMime::Subtype::TELEPHONE_EVENT }, // Feature codecs: { "rtx", RtpCodecMime::Subtype::RTX }, { "ulpfec", RtpCodecMime::Subtype::ULPFEC }, { "flexfec", RtpCodecMime::Subtype::FLEXFEC }, { "red", RtpCodecMime::Subtype::RED } }; std::map<RtpCodecMime::Subtype, std::string> RtpCodecMime::subtype2String = { // Audio codecs: { RtpCodecMime::Subtype::OPUS, "opus" }, { RtpCodecMime::Subtype::PCMA, "PCMA" }, { RtpCodecMime::Subtype::PCMU, "PCMU" }, { RtpCodecMime::Subtype::ISAC, "ISAC" }, { RtpCodecMime::Subtype::G722, "G722" }, { RtpCodecMime::Subtype::ILBC, "iLBC" }, { RtpCodecMime::Subtype::SILK, "SILK" }, // Video codecs: { RtpCodecMime::Subtype::VP8, "VP8" }, { RtpCodecMime::Subtype::VP9, "VP9" }, { RtpCodecMime::Subtype::H264, "H264" }, { RtpCodecMime::Subtype::H265, "H265" }, // Complementary codecs: { RtpCodecMime::Subtype::CN, "CN" }, { RtpCodecMime::Subtype::TELEPHONE_EVENT, "telephone-event" }, // Feature codecs: { RtpCodecMime::Subtype::RTX, "rtx" }, { RtpCodecMime::Subtype::ULPFEC, "ulpfec" }, { RtpCodecMime::Subtype::FLEXFEC, "flexfec" }, { RtpCodecMime::Subtype::RED, "red" } }; /* Instance methods. */ void RtpCodecMime::SetName(std::string& name) { MS_TRACE(); auto slash_pos = name.find('/'); if (slash_pos == std::string::npos || slash_pos == 0 || slash_pos == name.length() - 1) MS_THROW_ERROR("wrong codec MIME"); std::string type = name.substr(0, slash_pos); std::string subtype = name.substr(slash_pos + 1); // Force lowcase names. Utils::String::ToLowerCase(type); Utils::String::ToLowerCase(subtype); // Set MIME type. { auto it = RtpCodecMime::string2Type.find(type); if (it != RtpCodecMime::string2Type.end()) this->type = it->second; else MS_THROW_ERROR("unknown codec MIME type"); } // Set MIME subtype. { auto it = RtpCodecMime::string2Subtype.find(subtype); if (it != RtpCodecMime::string2Subtype.end()) this->subtype = it->second; else MS_THROW_ERROR("unknown codec MIME subtype"); } // Set name. this->name = type2String[this->type] + "/" + subtype2String[this->subtype]; } } <|endoftext|>
<commit_before><commit_msg>Aura: fix the touch event doesn't work on Tizen 3.0 issue.<commit_after><|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 <windows.h> #include <uxtheme.h> #include <vsstyle.h> #include <vssym32.h> #include "base/command_line.h" #include "base/memory/ref_counted_memory.h" #include "base/memory/scoped_ptr.h" #include "base/resource_util.h" #include "grit/gfx_resources.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/brush.h" #include "ui/gfx/canvas_direct2d.h" #include "ui/gfx/canvas_skia.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/native_theme_win.h" #include "ui/gfx/rect.h" #include "ui/gfx/win_util.h" namespace { const char kVisibleModeFlag[] = "d2d-canvas-visible"; const wchar_t kWindowClassName[] = L"GFXD2DTestWindowClass"; class TestWindow { public: static const int kWindowSize = 500; static const int kWindowPosition = 10; TestWindow() : hwnd_(NULL) { if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag)) Sleep(1000); RegisterMyClass(); hwnd_ = CreateWindowEx(0, kWindowClassName, NULL, WS_OVERLAPPEDWINDOW, kWindowPosition, kWindowPosition, kWindowSize, kWindowSize, NULL, NULL, NULL, this); DCHECK(hwnd_); // Initialize the RenderTarget for the window. rt_ = MakeHWNDRenderTarget(); if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag)) ShowWindow(hwnd(), SW_SHOW); } virtual ~TestWindow() { if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag)) Sleep(1000); DestroyWindow(hwnd()); UnregisterMyClass(); } HWND hwnd() const { return hwnd_; } ID2D1RenderTarget* rt() const { return rt_.get(); } private: ID2D1RenderTarget* MakeHWNDRenderTarget() { D2D1_RENDER_TARGET_PROPERTIES rt_properties = D2D1::RenderTargetProperties(); rt_properties.usage = D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE; ID2D1HwndRenderTarget* rt = NULL; gfx::CanvasDirect2D::GetD2D1Factory()->CreateHwndRenderTarget( rt_properties, D2D1::HwndRenderTargetProperties(hwnd(), D2D1::SizeU(500, 500)), &rt); return rt; } void RegisterMyClass() { WNDCLASSEX class_ex; class_ex.cbSize = sizeof(WNDCLASSEX); class_ex.style = CS_DBLCLKS; class_ex.lpfnWndProc = &DefWindowProc; class_ex.cbClsExtra = 0; class_ex.cbWndExtra = 0; class_ex.hInstance = NULL; class_ex.hIcon = NULL; class_ex.hCursor = LoadCursor(NULL, IDC_ARROW); class_ex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND); class_ex.lpszMenuName = NULL; class_ex.lpszClassName = kWindowClassName; class_ex.hIconSm = class_ex.hIcon; ATOM atom = RegisterClassEx(&class_ex); DCHECK(atom); } void UnregisterMyClass() { ::UnregisterClass(kWindowClassName, NULL); } HWND hwnd_; ScopedComPtr<ID2D1RenderTarget> rt_; DISALLOW_COPY_AND_ASSIGN(TestWindow); }; // Loads a png data blob from the data resources associated with this // executable, decodes it and returns a SkBitmap. SkBitmap LoadBitmapFromResources(int resource_id) { SkBitmap bitmap; HINSTANCE resource_instance = GetModuleHandle(NULL); void* data_ptr; size_t data_size; if (base::GetDataResourceFromModule(resource_instance, resource_id, &data_ptr, &data_size)) { scoped_refptr<RefCountedMemory> memory(new RefCountedStaticMemory( reinterpret_cast<const unsigned char*>(data_ptr), data_size)); if (!memory) return bitmap; if (!gfx::PNGCodec::Decode(memory->front(), memory->size(), &bitmap)) NOTREACHED() << "Unable to decode theme image resource " << resource_id; } return bitmap; } bool CheckForD2DCompatibility() { if (!gfx::Direct2dIsAvailable()) { LOG(WARNING) << "Test is disabled as it requires either Windows 7 or " << "Vista with Platform Update KB971644"; return false; } return true; } } // namespace TEST(CanvasDirect2D, CreateCanvas) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); } TEST(CanvasDirect2D, SaveRestoreNesting) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); // Simple. canvas.Save(); canvas.Restore(); // Nested. canvas.Save(); canvas.Save(); canvas.Restore(); canvas.Restore(); // Simple alpha. canvas.SaveLayerAlpha(127); canvas.Restore(); // Alpha with sub-rect. canvas.SaveLayerAlpha(127, gfx::Rect(20, 20, 100, 100)); canvas.Restore(); // Nested alpha. canvas.Save(); canvas.SaveLayerAlpha(127); canvas.Save(); canvas.Restore(); canvas.Restore(); canvas.Restore(); } TEST(CanvasDirect2D, SaveLayerAlpha) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.FillRectInt(SK_ColorBLUE, 20, 20, 100, 100); canvas.SaveLayerAlpha(127); canvas.FillRectInt(SK_ColorRED, 60, 60, 100, 100); canvas.Restore(); canvas.Restore(); } TEST(CanvasDirect2D, SaveLayerAlphaWithBounds) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.FillRectInt(SK_ColorBLUE, 20, 20, 100, 100); canvas.SaveLayerAlpha(127, gfx::Rect(60, 60, 50, 50)); canvas.FillRectInt(SK_ColorRED, 60, 60, 100, 100); canvas.Restore(); canvas.Restore(); } TEST(CanvasDirect2D, FillRect) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.FillRectInt(SK_ColorRED, 20, 20, 100, 100); } TEST(CanvasDirect2D, PlatformPainting) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); gfx::NativeDrawingContext dc = canvas.BeginPlatformPaint(); // Use the system theme engine to draw a native button. This only works on a // GDI device context. RECT r = { 20, 20, 220, 80 }; gfx::NativeThemeWin::instance()->PaintButton( dc, BP_PUSHBUTTON, PBS_NORMAL, DFCS_BUTTONPUSH, &r); canvas.EndPlatformPaint(); } TEST(CanvasDirect2D, ClipRect) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500); canvas.ClipRectInt(20, 20, 120, 120); canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500); } TEST(CanvasDirect2D, ClipRectWithTranslate) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); // Repeat the same rendering as in ClipRect... canvas.Save(); canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500); canvas.ClipRectInt(20, 20, 120, 120); canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500); canvas.Restore(); // ... then translate, clip and fill again relative to the new origin. canvas.Save(); canvas.TranslateInt(150, 150); canvas.ClipRectInt(10, 10, 110, 110); canvas.FillRectInt(SK_ColorRED, 0, 0, 500, 500); canvas.Restore(); } TEST(CanvasDirect2D, ClipRectWithScale) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); // Repeat the same rendering as in ClipRect... canvas.Save(); canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500); canvas.ClipRectInt(20, 20, 120, 120); canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500); canvas.Restore(); // ... then translate and scale, clip and fill again relative to the new // origin. canvas.Save(); canvas.TranslateInt(150, 150); canvas.ScaleInt(2, 2); canvas.ClipRectInt(10, 10, 110, 110); canvas.FillRectInt(SK_ColorRED, 0, 0, 500, 500); canvas.Restore(); } TEST(CanvasDirect2D, DrawRectInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.DrawRectInt(SK_ColorRED, 10, 10, 200, 200); canvas.Restore(); } TEST(CanvasDirect2D, DrawLineInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.DrawLineInt(SK_ColorRED, 10, 10, 210, 210); canvas.Restore(); } TEST(CanvasDirect2D, DrawBitmapInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE); canvas.Save(); canvas.DrawBitmapInt(bitmap, 100, 100); canvas.Restore(); } TEST(CanvasDirect2D, DrawBitmapInt2) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE); canvas.Save(); canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 10, 10, 30, 30, false); canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 110, 110, 100, 100, true); canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 220, 220, 100, 100, false); canvas.Restore(); } TEST(CanvasDirect2D, TileImageInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE); canvas.Save(); canvas.TileImageInt(bitmap, 10, 10, 300, 300); canvas.Restore(); } <commit_msg>Removing uneeded test. Because of the native theme cleanup, the method being called here is going away anyway.<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 <windows.h> #include <uxtheme.h> #include <vsstyle.h> #include <vssym32.h> #include "base/command_line.h" #include "base/memory/ref_counted_memory.h" #include "base/memory/scoped_ptr.h" #include "base/resource_util.h" #include "grit/gfx_resources.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/brush.h" #include "ui/gfx/canvas_direct2d.h" #include "ui/gfx/canvas_skia.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/rect.h" #include "ui/gfx/win_util.h" namespace { const char kVisibleModeFlag[] = "d2d-canvas-visible"; const wchar_t kWindowClassName[] = L"GFXD2DTestWindowClass"; class TestWindow { public: static const int kWindowSize = 500; static const int kWindowPosition = 10; TestWindow() : hwnd_(NULL) { if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag)) Sleep(1000); RegisterMyClass(); hwnd_ = CreateWindowEx(0, kWindowClassName, NULL, WS_OVERLAPPEDWINDOW, kWindowPosition, kWindowPosition, kWindowSize, kWindowSize, NULL, NULL, NULL, this); DCHECK(hwnd_); // Initialize the RenderTarget for the window. rt_ = MakeHWNDRenderTarget(); if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag)) ShowWindow(hwnd(), SW_SHOW); } virtual ~TestWindow() { if (CommandLine::ForCurrentProcess()->HasSwitch(kVisibleModeFlag)) Sleep(1000); DestroyWindow(hwnd()); UnregisterMyClass(); } HWND hwnd() const { return hwnd_; } ID2D1RenderTarget* rt() const { return rt_.get(); } private: ID2D1RenderTarget* MakeHWNDRenderTarget() { D2D1_RENDER_TARGET_PROPERTIES rt_properties = D2D1::RenderTargetProperties(); rt_properties.usage = D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE; ID2D1HwndRenderTarget* rt = NULL; gfx::CanvasDirect2D::GetD2D1Factory()->CreateHwndRenderTarget( rt_properties, D2D1::HwndRenderTargetProperties(hwnd(), D2D1::SizeU(500, 500)), &rt); return rt; } void RegisterMyClass() { WNDCLASSEX class_ex; class_ex.cbSize = sizeof(WNDCLASSEX); class_ex.style = CS_DBLCLKS; class_ex.lpfnWndProc = &DefWindowProc; class_ex.cbClsExtra = 0; class_ex.cbWndExtra = 0; class_ex.hInstance = NULL; class_ex.hIcon = NULL; class_ex.hCursor = LoadCursor(NULL, IDC_ARROW); class_ex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND); class_ex.lpszMenuName = NULL; class_ex.lpszClassName = kWindowClassName; class_ex.hIconSm = class_ex.hIcon; ATOM atom = RegisterClassEx(&class_ex); DCHECK(atom); } void UnregisterMyClass() { ::UnregisterClass(kWindowClassName, NULL); } HWND hwnd_; ScopedComPtr<ID2D1RenderTarget> rt_; DISALLOW_COPY_AND_ASSIGN(TestWindow); }; // Loads a png data blob from the data resources associated with this // executable, decodes it and returns a SkBitmap. SkBitmap LoadBitmapFromResources(int resource_id) { SkBitmap bitmap; HINSTANCE resource_instance = GetModuleHandle(NULL); void* data_ptr; size_t data_size; if (base::GetDataResourceFromModule(resource_instance, resource_id, &data_ptr, &data_size)) { scoped_refptr<RefCountedMemory> memory(new RefCountedStaticMemory( reinterpret_cast<const unsigned char*>(data_ptr), data_size)); if (!memory) return bitmap; if (!gfx::PNGCodec::Decode(memory->front(), memory->size(), &bitmap)) NOTREACHED() << "Unable to decode theme image resource " << resource_id; } return bitmap; } bool CheckForD2DCompatibility() { if (!gfx::Direct2dIsAvailable()) { LOG(WARNING) << "Test is disabled as it requires either Windows 7 or " << "Vista with Platform Update KB971644"; return false; } return true; } } // namespace TEST(CanvasDirect2D, CreateCanvas) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); } TEST(CanvasDirect2D, SaveRestoreNesting) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); // Simple. canvas.Save(); canvas.Restore(); // Nested. canvas.Save(); canvas.Save(); canvas.Restore(); canvas.Restore(); // Simple alpha. canvas.SaveLayerAlpha(127); canvas.Restore(); // Alpha with sub-rect. canvas.SaveLayerAlpha(127, gfx::Rect(20, 20, 100, 100)); canvas.Restore(); // Nested alpha. canvas.Save(); canvas.SaveLayerAlpha(127); canvas.Save(); canvas.Restore(); canvas.Restore(); canvas.Restore(); } TEST(CanvasDirect2D, SaveLayerAlpha) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.FillRectInt(SK_ColorBLUE, 20, 20, 100, 100); canvas.SaveLayerAlpha(127); canvas.FillRectInt(SK_ColorRED, 60, 60, 100, 100); canvas.Restore(); canvas.Restore(); } TEST(CanvasDirect2D, SaveLayerAlphaWithBounds) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.FillRectInt(SK_ColorBLUE, 20, 20, 100, 100); canvas.SaveLayerAlpha(127, gfx::Rect(60, 60, 50, 50)); canvas.FillRectInt(SK_ColorRED, 60, 60, 100, 100); canvas.Restore(); canvas.Restore(); } TEST(CanvasDirect2D, FillRect) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.FillRectInt(SK_ColorRED, 20, 20, 100, 100); } TEST(CanvasDirect2D, ClipRect) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500); canvas.ClipRectInt(20, 20, 120, 120); canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500); } TEST(CanvasDirect2D, ClipRectWithTranslate) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); // Repeat the same rendering as in ClipRect... canvas.Save(); canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500); canvas.ClipRectInt(20, 20, 120, 120); canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500); canvas.Restore(); // ... then translate, clip and fill again relative to the new origin. canvas.Save(); canvas.TranslateInt(150, 150); canvas.ClipRectInt(10, 10, 110, 110); canvas.FillRectInt(SK_ColorRED, 0, 0, 500, 500); canvas.Restore(); } TEST(CanvasDirect2D, ClipRectWithScale) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); // Repeat the same rendering as in ClipRect... canvas.Save(); canvas.FillRectInt(SK_ColorGREEN, 0, 0, 500, 500); canvas.ClipRectInt(20, 20, 120, 120); canvas.FillRectInt(SK_ColorBLUE, 0, 0, 500, 500); canvas.Restore(); // ... then translate and scale, clip and fill again relative to the new // origin. canvas.Save(); canvas.TranslateInt(150, 150); canvas.ScaleInt(2, 2); canvas.ClipRectInt(10, 10, 110, 110); canvas.FillRectInt(SK_ColorRED, 0, 0, 500, 500); canvas.Restore(); } TEST(CanvasDirect2D, DrawRectInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.DrawRectInt(SK_ColorRED, 10, 10, 200, 200); canvas.Restore(); } TEST(CanvasDirect2D, DrawLineInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); canvas.Save(); canvas.DrawLineInt(SK_ColorRED, 10, 10, 210, 210); canvas.Restore(); } TEST(CanvasDirect2D, DrawBitmapInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE); canvas.Save(); canvas.DrawBitmapInt(bitmap, 100, 100); canvas.Restore(); } TEST(CanvasDirect2D, DrawBitmapInt2) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE); canvas.Save(); canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 10, 10, 30, 30, false); canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 110, 110, 100, 100, true); canvas.DrawBitmapInt(bitmap, 5, 5, 30, 30, 220, 220, 100, 100, false); canvas.Restore(); } TEST(CanvasDirect2D, TileImageInt) { if (!CheckForD2DCompatibility()) return; TestWindow window; gfx::CanvasDirect2D canvas(window.rt()); SkBitmap bitmap = LoadBitmapFromResources(IDR_BITMAP_BRUSH_IMAGE); canvas.Save(); canvas.TileImageInt(bitmap, 10, 10, 300, 300); canvas.Restore(); } <|endoftext|>
<commit_before>//===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/Support/TimeValue.h" #include <time.h> using namespace llvm; namespace { TEST(TimeValue, time_t) { sys::TimeValue now = sys::TimeValue::now(); time_t now_t = time(NULL); EXPECT_TRUE(abs(static_cast<long>(now_t - now.toEpochTime())) < 2); } TEST(TimeValue, Win32FILETIME) { uint64_t epoch_as_filetime = 0x19DB1DED53E8000ULL; uint32_t ns = 765432100; sys::TimeValue epoch; // FILETIME has 100ns of intervals. uint64_t ft1970 = epoch_as_filetime + ns / 100; epoch.fromWin32Time(ft1970); // The "seconds" part in Posix time may be expected as zero. EXPECT_EQ(0u, epoch.toEpochTime()); EXPECT_EQ(ns, static_cast<uint32_t>(epoch.nanoseconds())); // Confirm it reversible. EXPECT_EQ(ft1970, epoch.toWin32Time()); } } <commit_msg>Use the overloaded std::abs rather than C's abs(int) to address Clang's -Wabsolute-value<commit_after>//===- llvm/unittest/Support/TimeValueTest.cpp - Time Value tests ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/Support/TimeValue.h" #include <time.h> using namespace llvm; namespace { TEST(TimeValue, time_t) { sys::TimeValue now = sys::TimeValue::now(); time_t now_t = time(NULL); EXPECT_TRUE(std::abs(static_cast<long>(now_t - now.toEpochTime())) < 2); } TEST(TimeValue, Win32FILETIME) { uint64_t epoch_as_filetime = 0x19DB1DED53E8000ULL; uint32_t ns = 765432100; sys::TimeValue epoch; // FILETIME has 100ns of intervals. uint64_t ft1970 = epoch_as_filetime + ns / 100; epoch.fromWin32Time(ft1970); // The "seconds" part in Posix time may be expected as zero. EXPECT_EQ(0u, epoch.toEpochTime()); EXPECT_EQ(ns, static_cast<uint32_t>(epoch.nanoseconds())); // Confirm it reversible. EXPECT_EQ(ft1970, epoch.toWin32Time()); } } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: bootstrap.hxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "unotools/unotoolsdllapi.h" #ifndef _UTL_BOOTSTRAP_HXX #define _UTL_BOOTSTRAP_HXX namespace rtl { class OUString; } namespace utl { //----------------------------------------------------------------------------- /** provides configuration information needed for application startup. <p>This class handles the startup information for the office application. It encapsulates knowledge of how to retriev such information and how to diagnose failures to retriev required data. </p> */ class UNOTOOLS_DLLPUBLIC Bootstrap { // the static interface public: // some common information items /// retrieve the product key; defaults to executable name (without extension) static rtl::OUString getProductKey(); /// retrieve the product key; uses the given default, if not found static rtl::OUString getProductKey(rtl::OUString const& _sDefault); /// retrieve the LOGO information item; uses the given default, if not found static rtl::OUString getLogoData(rtl::OUString const& _sDefault); // /// retrieve the BUILDID information item; uses the given default, if not found static rtl::OUString getBuildIdData(rtl::OUString const& _sDefault); /// retrieve the product patch level; uses the given default, if not found static rtl::OUString getProductPatchLevel(rtl::OUString const& _sDefault); /// retrieve the ALLUSERS information item from setup.ini file; uses the given default, if not found static rtl::OUString getAllUsersValue(rtl::OUString const& _sDefault); /// reload cached data static void reloadData(); public: // retrieve path information about the installaton location enum PathStatus { PATH_EXISTS, // Success: Found a path to an existing file or directory PATH_VALID, // Found a valid path, but the file or directory does not exist DATA_INVALID, // Retrieved a string for this path, that is not a valid file url or system path DATA_MISSING, // Could not retrieve any data for this path DATA_UNKNOWN // No attempt to retrieve data for this path was made }; /// get a file URL to the common base installation [${insturl}] static PathStatus locateBaseInstallation(rtl::OUString& _rURL); /// get a file URL to the user installation [${userurl}] static PathStatus locateUserInstallation(rtl::OUString& _rURL); /// get a file URL to the shared data directory [default is ${insturl}/share] static PathStatus locateSharedData(rtl::OUString& _rURL); /// get a file URL to the user data directory [default is ${userurl}/user] static PathStatus locateUserData(rtl::OUString& _rURL); // the next two items are mainly supported for diagnostic purposes. both items may be unused /// get a file URL to the bootstrap INI file used [e.g. ${insturl}/program/bootraprc] static PathStatus locateBootstrapFile(rtl::OUString& _rURL); /// get a file URL to the version locator INI file used [e.g. ${SYSUSERCONFIG}/sversion.ini] static PathStatus locateVersionFile(rtl::OUString& _rURL); public: // evaluate the validity of the installation /// high-level status of bootstrap success enum Status { DATA_OK, /// user-dir and share-dir do exist, product key found or can be defaulted to exe-name MISSING_USER_INSTALL, /// ${userurl} does not exist; or version-file cannot be found or is invalid INVALID_USER_INSTALL, /// can locate ${userurl}, but user-dir is missing INVALID_BASE_INSTALL /// other failure: e.g. cannot locate share-dir; bootstraprc missing or invalid; no product key }; /// error code for detailed diagnostics of bootstrap failures enum FailureCode { NO_FAILURE, /// bootstrap was successful MISSING_INSTALL_DIRECTORY, /// the shared installation directory could not be located MISSING_BOOTSTRAP_FILE, /// the bootstrap INI file could not be found or read MISSING_BOOTSTRAP_FILE_ENTRY, /// the bootstrap INI is missing a required entry INVALID_BOOTSTRAP_FILE_ENTRY, /// the bootstrap INI contains invalid data MISSING_VERSION_FILE, /// the version locator INI file could not be found or read MISSING_VERSION_FILE_ENTRY, /// the version locator INI has no entry for this version INVALID_VERSION_FILE_ENTRY, /// the version locator INI entry is not a valid directory URL MISSING_USER_DIRECTORY, /// the user installation directory does not exist INVALID_BOOTSTRAP_DATA /// some bootstrap data was invalid in unexpected ways }; /// Evaluates the status of the installation and returns a diagnostic message corresponding to this status static Status checkBootstrapStatus(rtl::OUString& _rDiagnosticMessage); /** Evaluates the status of the installation and returns a diagnostic message and error code corresponding to this status */ static Status checkBootstrapStatus(rtl::OUString& _rDiagnosticMessage, FailureCode& _rErrCode); public: // singleton impl-class class Impl; static Impl const& data(); // the data related to the bootstrap.ini file }; //----------------------------------------------------------------------------- } // namespace utl #endif // _UTL_BOOTSTRAP_HXX <commit_msg>INTEGRATION: CWS fwk88 (1.13.8); FILE MERGED 2008/05/26 11:36:51 pb 1.13.8.1: fix: #i89054# new: getProductSource()<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: bootstrap.hxx,v $ * $Revision: 1.14 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "unotools/unotoolsdllapi.h" #ifndef _UTL_BOOTSTRAP_HXX #define _UTL_BOOTSTRAP_HXX namespace rtl { class OUString; } namespace utl { //----------------------------------------------------------------------------- /** provides configuration information needed for application startup. <p>This class handles the startup information for the office application. It encapsulates knowledge of how to retriev such information and how to diagnose failures to retriev required data. </p> */ class UNOTOOLS_DLLPUBLIC Bootstrap { // the static interface public: // some common information items /// retrieve the product key; defaults to executable name (without extension) static rtl::OUString getProductKey(); /// retrieve the product key; uses the given default, if not found static rtl::OUString getProductKey(rtl::OUString const& _sDefault); /// retrieve the product source (MWS name) static ::rtl::OUString getProductSource(rtl::OUString const& _sDefault); /// retrieve the LOGO information item; uses the given default, if not found static rtl::OUString getLogoData(rtl::OUString const& _sDefault); // /// retrieve the BUILDID information item; uses the given default, if not found static rtl::OUString getBuildIdData(rtl::OUString const& _sDefault); /// retrieve the product patch level; uses the given default, if not found static rtl::OUString getProductPatchLevel(rtl::OUString const& _sDefault); /// retrieve the ALLUSERS information item from setup.ini file; uses the given default, if not found static rtl::OUString getAllUsersValue(rtl::OUString const& _sDefault); /// reload cached data static void reloadData(); public: // retrieve path information about the installaton location enum PathStatus { PATH_EXISTS, // Success: Found a path to an existing file or directory PATH_VALID, // Found a valid path, but the file or directory does not exist DATA_INVALID, // Retrieved a string for this path, that is not a valid file url or system path DATA_MISSING, // Could not retrieve any data for this path DATA_UNKNOWN // No attempt to retrieve data for this path was made }; /// get a file URL to the common base installation [${insturl}] static PathStatus locateBaseInstallation(rtl::OUString& _rURL); /// get a file URL to the user installation [${userurl}] static PathStatus locateUserInstallation(rtl::OUString& _rURL); /// get a file URL to the shared data directory [default is ${insturl}/share] static PathStatus locateSharedData(rtl::OUString& _rURL); /// get a file URL to the user data directory [default is ${userurl}/user] static PathStatus locateUserData(rtl::OUString& _rURL); // the next two items are mainly supported for diagnostic purposes. both items may be unused /// get a file URL to the bootstrap INI file used [e.g. ${insturl}/program/bootraprc] static PathStatus locateBootstrapFile(rtl::OUString& _rURL); /// get a file URL to the version locator INI file used [e.g. ${SYSUSERCONFIG}/sversion.ini] static PathStatus locateVersionFile(rtl::OUString& _rURL); public: // evaluate the validity of the installation /// high-level status of bootstrap success enum Status { DATA_OK, /// user-dir and share-dir do exist, product key found or can be defaulted to exe-name MISSING_USER_INSTALL, /// ${userurl} does not exist; or version-file cannot be found or is invalid INVALID_USER_INSTALL, /// can locate ${userurl}, but user-dir is missing INVALID_BASE_INSTALL /// other failure: e.g. cannot locate share-dir; bootstraprc missing or invalid; no product key }; /// error code for detailed diagnostics of bootstrap failures enum FailureCode { NO_FAILURE, /// bootstrap was successful MISSING_INSTALL_DIRECTORY, /// the shared installation directory could not be located MISSING_BOOTSTRAP_FILE, /// the bootstrap INI file could not be found or read MISSING_BOOTSTRAP_FILE_ENTRY, /// the bootstrap INI is missing a required entry INVALID_BOOTSTRAP_FILE_ENTRY, /// the bootstrap INI contains invalid data MISSING_VERSION_FILE, /// the version locator INI file could not be found or read MISSING_VERSION_FILE_ENTRY, /// the version locator INI has no entry for this version INVALID_VERSION_FILE_ENTRY, /// the version locator INI entry is not a valid directory URL MISSING_USER_DIRECTORY, /// the user installation directory does not exist INVALID_BOOTSTRAP_DATA /// some bootstrap data was invalid in unexpected ways }; /// Evaluates the status of the installation and returns a diagnostic message corresponding to this status static Status checkBootstrapStatus(rtl::OUString& _rDiagnosticMessage); /** Evaluates the status of the installation and returns a diagnostic message and error code corresponding to this status */ static Status checkBootstrapStatus(rtl::OUString& _rDiagnosticMessage, FailureCode& _rErrCode); public: // singleton impl-class class Impl; static Impl const& data(); // the data related to the bootstrap.ini file }; //----------------------------------------------------------------------------- } // namespace utl #endif // _UTL_BOOTSTRAP_HXX <|endoftext|>
<commit_before>/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Zip alignment tool */ #include "ZipFile.h" #include <stdlib.h> #include <stdio.h> using namespace android; /* * Show program usage. */ void usage(void) { fprintf(stderr, "Zip alignment utility\n"); fprintf(stderr, "Copyright (C) 2009 The Android Open Source Project\n\n"); fprintf(stderr, "Usage: zipalign [-f] [-v] <align> infile.zip outfile.zip\n" " zipalign -c [-v] <align> infile.zip\n\n" ); fprintf(stderr, " <align>: alignment in bytes, e.g. '4' provides 32-bit alignment\n"); fprintf(stderr, " -c: check alignment only (does not modify file)\n"); fprintf(stderr, " -f: overwrite existing outfile.zip\n"); fprintf(stderr, " -v: verbose output\n"); } /* * Copy all entries from "pZin" to "pZout", aligning as needed. */ static int copyAndAlign(ZipFile* pZin, ZipFile* pZout, int alignment) { int numEntries = pZin->getNumEntries(); ZipEntry* pEntry; int bias = 0; status_t status; for (int i = 0; i < numEntries; i++) { ZipEntry* pNewEntry; int padding = 0; pEntry = pZin->getEntryByIndex(i); if (pEntry == NULL) { fprintf(stderr, "ERROR: unable to retrieve entry %d\n", i); return 1; } if (pEntry->isCompressed()) { /* copy the entry without padding */ //printf("--- %s: orig at %ld len=%ld (compressed)\n", // pEntry->getFileName(), (long) pEntry->getFileOffset(), // (long) pEntry->getUncompressedLen()); } else { /* * Copy the entry, adjusting as required. We assume that the * file position in the new file will be equal to the file * position in the original. */ long newOffset = pEntry->getFileOffset() + bias; padding = (alignment - (newOffset % alignment)) % alignment; //printf("--- %s: orig at %ld(+%d) len=%ld, adding pad=%d\n", // pEntry->getFileName(), (long) pEntry->getFileOffset(), // bias, (long) pEntry->getUncompressedLen(), padding); } status = pZout->add(pZin, pEntry, padding, &pNewEntry); if (status != NO_ERROR) return 1; bias += padding; //printf(" added '%s' at %ld (pad=%d)\n", // pNewEntry->getFileName(), (long) pNewEntry->getFileOffset(), // padding); } return 0; } /* * Process a file. We open the input and output files, failing if the * output file exists and "force" wasn't specified. */ static int process(const char* inFileName, const char* outFileName, int alignment, bool force) { ZipFile zin, zout; //printf("PROCESS: align=%d in='%s' out='%s' force=%d\n", // alignment, inFileName, outFileName, force); /* this mode isn't supported -- do a trivial check */ if (strcmp(inFileName, outFileName) == 0) { fprintf(stderr, "Input and output can't be same file\n"); return 1; } /* don't overwrite existing unless given permission */ if (!force && access(outFileName, F_OK) == 0) { fprintf(stderr, "Output file '%s' exists\n", outFileName); return 1; } if (zin.open(inFileName, ZipFile::kOpenReadOnly) != NO_ERROR) { fprintf(stderr, "Unable to open '%s' as zip archive\n", inFileName); return 1; } if (zout.open(outFileName, ZipFile::kOpenReadWrite|ZipFile::kOpenCreate|ZipFile::kOpenTruncate) != NO_ERROR) { fprintf(stderr, "Unable to open '%s' as zip archive\n", inFileName); return 1; } int result = copyAndAlign(&zin, &zout, alignment); if (result != 0) { printf("zipalign: failed rewriting '%s' to '%s'\n", inFileName, outFileName); } return result; } /* * Verify the alignment of a zip archive. */ static int verify(const char* fileName, int alignment, bool verbose) { ZipFile zipFile; bool foundBad = false; if (verbose) printf("Verifying alignment of %s (%d)...\n", fileName, alignment); if (zipFile.open(fileName, ZipFile::kOpenReadOnly) != NO_ERROR) { fprintf(stderr, "Unable to open '%s' for verification\n", fileName); return 1; } int numEntries = zipFile.getNumEntries(); ZipEntry* pEntry; for (int i = 0; i < numEntries; i++) { pEntry = zipFile.getEntryByIndex(i); if (pEntry->isCompressed()) { if (verbose) { printf("%8ld %s (OK - compressed)\n", (long) pEntry->getFileOffset(), pEntry->getFileName()); } } else { long offset = pEntry->getFileOffset(); if ((offset % alignment) != 0) { if (verbose) { printf("%8ld %s (BAD - %ld)\n", (long) offset, pEntry->getFileName(), offset % alignment); } foundBad = true; } else { if (verbose) { printf("%8ld %s (OK)\n", (long) offset, pEntry->getFileName()); } } } } if (verbose) printf("Verification %s\n", foundBad ? "FAILED" : "succesful"); return foundBad ? 1 : 0; } /* * Parse args. */ int main(int argc, char* const argv[]) { bool wantUsage = false; bool check = false; bool force = false; bool verbose = false; int result = 1; int alignment; char* endp; if (argc < 4) { wantUsage = true; goto bail; } argc--; argv++; while (argc && argv[0][0] == '-') { const char* cp = argv[0] +1; while (*cp != '\0') { switch (*cp) { case 'c': check = true; break; case 'f': force = true; break; case 'v': verbose = true; break; default: fprintf(stderr, "ERROR: unknown flag -%c\n", *cp); wantUsage = true; goto bail; } cp++; } argc--; argv++; } if (!((check && argc == 2) || (!check && argc == 3))) { wantUsage = true; goto bail; } alignment = strtol(argv[0], &endp, 10); if (*endp != '\0' || alignment <= 0) { fprintf(stderr, "Invalid value for alignment: %s\n", argv[0]); wantUsage = true; goto bail; } if (check) { /* check existing archive for correct alignment */ result = verify(argv[1], alignment, verbose); } else { /* create the new archive */ result = process(argv[1], argv[2], alignment, force); /* trust, but verify */ if (result == 0) result = verify(argv[2], alignment, verbose); } bail: if (wantUsage) { usage(); result = 2; } return result; } <commit_msg>am 5ac65f86: Merge "Fix reporting wrong error message for zipalign output file"<commit_after>/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Zip alignment tool */ #include "ZipFile.h" #include <stdlib.h> #include <stdio.h> using namespace android; /* * Show program usage. */ void usage(void) { fprintf(stderr, "Zip alignment utility\n"); fprintf(stderr, "Copyright (C) 2009 The Android Open Source Project\n\n"); fprintf(stderr, "Usage: zipalign [-f] [-v] <align> infile.zip outfile.zip\n" " zipalign -c [-v] <align> infile.zip\n\n" ); fprintf(stderr, " <align>: alignment in bytes, e.g. '4' provides 32-bit alignment\n"); fprintf(stderr, " -c: check alignment only (does not modify file)\n"); fprintf(stderr, " -f: overwrite existing outfile.zip\n"); fprintf(stderr, " -v: verbose output\n"); } /* * Copy all entries from "pZin" to "pZout", aligning as needed. */ static int copyAndAlign(ZipFile* pZin, ZipFile* pZout, int alignment) { int numEntries = pZin->getNumEntries(); ZipEntry* pEntry; int bias = 0; status_t status; for (int i = 0; i < numEntries; i++) { ZipEntry* pNewEntry; int padding = 0; pEntry = pZin->getEntryByIndex(i); if (pEntry == NULL) { fprintf(stderr, "ERROR: unable to retrieve entry %d\n", i); return 1; } if (pEntry->isCompressed()) { /* copy the entry without padding */ //printf("--- %s: orig at %ld len=%ld (compressed)\n", // pEntry->getFileName(), (long) pEntry->getFileOffset(), // (long) pEntry->getUncompressedLen()); } else { /* * Copy the entry, adjusting as required. We assume that the * file position in the new file will be equal to the file * position in the original. */ long newOffset = pEntry->getFileOffset() + bias; padding = (alignment - (newOffset % alignment)) % alignment; //printf("--- %s: orig at %ld(+%d) len=%ld, adding pad=%d\n", // pEntry->getFileName(), (long) pEntry->getFileOffset(), // bias, (long) pEntry->getUncompressedLen(), padding); } status = pZout->add(pZin, pEntry, padding, &pNewEntry); if (status != NO_ERROR) return 1; bias += padding; //printf(" added '%s' at %ld (pad=%d)\n", // pNewEntry->getFileName(), (long) pNewEntry->getFileOffset(), // padding); } return 0; } /* * Process a file. We open the input and output files, failing if the * output file exists and "force" wasn't specified. */ static int process(const char* inFileName, const char* outFileName, int alignment, bool force) { ZipFile zin, zout; //printf("PROCESS: align=%d in='%s' out='%s' force=%d\n", // alignment, inFileName, outFileName, force); /* this mode isn't supported -- do a trivial check */ if (strcmp(inFileName, outFileName) == 0) { fprintf(stderr, "Input and output can't be same file\n"); return 1; } /* don't overwrite existing unless given permission */ if (!force && access(outFileName, F_OK) == 0) { fprintf(stderr, "Output file '%s' exists\n", outFileName); return 1; } if (zin.open(inFileName, ZipFile::kOpenReadOnly) != NO_ERROR) { fprintf(stderr, "Unable to open '%s' as zip archive\n", inFileName); return 1; } if (zout.open(outFileName, ZipFile::kOpenReadWrite|ZipFile::kOpenCreate|ZipFile::kOpenTruncate) != NO_ERROR) { fprintf(stderr, "Unable to open '%s' as zip archive\n", outFileName); return 1; } int result = copyAndAlign(&zin, &zout, alignment); if (result != 0) { printf("zipalign: failed rewriting '%s' to '%s'\n", inFileName, outFileName); } return result; } /* * Verify the alignment of a zip archive. */ static int verify(const char* fileName, int alignment, bool verbose) { ZipFile zipFile; bool foundBad = false; if (verbose) printf("Verifying alignment of %s (%d)...\n", fileName, alignment); if (zipFile.open(fileName, ZipFile::kOpenReadOnly) != NO_ERROR) { fprintf(stderr, "Unable to open '%s' for verification\n", fileName); return 1; } int numEntries = zipFile.getNumEntries(); ZipEntry* pEntry; for (int i = 0; i < numEntries; i++) { pEntry = zipFile.getEntryByIndex(i); if (pEntry->isCompressed()) { if (verbose) { printf("%8ld %s (OK - compressed)\n", (long) pEntry->getFileOffset(), pEntry->getFileName()); } } else { long offset = pEntry->getFileOffset(); if ((offset % alignment) != 0) { if (verbose) { printf("%8ld %s (BAD - %ld)\n", (long) offset, pEntry->getFileName(), offset % alignment); } foundBad = true; } else { if (verbose) { printf("%8ld %s (OK)\n", (long) offset, pEntry->getFileName()); } } } } if (verbose) printf("Verification %s\n", foundBad ? "FAILED" : "succesful"); return foundBad ? 1 : 0; } /* * Parse args. */ int main(int argc, char* const argv[]) { bool wantUsage = false; bool check = false; bool force = false; bool verbose = false; int result = 1; int alignment; char* endp; if (argc < 4) { wantUsage = true; goto bail; } argc--; argv++; while (argc && argv[0][0] == '-') { const char* cp = argv[0] +1; while (*cp != '\0') { switch (*cp) { case 'c': check = true; break; case 'f': force = true; break; case 'v': verbose = true; break; default: fprintf(stderr, "ERROR: unknown flag -%c\n", *cp); wantUsage = true; goto bail; } cp++; } argc--; argv++; } if (!((check && argc == 2) || (!check && argc == 3))) { wantUsage = true; goto bail; } alignment = strtol(argv[0], &endp, 10); if (*endp != '\0' || alignment <= 0) { fprintf(stderr, "Invalid value for alignment: %s\n", argv[0]); wantUsage = true; goto bail; } if (check) { /* check existing archive for correct alignment */ result = verify(argv[1], alignment, verbose); } else { /* create the new archive */ result = process(argv[1], argv[2], alignment, force); /* trust, but verify */ if (result == 0) result = verify(argv[2], alignment, verbose); } bail: if (wantUsage) { usage(); result = 2; } return result; } <|endoftext|>
<commit_before>// // NativeGL_iOS.hpp // G3MiOSSDK // // Created by José Miguel S N on 31/07/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #ifndef G3MiOSSDK_NativeGL_iOS_hpp #define G3MiOSSDK_NativeGL_iOS_hpp #include <OpenGLES/ES2/gl.h> #include "INativeGL.hpp" class NativeGL2_iOS: public INativeGL { inline GLbitfield getBitField(GLBufferType b) const { switch (b) { case ColorBuffer: return GL_COLOR_BUFFER_BIT; case DepthBuffer: return GL_DEPTH_BUFFER_BIT; } } inline GLenum getEnum(GLFeature f) const { switch (f) { case PolygonOffsetFill: return GL_POLYGON_OFFSET_FILL; case DepthTest: return GL_DEPTH_TEST; case Blend: return GL_BLEND; case CullFacing: return GL_CULL_FACE; } } inline GLenum getEnum(GLCullFace f) const { switch (f) { case Front: return GL_FRONT; case FrontAndBack: return GL_FRONT_AND_BACK; case Back: return GL_BACK; } } inline GLenum getEnum(GLType t) const { switch (t) { case Float: return GL_FLOAT; case UnsignedByte: return GL_UNSIGNED_BYTE; case UnsignedInt: return GL_UNSIGNED_INT; case Int: return GL_INT; } } inline GLenum getEnum(GLPrimitive p) const { switch (p) { case TriangleStrip: return GL_TRIANGLE_STRIP; case Lines: return GL_LINES; case LineLoop: return GL_LINE_LOOP; case Points: return GL_POINTS; } } inline GLError getError(GLenum e) const { switch (e) { case GL_NO_ERROR: return NoError; case GL_INVALID_ENUM: return InvalidEnum; case GL_INVALID_VALUE: return InvalidValue; case GL_INVALID_OPERATION: return InvalidOperation; case GL_OUT_OF_MEMORY: return OutOfMemory; } return UnknownError; } inline GLenum getEnum(GLBlendFactor b) const { switch (b) { case SrcAlpha: return GL_SRC_ALPHA; case OneMinusSrcAlpha: return GL_ONE_MINUS_SRC_ALPHA; } } inline GLenum getEnum(GLAlignment a) const { switch (a) { case Unpack: return GL_UNPACK_ALIGNMENT; case Pack: return GL_PACK_ALIGNMENT; } } inline GLenum getEnum(GLTextureType t) const { switch (t) { case Texture2D: return GL_TEXTURE_2D; } } inline GLenum getEnum(GLTextureParameter t) const { switch (t) { case MinFilter: return GL_TEXTURE_MIN_FILTER; case MagFilter: return GL_TEXTURE_MAG_FILTER; case WrapS: return GL_TEXTURE_WRAP_S; case WrapT: return GL_TEXTURE_WRAP_T; } } inline GLint getValue(GLTextureParameterValue t) const { switch (t) { case Linear: return GL_LINEAR; case ClampToEdge: return GL_CLAMP_TO_EDGE; } } inline GLenum getEnum(GLFormat f) const { switch (f) { case RGBA: return GL_RGBA; } } inline GLenum getEnum(GLVariable f) const { switch (f) { case Viewport: return GL_VIEWPORT; } } public: void useProgram(int program) const { glUseProgram(program); } int getAttribLocation(int program, const std::string& name) const { return glGetAttribLocation(program, name.c_str()); } int getUniformLocation(int program, const std::string& name) const { return glGetUniformLocation(program, name.c_str()); } void uniform2f(int loc, float x, float y) const { glUniform2f(loc, x, y); } void uniform1f(int loc, float x) const { glUniform1f(loc, x); } void uniform1i(int loc, int v) const { glUniform1i(loc, v); } void uniformMatrix4fv(int location, int count, bool transpose, const float value[]) const { glUniformMatrix4fv(location, count, transpose, value); } void clearColor(float red, float green, float blue, float alpha) const { glClearColor(red, green, blue, alpha); } void clear(int nBuffer, GLBufferType buffers[]) const { GLbitfield b = 0x000000; for (int i = 0; i < nBuffer; i++) { b |= getBitField(buffers[i]); } glClear(b); } void uniform4f(int location, float v0, float v1, float v2, float v3) const { glUniform4f(location, v0, v1, v2, v3); } void enable(GLFeature feature) const { GLenum v = getEnum(feature); glEnable(v); } void disable(GLFeature feature) const { GLenum v = getEnum(feature); glDisable(v); } void polygonOffset(float factor, float units) const { glPolygonOffset(factor, units); } void vertexAttribPointer(int index, int size, bool normalized, int stride, IFloatBuffer* buffer) const { float* pointer = ((FloatBuffer_iOS*) buffer)->getPointer(); glVertexAttribPointer(index, size, GL_FLOAT, normalized, stride, pointer); } void drawElements(GLPrimitive mode, int count, IIntBuffer* buffer) const { int has_to_set_GL_UNSIGNED_INT; //??????? int* pointer = ((IntBuffer_iOS*) buffer)->getPointer(); glDrawElements(getEnum(mode), count, GL_UNSIGNED_INT, pointer); } void lineWidth(float width) const { glLineWidth(width); } GLError getError() const { return getError(glGetError()); } void blendFunc(GLBlendFactor sfactor, GLBlendFactor dfactor) const { glBlendFunc(getEnum(sfactor), getEnum(dfactor)); } void bindTexture(GLTextureType target, int texture) const { glBindTexture(getEnum(target), texture); } void deleteTextures(int n, const int textures[]) const { unsigned int ts[n]; for(int i = 0; i < n; i++){ ts[i] = textures[i]; } glDeleteTextures(n, ts); } void enableVertexAttribArray(int location) const { glEnableVertexAttribArray(location); } void disableVertexAttribArray(int location) const { glDisableVertexAttribArray(location); } void pixelStorei(GLAlignment pname, int param) const { glPixelStorei(getEnum(pname), param); } std::vector<GLTextureId> genTextures(int n) const { GLuint textures[n]; glGenTextures(n, textures); std::vector<GLTextureId> ts; for(int i = 0; i < n; i++){ ts.push_back( GLTextureId(textures[i]) ); } return ts; } void texParameteri(GLTextureType target, GLTextureParameter par, GLTextureParameterValue v) const { glTexParameteri(getEnum(target), getEnum(par), getValue(v)); } void texImage2D(const IImage* image, GLFormat format) const { IByteBuffer* bb = ((Image_iOS*) image)->createByteBufferRGBA8888(image->getWidth(), image->getHeight()); glTexImage2D(GL_TEXTURE_2D, 0, getEnum(format), image->getWidth(), image->getHeight(), 0, getEnum(format), GL_UNSIGNED_BYTE, ((ByteBuffer_iOS*)bb)->getPointer()); } // void texImage2D(GLTextureType target, // int level, // GLFormat internalFormat, // int width, // int height, // int border, // GLFormat format, // GLType type, // const void* data) const { // glTexImage2D(getEnum(target), level, getEnum(internalFormat), // width, height, border, getEnum(format), getEnum(type), data); // } void generateMipmap(GLTextureType target) const { glGenerateMipmap(getEnum(target)); } void drawArrays(GLPrimitive mode, int first, int count) const { glDrawArrays(getEnum(mode), first, count); } void cullFace(GLCullFace c) const { glCullFace(getEnum(c)); } void getIntegerv(GLVariable v, int i[]) const { glGetIntegerv(getEnum(v), i); } }; #endif <commit_msg>Leak solved<commit_after>// // NativeGL_iOS.hpp // G3MiOSSDK // // Created by José Miguel S N on 31/07/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #ifndef G3MiOSSDK_NativeGL_iOS_hpp #define G3MiOSSDK_NativeGL_iOS_hpp #include <OpenGLES/ES2/gl.h> #include "INativeGL.hpp" class NativeGL2_iOS: public INativeGL { inline GLbitfield getBitField(GLBufferType b) const { switch (b) { case ColorBuffer: return GL_COLOR_BUFFER_BIT; case DepthBuffer: return GL_DEPTH_BUFFER_BIT; } } inline GLenum getEnum(GLFeature f) const { switch (f) { case PolygonOffsetFill: return GL_POLYGON_OFFSET_FILL; case DepthTest: return GL_DEPTH_TEST; case Blend: return GL_BLEND; case CullFacing: return GL_CULL_FACE; } } inline GLenum getEnum(GLCullFace f) const { switch (f) { case Front: return GL_FRONT; case FrontAndBack: return GL_FRONT_AND_BACK; case Back: return GL_BACK; } } inline GLenum getEnum(GLType t) const { switch (t) { case Float: return GL_FLOAT; case UnsignedByte: return GL_UNSIGNED_BYTE; case UnsignedInt: return GL_UNSIGNED_INT; case Int: return GL_INT; } } inline GLenum getEnum(GLPrimitive p) const { switch (p) { case TriangleStrip: return GL_TRIANGLE_STRIP; case Lines: return GL_LINES; case LineLoop: return GL_LINE_LOOP; case Points: return GL_POINTS; } } inline GLError getError(GLenum e) const { switch (e) { case GL_NO_ERROR: return NoError; case GL_INVALID_ENUM: return InvalidEnum; case GL_INVALID_VALUE: return InvalidValue; case GL_INVALID_OPERATION: return InvalidOperation; case GL_OUT_OF_MEMORY: return OutOfMemory; } return UnknownError; } inline GLenum getEnum(GLBlendFactor b) const { switch (b) { case SrcAlpha: return GL_SRC_ALPHA; case OneMinusSrcAlpha: return GL_ONE_MINUS_SRC_ALPHA; } } inline GLenum getEnum(GLAlignment a) const { switch (a) { case Unpack: return GL_UNPACK_ALIGNMENT; case Pack: return GL_PACK_ALIGNMENT; } } inline GLenum getEnum(GLTextureType t) const { switch (t) { case Texture2D: return GL_TEXTURE_2D; } } inline GLenum getEnum(GLTextureParameter t) const { switch (t) { case MinFilter: return GL_TEXTURE_MIN_FILTER; case MagFilter: return GL_TEXTURE_MAG_FILTER; case WrapS: return GL_TEXTURE_WRAP_S; case WrapT: return GL_TEXTURE_WRAP_T; } } inline GLint getValue(GLTextureParameterValue t) const { switch (t) { case Linear: return GL_LINEAR; case ClampToEdge: return GL_CLAMP_TO_EDGE; } } inline GLenum getEnum(GLFormat f) const { switch (f) { case RGBA: return GL_RGBA; } } inline GLenum getEnum(GLVariable f) const { switch (f) { case Viewport: return GL_VIEWPORT; } } public: void useProgram(int program) const { glUseProgram(program); } int getAttribLocation(int program, const std::string& name) const { return glGetAttribLocation(program, name.c_str()); } int getUniformLocation(int program, const std::string& name) const { return glGetUniformLocation(program, name.c_str()); } void uniform2f(int loc, float x, float y) const { glUniform2f(loc, x, y); } void uniform1f(int loc, float x) const { glUniform1f(loc, x); } void uniform1i(int loc, int v) const { glUniform1i(loc, v); } void uniformMatrix4fv(int location, int count, bool transpose, const float value[]) const { glUniformMatrix4fv(location, count, transpose, value); } void clearColor(float red, float green, float blue, float alpha) const { glClearColor(red, green, blue, alpha); } void clear(int nBuffer, GLBufferType buffers[]) const { GLbitfield b = 0x000000; for (int i = 0; i < nBuffer; i++) { b |= getBitField(buffers[i]); } glClear(b); } void uniform4f(int location, float v0, float v1, float v2, float v3) const { glUniform4f(location, v0, v1, v2, v3); } void enable(GLFeature feature) const { GLenum v = getEnum(feature); glEnable(v); } void disable(GLFeature feature) const { GLenum v = getEnum(feature); glDisable(v); } void polygonOffset(float factor, float units) const { glPolygonOffset(factor, units); } void vertexAttribPointer(int index, int size, bool normalized, int stride, IFloatBuffer* buffer) const { float* pointer = ((FloatBuffer_iOS*) buffer)->getPointer(); glVertexAttribPointer(index, size, GL_FLOAT, normalized, stride, pointer); } void drawElements(GLPrimitive mode, int count, IIntBuffer* buffer) const { int has_to_set_GL_UNSIGNED_INT; //??????? int* pointer = ((IntBuffer_iOS*) buffer)->getPointer(); glDrawElements(getEnum(mode), count, GL_UNSIGNED_INT, pointer); } void lineWidth(float width) const { glLineWidth(width); } GLError getError() const { return getError(glGetError()); } void blendFunc(GLBlendFactor sfactor, GLBlendFactor dfactor) const { glBlendFunc(getEnum(sfactor), getEnum(dfactor)); } void bindTexture(GLTextureType target, int texture) const { glBindTexture(getEnum(target), texture); } void deleteTextures(int n, const int textures[]) const { unsigned int ts[n]; for(int i = 0; i < n; i++){ ts[i] = textures[i]; } glDeleteTextures(n, ts); } void enableVertexAttribArray(int location) const { glEnableVertexAttribArray(location); } void disableVertexAttribArray(int location) const { glDisableVertexAttribArray(location); } void pixelStorei(GLAlignment pname, int param) const { glPixelStorei(getEnum(pname), param); } std::vector<GLTextureId> genTextures(int n) const { GLuint textures[n]; glGenTextures(n, textures); std::vector<GLTextureId> ts; for(int i = 0; i < n; i++){ ts.push_back( GLTextureId(textures[i]) ); } return ts; } void texParameteri(GLTextureType target, GLTextureParameter par, GLTextureParameterValue v) const { glTexParameteri(getEnum(target), getEnum(par), getValue(v)); } void texImage2D(const IImage* image, GLFormat format) const { IByteBuffer* bb = ((Image_iOS*) image)->createByteBufferRGBA8888(image->getWidth(), image->getHeight()); glTexImage2D(GL_TEXTURE_2D, 0, getEnum(format), image->getWidth(), image->getHeight(), 0, getEnum(format), GL_UNSIGNED_BYTE, ((ByteBuffer_iOS*)bb)->getPointer()); delete bb; } // void texImage2D(GLTextureType target, // int level, // GLFormat internalFormat, // int width, // int height, // int border, // GLFormat format, // GLType type, // const void* data) const { // glTexImage2D(getEnum(target), level, getEnum(internalFormat), // width, height, border, getEnum(format), getEnum(type), data); // } void generateMipmap(GLTextureType target) const { glGenerateMipmap(getEnum(target)); } void drawArrays(GLPrimitive mode, int first, int count) const { glDrawArrays(getEnum(mode), first, count); } void cullFace(GLCullFace c) const { glCullFace(getEnum(c)); } void getIntegerv(GLVariable v, int i[]) const { glGetIntegerv(getEnum(v), i); } }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: uiconfigurationmanager.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-03-11 11:05:24 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_ #define __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_ /** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble with solaris headers ... */ #include <vector> #include <list> #include <hash_map> //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif #ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_ #include <macros/xserviceinfo.hxx> #endif #ifndef __FRAMEWORK_STDTYPES_H_ #include <stdtypes.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATION_HPP_ #include <drafts/com/sun/star/ui/XUIConfiguration.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATIONPERSISTENCE_HPP_ #include <drafts/com/sun/star/ui/XUIConfigurationPersistence.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATIONSTORGAE_HPP_ #include <drafts/com/sun/star/ui/XUIConfigurationStorage.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATIONMANAGER_HPP_ #include <drafts/com/sun/star/ui/XUIConfigurationManager.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_CONFIGURATIONEVENT_HPP_ #include <drafts/com/sun/star/ui/ConfigurationEvent.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_ #include <drafts/com/sun/star/ui/UIElementType.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_ #include <com/sun/star/container/XIndexContainer.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif namespace framework { class UIConfigurationManager : public com::sun::star::lang::XTypeProvider , public com::sun::star::lang::XServiceInfo , public com::sun::star::lang::XComponent , public drafts::com::sun::star::ui::XUIConfiguration , public drafts::com::sun::star::ui::XUIConfigurationManager , public drafts::com::sun::star::ui::XUIConfigurationPersistence , public drafts::com::sun::star::ui::XUIConfigurationStorage , private ThreadHelpBase , // Struct for right initalization of mutex member! Must be first of baseclasses. public ::cppu::OWeakObject { public: // XInterface, XTypeProvider, XServiceInfo DECLARE_XINTERFACE DECLARE_XTYPEPROVIDER DECLARE_XSERVICEINFO UIConfigurationManager( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > xServiceManager ); virtual ~UIConfigurationManager(); // XComponent virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // XUIConfiguration virtual void SAL_CALL addConfigurationListener( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::ui::XUIConfigurationListener >& Listener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeConfigurationListener( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::ui::XUIConfigurationListener >& Listener ) throw (::com::sun::star::uno::RuntimeException); // XUIConfigurationManager virtual void SAL_CALL reset() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > SAL_CALL getUIElementsInfo( sal_Int16 ElementType ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer > SAL_CALL createSettings( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > SAL_CALL getSettings( const ::rtl::OUString& ResourceURL, sal_Bool bWriteable ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL replaceSettings( const ::rtl::OUString& ResourceURL, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& aNewData ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL insertSettings( const ::rtl::OUString& NewResourceURL, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& aNewData ) throw (::com::sun::star::container::ElementExistException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getImageManager() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getShortCutManager() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getEventsManager() throw (::com::sun::star::uno::RuntimeException); // XUIConfigurationPersistence virtual void SAL_CALL reload() throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL store() throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL storeToStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isModified() throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isReadOnly() throw (::com::sun::star::uno::RuntimeException); // XUIConfigurationStorage virtual void SAL_CALL setStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasStorage() throw (::com::sun::star::uno::RuntimeException); private: // private data types enum NotifyOp { NotifyOp_Remove, NotifyOp_Insert, NotifyOp_Replace }; struct UIElementInfo { UIElementInfo( const rtl::OUString& rResourceURL, const rtl::OUString& rUIName ) : aResourceURL( rResourceURL), aUIName( rUIName ) {} rtl::OUString aResourceURL; rtl::OUString aUIName; }; struct UIElementData { UIElementData() : bModified( false ), bDefault( true ) {}; rtl::OUString aResourceURL; rtl::OUString aName; bool bModified; // has been changed since last storing bool bDefault; // default settings com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > xSettings; }; struct UIElementType; friend struct UIElementType; typedef ::std::hash_map< rtl::OUString, UIElementData, OUStringHashCode, ::std::equal_to< rtl::OUString > > UIElementDataHashMap; struct UIElementType { UIElementType() : nElementType( drafts::com::sun::star::ui::UIElementType::UNKNOWN ), bLoaded( false ), bModified( false ), bDefaultLayer( false ) {} bool bModified; bool bLoaded; bool bDefaultLayer; sal_Int16 nElementType; UIElementDataHashMap aElementsHashMap; com::sun::star::uno::Reference< com::sun::star::embed::XStorage > xStorage; }; typedef ::std::vector< UIElementType > UIElementTypesVector; typedef ::std::vector< drafts::com::sun::star::ui::ConfigurationEvent > ConfigEventNotifyContainer; typedef ::std::hash_map< rtl::OUString, UIElementInfo, OUStringHashCode, ::std::equal_to< rtl::OUString > > UIElementInfoHashMap; // private methods void impl_Initialize(); void implts_notifyContainerListener( const drafts::com::sun::star::ui::ConfigurationEvent& aEvent, NotifyOp eOp ); void impl_fillSequenceWithElementTypeInfo( UIElementInfoHashMap& aUIElementInfoCollection, sal_Int16 nElementType ); void impl_preloadUIElementTypeList( sal_Int16 nElementType ); UIElementData* impl_findUIElementData( const rtl::OUString& aResourceURL, sal_Int16 nElementType, bool bLoad = true ); void impl_requestUIElementData( sal_Int16 nElementType, UIElementData& aUIElementData ); void impl_storeElementTypeData( com::sun::star::uno::Reference< com::sun::star::embed::XStorage >& xStorage, UIElementType& rElementType, bool bResetModifyState = true ); void impl_resetElementTypeData( UIElementType& rDocElementType, ConfigEventNotifyContainer& rRemoveNotifyContainer ); void impl_reloadElementTypeData( UIElementType& rDocElementType, ConfigEventNotifyContainer& rRemoveNotifyContainer, ConfigEventNotifyContainer& rReplaceNotifyContainer ); UIElementTypesVector m_aUIElements; com::sun::star::uno::Reference< com::sun::star::embed::XStorage > m_xDocConfigStorage; bool m_bReadOnly; bool m_bInitialized; bool m_bModified; bool m_bConfigRead; bool m_bDisposed; rtl::OUString m_aXMLPostfix; rtl::OUString m_aPropUIName; rtl::OUString m_aPropResourceURL; rtl::OUString m_aModuleIdentifier; com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > m_xServiceManager; ::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener }; } #endif // __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_ <commit_msg>INTEGRATION: CWS docking1 (1.3.10); FILE MERGED 2004/06/20 19:55:01 cd 1.3.10.1: #i30169# Added files for image manager<commit_after>/************************************************************************* * * $RCSfile: uiconfigurationmanager.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-07-06 16:51:32 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_ #define __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_ /** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble with solaris headers ... */ #include <vector> #include <list> #include <hash_map> //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif #ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_ #include <macros/xserviceinfo.hxx> #endif #ifndef __FRAMEWORK_STDTYPES_H_ #include <stdtypes.h> #endif #ifndef __FRAMEWORK_UICONFIGURATION_IMAGEMANAGER_HXX_ #include <uiconfiguration/imagemanager.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATION_HPP_ #include <drafts/com/sun/star/ui/XUIConfiguration.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATIONPERSISTENCE_HPP_ #include <drafts/com/sun/star/ui/XUIConfigurationPersistence.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATIONSTORGAE_HPP_ #include <drafts/com/sun/star/ui/XUIConfigurationStorage.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATIONMANAGER_HPP_ #include <drafts/com/sun/star/ui/XUIConfigurationManager.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_CONFIGURATIONEVENT_HPP_ #include <drafts/com/sun/star/ui/ConfigurationEvent.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_ #include <drafts/com/sun/star/ui/UIElementType.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_ #include <com/sun/star/container/XIndexContainer.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif namespace framework { class UIConfigurationManager : public com::sun::star::lang::XTypeProvider , public com::sun::star::lang::XServiceInfo , public com::sun::star::lang::XComponent , public drafts::com::sun::star::ui::XUIConfiguration , public drafts::com::sun::star::ui::XUIConfigurationManager , public drafts::com::sun::star::ui::XUIConfigurationPersistence , public drafts::com::sun::star::ui::XUIConfigurationStorage , private ThreadHelpBase , // Struct for right initalization of mutex member! Must be first of baseclasses. public ::cppu::OWeakObject { public: // XInterface, XTypeProvider, XServiceInfo DECLARE_XINTERFACE DECLARE_XTYPEPROVIDER DECLARE_XSERVICEINFO UIConfigurationManager( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > xServiceManager ); virtual ~UIConfigurationManager(); // XComponent virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException); // XUIConfiguration virtual void SAL_CALL addConfigurationListener( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::ui::XUIConfigurationListener >& Listener ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeConfigurationListener( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::ui::XUIConfigurationListener >& Listener ) throw (::com::sun::star::uno::RuntimeException); // XUIConfigurationManager virtual void SAL_CALL reset() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > SAL_CALL getUIElementsInfo( sal_Int16 ElementType ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer > SAL_CALL createSettings( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > SAL_CALL getSettings( const ::rtl::OUString& ResourceURL, sal_Bool bWriteable ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL replaceSettings( const ::rtl::OUString& ResourceURL, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& aNewData ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL insertSettings( const ::rtl::OUString& NewResourceURL, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& aNewData ) throw (::com::sun::star::container::ElementExistException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getImageManager() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getShortCutManager() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getEventsManager() throw (::com::sun::star::uno::RuntimeException); // XUIConfigurationPersistence virtual void SAL_CALL reload() throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL store() throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL storeToStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isModified() throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isReadOnly() throw (::com::sun::star::uno::RuntimeException); // XUIConfigurationStorage virtual void SAL_CALL setStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasStorage() throw (::com::sun::star::uno::RuntimeException); private: // private data types enum NotifyOp { NotifyOp_Remove, NotifyOp_Insert, NotifyOp_Replace }; struct UIElementInfo { UIElementInfo( const rtl::OUString& rResourceURL, const rtl::OUString& rUIName ) : aResourceURL( rResourceURL), aUIName( rUIName ) {} rtl::OUString aResourceURL; rtl::OUString aUIName; }; struct UIElementData { UIElementData() : bModified( false ), bDefault( true ) {}; rtl::OUString aResourceURL; rtl::OUString aName; bool bModified; // has been changed since last storing bool bDefault; // default settings com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > xSettings; }; struct UIElementType; friend struct UIElementType; typedef ::std::hash_map< rtl::OUString, UIElementData, OUStringHashCode, ::std::equal_to< rtl::OUString > > UIElementDataHashMap; struct UIElementType { UIElementType() : nElementType( drafts::com::sun::star::ui::UIElementType::UNKNOWN ), bLoaded( false ), bModified( false ), bDefaultLayer( false ) {} bool bModified; bool bLoaded; bool bDefaultLayer; sal_Int16 nElementType; UIElementDataHashMap aElementsHashMap; com::sun::star::uno::Reference< com::sun::star::embed::XStorage > xStorage; }; typedef ::std::vector< UIElementType > UIElementTypesVector; typedef ::std::vector< drafts::com::sun::star::ui::ConfigurationEvent > ConfigEventNotifyContainer; typedef ::std::hash_map< rtl::OUString, UIElementInfo, OUStringHashCode, ::std::equal_to< rtl::OUString > > UIElementInfoHashMap; // private methods void impl_Initialize(); void implts_notifyContainerListener( const drafts::com::sun::star::ui::ConfigurationEvent& aEvent, NotifyOp eOp ); void impl_fillSequenceWithElementTypeInfo( UIElementInfoHashMap& aUIElementInfoCollection, sal_Int16 nElementType ); void impl_preloadUIElementTypeList( sal_Int16 nElementType ); UIElementData* impl_findUIElementData( const rtl::OUString& aResourceURL, sal_Int16 nElementType, bool bLoad = true ); void impl_requestUIElementData( sal_Int16 nElementType, UIElementData& aUIElementData ); void impl_storeElementTypeData( com::sun::star::uno::Reference< com::sun::star::embed::XStorage >& xStorage, UIElementType& rElementType, bool bResetModifyState = true ); void impl_resetElementTypeData( UIElementType& rDocElementType, ConfigEventNotifyContainer& rRemoveNotifyContainer ); void impl_reloadElementTypeData( UIElementType& rDocElementType, ConfigEventNotifyContainer& rRemoveNotifyContainer, ConfigEventNotifyContainer& rReplaceNotifyContainer ); UIElementTypesVector m_aUIElements; com::sun::star::uno::Reference< com::sun::star::embed::XStorage > m_xDocConfigStorage; bool m_bReadOnly; bool m_bInitialized; bool m_bModified; bool m_bConfigRead; bool m_bDisposed; rtl::OUString m_aXMLPostfix; rtl::OUString m_aPropUIName; rtl::OUString m_aPropResourceURL; rtl::OUString m_aModuleIdentifier; com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > m_xServiceManager; ::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener com::sun::star::uno::Reference< com::sun::star::lang::XComponent > m_xImageManager; }; } #endif // __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_ <|endoftext|>
<commit_before>#include <ph.h> #include <phInput.h> #include <phBC.h> #include <phRestart.h> #include <phAdapt.h> #include <phOutput.h> #include <phPartition.h> #include <apfMDS.h> #include <apfMesh2.h> #include <apf.h> #include <gmi_mesh.h> #include <PCU.h> #include <cassert> #error "recompile with ENABLE_THREADS=OFF. blame Cameron" ph::Input* globalInput; ph::BCs* globalBCs; int globalPeers; static void afterSplit(apf::Mesh2* m) { ph::Input& in = *globalInput; ph::BCs& bcs = *globalBCs; std::string path = ph::setupOutputDir(); ph::setupOutputSubdir(path); /* check if the mesh changed at all */ if ((PCU_Comm_Peers()!=globalPeers) || in.adaptFlag || in.tetrahedronize) { if (in.parmaPtn && PCU_Comm_Peers() > 1) ph::balance(in,m); apf::reorderMdsMesh(m); } assert(!in.filterMatches); ph::Output o; ph::generateOutput(in, bcs, m, o); ph::detachAndWriteSolution(in, m, path); ph::writeGeomBC(o, path); ph::writeAuxiliaryFiles(path, in.timeStepNumber); if ( ! in.outMeshFileName.empty() ) m->writeNative(in.outMeshFileName.c_str()); m->verify(); m->destroyNative(); apf::destroyMesh(m); } int main(int argc, char** argv) { int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); assert(provided == MPI_THREAD_MULTIPLE); PCU_Comm_Init(); PCU_Protect(); gmi_register_mesh(); globalPeers = PCU_Comm_Peers(); ph::Input in; in.load("adapt.inp"); apf::Mesh2* m = apf::loadMdsMesh( in.modelFileName.c_str(), in.meshFileName.c_str()); m->verify(); ph::BCs bcs; ph::readBCs(in.attributeFileName.c_str(), bcs); if (in.solutionMigration) ph::readAndAttachSolution(in, m); else ph::attachZeroSolution(in, m); if (in.buildMapping) ph::buildMapping(m); apf::setMigrationLimit(in.elementsPerMigration); if (in.adaptFlag) { ph::adapt(in, m); ph::goToStepDir(in.timeStepNumber); } if (in.tetrahedronize) ph::tetrahedronize(in, m); globalInput = &in; globalBCs = &bcs; ph::split(in, m, afterSplit); PCU_Comm_Free(); MPI_Finalize(); } <commit_msg>set file readers and writers<commit_after>#include <ph.h> #include <phInput.h> #include <phBC.h> #include <phRestart.h> #include <phAdapt.h> #include <phOutput.h> #include <phPartition.h> #include <apfMDS.h> #include <apfMesh2.h> #include <apf.h> #include <gmi_mesh.h> #include <PCU.h> #include <cassert> namespace { static FILE* openFileRead(ph::Input&, const char* path) { return fopen(path, "r"); } static FILE* openFileWrite(ph::Output&, const char* path) { return fopen(path, "w"); } } ph::Input* globalInput; ph::BCs* globalBCs; int globalPeers; static void afterSplit(apf::Mesh2* m) { ph::Input& in = *globalInput; ph::BCs& bcs = *globalBCs; std::string path = ph::setupOutputDir(); ph::setupOutputSubdir(path); /* check if the mesh changed at all */ if ((PCU_Comm_Peers()!=globalPeers) || in.adaptFlag || in.tetrahedronize) { if (in.parmaPtn && PCU_Comm_Peers() > 1) ph::balance(in,m); apf::reorderMdsMesh(m); } assert(!in.filterMatches); ph::Output o; o.openfile_write = openFileWrite; ph::generateOutput(in, bcs, m, o); ph::detachAndWriteSolution(in, o, m, path); ph::writeGeomBC(o, path); ph::writeAuxiliaryFiles(path, in.timeStepNumber); if ( ! in.outMeshFileName.empty() ) m->writeNative(in.outMeshFileName.c_str()); m->verify(); m->destroyNative(); apf::destroyMesh(m); } int main(int argc, char** argv) { int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); assert(provided == MPI_THREAD_MULTIPLE); PCU_Comm_Init(); PCU_Protect(); gmi_register_mesh(); globalPeers = PCU_Comm_Peers(); ph::Input in; in.openfile_read = openFileRead; in.load("adapt.inp"); apf::Mesh2* m = apf::loadMdsMesh( in.modelFileName.c_str(), in.meshFileName.c_str()); m->verify(); ph::BCs bcs; ph::readBCs(in.attributeFileName.c_str(), bcs); if (in.solutionMigration) ph::readAndAttachSolution(in, m); else ph::attachZeroSolution(in, m); if (in.buildMapping) ph::buildMapping(m); apf::setMigrationLimit(in.elementsPerMigration); if (in.adaptFlag) { ph::adapt(in, m); ph::goToStepDir(in.timeStepNumber); } if (in.tetrahedronize) ph::tetrahedronize(in, m); globalInput = &in; globalBCs = &bcs; ph::split(in, m, afterSplit); PCU_Comm_Free(); MPI_Finalize(); } <|endoftext|>
<commit_before>/** @file * @author Edouard DUPIN * @copyright 2016, Edouard DUPIN, all right reserved * @license MPL v2.0 (see license file) */ #pragma once #include <zeus/WebServer.hpp> #include <eproperty/Value.hpp> #include <zeus/AbstractFunctionTypeDirect.hpp> #include <zeus/AbstractFunctionTypeClass.hpp> #include <zeus/debug.hpp> #include <zeus/RemoteProcessCall.hpp> #include <zeus/Future.hpp> #include <zeus/Client.hpp> /** * @brief Main zeus library namespace */ namespace zeus { class Client; /** * @brief An object is an element callable from the remote. */ class Object : public zeus::RemoteProcessCall { public: /** * @brief Get the current object local unique ID * @return The unique Object id */ uint16_t getObjectId() { return m_objectId; } /** * @brief Contruct a new callable object * @param[in] _iface Network interface * @param[in] _objectId Unique Id of the object */ Object(const ememory::SharedPtr<zeus::WebServer>& _iface, uint16_t _objectId); /** * @brief generic destructor */ virtual ~Object() = default; public: /** * @brief Receive message to parse and execute * @param[in] _value Message to process */ void receive(ememory::SharedPtr<zeus::Message> _value); private: /** * @brief Specific call depending of the type of the object. * @param[in] _call Name of the function that is called. * @param[in] _value Message to process. */ virtual void callBinary(const std::string& _call, ememory::SharedPtr<zeus::message::Call> _value) = 0; public: /** * @brief Advertise a new function in the service/object ==> it is force the start with "obj.". * @param[in] _name Name of the function * @param[in] _func pointer on the function that might be used to call it. * @return an handle on an abstract function that can be called. */ // Add Local fuction (depend on this class) template<class ZEUS_RETURN_VALUE, class ZEUS_CLASS_TYPE, class... ZEUS_FUNC_ARGS_TYPE> zeus::AbstractFunction* advertise(std::string _name, ZEUS_RETURN_VALUE (ZEUS_CLASS_TYPE::*_func)(ZEUS_FUNC_ARGS_TYPE... _args)) { _name = "obj." + _name; for (auto &it : m_listFunction) { if (it == nullptr) { continue; } if (it->getName() == _name) { ZEUS_ERROR("Advertise function already bind .. ==> can not be done...: '" << _name << "'"); return nullptr; } } AbstractFunction* tmp = createAbstractFunctionClass(_name, _func); if (tmp == nullptr) { ZEUS_ERROR("can not create abstract function ... '" << _name << "'"); return nullptr; } tmp->setType(zeus::AbstractFunction::type::service); ZEUS_VERBOSE("Add function '" << _name << "' in local mode"); m_listFunction.push_back(tmp); return tmp; } }; /** * @brief The object is all time different, and we need to called it corectly and keep it alive while the remote user need it. * The this class permit to have a a pointer on the temporary object. */ template<class ZEUS_TYPE_OBJECT> class ObjectType : public zeus::Object { private: ememory::SharedPtr<ZEUS_TYPE_OBJECT> m_interface; //!< handle on the object that might be called. public: ObjectType(const ememory::SharedPtr<zeus::WebServer>& _iface, uint16_t _objectId, const ememory::SharedPtr<ZEUS_TYPE_OBJECT>& _element) : Object(_iface, _objectId), m_interface(_element) { // nothing else to do ... } public: /** * @brief Advertise a new signal that use a specific call processing order * @param[in] _name Name of the function * @param[in] _func Pointer on the function to call when name call is requested * @return Pointer on the function abstraction call that is done * @note: this is for ACTION function call not normal function call */ template<class ZEUS_RETURN_VALUE, class ZEUS_ACTION_TYPE, class ZEUS_CLASS_TYPE, class... ZEUS_FUNC_ARGS_TYPE> zeus::AbstractFunction* advertise(const std::string& _name, ZEUS_RETURN_VALUE (ZEUS_CLASS_TYPE::*_func)(zeus::ActionNotification<ZEUS_ACTION_TYPE>& _notifs, ZEUS_FUNC_ARGS_TYPE... _args)) { if (etk::start_with(_name, "srv.") == true) { ZEUS_ERROR("Advertise function start with 'srv.' is not permited ==> only allow for internal service: '" << _name << "'"); return nullptr; } for (auto &it : m_listFunction) { if (it == nullptr) { continue; } if (it->getName() == _name) { ZEUS_ERROR("Advertise function already bind .. ==> can not be done...: '" << _name << "'"); return nullptr; } } zeus::AbstractFunction* tmp = createAbstractFunctionClass(_name, _func); if (tmp == nullptr) { ZEUS_ERROR("can not create abstract function ... '" << _name << "'"); return nullptr; } tmp->setType(zeus::AbstractFunction::type::object); ZEUS_VERBOSE("Add function '" << _name << "' in object mode"); m_listFunction.push_back(tmp); return tmp; } /** * @brief Advertise a new signal that use a specific call processing order * @param[in] _name Name of the function * @param[in] _func Pointer on the function to call when name call is requested * @return Pointer on the function abstraction call that is done * @note: this is for normal function call not action call */ template<class ZEUS_RETURN_VALUE, class ZEUS_CLASS_TYPE, class... ZEUS_FUNC_ARGS_TYPE> zeus::AbstractFunction* advertise(const std::string& _name, ZEUS_RETURN_VALUE (ZEUS_CLASS_TYPE::*_func)(ZEUS_FUNC_ARGS_TYPE... _args)) { if (etk::start_with(_name, "srv.") == true) { ZEUS_ERROR("Advertise function start with 'srv.' is not permited ==> only allow for internal service: '" << _name << "'"); return nullptr; } for (auto &it : m_listFunction) { if (it == nullptr) { continue; } if (it->getName() == _name) { ZEUS_ERROR("Advertise function already bind .. ==> can not be done...: '" << _name << "'"); return nullptr; } } zeus::AbstractFunction* tmp = createAbstractFunctionClass(_name, _func); if (tmp == nullptr) { ZEUS_ERROR("can not create abstract function ... '" << _name << "'"); return nullptr; } tmp->setType(zeus::AbstractFunction::type::object); ZEUS_VERBOSE("Add function '" << _name << "' in object mode"); m_listFunction.push_back(tmp); return tmp; } bool isFunctionAuthorized(uint64_t _clientId, const std::string& _funcName) override { /* auto it = m_interface.find(_clientId); if (it == m_interface.end()) { ZEUS_ERROR("CLIENT does not exist ... " << _clientId << " " << _funcName); return false; } return it->second.first->isFunctionAuthorized(_funcName); */ return true; } /** * @brief Find and call the functionwith a specific name * @param[in] _call Function name to call * @param[in] _value Message to process. */ void callBinary(const std::string& _call, ememory::SharedPtr<zeus::message::Call> _value) { for (auto &it2 : m_listFunction) { if (it2 == nullptr) { continue; } if (it2->getName() != _call) { continue; } // TODO: Check if client is athorized ... // depending on where the function is defined, the call is not the same ... switch (it2->getType()) { case zeus::AbstractFunction::type::object: { ZEUS_TYPE_OBJECT* elem = m_interface.get(); it2->execute(m_interfaceWeb, _value, (void*)elem); return; } case zeus::AbstractFunction::type::local: { it2->execute(m_interfaceWeb, _value, (void*)((RemoteProcessCall*)this)); return; } case zeus::AbstractFunction::type::service: { it2->execute(m_interfaceWeb, _value, (void*)this); return; } case zeus::AbstractFunction::type::global: { it2->execute(m_interfaceWeb, _value, nullptr); return; } case zeus::AbstractFunction::type::unknow: ZEUS_ERROR("Can not call unknow type ..."); break; } } m_interfaceWeb->answerError(_value->getTransactionId(), _value->getDestination(), _value->getSource(), "FUNCTION-UNKNOW", "not find function name: '" + _call + "'"); } }; } <commit_msg>[DEBUG] correct override missing<commit_after>/** @file * @author Edouard DUPIN * @copyright 2016, Edouard DUPIN, all right reserved * @license MPL v2.0 (see license file) */ #pragma once #include <zeus/WebServer.hpp> #include <eproperty/Value.hpp> #include <zeus/AbstractFunctionTypeDirect.hpp> #include <zeus/AbstractFunctionTypeClass.hpp> #include <zeus/debug.hpp> #include <zeus/RemoteProcessCall.hpp> #include <zeus/Future.hpp> #include <zeus/Client.hpp> /** * @brief Main zeus library namespace */ namespace zeus { class Client; /** * @brief An object is an element callable from the remote. */ class Object : public zeus::RemoteProcessCall { public: /** * @brief Get the current object local unique ID * @return The unique Object id */ uint16_t getObjectId() { return m_objectId; } /** * @brief Contruct a new callable object * @param[in] _iface Network interface * @param[in] _objectId Unique Id of the object */ Object(const ememory::SharedPtr<zeus::WebServer>& _iface, uint16_t _objectId); /** * @brief generic destructor */ virtual ~Object() = default; public: /** * @brief Receive message to parse and execute * @param[in] _value Message to process */ void receive(ememory::SharedPtr<zeus::Message> _value); private: /** * @brief Specific call depending of the type of the object. * @param[in] _call Name of the function that is called. * @param[in] _value Message to process. */ virtual void callBinary(const std::string& _call, ememory::SharedPtr<zeus::message::Call> _value) = 0; public: /** * @brief Advertise a new function in the service/object ==> it is force the start with "obj.". * @param[in] _name Name of the function * @param[in] _func pointer on the function that might be used to call it. * @return an handle on an abstract function that can be called. */ // Add Local fuction (depend on this class) template<class ZEUS_RETURN_VALUE, class ZEUS_CLASS_TYPE, class... ZEUS_FUNC_ARGS_TYPE> zeus::AbstractFunction* advertise(std::string _name, ZEUS_RETURN_VALUE (ZEUS_CLASS_TYPE::*_func)(ZEUS_FUNC_ARGS_TYPE... _args)) { _name = "obj." + _name; for (auto &it : m_listFunction) { if (it == nullptr) { continue; } if (it->getName() == _name) { ZEUS_ERROR("Advertise function already bind .. ==> can not be done...: '" << _name << "'"); return nullptr; } } AbstractFunction* tmp = createAbstractFunctionClass(_name, _func); if (tmp == nullptr) { ZEUS_ERROR("can not create abstract function ... '" << _name << "'"); return nullptr; } tmp->setType(zeus::AbstractFunction::type::service); ZEUS_VERBOSE("Add function '" << _name << "' in local mode"); m_listFunction.push_back(tmp); return tmp; } }; /** * @brief The object is all time different, and we need to called it corectly and keep it alive while the remote user need it. * The this class permit to have a a pointer on the temporary object. */ template<class ZEUS_TYPE_OBJECT> class ObjectType : public zeus::Object { private: ememory::SharedPtr<ZEUS_TYPE_OBJECT> m_interface; //!< handle on the object that might be called. public: ObjectType(const ememory::SharedPtr<zeus::WebServer>& _iface, uint16_t _objectId, const ememory::SharedPtr<ZEUS_TYPE_OBJECT>& _element) : Object(_iface, _objectId), m_interface(_element) { // nothing else to do ... } public: /** * @brief Advertise a new signal that use a specific call processing order * @param[in] _name Name of the function * @param[in] _func Pointer on the function to call when name call is requested * @return Pointer on the function abstraction call that is done * @note: this is for ACTION function call not normal function call */ template<class ZEUS_RETURN_VALUE, class ZEUS_ACTION_TYPE, class ZEUS_CLASS_TYPE, class... ZEUS_FUNC_ARGS_TYPE> zeus::AbstractFunction* advertise(const std::string& _name, ZEUS_RETURN_VALUE (ZEUS_CLASS_TYPE::*_func)(zeus::ActionNotification<ZEUS_ACTION_TYPE>& _notifs, ZEUS_FUNC_ARGS_TYPE... _args)) { if (etk::start_with(_name, "srv.") == true) { ZEUS_ERROR("Advertise function start with 'srv.' is not permited ==> only allow for internal service: '" << _name << "'"); return nullptr; } for (auto &it : m_listFunction) { if (it == nullptr) { continue; } if (it->getName() == _name) { ZEUS_ERROR("Advertise function already bind .. ==> can not be done...: '" << _name << "'"); return nullptr; } } zeus::AbstractFunction* tmp = createAbstractFunctionClass(_name, _func); if (tmp == nullptr) { ZEUS_ERROR("can not create abstract function ... '" << _name << "'"); return nullptr; } tmp->setType(zeus::AbstractFunction::type::object); ZEUS_VERBOSE("Add function '" << _name << "' in object mode"); m_listFunction.push_back(tmp); return tmp; } /** * @brief Advertise a new signal that use a specific call processing order * @param[in] _name Name of the function * @param[in] _func Pointer on the function to call when name call is requested * @return Pointer on the function abstraction call that is done * @note: this is for normal function call not action call */ template<class ZEUS_RETURN_VALUE, class ZEUS_CLASS_TYPE, class... ZEUS_FUNC_ARGS_TYPE> zeus::AbstractFunction* advertise(const std::string& _name, ZEUS_RETURN_VALUE (ZEUS_CLASS_TYPE::*_func)(ZEUS_FUNC_ARGS_TYPE... _args)) { if (etk::start_with(_name, "srv.") == true) { ZEUS_ERROR("Advertise function start with 'srv.' is not permited ==> only allow for internal service: '" << _name << "'"); return nullptr; } for (auto &it : m_listFunction) { if (it == nullptr) { continue; } if (it->getName() == _name) { ZEUS_ERROR("Advertise function already bind .. ==> can not be done...: '" << _name << "'"); return nullptr; } } zeus::AbstractFunction* tmp = createAbstractFunctionClass(_name, _func); if (tmp == nullptr) { ZEUS_ERROR("can not create abstract function ... '" << _name << "'"); return nullptr; } tmp->setType(zeus::AbstractFunction::type::object); ZEUS_VERBOSE("Add function '" << _name << "' in object mode"); m_listFunction.push_back(tmp); return tmp; } bool isFunctionAuthorized(uint64_t _clientId, const std::string& _funcName) override { /* auto it = m_interface.find(_clientId); if (it == m_interface.end()) { ZEUS_ERROR("CLIENT does not exist ... " << _clientId << " " << _funcName); return false; } return it->second.first->isFunctionAuthorized(_funcName); */ return true; } void callBinary(const std::string& _call, ememory::SharedPtr<zeus::message::Call> _value) override { for (auto &it2 : m_listFunction) { if (it2 == nullptr) { continue; } if (it2->getName() != _call) { continue; } // TODO: Check if client is athorized ... // depending on where the function is defined, the call is not the same ... switch (it2->getType()) { case zeus::AbstractFunction::type::object: { ZEUS_TYPE_OBJECT* elem = m_interface.get(); it2->execute(m_interfaceWeb, _value, (void*)elem); return; } case zeus::AbstractFunction::type::local: { it2->execute(m_interfaceWeb, _value, (void*)((RemoteProcessCall*)this)); return; } case zeus::AbstractFunction::type::service: { it2->execute(m_interfaceWeb, _value, (void*)this); return; } case zeus::AbstractFunction::type::global: { it2->execute(m_interfaceWeb, _value, nullptr); return; } case zeus::AbstractFunction::type::unknow: ZEUS_ERROR("Can not call unknow type ..."); break; } } m_interfaceWeb->answerError(_value->getTransactionId(), _value->getDestination(), _value->getSource(), "FUNCTION-UNKNOW", "not find function name: '" + _call + "'"); } }; } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATOR_PRODUCTS_HH #define DUNE_GDT_OPERATOR_PRODUCTS_HH #include <type_traits> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/functions/constant.hh> #include "../localoperator/codim0.hh" #include "../localfunctional/codim0.hh" #include "../localevaluation/product.hh" #include "../localevaluation/elliptic.hh" namespace Dune { namespace GDT { namespace ProductOperator { template <class GridPartType> class L2 { public: typedef typename GridPartType::template Codim<0>::EntityType EntityType; typedef typename GridPartType::ctype DomainFieldType; static const unsigned int dimDomain = GridPartType::dimension; L2(const GridPartType& grid_part) : grid_part_(grid_part) { } template <class RR, int rRR, int rCR, class RS, int rRS, int rCS> void apply2( const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RR, rRR, rCR>& /*range*/, const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RS, rRS, rCS>& /*source*/) const { static_assert((Dune::AlwaysFalse<RR>::value), "Not implemented for this combination!"); } template <class RangeFieldType, int dimRangeRows, int dimRangeCols> RangeFieldType apply2(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols>& range, const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols>& source) const { typedef Stuff:: LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols> RangeType; // some preparations const LocalFunctional::Codim0Integral<LocalEvaluation::Product<RangeType>> local_functional(range); RangeFieldType ret = 0; DynamicVector<RangeFieldType> local_functional_result(1, 0); std::vector<DynamicVector<RangeFieldType>> tmp_vectors(local_functional.numTmpObjectsRequired(), DynamicVector<RangeFieldType>(1, 0)); // walk the grid const auto entity_it_end = grid_part_.template end<0>(); for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; // get the local function const auto source_local_function = source.local_function(entity); // apply local functional local_functional.apply(*source_local_function, local_functional_result, tmp_vectors); assert(local_functional_result.size() == 1); ret += local_functional_result[0]; } // walk the grid return ret; } // ... apply2(...) private: const GridPartType& grid_part_; }; // class L2 template <class GridPartType> class H1 { public: typedef typename GridPartType::template Codim<0>::EntityType EntityType; typedef typename GridPartType::ctype DomainFieldType; static const unsigned int dimDomain = GridPartType::dimension; H1(const GridPartType& grid_part) : grid_part_(grid_part) { } template <class RR, int rRR, int rCR, class RS, int rRS, int rCS> void apply2( const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RR, rRR, rCR>& /*range*/, const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RS, rRS, rCS>& /*source*/) const { static_assert((Dune::AlwaysFalse<RR>::value), "Not implemented for this combination!"); } template <class RangeFieldType, int dimRangeRows, int dimRangeCols> RangeFieldType apply2(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols>& range, const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols>& source) const { // some preparations typedef Stuff::Function::Constant<EntityType, DomainFieldType, dimDomain, RangeFieldType, 1> ConstantFunctionType; const ConstantFunctionType one(1); const LocalOperator::Codim0Integral<LocalEvaluation::Elliptic<ConstantFunctionType>> local_operator(one); RangeFieldType ret = 0; DynamicMatrix<RangeFieldType> local_operator_result(1, 1, 0); std::vector<DynamicMatrix<RangeFieldType>> tmp_matrices(local_operator.numTmpObjectsRequired(), DynamicMatrix<RangeFieldType>(1, 1, 0)); // walk the grid const auto entity_it_end = grid_part_.template end<0>(); for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; // get the local functions const auto source_local_function = source.local_function(entity); const auto range_local_function = range.local_function(entity); // apply local operator local_operator.apply(*source_local_function, *range_local_function, local_operator_result, tmp_matrices); assert(local_operator_result.rows() == 1); assert(local_operator_result.cols() == 1); ret += local_operator_result[0][0]; } // walk the grid return ret; } // ... apply2(...) private: const GridPartType& grid_part_; }; // class H1 } // namespace ProductOperator } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATOR_PRODUCTS_HH <commit_msg>[operator.products] renamed H1 -> H1Semi<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATOR_PRODUCTS_HH #define DUNE_GDT_OPERATOR_PRODUCTS_HH #include <type_traits> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/functions/constant.hh> #include "../localoperator/codim0.hh" #include "../localfunctional/codim0.hh" #include "../localevaluation/product.hh" #include "../localevaluation/elliptic.hh" namespace Dune { namespace GDT { namespace ProductOperator { template <class GridPartType> class L2 { public: typedef typename GridPartType::template Codim<0>::EntityType EntityType; typedef typename GridPartType::ctype DomainFieldType; static const unsigned int dimDomain = GridPartType::dimension; L2(const GridPartType& grid_part) : grid_part_(grid_part) { } template <class RR, int rRR, int rCR, class RS, int rRS, int rCS> void apply2( const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RR, rRR, rCR>& /*range*/, const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RS, rRS, rCS>& /*source*/) const { static_assert((Dune::AlwaysFalse<RR>::value), "Not implemented for this combination!"); } template <class RangeFieldType, int dimRangeRows, int dimRangeCols> RangeFieldType apply2(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols>& range, const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols>& source) const { typedef Stuff:: LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols> RangeType; // some preparations const LocalFunctional::Codim0Integral<LocalEvaluation::Product<RangeType>> local_functional(range); RangeFieldType ret = 0; DynamicVector<RangeFieldType> local_functional_result(1, 0); std::vector<DynamicVector<RangeFieldType>> tmp_vectors(local_functional.numTmpObjectsRequired(), DynamicVector<RangeFieldType>(1, 0)); // walk the grid const auto entity_it_end = grid_part_.template end<0>(); for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; // get the local function const auto source_local_function = source.local_function(entity); // apply local functional local_functional.apply(*source_local_function, local_functional_result, tmp_vectors); assert(local_functional_result.size() == 1); ret += local_functional_result[0]; } // walk the grid return ret; } // ... apply2(...) private: const GridPartType& grid_part_; }; // class L2 template <class GridPartType> class H1Semi { public: typedef typename GridPartType::template Codim<0>::EntityType EntityType; typedef typename GridPartType::ctype DomainFieldType; static const unsigned int dimDomain = GridPartType::dimension; H1Semi(const GridPartType& grid_part) : grid_part_(grid_part) { } template <class RR, int rRR, int rCR, class RS, int rRS, int rCS> void apply2( const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RR, rRR, rCR>& /*range*/, const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RS, rRS, rCS>& /*source*/) const { static_assert((Dune::AlwaysFalse<RR>::value), "Not implemented for this combination!"); } template <class RangeFieldType, int dimRangeRows, int dimRangeCols> RangeFieldType apply2(const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols>& range, const Stuff::LocalizableFunctionInterface<EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols>& source) const { // some preparations typedef Stuff::Function::Constant<EntityType, DomainFieldType, dimDomain, RangeFieldType, 1> ConstantFunctionType; const ConstantFunctionType one(1); const LocalOperator::Codim0Integral<LocalEvaluation::Elliptic<ConstantFunctionType>> local_operator(one); RangeFieldType ret = 0; DynamicMatrix<RangeFieldType> local_operator_result(1, 1, 0); std::vector<DynamicMatrix<RangeFieldType>> tmp_matrices(local_operator.numTmpObjectsRequired(), DynamicMatrix<RangeFieldType>(1, 1, 0)); // walk the grid const auto entity_it_end = grid_part_.template end<0>(); for (auto entity_it = grid_part_.template begin<0>(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; // get the local functions const auto source_local_function = source.local_function(entity); const auto range_local_function = range.local_function(entity); // apply local operator local_operator.apply(*source_local_function, *range_local_function, local_operator_result, tmp_matrices); assert(local_operator_result.rows() == 1); assert(local_operator_result.cols() == 1); ret += local_operator_result[0][0]; } // walk the grid return ret; } // ... apply2(...) private: const GridPartType& grid_part_; }; // class H1Semi } // namespace ProductOperator } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATOR_PRODUCTS_HH <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_PRODUCTS_ELLIPTIC_HH #define DUNE_GDT_PRODUCTS_ELLIPTIC_HH #include "elliptic-internal.hh" #include "base.hh" namespace Dune { namespace GDT { namespace Products { /** * \brief A localizable elliptic product. * * Possible ctor signaturer are a combination of the ones from \sa LocalizableBase first and then \sa * internal::EllipticBase. * \todo Add more documentation, especially a mathematical definition. */ template< class GridView, class DiffusionFactor, class Range, class Source = Range, class FieldType = double, class DiffusionTensor = void > class EllipticLocalizable : public LocalizableBase< internal::EllipticBase< DiffusionFactor, GridView, FieldType, DiffusionTensor >, Range, Source > { typedef LocalizableBase < internal::EllipticBase< DiffusionFactor, GridView, FieldType, DiffusionTensor >, Range, Source > BaseType; public: template< class... Args > EllipticLocalizable(Args&& ...args) : BaseType(std::forward< Args >(args)...) {} }; /** * \brief An assemblable elliptic product. * * Possible ctor signaturer are a combination of the ones from \sa AssemblableBase first and then \sa * internal::EllipticBase. * \todo Add more documentation, especially a mathematical definition. */ template< class Matrix, class DiffusionFactor, class RangeSpace, class GridView = typename RangeSpace::GridViewType, class SourceSpace = RangeSpace, class FieldType = double, class DiffusionTensor = void > class EllipticAssemblable : public AssemblableBase< internal::EllipticBase< DiffusionFactor, GridView, FieldType, DiffusionTensor >, Matrix, RangeSpace, SourceSpace > { typedef AssemblableBase< internal::EllipticBase< DiffusionFactor, GridView, FieldType, DiffusionTensor >, Matrix, RangeSpace, SourceSpace > BaseType; public: template< class... Args > EllipticAssemblable(Args&& ...args) : BaseType(std::forward< Args >(args)...) {} }; /** * \brief An elliptic product. * * Possible ctor signaturer are a combination of the ones from \sa GenericBase first and then \sa * internal::EllipticBase. * \todo Add more documentation, especially a mathematical definition. */ template< class GridView, class DiffusionFactor, class FieldType = double, class DiffusionTensor = void > class Elliptic : public GenericBase< internal::EllipticBase< DiffusionFactor, GridView, FieldType, DiffusionTensor > > { typedef GenericBase< internal::EllipticBase< DiffusionFactor, GridView, FieldType, DiffusionTensor > > BaseType; public: template< class... Args > Elliptic(Args&& ...args) : BaseType(std::forward< Args >(args)...) {} }; template< class GV, class R, class DF, class DT > EllipticLocalizable< GV, DF, R, R, typename DF::RangeFieldType, DT > make_elliptic_localizable(const GV& grd_vw, const R& rng, const DF& diffusion_factor, const DT& diffusion_tensor, const size_t over_integrate = 0) { typedef EllipticLocalizable< GV, DF, R, R, typename DF::RangeFieldType, DT > ProductType; return ProductType(grd_vw, rng, diffusion_factor, diffusion_tensor, over_integrate); } } // namespace Products } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PRODUCTS_ELLIPTIC_HH <commit_msg>[products.elliptic] add docu<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_PRODUCTS_ELLIPTIC_HH #define DUNE_GDT_PRODUCTS_ELLIPTIC_HH #include "elliptic-internal.hh" #include "base.hh" namespace Dune { namespace GDT { namespace Products { /** * \brief A localizable elliptic product. * * Possible ctor signaturer are a combination of the ones from \sa LocalizableBase first and then \sa * internal::EllipticBase. * \todo Add more documentation, especially a mathematical definition. */ template< class GridView, class DiffusionFactor, class Range, class Source = Range, class FieldType = double, class DiffusionTensor = void > class EllipticLocalizable : public LocalizableBase< internal::EllipticBase< DiffusionFactor, GridView, FieldType, DiffusionTensor >, Range, Source > { typedef LocalizableBase < internal::EllipticBase< DiffusionFactor, GridView, FieldType, DiffusionTensor >, Range, Source > BaseType; public: template< class... Args > EllipticLocalizable(Args&& ...args) : BaseType(std::forward< Args >(args)...) {} }; /** * \brief An assemblable elliptic product. * * Possible ctor signaturer are a combination of the ones from \sa AssemblableBase first and then \sa * internal::EllipticBase. * \todo Add more documentation, especially a mathematical definition. */ template< class Matrix, class DiffusionFactor, class RangeSpace, class GridView = typename RangeSpace::GridViewType, class SourceSpace = RangeSpace, class FieldType = double, class DiffusionTensor = void > class EllipticAssemblable : public AssemblableBase< internal::EllipticBase< DiffusionFactor, GridView, FieldType, DiffusionTensor >, Matrix, RangeSpace, SourceSpace > { typedef AssemblableBase< internal::EllipticBase< DiffusionFactor, GridView, FieldType, DiffusionTensor >, Matrix, RangeSpace, SourceSpace > BaseType; public: template< class... Args > EllipticAssemblable(Args&& ...args) : BaseType(std::forward< Args >(args)...) {} }; /** * \brief An elliptic product. * * Possible ctor signaturer are a combination of the ones from \sa GenericBase first and then \sa * internal::EllipticBase. For instance:\code Elliptic(grid_view, diffusion, over_integrate = 0); Elliptic(grid_view, diffusion_factor, diffusion_tensor, over_integrate = 0); \endcode * \todo Add more documentation, especially a mathematical definition. */ template< class GridView, class DiffusionFactor, class FieldType = double, class DiffusionTensor = void > class Elliptic : public GenericBase< internal::EllipticBase< DiffusionFactor, GridView, FieldType, DiffusionTensor > > { typedef GenericBase< internal::EllipticBase< DiffusionFactor, GridView, FieldType, DiffusionTensor > > BaseType; public: template< class... Args > Elliptic(Args&& ...args) : BaseType(std::forward< Args >(args)...) {} }; template< class GV, class R, class DF, class DT > EllipticLocalizable< GV, DF, R, R, typename DF::RangeFieldType, DT > make_elliptic_localizable(const GV& grd_vw, const R& rng, const DF& diffusion_factor, const DT& diffusion_tensor, const size_t over_integrate = 0) { typedef EllipticLocalizable< GV, DF, R, R, typename DF::RangeFieldType, DT > ProductType; return ProductType(grd_vw, rng, diffusion_factor, diffusion_tensor, over_integrate); } } // namespace Products } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PRODUCTS_ELLIPTIC_HH <|endoftext|>
<commit_before>// This file is part of the dune-pymor project: // https://github.com/pyMor/dune-pymor // Copyright Holders: Felix Albrecht, Stephan Rave // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_PYMOR_PARAMETERS_BASE_HH #define DUNE_PYMOR_PARAMETERS_BASE_HH #include <string> #include <map> #include <vector> #include <initializer_list> #include <sstream> #include <dune/pymor/common/exceptions.hh> namespace Dune { namespace Pymor { class ParameterType { public: typedef std::string KeyType; typedef int ValueType; ParameterType(const KeyType& kk, const ValueType& vv) throw (Exception::key_is_not_valid, Exception::index_out_of_range) : dict_({std::make_pair(std::string(kk), vv)}) { if (kk.empty()) DUNE_PYMOR_THROW(Exception::key_is_not_valid, "kk is empty!"); if (vv <= 0) DUNE_PYMOR_THROW(Exception::index_out_of_range, "vv has to be positive (is " << vv << ")!"); } ParameterType(const std::initializer_list< KeyType >& kk, const std::initializer_list< ValueType >& vv) throw (Exception::key_is_not_valid, Exception::index_out_of_range, Exception::sizes_do_not_match) { if (kk.size() != vv.size()) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the size of kk (" << kk.size() << ") has to equal the size of vv (" << vv.size() << ")!"); if (kk.size() == 0) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "kk and vv are empty!"); const auto kk_end = kk.end(); const auto vv_end = vv.end(); auto kk_it = kk.begin(); size_t counter = 0; for (auto vv_it = vv.begin(); (kk_it != kk_end) && (vv_it != vv_end); ++kk_it, ++vv_it, ++counter) { const KeyType& key = *kk_it; const ValueType& value = *vv_it; if (key.empty()) DUNE_PYMOR_THROW(Exception::key_is_not_valid, "kk[" << counter << "] is empty!"); if (value <= 0) DUNE_PYMOR_THROW(Exception::index_out_of_range, "vv[" << counter << "] has to be positive (is " << value << ")!"); dict_.insert(std::make_pair(key, value)); } } std::vector< KeyType > keys() const { std::vector< KeyType > ret; for (auto element : dict_) ret.emplace_back(element.first); return ret; } std::vector< ValueType > values() const { std::vector< ValueType > ret; for (auto element : dict_) ret.emplace_back(element.second); return ret; } bool hasKey(const KeyType& key) const { const auto result = dict_.find(key); return result != dict_.end(); } void set(const KeyType& key, const ValueType& value) throw (Exception::key_is_not_valid, Exception::index_out_of_range) { if (key.empty()) DUNE_PYMOR_THROW(Exception::key_is_not_valid, "key is empty!"); if (value <= 0) DUNE_PYMOR_THROW(Exception::index_out_of_range, "value has to be positive (is " << value << ")!"); dict_[key] = value; } ValueType get(const KeyType& key) const throw (Exception::key_is_not_valid) { const auto result = dict_.find(key); if (result == dict_.end()) DUNE_PYMOR_THROW(Exception::key_is_not_valid, "key does not exist!"); return result->second; } bool operator==(const ParameterType& other) { return dict_ == other.dict_; } bool operator!=(const ParameterType& other) { return dict_ != other.dict_; } unsigned int size() const { return dict_.size(); } std::string report() const { std::ostringstream ret; ret << "Dune::Pymor::ParameterType("; if (dict_.size() == 1) { const auto element = dict_.begin(); ret << element->first << ", " << element->second; } else if (dict_.size() > 1) { std::vector< KeyType > kk; std::vector< ValueType > vv; for (auto element : dict_) { kk.emplace_back(element.first); vv.emplace_back(element.second); } ret << "{"; for (size_t ii = 0; ii < (kk.size() - 1); ++ii) ret << kk[ii] << ", "; ret << kk[kk.size() - 1] << "},\n {"; for (size_t ii = 0; ii < (vv.size() - 1); ++ii) ret << vv[ii] << ", "; ret << vv[vv.size() - 1] << "}"; } ret << ")"; return ret.str(); } private: std::map< KeyType, ValueType > dict_; public: auto begin() -> decltype (dict_.begin()) { return dict_.begin(); } auto end() -> decltype (dict_.end()) { return dict_.end(); } }; // class ParameterType } // namespace Pymor } // namespace Dune #endif // DUNE_PYMOR_PARAMETERS_BASE_HH <commit_msg>[parameters.base] added documentation and output to ParameterType<commit_after>// This file is part of the dune-pymor project: // https://github.com/pyMor/dune-pymor // Copyright Holders: Felix Albrecht, Stephan Rave // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_PYMOR_PARAMETERS_BASE_HH #define DUNE_PYMOR_PARAMETERS_BASE_HH #include <string> #include <map> #include <vector> #include <initializer_list> #include <sstream> #include <ostream> #include <dune/pymor/common/exceptions.hh> namespace Dune { namespace Pymor { /** * \brief Determines the type of any parameter as a set of components and their length. * * This class is implemented using a std::map, where the components are std::string keys and their length are * int values. We use int instead of size_t because pybindgen does not offer any bindings for size_t. Usage * example: * \code ParameterType param1("diffusion", 1); ParameterType param2({"diffusion", "force"}, {1, 2}); ParameterType param3 = {"diffusion", 1}; ParameterType param4 = {{"diffusion", "force"}, {1, 2}}; \code * * \see Dune::Pymor::Parameter, Dune::Pymor::Parametric */ class ParameterType { public: typedef std::string KeyType; typedef int ValueType; ParameterType(const KeyType& kk, const ValueType& vv) throw (Exception::key_is_not_valid, Exception::index_out_of_range) : dict_({std::make_pair(std::string(kk), vv)}) { if (kk.empty()) DUNE_PYMOR_THROW(Exception::key_is_not_valid, "kk is empty!"); if (vv <= 0) DUNE_PYMOR_THROW(Exception::index_out_of_range, "vv has to be positive (is " << vv << ")!"); } ParameterType(const std::initializer_list< KeyType >& kk, const std::initializer_list< ValueType >& vv) throw (Exception::key_is_not_valid, Exception::index_out_of_range, Exception::sizes_do_not_match) { if (kk.size() != vv.size()) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the size of kk (" << kk.size() << ") has to equal the size of vv (" << vv.size() << ")!"); if (kk.size() == 0) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "kk and vv are empty!"); const auto kk_end = kk.end(); const auto vv_end = vv.end(); auto kk_it = kk.begin(); size_t counter = 0; for (auto vv_it = vv.begin(); (kk_it != kk_end) && (vv_it != vv_end); ++kk_it, ++vv_it, ++counter) { const KeyType& key = *kk_it; const ValueType& value = *vv_it; if (key.empty()) DUNE_PYMOR_THROW(Exception::key_is_not_valid, "kk[" << counter << "] is empty!"); if (value <= 0) DUNE_PYMOR_THROW(Exception::index_out_of_range, "vv[" << counter << "] has to be positive (is " << value << ")!"); dict_.insert(std::make_pair(key, value)); } } std::vector< KeyType > keys() const { std::vector< KeyType > ret; for (auto element : dict_) ret.emplace_back(element.first); return ret; } std::vector< ValueType > values() const { std::vector< ValueType > ret; for (auto element : dict_) ret.emplace_back(element.second); return ret; } bool hasKey(const KeyType& key) const { const auto result = dict_.find(key); return result != dict_.end(); } void set(const KeyType& key, const ValueType& value) throw (Exception::key_is_not_valid, Exception::index_out_of_range) { if (key.empty()) DUNE_PYMOR_THROW(Exception::key_is_not_valid, "key is empty!"); if (value <= 0) DUNE_PYMOR_THROW(Exception::index_out_of_range, "value has to be positive (is " << value << ")!"); dict_[key] = value; } ValueType get(const KeyType& key) const throw (Exception::key_is_not_valid) { const auto result = dict_.find(key); if (result == dict_.end()) DUNE_PYMOR_THROW(Exception::key_is_not_valid, "key does not exist!"); return result->second; } bool operator==(const ParameterType& other) { return dict_ == other.dict_; } bool operator!=(const ParameterType& other) { return dict_ != other.dict_; } unsigned int size() const { return dict_.size(); } std::string report() const { std::ostringstream ret; ret << "Dune::Pymor::ParameterType("; if (dict_.size() == 1) { const auto element = dict_.begin(); ret << "\"" << element->first << "\", " << element->second; } else if (dict_.size() > 1) { std::vector< KeyType > kk; std::vector< ValueType > vv; for (auto element : dict_) { kk.emplace_back(element.first); vv.emplace_back(element.second); } ret << "{\""; for (size_t ii = 0; ii < (kk.size() - 1); ++ii) ret << kk[ii] << "\", \""; ret << kk[kk.size() - 1] << "\"}, {"; for (size_t ii = 0; ii < (vv.size() - 1); ++ii) ret << vv[ii] << ", "; ret << vv[vv.size() - 1] << "}"; } ret << ")"; return ret.str(); } private: std::map< KeyType, ValueType > dict_; public: auto begin() -> decltype (dict_.begin()) { return dict_.begin(); } auto end() -> decltype (dict_.end()) { return dict_.end(); } friend std::ostream& operator<<(std::ostream&, const ParameterType&); }; // class ParameterType std::ostream& operator<<(std::ostream& oo, const ParameterType& pp) { oo << pp.report(); return oo; } } // namespace Pymor } // namespace Dune #endif // DUNE_PYMOR_PARAMETERS_BASE_HH <|endoftext|>
<commit_before>// Copyright 2012 Luis Pedro Coelho <[email protected]> // License: MIT (see COPYING.MIT file) #include "base.h" #include "_png.h" #include "tools.h" #include <png.h> #include <cstring> #include <vector> namespace { void throw_error(png_structp png_ptr, png_const_charp error_msg) { throw CannotReadError(error_msg); } class png_holder { public: png_holder(int m) :png_ptr((m == write_mode ? png_create_write_struct : png_create_read_struct)(PNG_LIBPNG_VER_STRING, 0, throw_error, 0)) ,png_info(0) ,mode(holder_mode(m)) { } ~png_holder() { png_infopp pp = (png_info ? &png_info : 0); if (mode == read_mode) png_destroy_read_struct(&png_ptr, pp, 0); else png_destroy_write_struct(&png_ptr, pp); } void create_info() { png_info = png_create_info_struct(png_ptr); if (!png_info) throw "error"; } png_structp png_ptr; png_infop png_info; enum holder_mode { read_mode, write_mode } mode; }; void read_from_source(png_structp png_ptr, png_byte* buffer, size_t n) { byte_source* s = static_cast<byte_source*>(png_get_io_ptr(png_ptr)); const size_t actual = s->read(reinterpret_cast<byte*>(buffer), n); if (actual != n) { throw CannotReadError(); } } void write_to_source(png_structp png_ptr, png_byte* buffer, size_t n) { byte_sink* s = static_cast<byte_sink*>(png_get_io_ptr(png_ptr)); const size_t actual = s->write(reinterpret_cast<byte*>(buffer), n); if (actual != n) { throw CannotReadError(); } } void flush_source(png_structp png_ptr) { byte_sink* s = static_cast<byte_sink*>(png_get_io_ptr(png_ptr)); s->flush(); } int color_type_of(Image* im) { if (im->ndims() == 2) return PNG_COLOR_TYPE_GRAY; if (im->ndims() != 3) throw CannotWriteError(); if (im->dim(2) == 3) return PNG_COLOR_TYPE_RGB; if (im->dim(2) == 4) return PNG_COLOR_TYPE_RGBA; throw CannotWriteError(); } } std::auto_ptr<Image> PNGFormat::read(byte_source* src, ImageFactory* factory) { png_holder p(png_holder::read_mode); png_set_read_fn(p.png_ptr, src, read_from_source); p.create_info(); png_read_info(p.png_ptr, p.png_info); const int w = png_get_image_width (p.png_ptr, p.png_info); const int h = png_get_image_height(p.png_ptr, p.png_info); int d = -1; switch (png_get_color_type(p.png_ptr, p.png_info)) { case PNG_COLOR_TYPE_PALETTE: png_set_palette_to_rgb(p.png_ptr); case PNG_COLOR_TYPE_RGB: d = 3; break; case PNG_COLOR_TYPE_RGB_ALPHA: d = 4; break; case PNG_COLOR_TYPE_GRAY: d = -1; break; default: throw CannotReadError("Unhandled color type"); } if (png_get_bit_depth(p.png_ptr, p.png_info) != 8) { throw CannotReadError("Can currently only read 8-bit images"); } std::auto_ptr<Image> output(factory->create<byte>(h, w, d)); std::vector<png_bytep> rowps = allrows<png_byte>(*output); png_read_image(p.png_ptr, &rowps[0]); return output; } void PNGFormat::write(Image* input, byte_sink* output) { png_holder p(png_holder::write_mode); p.create_info(); png_set_write_fn(p.png_ptr, output, write_to_source, flush_source); const int height = input->dim(0); const int width = input->dim(1); const int bit_depth = 8; const int color_type = color_type_of(input); png_set_IHDR(p.png_ptr, p.png_info, width, height, bit_depth, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(p.png_ptr, p.png_info); std::vector<png_bytep> rowps = allrows<png_byte>(*input); png_write_image(p.png_ptr, &rowps[0]); png_write_end(p.png_ptr, p.png_info); } <commit_msg>ENH Support 16 bit PNGs<commit_after>// Copyright 2012 Luis Pedro Coelho <[email protected]> // License: MIT (see COPYING.MIT file) #include "base.h" #include "_png.h" #include "tools.h" #include <png.h> #include <cstring> #include <vector> namespace { void throw_error(png_structp png_ptr, png_const_charp error_msg) { throw CannotReadError(error_msg); } class png_holder { public: png_holder(int m) :png_ptr((m == write_mode ? png_create_write_struct : png_create_read_struct)(PNG_LIBPNG_VER_STRING, 0, throw_error, 0)) ,png_info(0) ,mode(holder_mode(m)) { } ~png_holder() { png_infopp pp = (png_info ? &png_info : 0); if (mode == read_mode) png_destroy_read_struct(&png_ptr, pp, 0); else png_destroy_write_struct(&png_ptr, pp); } void create_info() { png_info = png_create_info_struct(png_ptr); if (!png_info) throw "error"; } png_structp png_ptr; png_infop png_info; enum holder_mode { read_mode, write_mode } mode; }; void read_from_source(png_structp png_ptr, png_byte* buffer, size_t n) { byte_source* s = static_cast<byte_source*>(png_get_io_ptr(png_ptr)); const size_t actual = s->read(reinterpret_cast<byte*>(buffer), n); if (actual != n) { throw CannotReadError(); } } void write_to_source(png_structp png_ptr, png_byte* buffer, size_t n) { byte_sink* s = static_cast<byte_sink*>(png_get_io_ptr(png_ptr)); const size_t actual = s->write(reinterpret_cast<byte*>(buffer), n); if (actual != n) { throw CannotReadError(); } } void flush_source(png_structp png_ptr) { byte_sink* s = static_cast<byte_sink*>(png_get_io_ptr(png_ptr)); s->flush(); } int color_type_of(Image* im) { if (im->ndims() == 2) return PNG_COLOR_TYPE_GRAY; if (im->ndims() != 3) throw CannotWriteError(); if (im->dim(2) == 3) return PNG_COLOR_TYPE_RGB; if (im->dim(2) == 4) return PNG_COLOR_TYPE_RGBA; throw CannotWriteError(); } } std::auto_ptr<Image> PNGFormat::read(byte_source* src, ImageFactory* factory) { png_holder p(png_holder::read_mode); png_set_read_fn(p.png_ptr, src, read_from_source); p.create_info(); png_read_info(p.png_ptr, p.png_info); const int w = png_get_image_width (p.png_ptr, p.png_info); const int h = png_get_image_height(p.png_ptr, p.png_info); int bit_depth = png_get_bit_depth(p.png_ptr, p.png_info); int d = -1; switch (png_get_color_type(p.png_ptr, p.png_info)) { case PNG_COLOR_TYPE_PALETTE: png_set_palette_to_rgb(p.png_ptr); case PNG_COLOR_TYPE_RGB: d = 3; break; case PNG_COLOR_TYPE_RGB_ALPHA: d = 4; break; case PNG_COLOR_TYPE_GRAY: if (bit_depth < 8) { png_set_expand_gray_1_2_4_to_8(p.png_ptr); bit_depth = 8; } d = -1; break; default: throw CannotReadError("Unhandled color type"); } std::auto_ptr<Image> output; if (bit_depth == 8) { output.reset(factory->create<byte>(h, w, d)); } else if (bit_depth == 16) { output.reset(factory->create<uint16_t>(h, w, d)); } else { throw CannotReadError("Cannot read this bit depth and color combination"); } std::vector<png_bytep> rowps = allrows<png_byte>(*output); png_read_image(p.png_ptr, &rowps[0]); return output; } void PNGFormat::write(Image* input, byte_sink* output) { png_holder p(png_holder::write_mode); p.create_info(); png_set_write_fn(p.png_ptr, output, write_to_source, flush_source); const int height = input->dim(0); const int width = input->dim(1); const int bit_depth = 8; const int color_type = color_type_of(input); png_set_IHDR(p.png_ptr, p.png_info, width, height, bit_depth, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(p.png_ptr, p.png_info); std::vector<png_bytep> rowps = allrows<png_byte>(*input); png_write_image(p.png_ptr, &rowps[0]); png_write_end(p.png_ptr, p.png_info); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ChartFrameloader.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: bm $ $Date: 2003-10-06 09:58:28 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2003 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "ChartFrameloader.hxx" #include "servicenames.hxx" #include "MediaDescriptorHelper.hxx" //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; ChartFrameLoader::ChartFrameLoader( uno::Reference<uno::XComponentContext> const & xContext) : m_bCancelRequired( sal_False ) { m_xCC = xContext; m_oCancelFinished.reset(); } ChartFrameLoader::~ChartFrameLoader() { } sal_Bool ChartFrameLoader ::impl_checkCancel() { if(m_bCancelRequired) { m_oCancelFinished.set(); return sal_True; } return sal_False; } //----------------------------------------------------------------- // lang::XServiceInfo //----------------------------------------------------------------- APPHELPER_XSERVICEINFO_IMPL(ChartFrameLoader,CHART_FRAMELOADER_SERVICE_IMPLEMENTATION_NAME) uno::Sequence< rtl::OUString > ChartFrameLoader ::getSupportedServiceNames_Static() { uno::Sequence< rtl::OUString > aSNS( 1 ); aSNS.getArray()[ 0 ] = CHART_FRAMELOADER_SERVICE_NAME; return aSNS; } //----------------------------------------------------------------- // frame::XFrameLoader //----------------------------------------------------------------- sal_Bool SAL_CALL ChartFrameLoader ::load( const uno::Sequence< beans::PropertyValue >& rMediaDescriptor , const uno::Reference<frame::XFrame >& xFrame ) throw (uno::RuntimeException) { //@todo ? need to add as terminate listener to desktop? //create mediadescriptor to be attached to the model apphelper::MediaDescriptorHelper aMediaDescriptorHelper(rMediaDescriptor); //prepare data for model ... missing interface XPersist or XLoadable at Model.... { //@todo ... } /* static uno::Reference< frame::XFrame > xTestFrame = uno::Reference< frame::XFrame >( m_xCC->getServiceManager()->createInstanceWithContext( ::rtl::OUString::createFromAscii("com.sun.star.frame.Frame"), m_xCC ) , uno::UNO_QUERY ); static uno::Reference< awt::XWindow > xTestWindow = uno::Reference< awt::XWindow >( m_xCC->getServiceManager()->createInstanceWithContext( ::rtl::OUString::createFromAscii("com.sun.star.awt.Window"), m_xCC ) , uno::UNO_QUERY ); xTestFrame->initialize(xTestWindow); */ //create and initialize the model uno::Reference< frame::XModel > xModel = NULL; { //@todo?? load mechanism to cancel during loading of document xModel = uno::Reference< frame::XModel >( m_xCC->getServiceManager()->createInstanceWithContext( CHART_MODEL_SERVICE_IMPLEMENTATION_NAME, m_xCC ) , uno::UNO_QUERY ); if( impl_checkCancel() ) return sal_False; //@todo load data to model ... missing interface XPersist or XLoadable at Model.... xModel->attachResource( aMediaDescriptorHelper.URL.Complete, aMediaDescriptorHelper.getReducedForModel() ); } //create the component context for the controller uno::Reference< uno::XComponentContext > xComponentContext_ForController = NULL; { xComponentContext_ForController = uno::Reference< uno::XComponentContext >( m_xCC->getServiceManager()->createInstanceWithContext( ::rtl::OUString::createFromAscii("com.sun.star.uno.ComponentContext"), m_xCC ) , uno::UNO_QUERY ); //@todo if( impl_checkCancel() ) return sal_False; } //create the controller(+XWindow) uno::Reference< frame::XController > xController = NULL; uno::Reference< awt::XWindow > xComponentWindow = NULL; { xController = uno::Reference< frame::XController >( m_xCC->getServiceManager()->createInstanceWithContext( CHART_CONTROLLER_SERVICE_IMPLEMENTATION_NAME,m_xCC ) //, xComponentContext_ForController ) , uno::UNO_QUERY ); //!!!it is a special characteristic of the example application //that the controller simultaniously provides the XWindow controller functionality xComponentWindow = uno::Reference< awt::XWindow >( xController, uno::UNO_QUERY ); if( impl_checkCancel() ) return sal_False; } //connect frame, controller and model one to each other: if(xController.is()&&xModel.is()) { xController->attachFrame(xFrame); xController->attachModel(xModel); xModel->connectController(xController); if(xFrame.is()) xFrame->setComponent(xComponentWindow,xController); } return sal_True; } void SAL_CALL ChartFrameLoader ::cancel() throw (uno::RuntimeException) { m_oCancelFinished.reset(); m_bCancelRequired = sal_True; m_oCancelFinished.wait(); m_bCancelRequired = sal_False; } //............................................................................. } //namespace chart //............................................................................. <commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.110); FILE MERGED 2005/09/05 18:42:43 rt 1.1.1.1.110.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ChartFrameloader.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 00:33:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "ChartFrameloader.hxx" #include "servicenames.hxx" #include "MediaDescriptorHelper.hxx" //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; ChartFrameLoader::ChartFrameLoader( uno::Reference<uno::XComponentContext> const & xContext) : m_bCancelRequired( sal_False ) { m_xCC = xContext; m_oCancelFinished.reset(); } ChartFrameLoader::~ChartFrameLoader() { } sal_Bool ChartFrameLoader ::impl_checkCancel() { if(m_bCancelRequired) { m_oCancelFinished.set(); return sal_True; } return sal_False; } //----------------------------------------------------------------- // lang::XServiceInfo //----------------------------------------------------------------- APPHELPER_XSERVICEINFO_IMPL(ChartFrameLoader,CHART_FRAMELOADER_SERVICE_IMPLEMENTATION_NAME) uno::Sequence< rtl::OUString > ChartFrameLoader ::getSupportedServiceNames_Static() { uno::Sequence< rtl::OUString > aSNS( 1 ); aSNS.getArray()[ 0 ] = CHART_FRAMELOADER_SERVICE_NAME; return aSNS; } //----------------------------------------------------------------- // frame::XFrameLoader //----------------------------------------------------------------- sal_Bool SAL_CALL ChartFrameLoader ::load( const uno::Sequence< beans::PropertyValue >& rMediaDescriptor , const uno::Reference<frame::XFrame >& xFrame ) throw (uno::RuntimeException) { //@todo ? need to add as terminate listener to desktop? //create mediadescriptor to be attached to the model apphelper::MediaDescriptorHelper aMediaDescriptorHelper(rMediaDescriptor); //prepare data for model ... missing interface XPersist or XLoadable at Model.... { //@todo ... } /* static uno::Reference< frame::XFrame > xTestFrame = uno::Reference< frame::XFrame >( m_xCC->getServiceManager()->createInstanceWithContext( ::rtl::OUString::createFromAscii("com.sun.star.frame.Frame"), m_xCC ) , uno::UNO_QUERY ); static uno::Reference< awt::XWindow > xTestWindow = uno::Reference< awt::XWindow >( m_xCC->getServiceManager()->createInstanceWithContext( ::rtl::OUString::createFromAscii("com.sun.star.awt.Window"), m_xCC ) , uno::UNO_QUERY ); xTestFrame->initialize(xTestWindow); */ //create and initialize the model uno::Reference< frame::XModel > xModel = NULL; { //@todo?? load mechanism to cancel during loading of document xModel = uno::Reference< frame::XModel >( m_xCC->getServiceManager()->createInstanceWithContext( CHART_MODEL_SERVICE_IMPLEMENTATION_NAME, m_xCC ) , uno::UNO_QUERY ); if( impl_checkCancel() ) return sal_False; //@todo load data to model ... missing interface XPersist or XLoadable at Model.... xModel->attachResource( aMediaDescriptorHelper.URL.Complete, aMediaDescriptorHelper.getReducedForModel() ); } //create the component context for the controller uno::Reference< uno::XComponentContext > xComponentContext_ForController = NULL; { xComponentContext_ForController = uno::Reference< uno::XComponentContext >( m_xCC->getServiceManager()->createInstanceWithContext( ::rtl::OUString::createFromAscii("com.sun.star.uno.ComponentContext"), m_xCC ) , uno::UNO_QUERY ); //@todo if( impl_checkCancel() ) return sal_False; } //create the controller(+XWindow) uno::Reference< frame::XController > xController = NULL; uno::Reference< awt::XWindow > xComponentWindow = NULL; { xController = uno::Reference< frame::XController >( m_xCC->getServiceManager()->createInstanceWithContext( CHART_CONTROLLER_SERVICE_IMPLEMENTATION_NAME,m_xCC ) //, xComponentContext_ForController ) , uno::UNO_QUERY ); //!!!it is a special characteristic of the example application //that the controller simultaniously provides the XWindow controller functionality xComponentWindow = uno::Reference< awt::XWindow >( xController, uno::UNO_QUERY ); if( impl_checkCancel() ) return sal_False; } //connect frame, controller and model one to each other: if(xController.is()&&xModel.is()) { xController->attachFrame(xFrame); xController->attachModel(xModel); xModel->connectController(xController); if(xFrame.is()) xFrame->setComponent(xComponentWindow,xController); } return sal_True; } void SAL_CALL ChartFrameLoader ::cancel() throw (uno::RuntimeException) { m_oCancelFinished.reset(); m_bCancelRequired = sal_True; m_oCancelFinished.wait(); m_bCancelRequired = sal_False; } //............................................................................. } //namespace chart //............................................................................. <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: PlottingPositionHelper.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: iha $ $Date: 2003-11-19 13:14:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2003 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "PlottingPositionHelper.hxx" #include "CommonConverters.hxx" #include "ViewDefines.hxx" #include "Linear3DTransformation.hxx" #ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_ #include <com/sun/star/drawing/Position3D.hpp> #endif //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::drafts::com::sun::star::chart2; PlottingPositionHelper::PlottingPositionHelper() : m_aScales() , m_aMatrixScreenToScene() , m_xTransformationLogicToScene(NULL) { } PlottingPositionHelper::~PlottingPositionHelper() { } void PlottingPositionHelper::setTransformationSceneToScreen( const drawing::HomogenMatrix& rMatrix) { m_aMatrixScreenToScene = HomogenMatrixToMatrix4D(rMatrix); m_xTransformationLogicToScene = NULL; } void PlottingPositionHelper::setScales( const uno::Sequence< ExplicitScaleData >& rScales ) { m_aScales = rScales; m_xTransformationLogicToScene = NULL; } uno::Reference< XTransformation > PlottingPositionHelper::getTransformationLogicToScene() const { //this is a standard transformation for a cartesian coordinate system //transformation from 2) to 4) //@todo 2) and 4) need a ink to a document //we need to apply this transformation to each geometric object because of a bug/problem //of the old drawing layer (the UNO_NAME_3D_EXTRUDE_DEPTH is an integer value instead of an double ) if(!m_xTransformationLogicToScene.is()) { Matrix4D aMatrix; double MinX = getLogicMinX(); double MinY = getLogicMinY(); double MinZ = getLogicMinZ(); double MaxX = getLogicMaxX(); double MaxY = getLogicMaxY(); double MaxZ = getLogicMaxZ(); //apply scaling doLogicScaling( &MinX, &MinY, &MinZ ); doLogicScaling( &MaxX, &MaxY, &MaxZ); if( AxisOrientation_MATHEMATICAL==m_aScales[0].Orientation ) aMatrix.TranslateX(-MinX); else aMatrix.TranslateX(-MaxX); if( AxisOrientation_MATHEMATICAL==m_aScales[1].Orientation ) aMatrix.TranslateY(-MinY); else aMatrix.TranslateY(-MaxY); if( AxisOrientation_MATHEMATICAL==m_aScales[2].Orientation ) aMatrix.TranslateZ(-MaxZ);//z direction in draw is reverse mathematical direction else aMatrix.TranslateY(-MinZ); double fWidthX = MaxX - MinX; double fWidthY = MaxY - MinY; double fWidthZ = MaxZ - MinZ; double fScaleDirectionX = AxisOrientation_MATHEMATICAL==m_aScales[0].Orientation ? 1.0 : -1.0; double fScaleDirectionY = AxisOrientation_MATHEMATICAL==m_aScales[1].Orientation ? 1.0 : -1.0; double fScaleDirectionZ = AxisOrientation_MATHEMATICAL==m_aScales[2].Orientation ? -1.0 : 1.0; aMatrix.ScaleX(fScaleDirectionX*FIXED_SIZE_FOR_3D_CHART_VOLUME/fWidthX); aMatrix.ScaleY(fScaleDirectionY*FIXED_SIZE_FOR_3D_CHART_VOLUME/fWidthY); aMatrix.ScaleZ(fScaleDirectionZ*FIXED_SIZE_FOR_3D_CHART_VOLUME/fWidthZ); aMatrix = aMatrix*m_aMatrixScreenToScene; m_xTransformationLogicToScene = new Linear3DTransformation(Matrix4DToHomogenMatrix( aMatrix )); } return m_xTransformationLogicToScene; } void PlottingPositionHelper::getScreenValuesForMinimum( uno::Sequence< double >& rSeq ) const { double fX = this->getLogicMinX(); double fY = this->getLogicMinY(); double fZ = this->getLogicMinZ(); this->doLogicScaling( &fX,&fY,&fZ ); drawing::Position3D aPos( fX, fY, fZ); uno::Reference< XTransformation > xTransformation = this->getTransformationLogicToScene(); rSeq = xTransformation->transform( Position3DToSequence(aPos) ); } void PlottingPositionHelper::getScreenValuesForMaximum( uno::Sequence< double >& rSeq ) const { double fX = this->getLogicMaxX(); double fY = this->getLogicMaxY(); double fZ = this->getLogicMaxZ(); this->doLogicScaling( &fX,&fY,&fZ ); drawing::Position3D aPos( fX, fY, fZ); uno::Reference< XTransformation > xTransformation = this->getTransformationLogicToScene(); rSeq = xTransformation->transform( Position3DToSequence(aPos) ); } void PlottingPositionHelper::getLogicMinimum( ::com::sun::star::uno::Sequence< double >& rSeq ) const { rSeq.realloc(3); rSeq[0] = this->getLogicMinX(); rSeq[1] = this->getLogicMinY(); rSeq[2] = this->getLogicMinZ(); } void PlottingPositionHelper::getLogicMaximum( ::com::sun::star::uno::Sequence< double >& rSeq ) const { rSeq.realloc(3); rSeq[0] = this->getLogicMaxX(); rSeq[1] = this->getLogicMaxY(); rSeq[2] = this->getLogicMaxZ(); } //............................................................................. } //namespace chart //............................................................................. <commit_msg>#112587# changed matrix multiplication operator<commit_after>/************************************************************************* * * $RCSfile: PlottingPositionHelper.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: iha $ $Date: 2003-12-04 15:56:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2003 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "PlottingPositionHelper.hxx" #include "CommonConverters.hxx" #include "ViewDefines.hxx" #include "Linear3DTransformation.hxx" #ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_ #include <com/sun/star/drawing/Position3D.hpp> #endif //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; using namespace ::drafts::com::sun::star::chart2; PlottingPositionHelper::PlottingPositionHelper() : m_aScales() , m_aMatrixScreenToScene() , m_xTransformationLogicToScene(NULL) { } PlottingPositionHelper::~PlottingPositionHelper() { } void PlottingPositionHelper::setTransformationSceneToScreen( const drawing::HomogenMatrix& rMatrix) { m_aMatrixScreenToScene = HomogenMatrixToMatrix4D(rMatrix); m_xTransformationLogicToScene = NULL; } void PlottingPositionHelper::setScales( const uno::Sequence< ExplicitScaleData >& rScales ) { m_aScales = rScales; m_xTransformationLogicToScene = NULL; } uno::Reference< XTransformation > PlottingPositionHelper::getTransformationLogicToScene() const { //this is a standard transformation for a cartesian coordinate system //transformation from 2) to 4) //@todo 2) and 4) need a ink to a document //we need to apply this transformation to each geometric object because of a bug/problem //of the old drawing layer (the UNO_NAME_3D_EXTRUDE_DEPTH is an integer value instead of an double ) if(!m_xTransformationLogicToScene.is()) { Matrix4D aMatrix; double MinX = getLogicMinX(); double MinY = getLogicMinY(); double MinZ = getLogicMinZ(); double MaxX = getLogicMaxX(); double MaxY = getLogicMaxY(); double MaxZ = getLogicMaxZ(); //apply scaling doLogicScaling( &MinX, &MinY, &MinZ ); doLogicScaling( &MaxX, &MaxY, &MaxZ); if( AxisOrientation_MATHEMATICAL==m_aScales[0].Orientation ) aMatrix.TranslateX(-MinX); else aMatrix.TranslateX(-MaxX); if( AxisOrientation_MATHEMATICAL==m_aScales[1].Orientation ) aMatrix.TranslateY(-MinY); else aMatrix.TranslateY(-MaxY); if( AxisOrientation_MATHEMATICAL==m_aScales[2].Orientation ) aMatrix.TranslateZ(-MaxZ);//z direction in draw is reverse mathematical direction else aMatrix.TranslateY(-MinZ); double fWidthX = MaxX - MinX; double fWidthY = MaxY - MinY; double fWidthZ = MaxZ - MinZ; double fScaleDirectionX = AxisOrientation_MATHEMATICAL==m_aScales[0].Orientation ? 1.0 : -1.0; double fScaleDirectionY = AxisOrientation_MATHEMATICAL==m_aScales[1].Orientation ? 1.0 : -1.0; double fScaleDirectionZ = AxisOrientation_MATHEMATICAL==m_aScales[2].Orientation ? -1.0 : 1.0; aMatrix.ScaleX(fScaleDirectionX*FIXED_SIZE_FOR_3D_CHART_VOLUME/fWidthX); aMatrix.ScaleY(fScaleDirectionY*FIXED_SIZE_FOR_3D_CHART_VOLUME/fWidthY); aMatrix.ScaleZ(fScaleDirectionZ*FIXED_SIZE_FOR_3D_CHART_VOLUME/fWidthZ); aMatrix = m_aMatrixScreenToScene*aMatrix; m_xTransformationLogicToScene = new Linear3DTransformation(Matrix4DToHomogenMatrix( aMatrix )); } return m_xTransformationLogicToScene; } void PlottingPositionHelper::getScreenValuesForMinimum( uno::Sequence< double >& rSeq ) const { double fX = this->getLogicMinX(); double fY = this->getLogicMinY(); double fZ = this->getLogicMinZ(); this->doLogicScaling( &fX,&fY,&fZ ); drawing::Position3D aPos( fX, fY, fZ); uno::Reference< XTransformation > xTransformation = this->getTransformationLogicToScene(); rSeq = xTransformation->transform( Position3DToSequence(aPos) ); } void PlottingPositionHelper::getScreenValuesForMaximum( uno::Sequence< double >& rSeq ) const { double fX = this->getLogicMaxX(); double fY = this->getLogicMaxY(); double fZ = this->getLogicMaxZ(); this->doLogicScaling( &fX,&fY,&fZ ); drawing::Position3D aPos( fX, fY, fZ); uno::Reference< XTransformation > xTransformation = this->getTransformationLogicToScene(); rSeq = xTransformation->transform( Position3DToSequence(aPos) ); } void PlottingPositionHelper::getLogicMinimum( ::com::sun::star::uno::Sequence< double >& rSeq ) const { rSeq.realloc(3); rSeq[0] = this->getLogicMinX(); rSeq[1] = this->getLogicMinY(); rSeq[2] = this->getLogicMinZ(); } void PlottingPositionHelper::getLogicMaximum( ::com::sun::star::uno::Sequence< double >& rSeq ) const { rSeq.realloc(3); rSeq[0] = this->getLogicMaxX(); rSeq[1] = this->getLogicMaxY(); rSeq[2] = this->getLogicMaxZ(); } //............................................................................. } //namespace chart //............................................................................. <|endoftext|>
<commit_before>/* Copyright (c) 2013, 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. */ #ifndef TORRENT_PERFORMANCE_COUNTERS_HPP_INCLUDED #define TORRENT_PERFORMANCE_COUNTERS_HPP_INCLUDED #include <boost/cstdint.hpp> #include <boost/atomic.hpp> #include "libtorrent/config.hpp" namespace libtorrent { struct TORRENT_EXTRA_EXPORT counters { enum stats_counter_t { // the number of peers that were disconnected this // tick due to protocol error error_peers, disconnected_peers, eof_peers, connreset_peers, connrefused_peers, connaborted_peers, perm_peers, buffer_peers, unreachable_peers, broken_pipe_peers, addrinuse_peers, no_access_peers, invalid_arg_peers, aborted_peers, piece_requests, max_piece_requests, invalid_piece_requests, choked_piece_requests, cancelled_piece_requests, piece_rejects, error_incoming_peers, error_outgoing_peers, error_rc4_peers, error_encrypted_peers, error_tcp_peers, error_utp_peers, // the number of times the piece picker was // successfully invoked, split by the reason // it was invoked reject_piece_picks, unchoke_piece_picks, incoming_redundant_piece_picks, incoming_piece_picks, end_game_piece_picks, snubbed_piece_picks, interesting_piece_picks, hash_fail_piece_picks, // these counters indicate which parts // of the piece picker CPU is spent in piece_picker_partial_loops, piece_picker_suggest_loops, piece_picker_sequential_loops, piece_picker_reverse_rare_loops, piece_picker_rare_loops, piece_picker_rand_start_loops, piece_picker_rand_loops, piece_picker_busy_loops, // reasons to disconnect peers connect_timeouts, uninteresting_peers, timeout_peers, no_memory_peers, too_many_peers, transport_timeout_peers, num_banned_peers, banned_for_hash_failure, // connection attempts (not necessarily successful) connection_attempts, // the number of iterations over the peer list when finding // a connect candidate connection_attempt_loops, // successful incoming connections (not rejected for any reason) incoming_connections, // counts events where the network // thread wakes up on_read_counter, on_write_counter, on_tick_counter, on_lsd_counter, on_lsd_peer_counter, on_udp_counter, on_accept_counter, on_disk_queue_counter, on_disk_counter, torrent_evicted_counter, // bittorrent message counters // TODO: should keepalives be in here too? // how about dont-have, share-mode, upload-only num_incoming_choke, num_incoming_unchoke, num_incoming_interested, num_incoming_not_interested, num_incoming_have, num_incoming_bitfield, num_incoming_request, num_incoming_piece, num_incoming_cancel, num_incoming_dht_port, num_incoming_suggest, num_incoming_have_all, num_incoming_have_none, num_incoming_reject, num_incoming_allowed_fast, num_incoming_ext_handshake, num_incoming_pex, num_incoming_metadata, num_incoming_extended, num_outgoing_choke, num_outgoing_unchoke, num_outgoing_interested, num_outgoing_not_interested, num_outgoing_have, num_outgoing_bitfield, num_outgoing_request, num_outgoing_piece, num_outgoing_cancel, num_outgoing_dht_port, num_outgoing_suggest, num_outgoing_have_all, num_outgoing_have_none, num_outgoing_reject, num_outgoing_allowed_fast, num_outgoing_ext_handshake, num_outgoing_pex, num_outgoing_metadata, num_outgoing_extended, num_piece_passed, num_piece_failed, num_have_pieces, num_total_pieces_added, num_blocks_written, num_blocks_read, num_blocks_hashed, num_blocks_cache_hits, num_write_ops, num_read_ops, num_read_back, disk_read_time, disk_write_time, disk_hash_time, disk_job_time, waste_piece_timed_out, waste_piece_cancelled, waste_piece_unknown, waste_piece_seed, waste_piece_end_game, waste_piece_closing, sent_payload_bytes, sent_bytes, sent_ip_overhead_bytes, sent_tracker_bytes, recv_payload_bytes, recv_bytes, recv_ip_overhead_bytes, recv_tracker_bytes, recv_failed_bytes, recv_redundant_bytes, dht_messages_in, dht_messages_out, dht_messages_out_dropped, dht_bytes_in, dht_bytes_out, dht_ping_in, dht_ping_out, dht_find_node_in, dht_find_node_out, dht_get_peers_in, dht_get_peers_out, dht_announce_peer_in, dht_announce_peer_out, dht_get_in, dht_get_out, dht_put_in, dht_put_out, // uTP counters utp_packet_loss, utp_timeout, utp_packets_in, utp_packets_out, utp_fast_retransmit, utp_packet_resend, utp_samples_above_target, utp_samples_below_target, utp_payload_pkts_in, utp_payload_pkts_out, utp_invalid_pkts_in, utp_redundant_pkts_in, // the buffer sizes accepted by // socket send calls. The larger // the more efficient. The size is // 1 << n, where n is the number // at the end of the counter name // 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, // 16384, 32768, 65536, 131072, 262144, 524288, 1048576 socket_send_size3, socket_send_size4, socket_send_size5, socket_send_size6, socket_send_size7, socket_send_size8, socket_send_size9, socket_send_size10, socket_send_size11, socket_send_size12, socket_send_size13, socket_send_size14, socket_send_size15, socket_send_size16, socket_send_size17, socket_send_size18, socket_send_size19, socket_send_size20, // the buffer sizes returned by // socket recv calls. The larger // the more efficient. The size is // 1 << n, where n is the number // at the end of the counter name // 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, // 16384, 32768, 65536, 131072, 262144, 524288, 1048576 socket_recv_size3, socket_recv_size4, socket_recv_size5, socket_recv_size6, socket_recv_size7, socket_recv_size8, socket_recv_size9, socket_recv_size10, socket_recv_size11, socket_recv_size12, socket_recv_size13, socket_recv_size14, socket_recv_size15, socket_recv_size16, socket_recv_size17, socket_recv_size18, socket_recv_size19, socket_recv_size20, num_stats_counters }; // it is important that all gauges have a higher index than counters. // This assumption is relied upon in other parts of the code enum stats_gauges_t { num_checking_torrents = num_stats_counters, num_stopped_torrents, // upload_only means finished num_upload_only_torrents, num_downloading_torrents, num_seeding_torrents, num_queued_seeding_torrents, num_queued_download_torrents, num_error_torrents, // the number of torrents that don't have the // IP filter applied to them. non_filter_torrents, // counters related to evicting torrents num_loaded_torrents, num_pinned_torrents, // these counter indices deliberatly // match the order of socket type IDs // defined in socket_type.hpp. num_tcp_peers, num_socks5_peers, num_http_proxy_peers, num_utp_peers, num_i2p_peers, num_ssl_peers, num_ssl_socks5_peers, num_ssl_http_proxy_peers, num_ssl_utp_peers, num_peers_half_open, num_peers_connected, num_peers_up_interested, num_peers_down_interested, num_peers_up_unchoked, num_peers_down_unchoked, num_peers_up_requests, num_peers_down_requests, num_peers_up_disk, num_peers_down_disk, num_peers_end_game, write_cache_blocks, read_cache_blocks, request_latency, pinned_blocks, disk_blocks_in_use, queued_disk_jobs, num_read_jobs, num_write_jobs, num_jobs, num_writing_threads, num_running_threads, blocked_disk_jobs, queued_write_bytes, num_unchoke_slots, arc_mru_size, arc_mru_ghost_size, arc_mfu_size, arc_mfu_ghost_size, arc_write_size, arc_volatile_size, dht_nodes, dht_node_cache, dht_torrents, dht_peers, dht_immutable_data, dht_mutable_data, dht_allocated_observers, has_incoming_connections, limiter_up_queue, limiter_down_queue, limiter_up_bytes, limiter_down_bytes, num_counters, num_gauge_counters = num_counters - num_stats_counters }; counters(); counters(counters const&); counters& operator=(counters const&); // returns the new value boost::int64_t inc_stats_counter(int c, boost::int64_t value = 1); boost::int64_t operator[](int i) const; void set_value(int c, boost::int64_t value); void blend_stats_counter(int c, boost::int64_t value, int ratio); private: // TODO: some space could be saved here by making gauges 32 bits #if BOOST_ATOMIC_LLONG_LOCK_FREE == 2 boost::atomic<boost::int64_t> m_stats_counter[num_counters]; #else // if the atomic type is't lock-free, use a single lock instead, for // the whole array mutex m_mutex; boost::int64_t m_stats_counter[num_counters]; #endif }; } #endif <commit_msg>comment<commit_after>/* Copyright (c) 2013, 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. */ #ifndef TORRENT_PERFORMANCE_COUNTERS_HPP_INCLUDED #define TORRENT_PERFORMANCE_COUNTERS_HPP_INCLUDED #include <boost/cstdint.hpp> #include <boost/atomic.hpp> #include "libtorrent/config.hpp" namespace libtorrent { struct TORRENT_EXTRA_EXPORT counters { enum stats_counter_t { // the number of peers that were disconnected this // tick due to protocol error error_peers, disconnected_peers, eof_peers, connreset_peers, connrefused_peers, connaborted_peers, perm_peers, buffer_peers, unreachable_peers, broken_pipe_peers, addrinuse_peers, no_access_peers, invalid_arg_peers, aborted_peers, piece_requests, max_piece_requests, invalid_piece_requests, choked_piece_requests, cancelled_piece_requests, piece_rejects, error_incoming_peers, error_outgoing_peers, error_rc4_peers, error_encrypted_peers, error_tcp_peers, error_utp_peers, // the number of times the piece picker was // successfully invoked, split by the reason // it was invoked reject_piece_picks, unchoke_piece_picks, incoming_redundant_piece_picks, incoming_piece_picks, end_game_piece_picks, snubbed_piece_picks, interesting_piece_picks, hash_fail_piece_picks, // these counters indicate which parts // of the piece picker CPU is spent in piece_picker_partial_loops, piece_picker_suggest_loops, piece_picker_sequential_loops, piece_picker_reverse_rare_loops, piece_picker_rare_loops, piece_picker_rand_start_loops, piece_picker_rand_loops, piece_picker_busy_loops, // reasons to disconnect peers connect_timeouts, uninteresting_peers, timeout_peers, no_memory_peers, too_many_peers, transport_timeout_peers, num_banned_peers, banned_for_hash_failure, // connection attempts (not necessarily successful) connection_attempts, // the number of iterations over the peer list when finding // a connect candidate connection_attempt_loops, // successful incoming connections (not rejected for any reason) incoming_connections, // counts events where the network // thread wakes up on_read_counter, on_write_counter, on_tick_counter, on_lsd_counter, on_lsd_peer_counter, on_udp_counter, on_accept_counter, on_disk_queue_counter, on_disk_counter, torrent_evicted_counter, // bittorrent message counters // TODO: should keepalives be in here too? // how about dont-have, share-mode, upload-only num_incoming_choke, num_incoming_unchoke, num_incoming_interested, num_incoming_not_interested, num_incoming_have, num_incoming_bitfield, num_incoming_request, num_incoming_piece, num_incoming_cancel, num_incoming_dht_port, num_incoming_suggest, num_incoming_have_all, num_incoming_have_none, num_incoming_reject, num_incoming_allowed_fast, num_incoming_ext_handshake, num_incoming_pex, num_incoming_metadata, num_incoming_extended, num_outgoing_choke, num_outgoing_unchoke, num_outgoing_interested, num_outgoing_not_interested, num_outgoing_have, num_outgoing_bitfield, num_outgoing_request, num_outgoing_piece, num_outgoing_cancel, num_outgoing_dht_port, num_outgoing_suggest, num_outgoing_have_all, num_outgoing_have_none, num_outgoing_reject, num_outgoing_allowed_fast, num_outgoing_ext_handshake, num_outgoing_pex, num_outgoing_metadata, num_outgoing_extended, num_piece_passed, num_piece_failed, num_have_pieces, num_total_pieces_added, num_blocks_written, num_blocks_read, num_blocks_hashed, num_blocks_cache_hits, num_write_ops, num_read_ops, num_read_back, disk_read_time, disk_write_time, disk_hash_time, disk_job_time, waste_piece_timed_out, waste_piece_cancelled, waste_piece_unknown, waste_piece_seed, waste_piece_end_game, waste_piece_closing, sent_payload_bytes, sent_bytes, sent_ip_overhead_bytes, sent_tracker_bytes, recv_payload_bytes, recv_bytes, recv_ip_overhead_bytes, recv_tracker_bytes, recv_failed_bytes, recv_redundant_bytes, dht_messages_in, dht_messages_out, dht_messages_out_dropped, dht_bytes_in, dht_bytes_out, dht_ping_in, dht_ping_out, dht_find_node_in, dht_find_node_out, dht_get_peers_in, dht_get_peers_out, dht_announce_peer_in, dht_announce_peer_out, dht_get_in, dht_get_out, dht_put_in, dht_put_out, // uTP counters utp_packet_loss, utp_timeout, utp_packets_in, utp_packets_out, utp_fast_retransmit, utp_packet_resend, utp_samples_above_target, utp_samples_below_target, utp_payload_pkts_in, utp_payload_pkts_out, utp_invalid_pkts_in, utp_redundant_pkts_in, // the buffer sizes accepted by // socket send calls. The larger // the more efficient. The size is // 1 << n, where n is the number // at the end of the counter name // 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, // 16384, 32768, 65536, 131072, 262144, 524288, 1048576 socket_send_size3, socket_send_size4, socket_send_size5, socket_send_size6, socket_send_size7, socket_send_size8, socket_send_size9, socket_send_size10, socket_send_size11, socket_send_size12, socket_send_size13, socket_send_size14, socket_send_size15, socket_send_size16, socket_send_size17, socket_send_size18, socket_send_size19, socket_send_size20, // the buffer sizes returned by // socket recv calls. The larger // the more efficient. The size is // 1 << n, where n is the number // at the end of the counter name // 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, // 16384, 32768, 65536, 131072, 262144, 524288, 1048576 socket_recv_size3, socket_recv_size4, socket_recv_size5, socket_recv_size6, socket_recv_size7, socket_recv_size8, socket_recv_size9, socket_recv_size10, socket_recv_size11, socket_recv_size12, socket_recv_size13, socket_recv_size14, socket_recv_size15, socket_recv_size16, socket_recv_size17, socket_recv_size18, socket_recv_size19, socket_recv_size20, num_stats_counters }; // it is important that all gauges have a higher index than counters. // This assumption is relied upon in other parts of the code enum stats_gauges_t { num_checking_torrents = num_stats_counters, num_stopped_torrents, // upload_only means finished num_upload_only_torrents, num_downloading_torrents, num_seeding_torrents, num_queued_seeding_torrents, num_queued_download_torrents, num_error_torrents, // the number of torrents that don't have the // IP filter applied to them. non_filter_torrents, // counters related to evicting torrents num_loaded_torrents, num_pinned_torrents, // these counter indices deliberatly // match the order of socket type IDs // defined in socket_type.hpp. num_tcp_peers, num_socks5_peers, num_http_proxy_peers, num_utp_peers, num_i2p_peers, num_ssl_peers, num_ssl_socks5_peers, num_ssl_http_proxy_peers, num_ssl_utp_peers, num_peers_half_open, num_peers_connected, num_peers_up_interested, num_peers_down_interested, num_peers_up_unchoked, num_peers_down_unchoked, num_peers_up_requests, num_peers_down_requests, num_peers_up_disk, num_peers_down_disk, num_peers_end_game, write_cache_blocks, read_cache_blocks, request_latency, pinned_blocks, disk_blocks_in_use, queued_disk_jobs, num_read_jobs, num_write_jobs, num_jobs, num_writing_threads, num_running_threads, blocked_disk_jobs, queued_write_bytes, num_unchoke_slots, arc_mru_size, arc_mru_ghost_size, arc_mfu_size, arc_mfu_ghost_size, arc_write_size, arc_volatile_size, dht_nodes, dht_node_cache, dht_torrents, dht_peers, dht_immutable_data, dht_mutable_data, dht_allocated_observers, has_incoming_connections, limiter_up_queue, limiter_down_queue, limiter_up_bytes, limiter_down_bytes, num_counters, num_gauge_counters = num_counters - num_stats_counters }; counters(); counters(counters const&); counters& operator=(counters const&); // returns the new value boost::int64_t inc_stats_counter(int c, boost::int64_t value = 1); boost::int64_t operator[](int i) const; void set_value(int c, boost::int64_t value); void blend_stats_counter(int c, boost::int64_t value, int ratio); private: // TODO: some space could be saved here by making gauges 32 bits // TODO: restore these to regular integers. Instead have one copy // of the counters per thread and collect them at convenient // synchronization points #if BOOST_ATOMIC_LLONG_LOCK_FREE == 2 boost::atomic<boost::int64_t> m_stats_counter[num_counters]; #else // if the atomic type is't lock-free, use a single lock instead, for // the whole array mutex m_mutex; boost::int64_t m_stats_counter[num_counters]; #endif }; } #endif <|endoftext|>
<commit_before>// // George 'papanikge' Papanikolaou // CEID Advance Algorithm Desing Course 2014 // Library of Efficient Data types and Algorithms (LEDA) testing // // Strong Components identifier and checker implementation // #include "basic.h" using namespace leda; /* * My implementation of Kosaraju's algorithm for finding SCC. * Maybe we should leave the graph reversed to save some time. */ int my_STRONG_COMPONENTS(graph& G, node_array<int>& compnum) { int i; int scc_count = 0; int n = G.number_of_nodes(); node v; node* Stack = new node[n+1]; list<node> S; node_array<int> useless(G, 0); node_array<bool> reached(G, false); // reinitialize to our copy compnum.init(G, 0); // first DFS over the graph, to get the completion times DFS_NUM(G, useless, compnum); // create a sorted array of the completion times. The [0] position is vacant. forall_nodes(v,G) { Stack[compnum[v]] = v; } // reverse graph G.rev_all_edges(); // running DFS on the reversed graph starting from the top of the Stack for (i = n; i > 0; i--) { // we are performing DFS on the nodes in the Stack. We are using the // reached array to perform it only once for every one. if (!reached[Stack[i]]) { S = DFS(G, Stack[i], reached); // S now is the biggest strong component that contains Stack[i] // Reporting and updating arrays and counters forall(v, S) compnum[v] = scc_count; // writing the SCC nums on top of the compnums, which is kinda awkward. scc_count++; } } delete[] Stack; G.rev_all_edges(); return scc_count; } /* * Checker function for the SCC above implementation based on the fact that * all the nodes can reach the others when they are in the same SCC */ bool STRONG_COMPONENTS_checker(leda::graph& G, leda::node_array<int>& check_nums) { int orig_counter = 0; int rev_counter = 0; node v, a; list<node> LN1, LN2; node_array<int> for_bfs(G, -1); /* do we need to check a node from each SCC ?? */ a = G.choose_node(); /* Performing BFS on the original and on the reverse graph.*/ LN1 = BFS(G, a, for_bfs); forall(v, LN1) { if (check_nums[a] == check_nums[v]) orig_counter++; } G.rev_all_edges(); for_bfs.init(G, -1); LN2 = BFS(G, a, for_bfs); forall(v, LN2) { if (check_nums[a] == check_nums[v]) rev_counter++; } /* Checking the summing of the found nodes. They need to be the same. */ if (rev_counter == orig_counter) { std::cout << "\tCheck. Implementations match." << std::endl; return true; } else { std::cout << "\tBEWARE: Implementations DON'T match." << std::endl; return false; } } <commit_msg>Make the checker check all the cliques<commit_after>// // George 'papanikge' Papanikolaou // CEID Advance Algorithm Desing Course 2014 // Library of Efficient Data types and Algorithms (LEDA) testing // // Strong Components identifier and checker implementation // #include "basic.h" #include <LEDA/core/set.h> using namespace leda; /* * My implementation of Kosaraju's algorithm for finding SCC. * Maybe we should leave the graph reversed to save some time. */ int my_STRONG_COMPONENTS(graph& G, node_array<int>& compnum) { int i; int scc_count = 0; int n = G.number_of_nodes(); node v; node* Stack = new node[n+1]; list<node> S; node_array<int> useless(G, 0); node_array<bool> reached(G, false); // reinitialize to our copy compnum.init(G, 0); // first DFS over the graph, to get the completion times DFS_NUM(G, useless, compnum); // create a sorted array of the completion times. The [0] position is vacant. forall_nodes(v,G) { Stack[compnum[v]] = v; } // reverse graph G.rev_all_edges(); // running DFS on the reversed graph starting from the top of the Stack for (i = n; i > 0; i--) { // we are performing DFS on the nodes in the Stack. We are using the // reached array to perform it only once for every one. if (!reached[Stack[i]]) { S = DFS(G, Stack[i], reached); // S now is the biggest strong component that contains Stack[i] // Reporting and updating arrays and counters forall(v, S) compnum[v] = scc_count; // writing the SCC nums on top of the compnums, which is kinda awkward. scc_count++; } } delete[] Stack; G.rev_all_edges(); return scc_count; } /* * Checker function for the SCC above implementation based on the fact that * all the nodes can reach the others when they are in the same SCC */ bool STRONG_COMPONENTS_checker(leda::graph& G, leda::node_array<int>& check_nums) { node n, v; set<int> S; int orig_counter = 0; int rev_counter = 0; list<node> LN1, LN2; forall_nodes(n, G) { /* we need to perform the test for one node in each clique */ if (S.member(check_nums[n])) continue; else S.insert(check_nums[n]); node_array<int> for_bfs(G, -1); /* Performing BFS on the original and on the reverse graph.*/ LN1 = BFS(G, n, for_bfs); forall(v, LN1) { if (check_nums[n] == check_nums[v]) orig_counter++; } G.rev_all_edges(); for_bfs.init(G, -1); LN2 = BFS(G, n, for_bfs); forall(v, LN2) { if (check_nums[n] == check_nums[v]) rev_counter++; } } /* Checking the summing of the found nodes. They need to be the same. */ if (rev_counter == orig_counter) { std::cout << "\tCheck. Implementations match." << std::endl; return true; } else { std::cout << "\tBEWARE: Implementations DON'T match." << std::endl; return false; } } <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Philippe Canal 24/06/2003 /************************************************************************* * Copyright (C) 1995-2003, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TClassGenerator // // // // Objects following this interface can be passed onto the TROOT object // // to implement a user customized way to create the TClass objects. // // // // Use TROOT::AddClassGenerator to register a concrete instance. // // // ////////////////////////////////////////////////////////////////////////// #include "TClassGenerator.h" ClassImp(TClassGenerator); ////////////////////////////////////////////////////////////////////////// TClass *TClassGenerator::GetClass(const char* classname, Bool_t load, Bool_t /* silent */) { // Default implementation for backward compatibility ignoring the value of 'silent' return GetClass(classname,load); } ////////////////////////////////////////////////////////////////////////// TClass *TClassGenerator::GetClass(const type_info& typeinfo, Bool_t load, Bool_t /* silent */) { // Default implementation for backward compatibility ignoring the value of 'silent' return GetClass(typeinfo,load); } <commit_msg>Doxygen<commit_after>// @(#)root/base:$Id$ // Author: Philippe Canal 24/06/2003 /************************************************************************* * Copyright (C) 1995-2003, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /** \class TClassGenerator Objects following this interface can be passed onto the TROOT object to implement a user customized way to create the TClass objects. Use TROOT::AddClassGenerator to register a concrete instance. */ #include "TClassGenerator.h" ClassImp(TClassGenerator); ////////////////////////////////////////////////////////////////////////// TClass *TClassGenerator::GetClass(const char* classname, Bool_t load, Bool_t /* silent */) { // Default implementation for backward compatibility ignoring the value of 'silent' return GetClass(classname,load); } ////////////////////////////////////////////////////////////////////////// TClass *TClassGenerator::GetClass(const type_info& typeinfo, Bool_t load, Bool_t /* silent */) { // Default implementation for backward compatibility ignoring the value of 'silent' return GetClass(typeinfo,load); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "MiniAppManager.h" #include <vector> #include <iostream> #include <fstream> #include <algorithm> #include <string> #include <itkImageFileWriter.h> #include <itkMetaDataObject.h> #include <itkVectorImage.h> #include <mitkBaseDataIOFactory.h> #include <mitkBaseData.h> #include <mitkDiffusionCoreObjectFactory.h> #include <mitkFiberTrackingObjectFactory.h> #include <mitkFiberBundleX.h> #include "ctkCommandLineParser.h" #include <boost/lexical_cast.hpp> mitk::FiberBundleX::Pointer LoadFib(std::string filename) { const std::string s1="", s2=""; std::vector<mitk::BaseData::Pointer> fibInfile = mitk::BaseDataIO::LoadBaseDataFromFile( filename, s1, s2, false ); if( fibInfile.empty() ) MITK_INFO << "File " << filename << " could not be read!"; mitk::BaseData::Pointer baseData = fibInfile.at(0); return dynamic_cast<mitk::FiberBundleX*>(baseData.GetPointer()); } int FiberProcessing(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input fiber bundle (.fib)", us::Any(), false); parser.addArgument("outFile", "o", ctkCommandLineParser::String, "output fiber bundle (.fib)", us::Any(), false); parser.addArgument("resample", "r", ctkCommandLineParser::Float, "Resample fiber with the given point distance (in mm)"); parser.addArgument("smooth", "s", ctkCommandLineParser::Float, "Smooth fiber with the given point distance (in mm)"); parser.addArgument("minLength", "l", ctkCommandLineParser::Float, "Minimum fiber length (in mm)"); parser.addArgument("maxLength", "m", ctkCommandLineParser::Float, "Maximum fiber length (in mm)"); parser.addArgument("minCurv", "a", ctkCommandLineParser::Float, "Minimum curvature radius (in mm)"); parser.addArgument("mirror", "p", ctkCommandLineParser::Int, "Invert fiber coordinates XYZ (e.g. 010 to invert y-coordinate of each fiber point)"); map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; float pointDist = -1; if (parsedArgs.count("resample")) pointDist = us::any_cast<float>(parsedArgs["resample"]); float smoothDist = -1; if (parsedArgs.count("smooth")) smoothDist = us::any_cast<float>(parsedArgs["smooth"]); float minFiberLength = -1; if (parsedArgs.count("minLength")) minFiberLength = us::any_cast<float>(parsedArgs["minLength"]); float maxFiberLength = -1; if (parsedArgs.count("maxLength")) maxFiberLength = us::any_cast<float>(parsedArgs["maxLength"]); float curvThres = -1; if (parsedArgs.count("minCurv")) curvThres = us::any_cast<float>(parsedArgs["minCurv"]); int axis = 0; if (parsedArgs.count("mirror")) axis = us::any_cast<int>(parsedArgs["mirror"]); string inFileName = us::any_cast<string>(parsedArgs["input"]); string outFileName = us::any_cast<string>(parsedArgs["outFile"]); try { RegisterDiffusionCoreObjectFactory(); RegisterFiberTrackingObjectFactory(); mitk::FiberBundleX::Pointer fib = LoadFib(inFileName); if (minFiberLength>0) fib->RemoveShortFibers(minFiberLength); if (maxFiberLength>0) fib->RemoveLongFibers(maxFiberLength); if (curvThres>0) fib->ApplyCurvatureThreshold(curvThres, false); if (pointDist>0) fib->ResampleFibers(pointDist); if (smoothDist>0) fib->DoFiberSmoothing(smoothDist); if (axis/100==1) fib->MirrorFibers(0); if ((axis%100)/10==1) fib->MirrorFibers(1); if (axis%10==1) fib->MirrorFibers(2); mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) { if ( (*it)->CanWriteBaseDataType(fib.GetPointer()) ) { MITK_INFO << "writing " << outFileName; (*it)->SetFileName( outFileName.c_str() ); (*it)->DoWrite( fib.GetPointer() ); } } } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } } RegisterDiffusionMiniApp(FiberProcessing); <commit_msg>add copy and join function<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "MiniAppManager.h" #include <vector> #include <iostream> #include <fstream> #include <algorithm> #include <string> #include <itkImageFileWriter.h> #include <itkMetaDataObject.h> #include <itkVectorImage.h> #include <mitkBaseDataIOFactory.h> #include <mitkBaseData.h> #include <mitkDiffusionCoreObjectFactory.h> #include <mitkFiberTrackingObjectFactory.h> #include <mitkFiberBundleX.h> #include "ctkCommandLineParser.h" #include <boost/lexical_cast.hpp> mitk::FiberBundleX::Pointer LoadFib(std::string filename) { const std::string s1="", s2=""; std::vector<mitk::BaseData::Pointer> fibInfile = mitk::BaseDataIO::LoadBaseDataFromFile( filename, s1, s2, false ); if( fibInfile.empty() ) MITK_INFO << "File " << filename << " could not be read!"; mitk::BaseData::Pointer baseData = fibInfile.at(0); return dynamic_cast<mitk::FiberBundleX*>(baseData.GetPointer()); } int FiberProcessing(int argc, char* argv[]) { ctkCommandLineParser parser; parser.setArgumentPrefix("--", "-"); parser.addArgument("input", "i", ctkCommandLineParser::String, "input fiber bundle (.fib)", us::Any(), false); parser.addArgument("outFile", "o", ctkCommandLineParser::String, "output fiber bundle (.fib)", us::Any(), false); parser.addArgument("resample", "r", ctkCommandLineParser::Float, "Resample fiber with the given point distance (in mm)"); parser.addArgument("smooth", "s", ctkCommandLineParser::Float, "Smooth fiber with the given point distance (in mm)"); parser.addArgument("minLength", "l", ctkCommandLineParser::Float, "Minimum fiber length (in mm)"); parser.addArgument("maxLength", "m", ctkCommandLineParser::Float, "Maximum fiber length (in mm)"); parser.addArgument("minCurv", "a", ctkCommandLineParser::Float, "Minimum curvature radius (in mm)"); parser.addArgument("mirror", "p", ctkCommandLineParser::Int, "Invert fiber coordinates XYZ (e.g. 010 to invert y-coordinate of each fiber point)"); parser.addArgument("copyAndJoin", "c", ctkCommandLineParser::Bool, "Create a copy of the input fiber bundle (applied after resample/smooth/minLength/maxLength/minCurv/mirror) and join copy with original (applied after rotate/scale/translate)"); //parser.addArgument("join", "j", ctkCommandLineParser::Bool, "Join the original and copied fiber bundle (applied after rotate/scale/translate)"); map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv); if (parsedArgs.size()==0) return EXIT_FAILURE; float pointDist = -1; if (parsedArgs.count("resample")) pointDist = us::any_cast<float>(parsedArgs["resample"]); float smoothDist = -1; if (parsedArgs.count("smooth")) smoothDist = us::any_cast<float>(parsedArgs["smooth"]); float minFiberLength = -1; if (parsedArgs.count("minLength")) minFiberLength = us::any_cast<float>(parsedArgs["minLength"]); float maxFiberLength = -1; if (parsedArgs.count("maxLength")) maxFiberLength = us::any_cast<float>(parsedArgs["maxLength"]); float curvThres = -1; if (parsedArgs.count("minCurv")) curvThres = us::any_cast<float>(parsedArgs["minCurv"]); int axis = 0; if (parsedArgs.count("mirror")) axis = us::any_cast<int>(parsedArgs["mirror"]); bool copyAndJoin = false; if(parsedArgs.count("copyAndJoin")) copyAndJoin = us::any_cast<bool>(parsedArgs["copyAndJoin"]); string inFileName = us::any_cast<string>(parsedArgs["input"]); string outFileName = us::any_cast<string>(parsedArgs["outFile"]); try { RegisterDiffusionCoreObjectFactory(); RegisterFiberTrackingObjectFactory(); mitk::FiberBundleX::Pointer fib = LoadFib(inFileName); if (minFiberLength>0) fib->RemoveShortFibers(minFiberLength); if (maxFiberLength>0) fib->RemoveLongFibers(maxFiberLength); if (curvThres>0) fib->ApplyCurvatureThreshold(curvThres, false); if (pointDist>0) fib->ResampleFibers(pointDist); if (smoothDist>0) fib->DoFiberSmoothing(smoothDist); if (axis/100==1) fib->MirrorFibers(0); if ((axis%100)/10==1) fib->MirrorFibers(1); if (axis%10==1) fib->MirrorFibers(2); if (copyAndJoin == true) { MITK_INFO << "Create copy"; mitk::FiberBundleX::Pointer fibCopy = fib->GetDeepCopy(); MITK_INFO << "Join copy with original"; fib = fib->AddBundle(fibCopy.GetPointer()); } else { } mitk::CoreObjectFactory::FileWriterList fileWriters = mitk::CoreObjectFactory::GetInstance()->GetFileWriters(); for (mitk::CoreObjectFactory::FileWriterList::iterator it = fileWriters.begin() ; it != fileWriters.end() ; ++it) { if ( (*it)->CanWriteBaseDataType(fib.GetPointer()) ) { MITK_INFO << "writing " << outFileName; (*it)->SetFileName( outFileName.c_str() ); (*it)->DoWrite( fib.GetPointer() ); } } } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } } RegisterDiffusionMiniApp(FiberProcessing); <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkPolhemusInterface.h> #define _USE_MATH_DEFINES #include <math.h> #include <PDI.h> BYTE MotionBuf[0x1FA400]; mitk::PolhemusInterface::PolhemusInterface() { m_pdiDev = new CPDIdev(); } mitk::PolhemusInterface::~PolhemusInterface() { delete m_pdiDev; } bool mitk::PolhemusInterface::InitializeDevice() { m_pdiDev->ResetTracker(); m_pdiDev->ResetSAlignment(-1); m_pdiDev->Trace(TRUE, 7); return true; } bool mitk::PolhemusInterface::SetupDevice() { m_pdiDev->SetPnoBuffer(MotionBuf, 0x1FA400); m_pdiDev->SetMetric(true); //use cm instead of inches m_pdiDev->StartPipeExport(); CPDImdat pdiMDat; pdiMDat.Empty(); pdiMDat.Append(PDI_MODATA_FRAMECOUNT); pdiMDat.Append(PDI_MODATA_POS); pdiMDat.Append(PDI_MODATA_ORI); m_pdiDev->SetSDataList(-1, pdiMDat); CPDIbiterr cBE; m_pdiDev->GetBITErrs(cBE); if (!(cBE.IsClear())) {m_pdiDev->ClearBITErrs();} if (this->m_HemisphereTrackingEnabled) { m_pdiDev->SetSHemiTrack(-1); } else { m_pdiDev->SetSHemisphere(-1, { (float)2.54,0,0 }); } return true; } bool mitk::PolhemusInterface::StartTracking() { LPCTSTR szWindowClass = _T("PDIconsoleWinClass"); HINSTANCE hInst = GetModuleHandle(0); HWND hwnd = CreateWindowEx( WS_EX_NOACTIVATE,//WS_EX_STATICEDGE, // szWindowClass, _T("MyWindowName"), WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, 0, hInst, 0); m_continousTracking = true; return m_pdiDev->StartContPno(hwnd); } bool mitk::PolhemusInterface::StopTracking() { m_continousTracking = false; return true; } bool mitk::PolhemusInterface::Connect() { if (!InitializeDevice()) { return false; } if (m_pdiDev->CnxReady()) { return true; } CPDIser pdiSer; m_pdiDev->SetSerialIF(&pdiSer); ePiCommType eType = m_pdiDev->DiscoverCnx(); switch (eType) { case PI_CNX_USB: MITK_INFO << "USB Connection: " << m_pdiDev->GetLastResultStr(); break; case PI_CNX_SERIAL: MITK_INFO << "Serial Connection: " << m_pdiDev->GetLastResultStr(); break; default: MITK_INFO << "DiscoverCnx result: " << m_pdiDev->GetLastResultStr(); break; } if (!SetupDevice()) { return false; } return m_pdiDev->CnxReady(); } bool mitk::PolhemusInterface::Disconnect() { if (m_continousTracking) { m_continousTracking = false; if (!m_pdiDev->Disconnect()) return false; } return true; } std::vector<mitk::PolhemusInterface::trackingData> mitk::PolhemusInterface::GetLastFrame() { PBYTE pBuf; DWORD dwSize; //read one frame if (!m_pdiDev->LastPnoPtr(pBuf, dwSize)) {MITK_WARN << m_pdiDev->GetLastResultStr();} std::vector<mitk::PolhemusInterface::trackingData> returnValue = ParsePolhemusRawData(pBuf, dwSize); if (returnValue.empty()) { MITK_WARN << "Cannot parse data / no tools present"; } return returnValue; } unsigned int mitk::PolhemusInterface::GetNumberOfTools() { if (m_continousTracking) return GetLastFrame().size(); else return GetSingleFrame().size(); } std::vector<mitk::PolhemusInterface::trackingData> mitk::PolhemusInterface::GetSingleFrame() { if (m_continousTracking) return std::vector<mitk::PolhemusInterface::trackingData>(); PBYTE pBuf; DWORD dwSize; //read one frame if (!m_pdiDev->ReadSinglePnoBuf(pBuf, dwSize)) { MITK_WARN << m_pdiDev->GetLastResultStr(); } return ParsePolhemusRawData(pBuf, dwSize); } std::vector<mitk::PolhemusInterface::trackingData> mitk::PolhemusInterface::ParsePolhemusRawData(PBYTE pBuf, DWORD dwSize) { std::vector<mitk::PolhemusInterface::trackingData> returnValue; DWORD i = 0; while (i<dwSize) { BYTE ucSensor = pBuf[i + 2]; SHORT shSize = pBuf[i + 6]; // skip rest of header i += 8; PDWORD pFC = (PDWORD)(&pBuf[i]); PFLOAT pPno = (PFLOAT)(&pBuf[i + 4]); mitk::PolhemusInterface::trackingData currentTrackingData; currentTrackingData.id = ucSensor; currentTrackingData.pos[0] = pPno[0] * 10; //from cm to mm currentTrackingData.pos[1] = pPno[1] * 10; currentTrackingData.pos[2] = pPno[2] * 10; double azimuthAngle = pPno[3] / 180 * M_PI; //from degree to rad double elevationAngle = pPno[4] / 180 * M_PI; double rollAngle = pPno[5] / 180 * M_PI; vnl_quaternion<double> eulerQuat(rollAngle, elevationAngle, azimuthAngle); currentTrackingData.rot = eulerQuat; returnValue.push_back(currentTrackingData); i += shSize; } return returnValue; } <commit_msg>Intialized continous tracking to false to allow for auto detection in debug mode<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkPolhemusInterface.h> #define _USE_MATH_DEFINES #include <math.h> #include <PDI.h> BYTE MotionBuf[0x1FA400]; mitk::PolhemusInterface::PolhemusInterface() : m_continousTracking(false) { m_pdiDev = new CPDIdev(); } mitk::PolhemusInterface::~PolhemusInterface() { delete m_pdiDev; } bool mitk::PolhemusInterface::InitializeDevice() { m_pdiDev->ResetTracker(); m_pdiDev->ResetSAlignment(-1); m_pdiDev->Trace(TRUE, 7); m_continousTracking = false; return true; } bool mitk::PolhemusInterface::SetupDevice() { m_pdiDev->SetPnoBuffer(MotionBuf, 0x1FA400); m_pdiDev->SetMetric(true); //use cm instead of inches m_pdiDev->StartPipeExport(); CPDImdat pdiMDat; pdiMDat.Empty(); pdiMDat.Append(PDI_MODATA_FRAMECOUNT); pdiMDat.Append(PDI_MODATA_POS); pdiMDat.Append(PDI_MODATA_ORI); m_pdiDev->SetSDataList(-1, pdiMDat); CPDIbiterr cBE; m_pdiDev->GetBITErrs(cBE); if (!(cBE.IsClear())) {m_pdiDev->ClearBITErrs();} if (this->m_HemisphereTrackingEnabled) { m_pdiDev->SetSHemiTrack(-1); } else { m_pdiDev->SetSHemisphere(-1, { (float)2.54,0,0 }); } return true; } bool mitk::PolhemusInterface::StartTracking() { LPCTSTR szWindowClass = _T("PDIconsoleWinClass"); HINSTANCE hInst = GetModuleHandle(0); HWND hwnd = CreateWindowEx( WS_EX_NOACTIVATE,//WS_EX_STATICEDGE, // szWindowClass, _T("MyWindowName"), WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, 0, hInst, 0); m_continousTracking = true; return m_pdiDev->StartContPno(hwnd); } bool mitk::PolhemusInterface::StopTracking() { m_continousTracking = false; return true; } bool mitk::PolhemusInterface::Connect() { if (!InitializeDevice()) { return false; } if (m_pdiDev->CnxReady()) { return true; } CPDIser pdiSer; m_pdiDev->SetSerialIF(&pdiSer); ePiCommType eType = m_pdiDev->DiscoverCnx(); switch (eType) { case PI_CNX_USB: MITK_INFO << "USB Connection: " << m_pdiDev->GetLastResultStr(); break; case PI_CNX_SERIAL: MITK_INFO << "Serial Connection: " << m_pdiDev->GetLastResultStr(); break; default: MITK_INFO << "DiscoverCnx result: " << m_pdiDev->GetLastResultStr(); break; } if (!SetupDevice()) { return false; } return m_pdiDev->CnxReady(); } bool mitk::PolhemusInterface::Disconnect() { if (m_continousTracking) { m_continousTracking = false; if (!m_pdiDev->Disconnect()) return false; } return true; } std::vector<mitk::PolhemusInterface::trackingData> mitk::PolhemusInterface::GetLastFrame() { PBYTE pBuf; DWORD dwSize; //read one frame if (!m_pdiDev->LastPnoPtr(pBuf, dwSize)) {MITK_WARN << m_pdiDev->GetLastResultStr();} std::vector<mitk::PolhemusInterface::trackingData> returnValue = ParsePolhemusRawData(pBuf, dwSize); if (returnValue.empty()) { MITK_WARN << "Cannot parse data / no tools present"; } return returnValue; } unsigned int mitk::PolhemusInterface::GetNumberOfTools() { if (m_continousTracking) return GetLastFrame().size(); else return GetSingleFrame().size(); } std::vector<mitk::PolhemusInterface::trackingData> mitk::PolhemusInterface::GetSingleFrame() { if (m_continousTracking) { MITK_WARN << "Cannot get tool count when continously tracking"; return std::vector<mitk::PolhemusInterface::trackingData>(); } PBYTE pBuf; DWORD dwSize; //read one frame if (!m_pdiDev->ReadSinglePnoBuf(pBuf, dwSize)) { MITK_WARN << m_pdiDev->GetLastResultStr(); } return ParsePolhemusRawData(pBuf, dwSize); } std::vector<mitk::PolhemusInterface::trackingData> mitk::PolhemusInterface::ParsePolhemusRawData(PBYTE pBuf, DWORD dwSize) { std::vector<mitk::PolhemusInterface::trackingData> returnValue; DWORD i = 0; while (i<dwSize) { BYTE ucSensor = pBuf[i + 2]; SHORT shSize = pBuf[i + 6]; // skip rest of header i += 8; PDWORD pFC = (PDWORD)(&pBuf[i]); PFLOAT pPno = (PFLOAT)(&pBuf[i + 4]); mitk::PolhemusInterface::trackingData currentTrackingData; currentTrackingData.id = ucSensor; currentTrackingData.pos[0] = pPno[0] * 10; //from cm to mm currentTrackingData.pos[1] = pPno[1] * 10; currentTrackingData.pos[2] = pPno[2] * 10; double azimuthAngle = pPno[3] / 180 * M_PI; //from degree to rad double elevationAngle = pPno[4] / 180 * M_PI; double rollAngle = pPno[5] / 180 * M_PI; vnl_quaternion<double> eulerQuat(rollAngle, elevationAngle, azimuthAngle); currentTrackingData.rot = eulerQuat; returnValue.push_back(currentTrackingData); i += shSize; } return returnValue; } <|endoftext|>
<commit_before>/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <[email protected]> * * based on the Null Theme Engine for Gtk+. * Copyright (c) 2008 Robert Staudinger <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 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. */ #include "oxygendemodialog.h" #include "oxygeninputdemowidget.h" #include "oxygenbuttondemowidget.h" #include <iostream> namespace Oxygen { //_____________________________________________ DemoDialog::DemoDialog( void ) { // create main widget _mainWidget = gtk_window_new( GTK_WINDOW_TOPLEVEL ); gtk_window_set_title( GTK_WINDOW( _mainWidget ), "Oxygen-gtk Demo" ); // vertical container GtkWidget* vbox( gtk_vbox_new( false, 5 ) ); gtk_container_add( GTK_CONTAINER( _mainWidget ), vbox ); gtk_widget_show( vbox ); { // first horizontal container GtkWidget* hbox( gtk_hbox_new( false, 5 ) ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, true, true, 0 ); gtk_widget_show( hbox ); // iconview model _model = gtk_list_store_new( 2, GDK_TYPE_PIXBUF, G_TYPE_STRING ); // inconview GtkWidget* scrolledWindow( gtk_scrolled_window_new( 0L, 0L ) ); gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_SHADOW_IN ); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_POLICY_NEVER, GTK_POLICY_NEVER ); gtk_box_pack_start( GTK_BOX( hbox ), scrolledWindow, false, true, 0 ); gtk_widget_show( scrolledWindow ); GtkWidget* iconView( gtk_icon_view_new_with_model( GTK_TREE_MODEL( _model ) ) ); gtk_icon_view_set_pixbuf_column( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_text_column( GTK_ICON_VIEW( iconView ), 1 ); gtk_icon_view_set_columns( GTK_ICON_VIEW( iconView ), 1 ); gtk_icon_view_set_spacing( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_margin( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_item_padding( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_column_spacing( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_row_spacing( GTK_ICON_VIEW( iconView ), 0 ); _selectionChangedId.connect( G_OBJECT(iconView), "selection-changed", G_CALLBACK( selectionChanged ), this ); gtk_container_add( GTK_CONTAINER( scrolledWindow ), iconView ); gtk_widget_show( iconView ); // notebook _notebook = gtk_notebook_new(); gtk_notebook_set_show_tabs( GTK_NOTEBOOK( _notebook ), false ); gtk_box_pack_start( GTK_BOX( hbox ), _notebook, true, true, 0 ); gtk_widget_show( _notebook ); } { // statusbar GtkWidget* statusBar( gtk_hbox_new( false, 2 ) ); gtk_box_pack_start( GTK_BOX( vbox ), statusBar, false, true, 0 ); gtk_widget_show( statusBar ); // enable checkbox _stateButton = gtk_check_button_new_with_label( "Enabled" ); gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( _stateButton ), true ); gtk_box_pack_start( GTK_BOX( statusBar ), _stateButton, false, false, 0 ); gtk_widget_show( _stateButton ); _toggleEnableStateId.connect( G_OBJECT(_stateButton), "toggled", G_CALLBACK( toggleEnableState ), this ); // close button GtkWidget* button = gtk_button_new_from_stock( GTK_STOCK_OK ); gtk_box_pack_end( GTK_BOX( statusBar ), button, false, true, 0 ); gtk_widget_show( button ); } addPage( new InputDemoWidget() ); addPage( new ButtonDemoWidget() ); } //_____________________________________________ DemoDialog::~DemoDialog( void ) { //_selectionChangedId.disconnect(); //_toggleEnableStateId.disconnect(); } //_____________________________________________ void DemoDialog::addPage( DemoWidget* page ) { // get icon GdkPixbuf* icon( 0L ); if( !page->iconName().empty() ) { GtkIconTheme* theme( gtk_icon_theme_get_default() ); icon = gtk_icon_theme_load_icon( theme, page->iconName().c_str(), 22, (GtkIconLookupFlags) 0, 0L ); } // insert in list GtkTreeIter iter; gtk_list_store_append( _model, &iter ); gtk_list_store_set( _model, &iter, 0, icon, 1, page->name().c_str(), -1 ); // add to notebook int index( gtk_notebook_append_page( GTK_NOTEBOOK( _notebook ), page->mainWidget(), 0L ) ); gtk_widget_show( page->mainWidget() ); _pages.insert( std::make_pair( index, page ) ); } //_____________________________________________ void DemoDialog::selectionChanged( GtkIconView* view, gpointer data ) { // get pointer to dialog DemoDialog& dialog( *static_cast<DemoDialog*>( data ) ); // get selection GList* selection = gtk_icon_view_get_selected_items( view ); if( !selection ) return; // get first child GtkTreePath* path( static_cast<GtkTreePath*>( g_list_first( selection )->data ) ); const int page( gtk_tree_path_get_indices( path )[0] ); gtk_notebook_set_current_page( GTK_NOTEBOOK( dialog._notebook ), page ); g_list_free( selection ); // store enable state const bool enabled( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dialog._stateButton ) ) ); // get matching page DemoWidget* widget( dialog._pages[page] ); widget->setEnabled( enabled ); } //_____________________________________________ void DemoDialog::toggleEnableState( GtkToggleButton* button, gpointer data ) { // get pointer to dialog DemoDialog& dialog( *static_cast<DemoDialog*>( data ) ); // store enable state const bool enabled( gtk_toggle_button_get_active( button ) ); // get current page const int page( gtk_notebook_get_current_page( GTK_NOTEBOOK( dialog._notebook ) ) ); // get matching page DemoWidget* widget( dialog._pages[page] ); widget->setEnabled( enabled ); } } <commit_msg>Fixed margins for iconview.<commit_after>/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <[email protected]> * * based on the Null Theme Engine for Gtk+. * Copyright (c) 2008 Robert Staudinger <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 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. */ #include "oxygendemodialog.h" #include "oxygeninputdemowidget.h" #include "oxygenbuttondemowidget.h" #include <iostream> namespace Oxygen { //_____________________________________________ DemoDialog::DemoDialog( void ) { // create main widget _mainWidget = gtk_window_new( GTK_WINDOW_TOPLEVEL ); gtk_window_set_title( GTK_WINDOW( _mainWidget ), "Oxygen-gtk Demo" ); // vertical container GtkWidget* vbox( gtk_vbox_new( false, 5 ) ); gtk_container_add( GTK_CONTAINER( _mainWidget ), vbox ); gtk_widget_show( vbox ); { // first horizontal container GtkWidget* hbox( gtk_hbox_new( false, 5 ) ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, true, true, 0 ); gtk_widget_show( hbox ); // iconview model _model = gtk_list_store_new( 2, GDK_TYPE_PIXBUF, G_TYPE_STRING ); // inconview GtkWidget* scrolledWindow( gtk_scrolled_window_new( 0L, 0L ) ); gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_SHADOW_IN ); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_POLICY_NEVER, GTK_POLICY_NEVER ); gtk_box_pack_start( GTK_BOX( hbox ), scrolledWindow, false, true, 0 ); gtk_widget_show( scrolledWindow ); GtkWidget* iconView( gtk_icon_view_new_with_model( GTK_TREE_MODEL( _model ) ) ); gtk_icon_view_set_pixbuf_column( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_text_column( GTK_ICON_VIEW( iconView ), 1 ); gtk_icon_view_set_columns( GTK_ICON_VIEW( iconView ), 1 ); gtk_icon_view_set_spacing( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_margin( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_column_spacing( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_row_spacing( GTK_ICON_VIEW( iconView ), 0 ); _selectionChangedId.connect( G_OBJECT(iconView), "selection-changed", G_CALLBACK( selectionChanged ), this ); gtk_container_add( GTK_CONTAINER( scrolledWindow ), iconView ); gtk_widget_show( iconView ); // notebook _notebook = gtk_notebook_new(); gtk_notebook_set_show_tabs( GTK_NOTEBOOK( _notebook ), false ); gtk_box_pack_start( GTK_BOX( hbox ), _notebook, true, true, 0 ); gtk_widget_show( _notebook ); } { // statusbar GtkWidget* statusBar( gtk_hbox_new( false, 2 ) ); gtk_box_pack_start( GTK_BOX( vbox ), statusBar, false, true, 0 ); gtk_widget_show( statusBar ); // enable checkbox _stateButton = gtk_check_button_new_with_label( "Enabled" ); gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( _stateButton ), true ); gtk_box_pack_start( GTK_BOX( statusBar ), _stateButton, false, false, 0 ); gtk_widget_show( _stateButton ); _toggleEnableStateId.connect( G_OBJECT(_stateButton), "toggled", G_CALLBACK( toggleEnableState ), this ); // close button GtkWidget* button = gtk_button_new_from_stock( GTK_STOCK_OK ); gtk_box_pack_end( GTK_BOX( statusBar ), button, false, true, 0 ); gtk_widget_show( button ); } addPage( new InputDemoWidget() ); addPage( new ButtonDemoWidget() ); } //_____________________________________________ DemoDialog::~DemoDialog( void ) { //_selectionChangedId.disconnect(); //_toggleEnableStateId.disconnect(); } //_____________________________________________ void DemoDialog::addPage( DemoWidget* page ) { // get icon GdkPixbuf* icon( 0L ); if( !page->iconName().empty() ) { GtkIconTheme* theme( gtk_icon_theme_get_default() ); icon = gtk_icon_theme_load_icon( theme, page->iconName().c_str(), 22, (GtkIconLookupFlags) 0, 0L ); } // insert in list GtkTreeIter iter; gtk_list_store_append( _model, &iter ); gtk_list_store_set( _model, &iter, 0, icon, 1, page->name().c_str(), -1 ); // add to notebook int index( gtk_notebook_append_page( GTK_NOTEBOOK( _notebook ), page->mainWidget(), 0L ) ); gtk_widget_show( page->mainWidget() ); _pages.insert( std::make_pair( index, page ) ); } //_____________________________________________ void DemoDialog::selectionChanged( GtkIconView* view, gpointer data ) { // get pointer to dialog DemoDialog& dialog( *static_cast<DemoDialog*>( data ) ); // get selection GList* selection = gtk_icon_view_get_selected_items( view ); if( !selection ) return; // get first child GtkTreePath* path( static_cast<GtkTreePath*>( g_list_first( selection )->data ) ); const int page( gtk_tree_path_get_indices( path )[0] ); gtk_notebook_set_current_page( GTK_NOTEBOOK( dialog._notebook ), page ); g_list_free( selection ); // store enable state const bool enabled( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dialog._stateButton ) ) ); // get matching page DemoWidget* widget( dialog._pages[page] ); widget->setEnabled( enabled ); } //_____________________________________________ void DemoDialog::toggleEnableState( GtkToggleButton* button, gpointer data ) { // get pointer to dialog DemoDialog& dialog( *static_cast<DemoDialog*>( data ) ); // store enable state const bool enabled( gtk_toggle_button_get_active( button ) ); // get current page const int page( gtk_notebook_get_current_page( GTK_NOTEBOOK( dialog._notebook ) ) ); // get matching page DemoWidget* widget( dialog._pages[page] ); widget->setEnabled( enabled ); } } <|endoftext|>
<commit_before>/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <[email protected]> * * based on the Null Theme Engine for Gtk+. * Copyright (c) 2008 Robert Staudinger <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 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. */ #include "oxygendemodialog.h" #include "oxygeninputdemowidget.h" #include "oxygenbuttondemowidget.h" #include "oxygenframedemowidget.h" #include "oxygenlistdemowidget.h" #include "oxygensliderdemowidget.h" #include "oxygentabdemowidget.h" #include <gdk/gdkkeysyms.h> #include <iostream> #include <sstream> namespace Oxygen { //_____________________________________________ DemoDialog::DemoDialog( void ) { // create main widget _mainWidget = gtk_window_new( GTK_WINDOW_TOPLEVEL ); gtk_window_set_default_size( GTK_WINDOW( _mainWidget ), 630, 500 ); gtk_window_set_title( GTK_WINDOW( _mainWidget ), "Oxygen-gtk Demo" ); gtk_container_set_border_width( GTK_CONTAINER( _mainWidget ), 10 ); // vertical container GtkWidget* vbox( gtk_vbox_new( false, 5 ) ); gtk_container_add( GTK_CONTAINER( _mainWidget ), vbox ); gtk_widget_show( vbox ); GtkWidget* iconView(0L); { // first horizontal container GtkWidget* hbox( gtk_hbox_new( false, 8 ) ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, true, true, 0 ); gtk_widget_show( hbox ); // iconview model _model = gtk_list_store_new( 2, GDK_TYPE_PIXBUF, G_TYPE_STRING ); // inconview GtkWidget* scrolledWindow( gtk_scrolled_window_new( 0L, 0L ) ); gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_SHADOW_IN ); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_POLICY_NEVER, GTK_POLICY_NEVER ); gtk_box_pack_start( GTK_BOX( hbox ), scrolledWindow, false, true, 0 ); gtk_widget_show( scrolledWindow ); iconView = gtk_icon_view_new_with_model( GTK_TREE_MODEL( _model ) ); gtk_icon_view_set_pixbuf_column( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_text_column( GTK_ICON_VIEW( iconView ), 1 ); gtk_icon_view_set_columns( GTK_ICON_VIEW( iconView ), 1 ); gtk_icon_view_set_item_width( GTK_ICON_VIEW( iconView ), 108 ); gtk_icon_view_set_spacing( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_margin( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_column_spacing( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_row_spacing( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_selection_mode( GTK_ICON_VIEW( iconView ), GTK_SELECTION_BROWSE ); // get list of renderers, find text renderer and make font format bold GList* cells( gtk_cell_layout_get_cells( GTK_CELL_LAYOUT( iconView ) ) ); for( GList *cell = g_list_first( cells ); cell; cell = g_list_next( cell ) ) { if( !GTK_IS_CELL_RENDERER_TEXT( cell->data ) ) continue; // create pango attributes list PangoAttrList* attributes( pango_attr_list_new() ); pango_attr_list_insert( attributes, pango_attr_weight_new( PANGO_WEIGHT_BOLD ) ); GValue val = { 0, }; g_value_init(&val, PANGO_TYPE_ATTR_LIST ); g_value_set_boxed( &val, attributes ); g_object_set_property( G_OBJECT( cell->data ), "attributes", &val ); pango_attr_list_unref( attributes ); } if( cells ) g_list_free( cells ); // connect signals _selectionChangedId.connect( G_OBJECT(iconView), "selection-changed", G_CALLBACK( selectionChanged ), this ); gtk_container_add( GTK_CONTAINER( scrolledWindow ), iconView ); gtk_widget_show( iconView ); // notebook _notebook = gtk_notebook_new(); gtk_notebook_set_show_tabs( GTK_NOTEBOOK( _notebook ), false ); gtk_box_pack_start( GTK_BOX( hbox ), _notebook, true, true, 0 ); gtk_widget_show( _notebook ); } { // statusbar GtkWidget* statusBar( gtk_hbox_new( false, 2 ) ); gtk_box_pack_start( GTK_BOX( vbox ), statusBar, false, true, 0 ); gtk_widget_show( statusBar ); // enable checkbox _stateButton = gtk_check_button_new_with_label( "Enabled" ); gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( _stateButton ), true ); gtk_box_pack_start( GTK_BOX( statusBar ), _stateButton, false, false, 0 ); gtk_widget_show( _stateButton ); _toggleEnableStateId.connect( G_OBJECT(_stateButton), "toggled", G_CALLBACK( toggleEnableState ), this ); // widget direction checkbox GtkWidget* button( gtk_check_button_new_with_label( "Right to left layout" ) ); gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( button ), false ); gtk_box_pack_start( GTK_BOX( statusBar ), button, false, false, 0 ); gtk_widget_show( button ); _toggleWidgetDirectionId.connect( G_OBJECT(button), "toggled", G_CALLBACK( toggleWidgetDirection ), 0L ); // button box #if GTK_CHECK_VERSION( 3, 0, 0 ) GtkWidget* buttonBox( gtk_button_box_new( GTK_ORIENTATION_HORIZONTAL) ); #else GtkWidget* buttonBox( gtk_hbutton_box_new() ); #endif gtk_button_box_set_layout( GTK_BUTTON_BOX( buttonBox ), GTK_BUTTONBOX_END ); gtk_box_pack_end( GTK_BOX( statusBar ), buttonBox, true, true, 0 ); gtk_widget_show( buttonBox ); // close button button = gtk_button_new_from_stock( GTK_STOCK_OK ); gtk_box_pack_end( GTK_BOX( buttonBox ), button, false, true, 0 ); gtk_widget_show( button ); g_signal_connect( G_OBJECT(button), "clicked", G_CALLBACK( gtk_main_quit ), 0L ); } addPage( new InputDemoWidget() ); addPage( new TabDemoWidget() ); addPage( new ButtonDemoWidget() ); addPage( new ListDemoWidget() ); addPage( new FrameDemoWidget() ); addPage( _sliderDemoWidget = new SliderDemoWidget() ); // select first raw GtkTreePath *path( gtk_tree_path_new_from_indices(0, -1 ) ); gtk_icon_view_select_path( GTK_ICON_VIEW( iconView ), path ); // keypress signals _keyPressId.connect( G_OBJECT(_mainWidget), "key-press-event", G_CALLBACK( keyPress ), 0L ); } //_____________________________________________ DemoDialog::~DemoDialog( void ) {} //_____________________________________________ void DemoDialog::addPage( DemoWidget* page ) { // get icon GdkPixbuf* icon( 0L ); if( !page->iconName().empty() ) { // TODO: should get this icon size from options GtkIconTheme* theme( gtk_icon_theme_get_default() ); icon = gtk_icon_theme_load_icon( theme, page->iconName().c_str(), 32, (GtkIconLookupFlags) 0, 0L ); } // insert in list GtkTreeIter iter; gtk_list_store_append( _model, &iter ); gtk_list_store_set( _model, &iter, 0, icon, 1, page->name().c_str(), -1 ); // add to notebook int index( gtk_notebook_append_page( GTK_NOTEBOOK( _notebook ), page->mainWidget(), 0L ) ); gtk_widget_show( page->mainWidget() ); _pages.insert( std::make_pair( index, page ) ); } //_____________________________________________ void DemoDialog::selectionChanged( GtkIconView* view, gpointer data ) { // get pointer to dialog DemoDialog& dialog( *static_cast<DemoDialog*>( data ) ); // get selection GList* selection = gtk_icon_view_get_selected_items( view ); if( !selection ) return; // get first child GtkTreePath* path( static_cast<GtkTreePath*>( g_list_first( selection )->data ) ); const int page( gtk_tree_path_get_indices( path )[0] ); gtk_notebook_set_current_page( GTK_NOTEBOOK( dialog._notebook ), page ); g_list_free( selection ); // store enable state const bool enabled( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dialog._stateButton ) ) ); // get matching page DemoWidget* widget( dialog._pages[page] ); widget->setEnabled( enabled ); if( widget == dialog._sliderDemoWidget ) dialog._sliderDemoWidget->startPulse(); else dialog._sliderDemoWidget->stopPulse(); // update window title std::ostringstream what; what << widget->name() << " - Oxygen-gtk Demo"; gtk_window_set_title( GTK_WINDOW( dialog._mainWidget ), what.str().c_str() ); } //_____________________________________________ void DemoDialog::toggleEnableState( GtkToggleButton* button, gpointer data ) { // get pointer to dialog DemoDialog& dialog( *static_cast<DemoDialog*>( data ) ); // store enable state const bool enabled( gtk_toggle_button_get_active( button ) ); // get current page const int page( gtk_notebook_get_current_page( GTK_NOTEBOOK( dialog._notebook ) ) ); // get matching page DemoWidget* widget( dialog._pages[page] ); // set state widget->setEnabled( enabled ); // trigger repaint gtk_widget_queue_draw( widget->mainWidget() ); } //_____________________________________________ void DemoDialog::toggleWidgetDirection( GtkToggleButton* button, gpointer data ) { gtk_widget_set_default_direction( gtk_toggle_button_get_active( button ) ? GTK_TEXT_DIR_RTL:GTK_TEXT_DIR_LTR ); } //_____________________________________________ gboolean DemoDialog::keyPress( GtkWidget* widget, GdkEventKey* event, gpointer ) { guint modifiers( gtk_accelerator_get_default_mod_mask() ); if( gdk_keyval_to_upper( event->keyval ) == GDK_KEY_Q && (event->state&modifiers) == GDK_CONTROL_MASK ) { gtk_main_quit(); return TRUE; } return FALSE; } } <commit_msg>Fix GDK_KEY_Q for older GTK versions<commit_after>/* * this file is part of the oxygen gtk engine * Copyright (c) 2010 Hugo Pereira Da Costa <[email protected]> * * based on the Null Theme Engine for Gtk+. * Copyright (c) 2008 Robert Staudinger <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 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. */ #include "oxygendemodialog.h" #include "oxygeninputdemowidget.h" #include "oxygenbuttondemowidget.h" #include "oxygenframedemowidget.h" #include "oxygenlistdemowidget.h" #include "oxygensliderdemowidget.h" #include "oxygentabdemowidget.h" #include <gdk/gdkkeysyms.h> // Older (such as 2.20.1) GTK versions had different name for this #ifndef GDK_KEY_Q #define GDK_KEY_Q GDK_Q #endif #include <iostream> #include <sstream> namespace Oxygen { //_____________________________________________ DemoDialog::DemoDialog( void ) { // create main widget _mainWidget = gtk_window_new( GTK_WINDOW_TOPLEVEL ); gtk_window_set_default_size( GTK_WINDOW( _mainWidget ), 630, 500 ); gtk_window_set_title( GTK_WINDOW( _mainWidget ), "Oxygen-gtk Demo" ); gtk_container_set_border_width( GTK_CONTAINER( _mainWidget ), 10 ); // vertical container GtkWidget* vbox( gtk_vbox_new( false, 5 ) ); gtk_container_add( GTK_CONTAINER( _mainWidget ), vbox ); gtk_widget_show( vbox ); GtkWidget* iconView(0L); { // first horizontal container GtkWidget* hbox( gtk_hbox_new( false, 8 ) ); gtk_box_pack_start( GTK_BOX( vbox ), hbox, true, true, 0 ); gtk_widget_show( hbox ); // iconview model _model = gtk_list_store_new( 2, GDK_TYPE_PIXBUF, G_TYPE_STRING ); // inconview GtkWidget* scrolledWindow( gtk_scrolled_window_new( 0L, 0L ) ); gtk_scrolled_window_set_shadow_type( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_SHADOW_IN ); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( scrolledWindow ), GTK_POLICY_NEVER, GTK_POLICY_NEVER ); gtk_box_pack_start( GTK_BOX( hbox ), scrolledWindow, false, true, 0 ); gtk_widget_show( scrolledWindow ); iconView = gtk_icon_view_new_with_model( GTK_TREE_MODEL( _model ) ); gtk_icon_view_set_pixbuf_column( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_text_column( GTK_ICON_VIEW( iconView ), 1 ); gtk_icon_view_set_columns( GTK_ICON_VIEW( iconView ), 1 ); gtk_icon_view_set_item_width( GTK_ICON_VIEW( iconView ), 108 ); gtk_icon_view_set_spacing( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_margin( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_column_spacing( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_row_spacing( GTK_ICON_VIEW( iconView ), 0 ); gtk_icon_view_set_selection_mode( GTK_ICON_VIEW( iconView ), GTK_SELECTION_BROWSE ); // get list of renderers, find text renderer and make font format bold GList* cells( gtk_cell_layout_get_cells( GTK_CELL_LAYOUT( iconView ) ) ); for( GList *cell = g_list_first( cells ); cell; cell = g_list_next( cell ) ) { if( !GTK_IS_CELL_RENDERER_TEXT( cell->data ) ) continue; // create pango attributes list PangoAttrList* attributes( pango_attr_list_new() ); pango_attr_list_insert( attributes, pango_attr_weight_new( PANGO_WEIGHT_BOLD ) ); GValue val = { 0, }; g_value_init(&val, PANGO_TYPE_ATTR_LIST ); g_value_set_boxed( &val, attributes ); g_object_set_property( G_OBJECT( cell->data ), "attributes", &val ); pango_attr_list_unref( attributes ); } if( cells ) g_list_free( cells ); // connect signals _selectionChangedId.connect( G_OBJECT(iconView), "selection-changed", G_CALLBACK( selectionChanged ), this ); gtk_container_add( GTK_CONTAINER( scrolledWindow ), iconView ); gtk_widget_show( iconView ); // notebook _notebook = gtk_notebook_new(); gtk_notebook_set_show_tabs( GTK_NOTEBOOK( _notebook ), false ); gtk_box_pack_start( GTK_BOX( hbox ), _notebook, true, true, 0 ); gtk_widget_show( _notebook ); } { // statusbar GtkWidget* statusBar( gtk_hbox_new( false, 2 ) ); gtk_box_pack_start( GTK_BOX( vbox ), statusBar, false, true, 0 ); gtk_widget_show( statusBar ); // enable checkbox _stateButton = gtk_check_button_new_with_label( "Enabled" ); gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( _stateButton ), true ); gtk_box_pack_start( GTK_BOX( statusBar ), _stateButton, false, false, 0 ); gtk_widget_show( _stateButton ); _toggleEnableStateId.connect( G_OBJECT(_stateButton), "toggled", G_CALLBACK( toggleEnableState ), this ); // widget direction checkbox GtkWidget* button( gtk_check_button_new_with_label( "Right to left layout" ) ); gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON( button ), false ); gtk_box_pack_start( GTK_BOX( statusBar ), button, false, false, 0 ); gtk_widget_show( button ); _toggleWidgetDirectionId.connect( G_OBJECT(button), "toggled", G_CALLBACK( toggleWidgetDirection ), 0L ); // button box #if GTK_CHECK_VERSION( 3, 0, 0 ) GtkWidget* buttonBox( gtk_button_box_new( GTK_ORIENTATION_HORIZONTAL) ); #else GtkWidget* buttonBox( gtk_hbutton_box_new() ); #endif gtk_button_box_set_layout( GTK_BUTTON_BOX( buttonBox ), GTK_BUTTONBOX_END ); gtk_box_pack_end( GTK_BOX( statusBar ), buttonBox, true, true, 0 ); gtk_widget_show( buttonBox ); // close button button = gtk_button_new_from_stock( GTK_STOCK_OK ); gtk_box_pack_end( GTK_BOX( buttonBox ), button, false, true, 0 ); gtk_widget_show( button ); g_signal_connect( G_OBJECT(button), "clicked", G_CALLBACK( gtk_main_quit ), 0L ); } addPage( new InputDemoWidget() ); addPage( new TabDemoWidget() ); addPage( new ButtonDemoWidget() ); addPage( new ListDemoWidget() ); addPage( new FrameDemoWidget() ); addPage( _sliderDemoWidget = new SliderDemoWidget() ); // select first raw GtkTreePath *path( gtk_tree_path_new_from_indices(0, -1 ) ); gtk_icon_view_select_path( GTK_ICON_VIEW( iconView ), path ); // keypress signals _keyPressId.connect( G_OBJECT(_mainWidget), "key-press-event", G_CALLBACK( keyPress ), 0L ); } //_____________________________________________ DemoDialog::~DemoDialog( void ) {} //_____________________________________________ void DemoDialog::addPage( DemoWidget* page ) { // get icon GdkPixbuf* icon( 0L ); if( !page->iconName().empty() ) { // TODO: should get this icon size from options GtkIconTheme* theme( gtk_icon_theme_get_default() ); icon = gtk_icon_theme_load_icon( theme, page->iconName().c_str(), 32, (GtkIconLookupFlags) 0, 0L ); } // insert in list GtkTreeIter iter; gtk_list_store_append( _model, &iter ); gtk_list_store_set( _model, &iter, 0, icon, 1, page->name().c_str(), -1 ); // add to notebook int index( gtk_notebook_append_page( GTK_NOTEBOOK( _notebook ), page->mainWidget(), 0L ) ); gtk_widget_show( page->mainWidget() ); _pages.insert( std::make_pair( index, page ) ); } //_____________________________________________ void DemoDialog::selectionChanged( GtkIconView* view, gpointer data ) { // get pointer to dialog DemoDialog& dialog( *static_cast<DemoDialog*>( data ) ); // get selection GList* selection = gtk_icon_view_get_selected_items( view ); if( !selection ) return; // get first child GtkTreePath* path( static_cast<GtkTreePath*>( g_list_first( selection )->data ) ); const int page( gtk_tree_path_get_indices( path )[0] ); gtk_notebook_set_current_page( GTK_NOTEBOOK( dialog._notebook ), page ); g_list_free( selection ); // store enable state const bool enabled( gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON( dialog._stateButton ) ) ); // get matching page DemoWidget* widget( dialog._pages[page] ); widget->setEnabled( enabled ); if( widget == dialog._sliderDemoWidget ) dialog._sliderDemoWidget->startPulse(); else dialog._sliderDemoWidget->stopPulse(); // update window title std::ostringstream what; what << widget->name() << " - Oxygen-gtk Demo"; gtk_window_set_title( GTK_WINDOW( dialog._mainWidget ), what.str().c_str() ); } //_____________________________________________ void DemoDialog::toggleEnableState( GtkToggleButton* button, gpointer data ) { // get pointer to dialog DemoDialog& dialog( *static_cast<DemoDialog*>( data ) ); // store enable state const bool enabled( gtk_toggle_button_get_active( button ) ); // get current page const int page( gtk_notebook_get_current_page( GTK_NOTEBOOK( dialog._notebook ) ) ); // get matching page DemoWidget* widget( dialog._pages[page] ); // set state widget->setEnabled( enabled ); // trigger repaint gtk_widget_queue_draw( widget->mainWidget() ); } //_____________________________________________ void DemoDialog::toggleWidgetDirection( GtkToggleButton* button, gpointer data ) { gtk_widget_set_default_direction( gtk_toggle_button_get_active( button ) ? GTK_TEXT_DIR_RTL:GTK_TEXT_DIR_LTR ); } //_____________________________________________ gboolean DemoDialog::keyPress( GtkWidget* widget, GdkEventKey* event, gpointer ) { guint modifiers( gtk_accelerator_get_default_mod_mask() ); if( gdk_keyval_to_upper( event->keyval ) == GDK_KEY_Q && (event->state&modifiers) == GDK_CONTROL_MASK ) { gtk_main_quit(); return TRUE; } return FALSE; } } <|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 "base/command_line.h" #include "base/string16.h" #include "base/test/test_timeouts.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { class OptionsUITest : public UITest { public: OptionsUITest() { dom_automation_enabled_ = true; } void AssertIsOptionsPage(TabProxy* tab) { std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE); ASSERT_EQ(expected_title, WideToUTF16Hack(title)); } }; TEST_F(OptionsUITest, LoadOptionsByURL) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); // Go to the options tab via URL. NavigateToURL(GURL(chrome::kChromeUISettingsURL)); AssertIsOptionsPage(tab); } TEST_F(OptionsUITest, CommandOpensOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); } // TODO(csilv): Investigate why this fails and fix. http://crbug.com/48521 // Also, crashing on linux/views. #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_CommandAgainGoesBackToOptionsTab \ DISABLED_CommandAgainGoesBackToOptionsTab #else #define MAYBE_CommandAgainGoesBackToOptionsTab \ FLAKY_CommandAgainGoesBackToOptionsTab #endif TEST_F(OptionsUITest, MAYBE_CommandAgainGoesBackToOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); // Switch to first tab and run command again. ASSERT_TRUE(browser->ActivateTab(0)); ASSERT_TRUE(browser->WaitForTabToBecomeActive( 0, TestTimeouts::action_max_timeout_ms())); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); // Ensure the options ui tab is active. ASSERT_TRUE(browser->WaitForTabToBecomeActive( 1, TestTimeouts::action_max_timeout_ms())); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } // TODO(csilv): Investigate why this fails (sometimes) on 10.5 and fix. // http://crbug.com/48521. Also, crashing on linux/views. #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_TwoCommandsOneTab DISABLED_TwoCommandsOneTab #else #define MAYBE_TwoCommandsOneTab FLAKY_TwoCommandsOneTab #endif TEST_F(OptionsUITest, MAYBE_TwoCommandsOneTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } } // namespace <commit_msg>GTTF: disable flaky OptionsUITest tests that fail on automation timeouts<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 "base/command_line.h" #include "base/string16.h" #include "base/test/test_timeouts.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { class OptionsUITest : public UITest { public: OptionsUITest() { dom_automation_enabled_ = true; } void AssertIsOptionsPage(TabProxy* tab) { std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE); ASSERT_EQ(expected_title, WideToUTF16Hack(title)); } }; TEST_F(OptionsUITest, LoadOptionsByURL) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); // Go to the options tab via URL. NavigateToURL(GURL(chrome::kChromeUISettingsURL)); AssertIsOptionsPage(tab); } // Flaky, and takes very long to fail. http://crbug.com/64619. TEST_F(OptionsUITest, DISABLED_CommandOpensOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); } // Flaky, and takes very long to fail. http://crbug.com/48521 TEST_F(OptionsUITest, DISABLED_CommandAgainGoesBackToOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); // Switch to first tab and run command again. ASSERT_TRUE(browser->ActivateTab(0)); ASSERT_TRUE(browser->WaitForTabToBecomeActive( 0, TestTimeouts::action_max_timeout_ms())); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); // Ensure the options ui tab is active. ASSERT_TRUE(browser->WaitForTabToBecomeActive( 1, TestTimeouts::action_max_timeout_ms())); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } // Flaky, and takes very long to fail. http://crbug.com/48521 TEST_F(OptionsUITest, DISABLED_TwoCommandsOneTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } } // namespace <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include <shlobj.h> #include "chrome/browser/tab_contents/web_drop_target_win.h" #include "app/clipboard/clipboard_util_win.h" #include "app/os_exchange_data.h" #include "app/os_exchange_data_provider_win.h" #include "chrome/browser/bookmarks/bookmark_drag_data.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "gfx/point.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" #include "webkit/glue/webdropdata.h" #include "webkit/glue/window_open_disposition.h" using WebKit::WebDragOperationCopy; namespace { // A helper method for getting the preferred drop effect. DWORD GetPreferredDropEffect(DWORD effect) { if (effect & DROPEFFECT_COPY) return DROPEFFECT_COPY; if (effect & DROPEFFECT_LINK) return DROPEFFECT_LINK; if (effect & DROPEFFECT_MOVE) return DROPEFFECT_MOVE; return DROPEFFECT_NONE; } } // anonymous namespace // InterstitialDropTarget is like a BaseDropTarget implementation that // WebDropTarget passes through to if an interstitial is showing. Rather than // passing messages on to the renderer, we just check to see if there's a link // in the drop data and handle links as navigations. class InterstitialDropTarget { public: explicit InterstitialDropTarget(TabContents* tab_contents) : tab_contents_(tab_contents) {} DWORD OnDragEnter(IDataObject* data_object, DWORD effect) { return ClipboardUtil::HasUrl(data_object) ? GetPreferredDropEffect(effect) : DROPEFFECT_NONE; } DWORD OnDragOver(IDataObject* data_object, DWORD effect) { return ClipboardUtil::HasUrl(data_object) ? GetPreferredDropEffect(effect) : DROPEFFECT_NONE; } void OnDragLeave(IDataObject* data_object) { } DWORD OnDrop(IDataObject* data_object, DWORD effect) { if (ClipboardUtil::HasUrl(data_object)) { std::wstring url; std::wstring title; ClipboardUtil::GetUrl(data_object, &url, &title); tab_contents_->OpenURL(GURL(url), GURL(), CURRENT_TAB, PageTransition::AUTO_BOOKMARK); return GetPreferredDropEffect(effect); } return DROPEFFECT_NONE; } private: TabContents* tab_contents_; DISALLOW_EVIL_CONSTRUCTORS(InterstitialDropTarget); }; /////////////////////////////////////////////////////////////////////////////// // WebDropTarget, public: WebDropTarget::WebDropTarget(HWND source_hwnd, TabContents* tab_contents) : BaseDropTarget(source_hwnd), tab_contents_(tab_contents), current_rvh_(NULL), is_drop_target_(false), interstitial_drop_target_(new InterstitialDropTarget(tab_contents)) { } WebDropTarget::~WebDropTarget() { } DWORD WebDropTarget::OnDragEnter(IDataObject* data_object, DWORD key_state, POINT cursor_position, DWORD effect) { current_rvh_ = tab_contents_->render_view_host(); // Don't pass messages to the renderer if an interstitial page is showing // because we don't want the interstitial page to navigate. Instead, // pass the messages on to a separate interstitial DropTarget handler. if (tab_contents_->showing_interstitial_page()) return interstitial_drop_target_->OnDragEnter(data_object, effect); // TODO(tc): PopulateWebDropData can be slow depending on what is in the // IDataObject. Maybe we can do this in a background thread. WebDropData drop_data(GetDragIdentity()); WebDropData::PopulateWebDropData(data_object, &drop_data); if (drop_data.url.is_empty()) OSExchangeDataProviderWin::GetPlainTextURL(data_object, &drop_data.url); is_drop_target_ = true; POINT client_pt = cursor_position; ScreenToClient(GetHWND(), &client_pt); tab_contents_->render_view_host()->DragTargetDragEnter(drop_data, gfx::Point(client_pt.x, client_pt.y), gfx::Point(cursor_position.x, cursor_position.y), WebDragOperationCopy); // FIXME(snej): Send actual operation // This is non-null if tab_contents_ is showing an ExtensionDOMUI with // support for (at the moment experimental) drag and drop extensions. if (tab_contents_->GetBookmarkDragDelegate()) { OSExchangeData os_exchange_data(new OSExchangeDataProviderWin(data_object)); BookmarkDragData bookmark_drag_data; if (bookmark_drag_data.Read(os_exchange_data)) tab_contents_->GetBookmarkDragDelegate()->OnDragEnter(bookmark_drag_data); } // We lie here and always return a DROPEFFECT because we don't want to // wait for the IPC call to return. return GetPreferredDropEffect(effect); } DWORD WebDropTarget::OnDragOver(IDataObject* data_object, DWORD key_state, POINT cursor_position, DWORD effect) { DCHECK(current_rvh_); if (current_rvh_ != tab_contents_->render_view_host()) OnDragEnter(data_object, key_state, cursor_position, effect); if (tab_contents_->showing_interstitial_page()) return interstitial_drop_target_->OnDragOver(data_object, effect); POINT client_pt = cursor_position; ScreenToClient(GetHWND(), &client_pt); tab_contents_->render_view_host()->DragTargetDragOver( gfx::Point(client_pt.x, client_pt.y), gfx::Point(cursor_position.x, cursor_position.y), WebDragOperationCopy); // FIXME(snej): Send actual operation if (tab_contents_->GetBookmarkDragDelegate()) { OSExchangeData os_exchange_data(new OSExchangeDataProviderWin(data_object)); BookmarkDragData bookmark_drag_data; if (bookmark_drag_data.Read(os_exchange_data)) tab_contents_->GetBookmarkDragDelegate()->OnDragOver(bookmark_drag_data); } if (!is_drop_target_) return DROPEFFECT_NONE; return GetPreferredDropEffect(effect); } void WebDropTarget::OnDragLeave(IDataObject* data_object) { DCHECK(current_rvh_); if (current_rvh_ != tab_contents_->render_view_host()) return; if (tab_contents_->showing_interstitial_page()) { interstitial_drop_target_->OnDragLeave(data_object); } else { tab_contents_->render_view_host()->DragTargetDragLeave(); } if (tab_contents_->GetBookmarkDragDelegate()) { OSExchangeData os_exchange_data(new OSExchangeDataProviderWin(data_object)); BookmarkDragData bookmark_drag_data; if (bookmark_drag_data.Read(os_exchange_data)) tab_contents_->GetBookmarkDragDelegate()->OnDragLeave(bookmark_drag_data); } } DWORD WebDropTarget::OnDrop(IDataObject* data_object, DWORD key_state, POINT cursor_position, DWORD effect) { DCHECK(current_rvh_); if (current_rvh_ != tab_contents_->render_view_host()) OnDragEnter(data_object, key_state, cursor_position, effect); if (tab_contents_->showing_interstitial_page()) interstitial_drop_target_->OnDragOver(data_object, effect); if (tab_contents_->showing_interstitial_page()) return interstitial_drop_target_->OnDrop(data_object, effect); POINT client_pt = cursor_position; ScreenToClient(GetHWND(), &client_pt); tab_contents_->render_view_host()->DragTargetDrop( gfx::Point(client_pt.x, client_pt.y), gfx::Point(cursor_position.x, cursor_position.y)); if (tab_contents_->GetBookmarkDragDelegate()) { OSExchangeData os_exchange_data(new OSExchangeDataProviderWin(data_object)); BookmarkDragData bookmark_drag_data; if (bookmark_drag_data.Read(os_exchange_data)) tab_contents_->GetBookmarkDragDelegate()->OnDrop(bookmark_drag_data); } current_rvh_ = NULL; // We lie and always claim that the drop operation didn't happen because we // don't want to wait for the renderer to respond. return DROPEFFECT_NONE; } <commit_msg>Fix Issue 33145: Content Editable Move Image or Selected Block of Text Broken<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include <shlobj.h> #include "chrome/browser/tab_contents/web_drop_target_win.h" #include "app/clipboard/clipboard_util_win.h" #include "app/os_exchange_data.h" #include "app/os_exchange_data_provider_win.h" #include "chrome/browser/bookmarks/bookmark_drag_data.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "gfx/point.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" #include "webkit/glue/webdropdata.h" #include "webkit/glue/window_open_disposition.h" using WebKit::WebDragOperationCopy; using WebKit::WebDragOperationMove; using WebKit::WebDragOperationsMask; namespace { // A helper method for getting the preferred drop effect. DWORD GetPreferredDropEffect(DWORD effect) { if (effect & DROPEFFECT_COPY) return DROPEFFECT_COPY; if (effect & DROPEFFECT_LINK) return DROPEFFECT_LINK; if (effect & DROPEFFECT_MOVE) return DROPEFFECT_MOVE; return DROPEFFECT_NONE; } } // anonymous namespace // InterstitialDropTarget is like a BaseDropTarget implementation that // WebDropTarget passes through to if an interstitial is showing. Rather than // passing messages on to the renderer, we just check to see if there's a link // in the drop data and handle links as navigations. class InterstitialDropTarget { public: explicit InterstitialDropTarget(TabContents* tab_contents) : tab_contents_(tab_contents) {} DWORD OnDragEnter(IDataObject* data_object, DWORD effect) { return ClipboardUtil::HasUrl(data_object) ? GetPreferredDropEffect(effect) : DROPEFFECT_NONE; } DWORD OnDragOver(IDataObject* data_object, DWORD effect) { return ClipboardUtil::HasUrl(data_object) ? GetPreferredDropEffect(effect) : DROPEFFECT_NONE; } void OnDragLeave(IDataObject* data_object) { } DWORD OnDrop(IDataObject* data_object, DWORD effect) { if (ClipboardUtil::HasUrl(data_object)) { std::wstring url; std::wstring title; ClipboardUtil::GetUrl(data_object, &url, &title); tab_contents_->OpenURL(GURL(url), GURL(), CURRENT_TAB, PageTransition::AUTO_BOOKMARK); return GetPreferredDropEffect(effect); } return DROPEFFECT_NONE; } private: TabContents* tab_contents_; DISALLOW_EVIL_CONSTRUCTORS(InterstitialDropTarget); }; /////////////////////////////////////////////////////////////////////////////// // WebDropTarget, public: WebDropTarget::WebDropTarget(HWND source_hwnd, TabContents* tab_contents) : BaseDropTarget(source_hwnd), tab_contents_(tab_contents), current_rvh_(NULL), is_drop_target_(false), interstitial_drop_target_(new InterstitialDropTarget(tab_contents)) { } WebDropTarget::~WebDropTarget() { } DWORD WebDropTarget::OnDragEnter(IDataObject* data_object, DWORD key_state, POINT cursor_position, DWORD effect) { current_rvh_ = tab_contents_->render_view_host(); // Don't pass messages to the renderer if an interstitial page is showing // because we don't want the interstitial page to navigate. Instead, // pass the messages on to a separate interstitial DropTarget handler. if (tab_contents_->showing_interstitial_page()) return interstitial_drop_target_->OnDragEnter(data_object, effect); // TODO(tc): PopulateWebDropData can be slow depending on what is in the // IDataObject. Maybe we can do this in a background thread. WebDropData drop_data(GetDragIdentity()); WebDropData::PopulateWebDropData(data_object, &drop_data); if (drop_data.url.is_empty()) OSExchangeDataProviderWin::GetPlainTextURL(data_object, &drop_data.url); is_drop_target_ = true; POINT client_pt = cursor_position; ScreenToClient(GetHWND(), &client_pt); tab_contents_->render_view_host()->DragTargetDragEnter(drop_data, gfx::Point(client_pt.x, client_pt.y), gfx::Point(cursor_position.x, cursor_position.y), static_cast<WebDragOperationsMask>(WebDragOperationCopy | WebDragOperationMove)); // FIXME(snej): Send actual operation // This is non-null if tab_contents_ is showing an ExtensionDOMUI with // support for (at the moment experimental) drag and drop extensions. if (tab_contents_->GetBookmarkDragDelegate()) { OSExchangeData os_exchange_data(new OSExchangeDataProviderWin(data_object)); BookmarkDragData bookmark_drag_data; if (bookmark_drag_data.Read(os_exchange_data)) tab_contents_->GetBookmarkDragDelegate()->OnDragEnter(bookmark_drag_data); } // We lie here and always return a DROPEFFECT because we don't want to // wait for the IPC call to return. return GetPreferredDropEffect(effect); } DWORD WebDropTarget::OnDragOver(IDataObject* data_object, DWORD key_state, POINT cursor_position, DWORD effect) { DCHECK(current_rvh_); if (current_rvh_ != tab_contents_->render_view_host()) OnDragEnter(data_object, key_state, cursor_position, effect); if (tab_contents_->showing_interstitial_page()) return interstitial_drop_target_->OnDragOver(data_object, effect); POINT client_pt = cursor_position; ScreenToClient(GetHWND(), &client_pt); tab_contents_->render_view_host()->DragTargetDragOver( gfx::Point(client_pt.x, client_pt.y), gfx::Point(cursor_position.x, cursor_position.y), static_cast<WebDragOperationsMask>(WebDragOperationCopy | WebDragOperationMove)); // FIXME(snej): Send actual operation if (tab_contents_->GetBookmarkDragDelegate()) { OSExchangeData os_exchange_data(new OSExchangeDataProviderWin(data_object)); BookmarkDragData bookmark_drag_data; if (bookmark_drag_data.Read(os_exchange_data)) tab_contents_->GetBookmarkDragDelegate()->OnDragOver(bookmark_drag_data); } if (!is_drop_target_) return DROPEFFECT_NONE; return GetPreferredDropEffect(effect); } void WebDropTarget::OnDragLeave(IDataObject* data_object) { DCHECK(current_rvh_); if (current_rvh_ != tab_contents_->render_view_host()) return; if (tab_contents_->showing_interstitial_page()) { interstitial_drop_target_->OnDragLeave(data_object); } else { tab_contents_->render_view_host()->DragTargetDragLeave(); } if (tab_contents_->GetBookmarkDragDelegate()) { OSExchangeData os_exchange_data(new OSExchangeDataProviderWin(data_object)); BookmarkDragData bookmark_drag_data; if (bookmark_drag_data.Read(os_exchange_data)) tab_contents_->GetBookmarkDragDelegate()->OnDragLeave(bookmark_drag_data); } } DWORD WebDropTarget::OnDrop(IDataObject* data_object, DWORD key_state, POINT cursor_position, DWORD effect) { DCHECK(current_rvh_); if (current_rvh_ != tab_contents_->render_view_host()) OnDragEnter(data_object, key_state, cursor_position, effect); if (tab_contents_->showing_interstitial_page()) interstitial_drop_target_->OnDragOver(data_object, effect); if (tab_contents_->showing_interstitial_page()) return interstitial_drop_target_->OnDrop(data_object, effect); POINT client_pt = cursor_position; ScreenToClient(GetHWND(), &client_pt); tab_contents_->render_view_host()->DragTargetDrop( gfx::Point(client_pt.x, client_pt.y), gfx::Point(cursor_position.x, cursor_position.y)); if (tab_contents_->GetBookmarkDragDelegate()) { OSExchangeData os_exchange_data(new OSExchangeDataProviderWin(data_object)); BookmarkDragData bookmark_drag_data; if (bookmark_drag_data.Read(os_exchange_data)) tab_contents_->GetBookmarkDragDelegate()->OnDrop(bookmark_drag_data); } current_rvh_ = NULL; // We lie and always claim that the drop operation didn't happen because we // don't want to wait for the renderer to respond. return DROPEFFECT_NONE; } <|endoftext|>
<commit_before>#include "musicusermodel.h" #include <QCryptographicHash> #include <QtSql/QSqlRecord> MusicUserModel::MusicUserModel(QObject *parent,QSqlDatabase db) : QSqlTableModel(parent,db) { setTable("MusicUser"); setEditStrategy(QSqlTableModel::OnManualSubmit); select(); } bool MusicUserModel::addUser(const QString &uid, const QString &pwd, const QString &mail) { insertRow(0); setData(index(0,fieldIndex("USERID")),uid); setData(index(0,fieldIndex("PASSWD")),userPasswordEncryption(pwd)); setData(index(0,fieldIndex("EMAIL")),mail); setData(index(0,fieldIndex("USERNAME")),uid); setData(index(0,fieldIndex("LOGINTIME")),0); database().transaction(); if(submitAll()) { database().commit(); M_LOOGER << "submit successfully"; return true; } else { M_LOOGER << "submit failed"; database().rollback(); return false; } } bool MusicUserModel::databaseSelectedFilter(const QString &uid) { setTable("MusicUser"); setFilter(QString("USERID='%1'").arg(uid)); select(); return (rowCount() == 0); } bool MusicUserModel::updateUser(const QString &uid, const QString &pwd, const QString &mail,const QString &name, const QString &time) { if(databaseSelectedFilter(uid)) { return false; } if(!pwd.isEmpty()) setData(index(0,fieldIndex("PASSWD")),userPasswordEncryption(pwd)); if(!mail.isEmpty()) setData(index(0,fieldIndex("EMAIL")),mail); if(!name.isEmpty()) setData(index(0,fieldIndex("USERNAME")),name); if(!time.isEmpty()) setData(index(0,fieldIndex("LOGINTIME")),time); submitAll(); return true; } bool MusicUserModel::checkUser(const QString &uid, const QString &pwd) { if(databaseSelectedFilter(uid)) { return false; } return record(0).value("PASSWD") == userPasswordEncryption(pwd); } bool MusicUserModel::deleteUser(const QString &uid) { if(databaseSelectedFilter(uid)) { return false; } removeRow(0); return submitAll(); } bool MusicUserModel::mailCheck(const QString &uid, const QString &mail) { if(databaseSelectedFilter(uid)) { return false; } return record(0).value("EMAIL") == mail; } QStringList MusicUserModel::getAllUsers() const { QStringList users; for(int i=0; i<rowCount(); ++i) { users<<record(i).value("USERID").toString(); } return users; } QString MusicUserModel::getUserLogTime(const QString &uid) { if(databaseSelectedFilter(uid)) { return QString(); } return record(0).value("LOGINTIME").toString(); } QString MusicUserModel::getUserName(const QString &uid) { if(databaseSelectedFilter(uid)) { return QString(); } return record(0).value("USERNAME").toString(); } QString MusicUserModel::getUserPWDMD5(const QString &uid) { if(databaseSelectedFilter(uid)) { return QString(); } return record(0).value("PASSWD").toString(); } QString MusicUserModel::userPasswordEncryption(const QString &pwd) const { return QCryptographicHash::hash( pwd.toLatin1(), QCryptographicHash::Sha256).toHex(); } <commit_msg>clean code for musicusermodel[548872]<commit_after>#include "musicusermodel.h" #include <QCryptographicHash> #include <QtSql/QSqlRecord> MusicUserModel::MusicUserModel(QObject *parent,QSqlDatabase db) : QSqlTableModel(parent,db) { setTable("MusicUser"); setEditStrategy(QSqlTableModel::OnManualSubmit); select(); } bool MusicUserModel::addUser(const QString &uid, const QString &pwd, const QString &mail) { insertRow(0); setData(index(0, fieldIndex("USERID")), uid); setData(index(0, fieldIndex("PASSWD")), userPasswordEncryption(pwd)); setData(index(0, fieldIndex("EMAIL")), mail); setData(index(0, fieldIndex("USERNAME")), uid); setData(index(0, fieldIndex("LOGINTIME")), 0); database().transaction(); if(submitAll()) { database().commit(); M_LOOGER << "submit successfully"; return true; } else { M_LOOGER << "submit failed"; database().rollback(); return false; } } bool MusicUserModel::databaseSelectedFilter(const QString &uid) { setTable("MusicUser"); setFilter(QString("USERID='%1'").arg(uid)); select(); return (rowCount() == 0); } bool MusicUserModel::updateUser(const QString &uid, const QString &pwd, const QString &mail,const QString &name, const QString &time) { if(databaseSelectedFilter(uid)) { return false; } if(!pwd.isEmpty()) setData(index(0, fieldIndex("PASSWD")), userPasswordEncryption(pwd)); if(!mail.isEmpty()) setData(index(0, fieldIndex("EMAIL")), mail); if(!name.isEmpty()) setData(index(0, fieldIndex("USERNAME")), name); if(!time.isEmpty()) setData(index(0, fieldIndex("LOGINTIME")), time); submitAll(); return true; } bool MusicUserModel::checkUser(const QString &uid, const QString &pwd) { if(databaseSelectedFilter(uid)) { return false; } return record(0).value("PASSWD") == userPasswordEncryption(pwd); } bool MusicUserModel::deleteUser(const QString &uid) { if(databaseSelectedFilter(uid)) { return false; } removeRow(0); return submitAll(); } bool MusicUserModel::mailCheck(const QString &uid, const QString &mail) { if(databaseSelectedFilter(uid)) { return false; } return record(0).value("EMAIL") == mail; } QStringList MusicUserModel::getAllUsers() const { QStringList users; for(int i=0; i<rowCount(); ++i) { users<<record(i).value("USERID").toString(); } return users; } QString MusicUserModel::getUserLogTime(const QString &uid) { if(databaseSelectedFilter(uid)) { return QString(); } return record(0).value("LOGINTIME").toString(); } QString MusicUserModel::getUserName(const QString &uid) { if(databaseSelectedFilter(uid)) { return QString(); } return record(0).value("USERNAME").toString(); } QString MusicUserModel::getUserPWDMD5(const QString &uid) { if(databaseSelectedFilter(uid)) { return QString(); } return record(0).value("PASSWD").toString(); } QString MusicUserModel::userPasswordEncryption(const QString &pwd) const { return QCryptographicHash::hash( pwd.toLatin1(), QCryptographicHash::Sha256).toHex(); } <|endoftext|>
<commit_before>#include <cmath> #include <vector> #include "drake/systems/plants/collision/DrakeCollision.h" #include "drake/systems/plants/collision/Model.h" #include "gtest/gtest.h" using Eigen::Isometry3d; using Eigen::Vector3d; namespace DrakeCollision { namespace { /* * Three bodies (cube (1 m edges) and two spheres (0.5 m radii) arranged like *this * * ***** * ** ** * * 3 * --+-- * ** ** | * ***** | * | * ^ 2 m * y | | * | | * +---+---+ ***** | * | | | ** * | * | +---+----> * 2 * --+-- * | 1 | x ** ** * +-------+ ***** * | | * +------ 2 m ---------+ * | | * */ TEST(ModelTest, ClosestPointsAllToAll) { // Set up the geometry. Isometry3d T_body1_to_world, T_body2_to_world, T_body3_to_world, T_elem2_to_body; T_body1_to_world.setIdentity(); T_body2_to_world.setIdentity(); T_body3_to_world.setIdentity(); T_body2_to_world.translation() << 1, 0, 0; T_elem2_to_body.setIdentity(); T_elem2_to_body.translation() << 1, 0, 0; T_body3_to_world.translation() << 2, 2, 0; T_body3_to_world.matrix().block<2, 2>(0, 0) << 0, -1, 1, 0; // rotate 90 degrees in z DrakeShapes::Box geometry_1(Vector3d(1, 1, 1)); DrakeShapes::Sphere geometry_2(0.5); DrakeShapes::Sphere geometry_3(0.5); CollisionElement element_1(geometry_1); CollisionElement element_2(geometry_2, T_elem2_to_body); CollisionElement element_3(geometry_3); // Populate the model. std::shared_ptr<Model> model = newModel(); ElementId id1 = model->addElement(element_1); ElementId id2 = model->addElement(element_2); ElementId id3 = model->addElement(element_3); model->updateElementWorldTransform(id1, T_body1_to_world); model->updateElementWorldTransform(id2, T_body2_to_world); model->updateElementWorldTransform(id3, T_body3_to_world); // Compute the closest points. const std::vector<ElementId> ids_to_check = {id1, id2, id3}; std::vector<PointPair> points; model->closestPointsAllToAll(ids_to_check, true, points); ASSERT_EQ(3, points.size()); // Check the closest point between object 1 and object 2. // TODO(david-german-tri): Migrate this test to use Eigen matchers once // they are available. EXPECT_EQ(id1, points[0].getIdA()); EXPECT_EQ(id2, points[0].getIdB()); EXPECT_EQ(1.0, points[0].getDistance()); EXPECT_EQ(Vector3d(-1, 0, 0), points[0].getNormal()); EXPECT_TRUE((Vector3d(0.5, 0, 0) - points[0].getPtA()).isZero()); EXPECT_TRUE((Vector3d(0.5, 0, 0) - points[0].getPtB()).isZero()); // Check the closest point between object 1 and object 3. EXPECT_EQ(id1, points[1].getIdA()); EXPECT_EQ(id3, points[1].getIdB()); EXPECT_EQ(1.6213203435596428, points[1].getDistance()); EXPECT_EQ(Vector3d(-sqrt(2) / 2, -sqrt(2) / 2, 0), points[1].getNormal()); EXPECT_TRUE((Vector3d(0.5, 0.5, 0) - points[1].getPtA()).isZero()); EXPECT_TRUE( (Vector3d(-sqrt(2) / 4, sqrt(2) / 4, 0) - points[1].getPtB()).isZero()); // Check the closest point between object 2 and object 3. EXPECT_EQ(id2, points[2].getIdA()); EXPECT_EQ(id3, points[2].getIdB()); EXPECT_EQ(1.0, points[2].getDistance()); EXPECT_EQ(Vector3d(0, -1, 0), points[2].getNormal()); EXPECT_TRUE((Vector3d(1, 0.5, 0) - points[2].getPtA()).isZero()); EXPECT_TRUE((Vector3d(-0.5, 0, 0) - points[2].getPtB()).isZero()); } TEST(ModelTest, CollisionGroups) { CollisionElement element_1, element_2, element_3; // Add to a number of collision groups in random order element_1.add_to_collision_group(2); element_1.add_to_collision_group(23); element_1.add_to_collision_group(11); element_1.add_to_collision_group(15); element_1.add_to_collision_group(9); std::vector<int> element_1_set = std::vector<int>({2, 9, 11, 15, 23}); // Some additions might be repeated element_1.add_to_collision_group(11); element_1.add_to_collision_group(23); // Add element 2 to its own set of groups. element_2.add_to_collision_group(11); element_2.add_to_collision_group(9); element_2.add_to_collision_group(13); element_2.add_to_collision_group(13); element_2.add_to_collision_group(11); // Add element 3 to its own set of groups. element_3.add_to_collision_group(1); element_3.add_to_collision_group(13); element_3.add_to_collision_group(13); element_3.add_to_collision_group(8); element_3.add_to_collision_group(1); // Check the correctness of each element's collision groups set. EXPECT_EQ(std::vector<int>({2, 9, 11, 15, 23}), element_1.collision_groups()); EXPECT_EQ(std::vector<int>({9, 11, 13}), element_2.collision_groups()); EXPECT_EQ(std::vector<int>({1, 8, 13}), element_3.collision_groups()); // Groups cannot be repeated. Therefore expect 5 groups (instead of 7). ASSERT_EQ(5, element_1.number_of_groups()); // Groups cannot be repeated for element_2 either. ASSERT_EQ(3, element_2.number_of_groups()); // Groups cannot be repeated for element_3 either. ASSERT_EQ(3, element_3.number_of_groups()); // element_2 does not collide with element_1 (groups 9 and 11 in common). EXPECT_FALSE(element_2.CollidesWith(&element_1)); // element_2 does not collide with element_3 (group 13 in common). EXPECT_FALSE(element_2.CollidesWith(&element_3)); // element_3 does collide with element_1 (no groups in common) EXPECT_TRUE(element_3.CollidesWith(&element_1)); // element_3 does not collide with element_2 (group 13 in common) EXPECT_FALSE(element_3.CollidesWith(&element_2)); } } // namespace } // namespace DrakeCollision <commit_msg>Fixed comments in model_test.cc<commit_after>#include <cmath> #include <vector> #include "drake/systems/plants/collision/DrakeCollision.h" #include "drake/systems/plants/collision/Model.h" #include "gtest/gtest.h" using Eigen::Isometry3d; using Eigen::Vector3d; namespace DrakeCollision { namespace { /* * Three bodies (cube (1 m edges) and two spheres (0.5 m radii) arranged like *this * * ***** * ** ** * * 3 * --+-- * ** ** | * ***** | * | * ^ 2 m * y | | * | | * +---+---+ ***** | * | | | ** * | * | +---+----> * 2 * --+-- * | 1 | x ** ** * +-------+ ***** * | | * +------ 2 m ---------+ * | | * */ TEST(ModelTest, ClosestPointsAllToAll) { // Set up the geometry. Isometry3d T_body1_to_world, T_body2_to_world, T_body3_to_world, T_elem2_to_body; T_body1_to_world.setIdentity(); T_body2_to_world.setIdentity(); T_body3_to_world.setIdentity(); T_body2_to_world.translation() << 1, 0, 0; T_elem2_to_body.setIdentity(); T_elem2_to_body.translation() << 1, 0, 0; T_body3_to_world.translation() << 2, 2, 0; T_body3_to_world.matrix().block<2, 2>(0, 0) << 0, -1, 1, 0; // rotate 90 degrees in z DrakeShapes::Box geometry_1(Vector3d(1, 1, 1)); DrakeShapes::Sphere geometry_2(0.5); DrakeShapes::Sphere geometry_3(0.5); CollisionElement element_1(geometry_1); CollisionElement element_2(geometry_2, T_elem2_to_body); CollisionElement element_3(geometry_3); // Populate the model. std::shared_ptr<Model> model = newModel(); ElementId id1 = model->addElement(element_1); ElementId id2 = model->addElement(element_2); ElementId id3 = model->addElement(element_3); model->updateElementWorldTransform(id1, T_body1_to_world); model->updateElementWorldTransform(id2, T_body2_to_world); model->updateElementWorldTransform(id3, T_body3_to_world); // Compute the closest points. const std::vector<ElementId> ids_to_check = {id1, id2, id3}; std::vector<PointPair> points; model->closestPointsAllToAll(ids_to_check, true, points); ASSERT_EQ(3, points.size()); // Check the closest point between object 1 and object 2. // TODO(david-german-tri): Migrate this test to use Eigen matchers once // they are available. EXPECT_EQ(id1, points[0].getIdA()); EXPECT_EQ(id2, points[0].getIdB()); EXPECT_EQ(1.0, points[0].getDistance()); EXPECT_EQ(Vector3d(-1, 0, 0), points[0].getNormal()); EXPECT_TRUE((Vector3d(0.5, 0, 0) - points[0].getPtA()).isZero()); EXPECT_TRUE((Vector3d(0.5, 0, 0) - points[0].getPtB()).isZero()); // Check the closest point between object 1 and object 3. EXPECT_EQ(id1, points[1].getIdA()); EXPECT_EQ(id3, points[1].getIdB()); EXPECT_EQ(1.6213203435596428, points[1].getDistance()); EXPECT_EQ(Vector3d(-sqrt(2) / 2, -sqrt(2) / 2, 0), points[1].getNormal()); EXPECT_TRUE((Vector3d(0.5, 0.5, 0) - points[1].getPtA()).isZero()); EXPECT_TRUE( (Vector3d(-sqrt(2) / 4, sqrt(2) / 4, 0) - points[1].getPtB()).isZero()); // Check the closest point between object 2 and object 3. EXPECT_EQ(id2, points[2].getIdA()); EXPECT_EQ(id3, points[2].getIdB()); EXPECT_EQ(1.0, points[2].getDistance()); EXPECT_EQ(Vector3d(0, -1, 0), points[2].getNormal()); EXPECT_TRUE((Vector3d(1, 0.5, 0) - points[2].getPtA()).isZero()); EXPECT_TRUE((Vector3d(-0.5, 0, 0) - points[2].getPtB()).isZero()); } TEST(ModelTest, CollisionGroups) { CollisionElement element_1, element_2, element_3; // Add element 1 to its own set of groups. element_1.add_to_collision_group(2); element_1.add_to_collision_group(23); element_1.add_to_collision_group(11); element_1.add_to_collision_group(15); element_1.add_to_collision_group(9); std::vector<int> element_1_set = std::vector<int>({2, 9, 11, 15, 23}); // Tests the situation where the same collision groups are added to a // collision element multiple times. // If a collision element is added to a group it already belongs to, the // addition has no effect. This is tested by asserting the total number of // elements in the test below. element_1.add_to_collision_group(11); element_1.add_to_collision_group(23); // Add element 2 to its own set of groups. element_2.add_to_collision_group(11); element_2.add_to_collision_group(9); element_2.add_to_collision_group(13); element_2.add_to_collision_group(13); element_2.add_to_collision_group(11); // Add element 3 to its own set of groups. element_3.add_to_collision_group(1); element_3.add_to_collision_group(13); element_3.add_to_collision_group(13); element_3.add_to_collision_group(8); element_3.add_to_collision_group(1); // Check the correctness of each element's collision groups set. EXPECT_EQ(std::vector<int>({2, 9, 11, 15, 23}), element_1.collision_groups()); EXPECT_EQ(std::vector<int>({9, 11, 13}), element_2.collision_groups()); EXPECT_EQ(std::vector<int>({1, 8, 13}), element_3.collision_groups()); // Groups cannot be repeated. Therefore expect 5 groups instead of 7. ASSERT_EQ(5, element_1.number_of_groups()); // Groups cannot be repeated for element_2 either. ASSERT_EQ(3, element_2.number_of_groups()); // Groups cannot be repeated for element_3 either. ASSERT_EQ(3, element_3.number_of_groups()); // element_2 does not collide with element_1 (groups 9 and 11 in common). EXPECT_FALSE(element_2.CollidesWith(&element_1)); // element_2 does not collide with element_3 (group 13 in common). EXPECT_FALSE(element_2.CollidesWith(&element_3)); // element_3 does collide with element_1 (no groups in common). EXPECT_TRUE(element_3.CollidesWith(&element_1)); // element_3 does not collide with element_2 (group 13 in common). EXPECT_FALSE(element_3.CollidesWith(&element_2)); } } // namespace } // namespace DrakeCollision <|endoftext|>
<commit_before>#include <iostream> #include <gtest/gtest.h> #include "drake/systems/plants/RigidBodyTree.h" namespace drake { namespace systems { namespace plants { namespace test { namespace { class RigidBodyTreeTest : public ::testing::Test { protected: virtual void SetUp() { tree.reset(new RigidBodyTree()); // Defines four rigid bodies. r1b1 = new RigidBody(); r1b1->model_name_ = "robot1"; r1b1->name_ = "body1"; r2b1 = new RigidBody(); r2b1->model_name_ = "robot2"; r2b1->name_ = "body1"; r3b1 = new RigidBody(); r3b1->model_name_ = "robot3"; r3b1->name_ = "body1"; r4b1 = new RigidBody(); r4b1->model_name_ = "robot4"; r4b1->name_ = "body1"; } public: // TODO(amcastro-tri): A stack object here (preferable to a pointer) // generates build issues on Windows platforms. See git-hub issue #1854. std::unique_ptr<RigidBodyTree> tree; // TODO(amcastro-tri): these pointers will be replaced by Sherm's // unique_ptr_reference's. RigidBody* r1b1{}; RigidBody* r2b1{}; RigidBody* r3b1{}; RigidBody* r4b1{}; }; TEST_F(RigidBodyTreeTest, TestAddFloatingJointNoOffset) { // Adds rigid bodies r1b1 and r2b1 to the rigid body tree and verify they can // be found. // RigidBodyTree takes ownership of these bodies. // User still has access to these bodies through the raw pointers. tree->add_rigid_body(std::unique_ptr<RigidBody>(r1b1)); tree->add_rigid_body(std::unique_ptr<RigidBody>(r2b1)); EXPECT_TRUE(tree->FindBody("body1", "robot1") != nullptr); EXPECT_TRUE(tree->FindBody("body1", "robot2") != nullptr); EXPECT_THROW(tree->FindBody("body2", "robot1"), std::logic_error); EXPECT_THROW(tree->FindBody("body2", "robot2"), std::logic_error); // Adds floating joints that connect r1b1 and r2b1 to the rigid body tree's // world at zero offset. tree->AddFloatingJoint(DrakeJoint::QUATERNION, {r1b1->body_index, r2b1->body_index}); // Verfies that the two rigid bodies are located in the correct place. const DrakeJoint& jointR1B1 = tree->FindBody("body1", "robot1")->getJoint(); EXPECT_TRUE(jointR1B1.isFloating()); EXPECT_TRUE(jointR1B1.getTransformToParentBody().matrix() == Eigen::Isometry3d::Identity().matrix()); const DrakeJoint& jointR2B1 = tree->FindBody("body1", "robot2")->getJoint(); EXPECT_TRUE(jointR2B1.isFloating()); EXPECT_TRUE(jointR2B1.getTransformToParentBody().matrix() == Eigen::Isometry3d::Identity().matrix()); } TEST_F(RigidBodyTreeTest, TestAddFloatingJointWithOffset) { // TODO(amcastro-tri): these pointers will be replaced by Sherm's // unique_ptr_reference's tree->add_rigid_body(std::unique_ptr<RigidBody>(r1b1)); tree->add_rigid_body(std::unique_ptr<RigidBody>(r2b1)); // Adds floating joints that connect r1b1 and r2b1 to the rigid body tree's // world at offset x = 1, y = 1, z = 1. Eigen::Isometry3d T_r1and2_to_world; { Eigen::Vector3d xyz, rpy; xyz << 1, 1, 1; rpy = Eigen::Vector3d::Zero(); T_r1and2_to_world.matrix() << rpy2rotmat(rpy), xyz, 0, 0, 0, 1; } auto weld_to_frame = std::allocate_shared<RigidBodyFrame>( Eigen::aligned_allocator<RigidBodyFrame>(), "world", nullptr, T_r1and2_to_world); tree->AddFloatingJoint(DrakeJoint::QUATERNION, {r1b1->body_index, r2b1->body_index}, weld_to_frame); // Verfies that the two rigid bodies are located in the correct place. const DrakeJoint& jointR1B1 = tree->FindBody("body1", "robot1")->getJoint(); EXPECT_TRUE(jointR1B1.isFloating()); EXPECT_TRUE(jointR1B1.getTransformToParentBody().matrix() == T_r1and2_to_world.matrix()); const DrakeJoint& jointR2B1 = tree->FindBody("body1", "robot2")->getJoint(); EXPECT_TRUE(jointR2B1.isFloating()); EXPECT_TRUE(jointR2B1.getTransformToParentBody().matrix() == T_r1and2_to_world.matrix()); } TEST_F(RigidBodyTreeTest, TestAddFloatingJointWeldToLink) { // Adds rigid body r1b1 to the rigid body tree and welds it to the world with // zero offset. Verifies that it is in the correct place. // TODO(amcastro-tri): these pointers will be replaced by Sherm's // unique_ptr_reference's tree->add_rigid_body(std::unique_ptr<RigidBody>(r1b1)); tree->AddFloatingJoint(DrakeJoint::QUATERNION, {r1b1->body_index}); // Adds rigid body r2b1 to the rigid body tree and welds it to r1b1 with // offset x = 1, y = 1, z = 1. Verifies that it is in the correct place. // TODO(amcastro-tri): these pointers will be replaced by Sherm's // unique_ptr_reference's tree->add_rigid_body(std::unique_ptr<RigidBody>(r2b1)); Eigen::Isometry3d T_r2_to_r1; { Eigen::Vector3d xyz, rpy; xyz << 1, 1, 1; rpy = Eigen::Vector3d::Zero(); T_r2_to_r1.matrix() << rpy2rotmat(rpy), xyz, 0, 0, 0, 1; } auto r2b1_weld = std::allocate_shared<RigidBodyFrame>( Eigen::aligned_allocator<RigidBodyFrame>(), "body1", tree->FindBody("body1", "robot1"), T_r2_to_r1); tree->AddFloatingJoint(DrakeJoint::QUATERNION, {r2b1->body_index}, r2b1_weld); // Adds rigid body r3b1 and r4b1 to the rigid body tree and welds it to r2b1 // with offset x = 2, y = 2, z = 2. Verifies that it is in the correct place. // TODO(amcastro-tri): these pointers will be replaced by Sherm's // unique_ptr_reference's tree->add_rigid_body(std::unique_ptr<RigidBody>(r3b1)); tree->add_rigid_body(std::unique_ptr<RigidBody>(r4b1)); Eigen::Isometry3d T_r3_and_r4_to_r2; { Eigen::Vector3d xyz, rpy; xyz << 2, 2, 2; rpy = Eigen::Vector3d::Zero(); T_r3_and_r4_to_r2.matrix() << rpy2rotmat(rpy), xyz, 0, 0, 0, 1; } auto r3b1_and_r4b1_weld = std::allocate_shared<RigidBodyFrame>( Eigen::aligned_allocator<RigidBodyFrame>(), "body1", tree->FindBody("body1", "robot2"), T_r3_and_r4_to_r2); tree->AddFloatingJoint(DrakeJoint::QUATERNION, {r3b1->body_index, r4b1->body_index}, r3b1_and_r4b1_weld); EXPECT_TRUE(tree->FindBody("body1", "robot1") ->getJoint() .getTransformToParentBody() .matrix() == Eigen::Isometry3d::Identity().matrix()); EXPECT_TRUE(tree->FindBody("body1", "robot2") ->getJoint() .getTransformToParentBody() .matrix() == T_r2_to_r1.matrix()); EXPECT_TRUE(tree->FindBody("body1", "robot3") ->getJoint() .getTransformToParentBody() .matrix() == T_r3_and_r4_to_r2.matrix()); EXPECT_TRUE(tree->FindBody("body1", "robot4") ->getJoint() .getTransformToParentBody() .matrix() == T_r3_and_r4_to_r2.matrix()); } } // namespace } // namespace test } // namespace plants } // namespace systems } // namespace drake <commit_msg>Added unit test for deprecated methods RigidBodyTree::findLink and RigidBodyTree::findLinkId.<commit_after>#include <iostream> #include <gtest/gtest.h> #include "drake/systems/plants/RigidBodyTree.h" namespace drake { namespace systems { namespace plants { namespace test { namespace { class RigidBodyTreeTest : public ::testing::Test { protected: virtual void SetUp() { tree.reset(new RigidBodyTree()); // Defines four rigid bodies. r1b1 = new RigidBody(); r1b1->model_name_ = "robot1"; r1b1->name_ = "body1"; r2b1 = new RigidBody(); r2b1->model_name_ = "robot2"; r2b1->name_ = "body1"; r3b1 = new RigidBody(); r3b1->model_name_ = "robot3"; r3b1->name_ = "body1"; r4b1 = new RigidBody(); r4b1->model_name_ = "robot4"; r4b1->name_ = "body1"; } public: // TODO(amcastro-tri): A stack object here (preferable to a pointer) // generates build issues on Windows platforms. See git-hub issue #1854. std::unique_ptr<RigidBodyTree> tree; // TODO(amcastro-tri): these pointers will be replaced by Sherm's // unique_ptr_reference's. RigidBody* r1b1{}; RigidBody* r2b1{}; RigidBody* r3b1{}; RigidBody* r4b1{}; }; TEST_F(RigidBodyTreeTest, TestAddFloatingJointNoOffset) { // Adds rigid bodies r1b1 and r2b1 to the rigid body tree and verify they can // be found. // RigidBodyTree takes ownership of these bodies. // User still has access to these bodies through the raw pointers. tree->add_rigid_body(std::unique_ptr<RigidBody>(r1b1)); tree->add_rigid_body(std::unique_ptr<RigidBody>(r2b1)); EXPECT_TRUE(tree->FindBody("body1", "robot1") != nullptr); EXPECT_TRUE(tree->FindBody("body1", "robot2") != nullptr); EXPECT_THROW(tree->FindBody("body2", "robot1"), std::logic_error); EXPECT_THROW(tree->FindBody("body2", "robot2"), std::logic_error); // Adds floating joints that connect r1b1 and r2b1 to the rigid body tree's // world at zero offset. tree->AddFloatingJoint(DrakeJoint::QUATERNION, {r1b1->body_index, r2b1->body_index}); // Verfies that the two rigid bodies are located in the correct place. const DrakeJoint& jointR1B1 = tree->FindBody("body1", "robot1")->getJoint(); EXPECT_TRUE(jointR1B1.isFloating()); EXPECT_TRUE(jointR1B1.getTransformToParentBody().matrix() == Eigen::Isometry3d::Identity().matrix()); const DrakeJoint& jointR2B1 = tree->FindBody("body1", "robot2")->getJoint(); EXPECT_TRUE(jointR2B1.isFloating()); EXPECT_TRUE(jointR2B1.getTransformToParentBody().matrix() == Eigen::Isometry3d::Identity().matrix()); } TEST_F(RigidBodyTreeTest, TestAddFloatingJointWithOffset) { // TODO(amcastro-tri): these pointers will be replaced by Sherm's // unique_ptr_reference's tree->add_rigid_body(std::unique_ptr<RigidBody>(r1b1)); tree->add_rigid_body(std::unique_ptr<RigidBody>(r2b1)); // Adds floating joints that connect r1b1 and r2b1 to the rigid body tree's // world at offset x = 1, y = 1, z = 1. Eigen::Isometry3d T_r1and2_to_world; { Eigen::Vector3d xyz, rpy; xyz << 1, 1, 1; rpy = Eigen::Vector3d::Zero(); T_r1and2_to_world.matrix() << rpy2rotmat(rpy), xyz, 0, 0, 0, 1; } auto weld_to_frame = std::allocate_shared<RigidBodyFrame>( Eigen::aligned_allocator<RigidBodyFrame>(), "world", nullptr, T_r1and2_to_world); tree->AddFloatingJoint(DrakeJoint::QUATERNION, {r1b1->body_index, r2b1->body_index}, weld_to_frame); // Verfies that the two rigid bodies are located in the correct place. const DrakeJoint& jointR1B1 = tree->FindBody("body1", "robot1")->getJoint(); EXPECT_TRUE(jointR1B1.isFloating()); EXPECT_TRUE(jointR1B1.getTransformToParentBody().matrix() == T_r1and2_to_world.matrix()); const DrakeJoint& jointR2B1 = tree->FindBody("body1", "robot2")->getJoint(); EXPECT_TRUE(jointR2B1.isFloating()); EXPECT_TRUE(jointR2B1.getTransformToParentBody().matrix() == T_r1and2_to_world.matrix()); } TEST_F(RigidBodyTreeTest, TestAddFloatingJointWeldToLink) { // Adds rigid body r1b1 to the rigid body tree and welds it to the world with // zero offset. Verifies that it is in the correct place. // TODO(amcastro-tri): these pointers will be replaced by Sherm's // unique_ptr_reference's tree->add_rigid_body(std::unique_ptr<RigidBody>(r1b1)); tree->AddFloatingJoint(DrakeJoint::QUATERNION, {r1b1->body_index}); // Adds rigid body r2b1 to the rigid body tree and welds it to r1b1 with // offset x = 1, y = 1, z = 1. Verifies that it is in the correct place. // TODO(amcastro-tri): these pointers will be replaced by Sherm's // unique_ptr_reference's tree->add_rigid_body(std::unique_ptr<RigidBody>(r2b1)); Eigen::Isometry3d T_r2_to_r1; { Eigen::Vector3d xyz, rpy; xyz << 1, 1, 1; rpy = Eigen::Vector3d::Zero(); T_r2_to_r1.matrix() << rpy2rotmat(rpy), xyz, 0, 0, 0, 1; } auto r2b1_weld = std::allocate_shared<RigidBodyFrame>( Eigen::aligned_allocator<RigidBodyFrame>(), "body1", tree->FindBody("body1", "robot1"), T_r2_to_r1); tree->AddFloatingJoint(DrakeJoint::QUATERNION, {r2b1->body_index}, r2b1_weld); // Adds rigid body r3b1 and r4b1 to the rigid body tree and welds it to r2b1 // with offset x = 2, y = 2, z = 2. Verifies that it is in the correct place. // TODO(amcastro-tri): these pointers will be replaced by Sherm's // unique_ptr_reference's tree->add_rigid_body(std::unique_ptr<RigidBody>(r3b1)); tree->add_rigid_body(std::unique_ptr<RigidBody>(r4b1)); Eigen::Isometry3d T_r3_and_r4_to_r2; { Eigen::Vector3d xyz, rpy; xyz << 2, 2, 2; rpy = Eigen::Vector3d::Zero(); T_r3_and_r4_to_r2.matrix() << rpy2rotmat(rpy), xyz, 0, 0, 0, 1; } auto r3b1_and_r4b1_weld = std::allocate_shared<RigidBodyFrame>( Eigen::aligned_allocator<RigidBodyFrame>(), "body1", tree->FindBody("body1", "robot2"), T_r3_and_r4_to_r2); tree->AddFloatingJoint(DrakeJoint::QUATERNION, {r3b1->body_index, r4b1->body_index}, r3b1_and_r4b1_weld); EXPECT_TRUE(tree->FindBody("body1", "robot1") ->getJoint() .getTransformToParentBody() .matrix() == Eigen::Isometry3d::Identity().matrix()); EXPECT_TRUE(tree->FindBody("body1", "robot2") ->getJoint() .getTransformToParentBody() .matrix() == T_r2_to_r1.matrix()); EXPECT_TRUE(tree->FindBody("body1", "robot3") ->getJoint() .getTransformToParentBody() .matrix() == T_r3_and_r4_to_r2.matrix()); EXPECT_TRUE(tree->FindBody("body1", "robot4") ->getJoint() .getTransformToParentBody() .matrix() == T_r3_and_r4_to_r2.matrix()); } TEST_F(RigidBodyTreeTest, TestCallingDeprecatedMethods) { // Adds rigid bodies r1b1 and r2b1 to the rigid body tree. tree->add_rigid_body(std::unique_ptr<RigidBody>(r1b1)); tree->add_rigid_body(std::unique_ptr<RigidBody>(r2b1)); // Calls deprecated method findLink on it. EXPECT_NE(tree->findLink("body1", "robot1"), nullptr); EXPECT_NE(tree->findLinkId("body1"), -1); } } // namespace } // namespace test } // namespace plants } // namespace systems } // namespace drake <|endoftext|>
<commit_before>// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // This source code is also licensed under the GPLv2 license found in the // COPYING file in the root directory of this source tree. #ifndef ROCKSDB_LITE #include "utilities/blob_db/blob_dump_tool.h" #include <inttypes.h> #include <stdio.h> #include <iostream> #include <memory> #include <string> #include "port/port.h" #include "rocksdb/convenience.h" #include "rocksdb/env.h" #include "util/coding.h" #include "util/crc32c.h" #include "util/string_util.h" namespace rocksdb { namespace blob_db { BlobDumpTool::BlobDumpTool() : reader_(nullptr), buffer_(nullptr), buffer_size_(0) {} Status BlobDumpTool::Run(const std::string& filename, DisplayType show_key, DisplayType show_blob) { Status s; Env* env = Env::Default(); s = env->FileExists(filename); if (!s.ok()) { return s; } uint64_t file_size = 0; s = env->GetFileSize(filename, &file_size); if (!s.ok()) { return s; } std::unique_ptr<RandomAccessFile> file; s = env->NewRandomAccessFile(filename, &file, EnvOptions()); if (!s.ok()) { return s; } if (file_size == 0) { return Status::Corruption("File is empty."); } reader_.reset(new RandomAccessFileReader(std::move(file))); uint64_t offset = 0; uint64_t footer_offset = 0; s = DumpBlobLogHeader(&offset); if (!s.ok()) { return s; } s = DumpBlobLogFooter(file_size, &footer_offset); if (!s.ok()) { return s; } if (show_key != DisplayType::kNone) { while (offset < footer_offset) { s = DumpRecord(show_key, show_blob, &offset); if (!s.ok()) { return s; } } } return s; } Status BlobDumpTool::Read(uint64_t offset, size_t size, Slice* result) { if (buffer_size_ < size) { if (buffer_size_ == 0) { buffer_size_ = 4096; } while (buffer_size_ < size) { buffer_size_ *= 2; } buffer_.reset(new char[buffer_size_]); } Status s = reader_->Read(offset, size, result, buffer_.get()); if (!s.ok()) { return s; } if (result->size() != size) { return Status::Corruption("Reach the end of the file unexpectedly."); } return s; } Status BlobDumpTool::DumpBlobLogHeader(uint64_t* offset) { Slice slice; Status s = Read(0, BlobLogHeader::kHeaderSize, &slice); if (!s.ok()) { return s; } BlobLogHeader header; s = header.DecodeFrom(slice); if (!s.ok()) { return s; } fprintf(stdout, "Blob log header:\n"); fprintf(stdout, " Magic Number : %u\n", header.magic_number()); fprintf(stdout, " Version : %d\n", header.version()); CompressionType compression = header.compression(); std::string compression_str; if (!GetStringFromCompressionType(&compression_str, compression).ok()) { compression_str = "Unrecongnized compression type (" + ToString((int)header.compression()) + ")"; } fprintf(stdout, " Compression : %s\n", compression_str.c_str()); fprintf(stdout, " TTL Range : %s\n", GetString(header.ttl_range()).c_str()); fprintf(stdout, " Timestamp Range: %s\n", GetString(header.ts_range()).c_str()); *offset = BlobLogHeader::kHeaderSize; return s; } Status BlobDumpTool::DumpBlobLogFooter(uint64_t file_size, uint64_t* footer_offset) { auto no_footer = [&]() { *footer_offset = file_size; fprintf(stdout, "No blob log footer.\n"); return Status::OK(); }; if (file_size < BlobLogHeader::kHeaderSize + BlobLogFooter::kFooterSize) { return no_footer(); } Slice slice; Status s = Read(file_size - 4, 4, &slice); if (!s.ok()) { return s; } uint32_t magic_number = DecodeFixed32(slice.data()); if (magic_number != kMagicNumber) { return no_footer(); } *footer_offset = file_size - BlobLogFooter::kFooterSize; s = Read(*footer_offset, BlobLogFooter::kFooterSize, &slice); if (!s.ok()) { return s; } BlobLogFooter footer; s = footer.DecodeFrom(slice); if (!s.ok()) { return s; } fprintf(stdout, "Blob log footer:\n"); fprintf(stdout, " Blob count : %" PRIu64 "\n", footer.GetBlobCount()); fprintf(stdout, " TTL Range : %s\n", GetString(footer.GetTTLRange()).c_str()); fprintf(stdout, " Time Range : %s\n", GetString(footer.GetTimeRange()).c_str()); fprintf(stdout, " Sequence Range : %s\n", GetString(footer.GetSNRange()).c_str()); return s; } Status BlobDumpTool::DumpRecord(DisplayType show_key, DisplayType show_blob, uint64_t* offset) { fprintf(stdout, "Read record with offset 0x%" PRIx64 " (%" PRIu64 "):\n", *offset, *offset); Slice slice; Status s = Read(*offset, BlobLogRecord::kHeaderSize, &slice); if (!s.ok()) { return s; } BlobLogRecord record; s = record.DecodeHeaderFrom(slice); if (!s.ok()) { return s; } uint32_t key_size = record.GetKeySize(); uint64_t blob_size = record.GetBlobSize(); fprintf(stdout, " key size : %d\n", key_size); fprintf(stdout, " blob size : %" PRIu64 "\n", record.GetBlobSize()); fprintf(stdout, " TTL : %u\n", record.GetTTL()); fprintf(stdout, " time : %" PRIu64 "\n", record.GetTimeVal()); fprintf(stdout, " type : %d, %d\n", record.type(), record.subtype()); fprintf(stdout, " header CRC : %u\n", record.header_checksum()); fprintf(stdout, " CRC : %u\n", record.checksum()); uint32_t header_crc = crc32c::Extend(0, slice.data(), slice.size() - 2 * sizeof(uint32_t)); *offset += BlobLogRecord::kHeaderSize; s = Read(*offset, key_size + blob_size + BlobLogRecord::kFooterSize, &slice); if (!s.ok()) { return s; } header_crc = crc32c::Extend(header_crc, slice.data(), key_size); header_crc = crc32c::Mask(header_crc); if (header_crc != record.header_checksum()) { return Status::Corruption("Record header checksum mismatch."); } uint32_t blob_crc = crc32c::Extend(0, slice.data() + key_size, blob_size); blob_crc = crc32c::Mask(blob_crc); if (blob_crc != record.checksum()) { return Status::Corruption("Blob checksum mismatch."); } if (show_key != DisplayType::kNone) { fprintf(stdout, " key : "); DumpSlice(Slice(slice.data(), key_size), show_key); if (show_blob != DisplayType::kNone) { fprintf(stdout, " blob : "); DumpSlice(Slice(slice.data() + key_size, blob_size), show_blob); } } Slice footer_slice(slice.data() + record.GetKeySize() + record.GetBlobSize(), BlobLogRecord::kFooterSize); s = record.DecodeFooterFrom(footer_slice); if (!s.ok()) { return s; } fprintf(stdout, " footer CRC : %u\n", record.footer_checksum()); fprintf(stdout, " sequence : %" PRIu64 "\n", record.GetSN()); *offset += key_size + blob_size + BlobLogRecord::kFooterSize; return s; } void BlobDumpTool::DumpSlice(const Slice s, DisplayType type) { if (type == DisplayType::kRaw) { fprintf(stdout, "%s\n", s.ToString().c_str()); } else if (type == DisplayType::kHex) { fprintf(stdout, "%s\n", s.ToString(true /*hex*/).c_str()); } else if (type == DisplayType::kDetail) { char buf[100]; for (size_t i = 0; i < s.size(); i += 16) { memset(buf, 0, sizeof(buf)); for (size_t j = 0; j < 16 && i + j < s.size(); j++) { unsigned char c = s[i + j]; snprintf(buf + j * 3 + 15, 2, "%x", c >> 4); snprintf(buf + j * 3 + 16, 2, "%x", c & 0xf); snprintf(buf + j + 65, 2, "%c", (0x20 <= c && c <= 0x7e) ? c : '.'); } for (size_t p = 0; p < sizeof(buf) - 1; p++) { if (buf[p] == 0) { buf[p] = ' '; } } fprintf(stdout, "%s\n", i == 0 ? buf + 15 : buf); } } } template <class T> std::string BlobDumpTool::GetString(std::pair<T, T> p) { if (p.first == 0 && p.second == 0) { return "nil"; } return "(" + ToString(p.first) + ", " + ToString(p.second) + ")"; } } // namespace blob_db } // namespace rocksdb #endif // ROCKSDB_LITE <commit_msg>Fix build errors in blob_dump_tool with GCC 4.8<commit_after>// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // This source code is also licensed under the GPLv2 license found in the // COPYING file in the root directory of this source tree. #ifndef ROCKSDB_LITE #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include "utilities/blob_db/blob_dump_tool.h" #include <inttypes.h> #include <stdio.h> #include <iostream> #include <memory> #include <string> #include "port/port.h" #include "rocksdb/convenience.h" #include "rocksdb/env.h" #include "util/coding.h" #include "util/crc32c.h" #include "util/string_util.h" namespace rocksdb { namespace blob_db { BlobDumpTool::BlobDumpTool() : reader_(nullptr), buffer_(nullptr), buffer_size_(0) {} Status BlobDumpTool::Run(const std::string& filename, DisplayType show_key, DisplayType show_blob) { Status s; Env* env = Env::Default(); s = env->FileExists(filename); if (!s.ok()) { return s; } uint64_t file_size = 0; s = env->GetFileSize(filename, &file_size); if (!s.ok()) { return s; } std::unique_ptr<RandomAccessFile> file; s = env->NewRandomAccessFile(filename, &file, EnvOptions()); if (!s.ok()) { return s; } if (file_size == 0) { return Status::Corruption("File is empty."); } reader_.reset(new RandomAccessFileReader(std::move(file))); uint64_t offset = 0; uint64_t footer_offset = 0; s = DumpBlobLogHeader(&offset); if (!s.ok()) { return s; } s = DumpBlobLogFooter(file_size, &footer_offset); if (!s.ok()) { return s; } if (show_key != DisplayType::kNone) { while (offset < footer_offset) { s = DumpRecord(show_key, show_blob, &offset); if (!s.ok()) { return s; } } } return s; } Status BlobDumpTool::Read(uint64_t offset, size_t size, Slice* result) { if (buffer_size_ < size) { if (buffer_size_ == 0) { buffer_size_ = 4096; } while (buffer_size_ < size) { buffer_size_ *= 2; } buffer_.reset(new char[buffer_size_]); } Status s = reader_->Read(offset, size, result, buffer_.get()); if (!s.ok()) { return s; } if (result->size() != size) { return Status::Corruption("Reach the end of the file unexpectedly."); } return s; } Status BlobDumpTool::DumpBlobLogHeader(uint64_t* offset) { Slice slice; Status s = Read(0, BlobLogHeader::kHeaderSize, &slice); if (!s.ok()) { return s; } BlobLogHeader header; s = header.DecodeFrom(slice); if (!s.ok()) { return s; } fprintf(stdout, "Blob log header:\n"); fprintf(stdout, " Magic Number : %u\n", header.magic_number()); fprintf(stdout, " Version : %d\n", header.version()); CompressionType compression = header.compression(); std::string compression_str; if (!GetStringFromCompressionType(&compression_str, compression).ok()) { compression_str = "Unrecongnized compression type (" + ToString((int)header.compression()) + ")"; } fprintf(stdout, " Compression : %s\n", compression_str.c_str()); fprintf(stdout, " TTL Range : %s\n", GetString(header.ttl_range()).c_str()); fprintf(stdout, " Timestamp Range: %s\n", GetString(header.ts_range()).c_str()); *offset = BlobLogHeader::kHeaderSize; return s; } Status BlobDumpTool::DumpBlobLogFooter(uint64_t file_size, uint64_t* footer_offset) { auto no_footer = [&]() { *footer_offset = file_size; fprintf(stdout, "No blob log footer.\n"); return Status::OK(); }; if (file_size < BlobLogHeader::kHeaderSize + BlobLogFooter::kFooterSize) { return no_footer(); } Slice slice; Status s = Read(file_size - 4, 4, &slice); if (!s.ok()) { return s; } uint32_t magic_number = DecodeFixed32(slice.data()); if (magic_number != kMagicNumber) { return no_footer(); } *footer_offset = file_size - BlobLogFooter::kFooterSize; s = Read(*footer_offset, BlobLogFooter::kFooterSize, &slice); if (!s.ok()) { return s; } BlobLogFooter footer; s = footer.DecodeFrom(slice); if (!s.ok()) { return s; } fprintf(stdout, "Blob log footer:\n"); fprintf(stdout, " Blob count : %" PRIu64 "\n", footer.GetBlobCount()); fprintf(stdout, " TTL Range : %s\n", GetString(footer.GetTTLRange()).c_str()); fprintf(stdout, " Time Range : %s\n", GetString(footer.GetTimeRange()).c_str()); fprintf(stdout, " Sequence Range : %s\n", GetString(footer.GetSNRange()).c_str()); return s; } Status BlobDumpTool::DumpRecord(DisplayType show_key, DisplayType show_blob, uint64_t* offset) { fprintf(stdout, "Read record with offset 0x%" PRIx64 " (%" PRIu64 "):\n", *offset, *offset); Slice slice; Status s = Read(*offset, BlobLogRecord::kHeaderSize, &slice); if (!s.ok()) { return s; } BlobLogRecord record; s = record.DecodeHeaderFrom(slice); if (!s.ok()) { return s; } uint32_t key_size = record.GetKeySize(); uint64_t blob_size = record.GetBlobSize(); fprintf(stdout, " key size : %d\n", key_size); fprintf(stdout, " blob size : %" PRIu64 "\n", record.GetBlobSize()); fprintf(stdout, " TTL : %u\n", record.GetTTL()); fprintf(stdout, " time : %" PRIu64 "\n", record.GetTimeVal()); fprintf(stdout, " type : %d, %d\n", record.type(), record.subtype()); fprintf(stdout, " header CRC : %u\n", record.header_checksum()); fprintf(stdout, " CRC : %u\n", record.checksum()); uint32_t header_crc = crc32c::Extend(0, slice.data(), slice.size() - 2 * sizeof(uint32_t)); *offset += BlobLogRecord::kHeaderSize; s = Read(*offset, key_size + blob_size + BlobLogRecord::kFooterSize, &slice); if (!s.ok()) { return s; } header_crc = crc32c::Extend(header_crc, slice.data(), key_size); header_crc = crc32c::Mask(header_crc); if (header_crc != record.header_checksum()) { return Status::Corruption("Record header checksum mismatch."); } uint32_t blob_crc = crc32c::Extend(0, slice.data() + key_size, blob_size); blob_crc = crc32c::Mask(blob_crc); if (blob_crc != record.checksum()) { return Status::Corruption("Blob checksum mismatch."); } if (show_key != DisplayType::kNone) { fprintf(stdout, " key : "); DumpSlice(Slice(slice.data(), key_size), show_key); if (show_blob != DisplayType::kNone) { fprintf(stdout, " blob : "); DumpSlice(Slice(slice.data() + key_size, blob_size), show_blob); } } Slice footer_slice(slice.data() + record.GetKeySize() + record.GetBlobSize(), BlobLogRecord::kFooterSize); s = record.DecodeFooterFrom(footer_slice); if (!s.ok()) { return s; } fprintf(stdout, " footer CRC : %u\n", record.footer_checksum()); fprintf(stdout, " sequence : %" PRIu64 "\n", record.GetSN()); *offset += key_size + blob_size + BlobLogRecord::kFooterSize; return s; } void BlobDumpTool::DumpSlice(const Slice s, DisplayType type) { if (type == DisplayType::kRaw) { fprintf(stdout, "%s\n", s.ToString().c_str()); } else if (type == DisplayType::kHex) { fprintf(stdout, "%s\n", s.ToString(true /*hex*/).c_str()); } else if (type == DisplayType::kDetail) { char buf[100]; for (size_t i = 0; i < s.size(); i += 16) { memset(buf, 0, sizeof(buf)); for (size_t j = 0; j < 16 && i + j < s.size(); j++) { unsigned char c = s[i + j]; snprintf(buf + j * 3 + 15, 2, "%x", c >> 4); snprintf(buf + j * 3 + 16, 2, "%x", c & 0xf); snprintf(buf + j + 65, 2, "%c", (0x20 <= c && c <= 0x7e) ? c : '.'); } for (size_t p = 0; p < sizeof(buf) - 1; p++) { if (buf[p] == 0) { buf[p] = ' '; } } fprintf(stdout, "%s\n", i == 0 ? buf + 15 : buf); } } } template <class T> std::string BlobDumpTool::GetString(std::pair<T, T> p) { if (p.first == 0 && p.second == 0) { return "nil"; } return "(" + ToString(p.first) + ", " + ToString(p.second) + ")"; } } // namespace blob_db } // namespace rocksdb #endif // ROCKSDB_LITE <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <math.h> #include <sstream> #include <string> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <SOIL/SOIL.h> #include "shader.h" using namespace std; // Window constants to keep viewport size consistent. const GLuint kWindowWidth = 800; const GLuint kWindowHeight = 600; GLuint loadTexture(string filepath); // Callbacks void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mode); int main() { // Initialize GLFW and set some hints that will create an OpenGL 3.3 context // using core profile. glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create a fixed 800x600 window that is not resizable. GLFWwindow* window = glfwCreateWindow(kWindowWidth, kWindowHeight, "LearnGL", nullptr, nullptr); if (window == nullptr) { cerr << "Failed to created GLFW window" << endl; glfwTerminate(); return 1; } // Create an OpenGL context and pass callbacks to GLFW. glfwMakeContextCurrent(window); glfwSetKeyCallback(window, keyCallback); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { cerr << "Failed to initialize GLEW" << endl; glfwTerminate(); return 1; } // Create a viewport the same size as the window. glViewport(0, 0, kWindowWidth, kWindowHeight); // Read and compile the vertex and fragment shaders using // the shader helper class. Shader shader("glsl/vertex.glsl", "glsl/fragment.glsl"); // Load the textures for the magic square. GLuint texture1 = loadTexture("assets/container.jpg"); GLuint texture2 = loadTexture("assets/awesomeface.png"); // Square vertex data. GLfloat vertices[] = { // Positions // Colors // Texture Coords 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // Top Right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Bottom Right -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Left -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // Top Left }; // Indices for the square. GLuint indices[] = { 0, 1, 3, // First triangle 1, 2, 3 // Second triangle }; // Create a VBO to store the vertex data, an EBO to store indice data, and // create a VAO to retain our vertex attribute pointers. GLuint VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // Bind the VAO for the square first, set the vertex buffers, // then the attribute pointers. glBindVertexArray(VAO); // Fill up the VBO and EBO for the square while the VAO for the square is // currently bound (see above). glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // Set the vertex attributes. // p = position, c = color, t = texture coordinate // format: pppccctt glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(2); // Unbind the VBO and VAO to get a clean state. DO NOT unbind the EBO or the // VAO will no longer be able to access it (I have no idea why). glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // Render loop. while (!glfwWindowShouldClose(window)) { // Check and call events. glfwPollEvents(); // Clear the screen to a nice blue color. glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Activate the shader program for this square. shader.use(); // Bind textures for the square to mix. glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glUniform1i(glGetUniformLocation(shader.program, "texture1"), 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); glUniform1i(glGetUniformLocation(shader.program, "texture2"), 1); // Draw the square! glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindVertexArray(0); // Swap buffers used for double buffering. glfwSwapBuffers(window); } // Properly deallocate the VBO and VAO. glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); // Terminate GLFW and clean any resources before exiting. glfwTerminate(); return 0; } GLuint loadTexture(string filepath) { // Generate the texture on the OpenGL side and bind it. GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); // Set some parameters for the bound texture. Use GL_LINEAR to get a gaussian // blur like effect on upscaled textures. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Load in the container texture using the soil library. int width, height; unsigned char* image = SOIL_load_image(filepath.c_str(), &width, &height, 0, SOIL_LOAD_RGB); // Load the image data to the currently bound texture. Also create some // mipmaps for it for perf. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); // Free the image and unbind the texture. SOIL_free_image_data(image); glBindTexture(GL_TEXTURE_2D, 0); return texture; } void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mode) { // Close the application when escape is pressed. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } } <commit_msg>Use framebuffer size as arguments to viewport size<commit_after>#include <fstream> #include <iostream> #include <math.h> #include <sstream> #include <string> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <SOIL/SOIL.h> #include "shader.h" using namespace std; // Window constants to keep viewport size consistent. const GLuint kWindowWidth = 800; const GLuint kWindowHeight = 600; GLuint loadTexture(string filepath); // Callbacks void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mode); int main() { // Initialize GLFW and set some hints that will create an OpenGL 3.3 context // using core profile. glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create a fixed 800x600 window that is not resizable. GLFWwindow* window = glfwCreateWindow(kWindowWidth, kWindowHeight, "LearnGL", nullptr, nullptr); if (window == nullptr) { cerr << "Failed to created GLFW window" << endl; glfwTerminate(); return 1; } // Create an OpenGL context and pass callbacks to GLFW. glfwMakeContextCurrent(window); glfwSetKeyCallback(window, keyCallback); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { cerr << "Failed to initialize GLEW" << endl; glfwTerminate(); return 1; } // Create a viewport the same size as the window. glfwGetFramebufferSize is // used rather than the size constants since some windowing systems have a // discrepancy between window size and framebuffer size // (e.g HiDPi screen coordinates), int fbWidth, fbHeight; glfwGetFramebufferSize(window, &fbWidth, &fbHeight); glViewport(0, 0, fbWidth, fbHeight); // Read and compile the vertex and fragment shaders using // the shader helper class. Shader shader("glsl/vertex.glsl", "glsl/fragment.glsl"); // Load the textures for the magic square. GLuint texture1 = loadTexture("assets/container.jpg"); GLuint texture2 = loadTexture("assets/awesomeface.png"); // Square vertex data. GLfloat vertices[] = { // Positions // Colors // Texture Coords 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // Top Right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Bottom Right -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Left -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // Top Left }; // Indices for the square. GLuint indices[] = { 0, 1, 3, // First triangle 1, 2, 3 // Second triangle }; // Create a VBO to store the vertex data, an EBO to store indice data, and // create a VAO to retain our vertex attribute pointers. GLuint VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); // Bind the VAO for the square first, set the vertex buffers, // then the attribute pointers. glBindVertexArray(VAO); // Fill up the VBO and EBO for the square while the VAO for the square is // currently bound (see above). glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // Set the vertex attributes. // p = position, c = color, t = texture coordinate // format: pppccctt glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(2); // Unbind the VBO and VAO to get a clean state. DO NOT unbind the EBO or the // VAO will no longer be able to access it (I have no idea why). glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // Render loop. while (!glfwWindowShouldClose(window)) { // Check and call events. glfwPollEvents(); // Clear the screen to a nice blue color. glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Activate the shader program for this square. shader.use(); // Bind textures for the square to mix. glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glUniform1i(glGetUniformLocation(shader.program, "texture1"), 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); glUniform1i(glGetUniformLocation(shader.program, "texture2"), 1); // Draw the square! glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindVertexArray(0); // Swap buffers used for double buffering. glfwSwapBuffers(window); } // Properly deallocate the VBO and VAO. glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); // Terminate GLFW and clean any resources before exiting. glfwTerminate(); return 0; } GLuint loadTexture(string filepath) { // Generate the texture on the OpenGL side and bind it. GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); // Set some parameters for the bound texture. Use GL_LINEAR to get a gaussian // blur like effect on upscaled textures. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Load in the container texture using the soil library. int width, height; unsigned char* image = SOIL_load_image(filepath.c_str(), &width, &height, 0, SOIL_LOAD_RGB); // Load the image data to the currently bound texture. Also create some // mipmaps for it for perf. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); // Free the image and unbind the texture. SOIL_free_image_data(image); glBindTexture(GL_TEXTURE_2D, 0); return texture; } void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mode) { // Close the application when escape is pressed. if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GL_TRUE); } } <|endoftext|>
<commit_before>#include "StableRand.h" #include <QDebug> StableRand::StableRand(double exponent, double skewness, double scale, double location) : U(-M_PI_2, M_PI_2), N(0, M_SQRT2) { setParameters(exponent, skewness, scale, location); } void StableRand::setParameters(double exponent, double skewness, double scale, double location) { alpha = std::min(exponent, 2.0); alpha = std::max(alpha, MIN_POSITIVE); alphaInv = 1.0 / alpha; alpha_alpham1 = alpha / (alpha - 1.0); alpham1Inv = alpha_alpham1 - 1.0; beta = std::min(skewness, 1.0); beta = std::max(beta, -1.0); sigma = std::max(scale, MIN_POSITIVE); mu = location; /// Should be cautious, known distributions in priority if (std::fabs(alpha - 2) < MIN_POSITIVE) alpha = 2; else if (std::fabs(alpha - 1) < MIN_POSITIVE) alpha = 1; else if (std::fabs(alpha - .5) < MIN_POSITIVE) alpha = .5; if (std::fabs(beta) < MIN_POSITIVE) beta = 0; else if (std::fabs(beta - 1) < MIN_POSITIVE) beta = 1; else if (std::fabs(beta + 1) < MIN_POSITIVE) beta = -1; if (alpha == 2) /// X ~ Normal(mu, 2sigma^2) { N.setMean(mu); N.setSigma(sigma * M_SQRT2); valuePtr = std::bind(&StableRand::valueNormal, this); pdfPtr = std::bind(&StableRand::pdfNormal, this, std::placeholders::_1); cdfPtr = std::bind(&StableRand::cdfNormal, this, std::placeholders::_1); } else if (alpha == 1) { if (beta == 0) /// X ~ Cauchy(mu, sigma) { C.setLocation(mu); C.setScale(sigma); valuePtr = std::bind(&StableRand::valueCauchy, this); pdfPtr = std::bind(&StableRand::pdfCauchy, this, std::placeholders::_1); cdfPtr = std::bind(&StableRand::cdfCauchy, this, std::placeholders::_1); } else /// just alpha == 1 { logSigma = std::log(sigma); pdfCoef = 0.5 / beta; valuePtr = std::bind(&StableRand::valueForAlphaEqualOne, this); pdfPtr = std::bind(&StableRand::pdfForAlphaEqualOne, this, std::placeholders::_1); cdfPtr = std::bind(&StableRand::cdfForAlphaEqualOne, this, std::placeholders::_1); } } else if (alpha == .5 && beta == 1) /// X ~ Levy(mu, sigma) { L.setLocation(mu); L.setScale(sigma); valuePtr = std::bind(&StableRand::valueLevy, this); pdfPtr = std::bind(&StableRand::pdfLevy, this, std::placeholders::_1); cdfPtr = std::bind(&StableRand::cdfLevy, this, std::placeholders::_1); } else if (alpha == .5 && beta == -1) /// -X ~ Levy(mu, sigma) { L.setLocation(mu); L.setScale(sigma); valuePtr = std::bind(&StableRand::valueLevyNegative, this); pdfPtr = std::bind(&StableRand::pdfLevyNegative, this, std::placeholders::_1); cdfPtr = std::bind(&StableRand::cdfLevyNegative, this, std::placeholders::_1); } else /// Common case: alpha != 1 { B = beta * std::tan(M_PI_2 * alpha); zeta = -B; S = std::pow(1 + B * B, .5 * alphaInv); B = std::atan(B); pdfCoef = M_1_PI * alpha / (std::fabs(1 - alpha) * sigma); xi = alphaInv * B; integrandCoef = std::pow(qFastCos(B), alpham1Inv); valuePtr = std::bind(&StableRand::valueForCommonAlpha, this); pdfPtr = std::bind(&StableRand::pdfForCommonAlpha, this, std::placeholders::_1); cdfPtr = std::bind(&StableRand::cdfForCommonAlpha, this, std::placeholders::_1); } } double StableRand::value() { /// Get standard value double rv = 0; int iter = 0; do { rv = valuePtr(); ++iter; } while ((std::isnan(rv) || std::isinf(rv)) && iter < 10); /// if we got nan 10 times - we have a problem, get out return rv; } double StableRand::valueForCommonAlpha() { double V = U.value(); double W = E.value(); double alphaVB = alpha * V + B; double rv = S * qFastSin(alphaVB); /// S * sin(alpha * V + B) double W_adj = W / qFastCos(V - alphaVB); rv *= W_adj; /// S * sin(alpha * V + B) * W / cos((1 - alpha) * V - B) rv *= std::pow(W_adj * qFastCos(V), -alphaInv);/// S * sin(alpha * V + B) * W / cos((1 - alpha) * V - B) / /// ((W * cos(V) / cos((1 - alpha) * V - B)) ^ (1 / alpha)) return mu + sigma * rv; } double StableRand::valueForAlphaEqualOne() { double V = U.value(); double W = E.value(); double pi_2BetaV = M_PI_2 + beta * V; double rv = logSigma; rv -= std::log(M_PI_2 * W * qFastCos(V) / pi_2BetaV); rv *= beta; rv += pi_2BetaV * std::tan(V); rv *= M_2_PI; return mu + sigma * rv; } double StableRand::f(double x) const { return pdfPtr(x); } double StableRand::pdfForCommonAlpha(double x) { x = (x - mu) / sigma; /// Standardize if (std::fabs(x) < 0.1) /// if we are close to 0 then we do interpolation avoiding dangerous values { double numen = std::tgamma(1 + alphaInv); numen *= qFastCos(xi); double denom = sigma * std::pow(1 + zeta * zeta, .5 * alphaInv); double y0 = M_1_PI * numen / denom; /// f(0) double b = (x > 0) ? 0.11 : -0.11; double y1 = pdfForCommonAlpha(mu + sigma * b); return RandMath::linearInterpolation(0, b, y0, y1, x); } double xiAdj = xi; /// +- xi if (x > 0) { if (alpha < 1 && beta == -1) return 0; } else { if (alpha < 1 && beta == 1) return 0; x = -x; xiAdj = -xi; } double xAdj = std::pow(x, alpha_alpham1); /// find peak of integrand integrandPtr = std::bind(&StableRand::rootFunctionForCommonAlpha, this, std::placeholders::_1, xAdj, xiAdj); double theta0 = M_PI_4 - .5 * xiAdj; RandMath::findRoot(integrandPtr, -xiAdj, std::max(-xiAdj, 0.99 * M_PI_2), theta0); /// calculate two integrals integrandPtr = std::bind(&StableRand::integrandForCommonAlpha, this, std::placeholders::_1, xAdj, xiAdj); double int1 = RandMath::integral(integrandPtr, -xiAdj, theta0); double int2 = RandMath::integral(integrandPtr, theta0, M_PI_2); return pdfCoef * (int1 + int2) / x; } double StableRand::pdfForAlphaEqualOne(double x) { x = (x - mu) / sigma - M_2_PI * beta * logSigma; /// Standardize double xAdj = std::exp(-M_PI * x * pdfCoef); /// find peak of integrand integrandPtr = std::bind(&StableRand::rootFunctionForAlphaEqualOne, this, std::placeholders::_1, xAdj); double theta0 = 0; if (beta > 0) RandMath::findRoot(integrandPtr, -M_PI_2, 0.99 * M_PI_2, theta0); else RandMath::findRoot(integrandPtr, -0.99 * M_PI_2, M_PI_2, theta0); integrandPtr = std::bind(&StableRand::integrandForAlphaEqualOne, this, std::placeholders::_1, xAdj); double int1 = RandMath::integral(integrandPtr, -M_PI_2, theta0); double int2 = RandMath::integral(integrandPtr, theta0, M_PI_2); return std::fabs(pdfCoef) * (int1 + int2) / sigma; } double StableRand::integrandAuxForAlphaEqualOne(double theta, double xAdj) const { double cosTheta = qFastCos(theta); /// if theta ~ +-pi / 2 if (std::fabs(cosTheta) < MIN_POSITIVE) return 0.0; double thetaAdj = (M_PI_2 + beta * theta) / cosTheta; double u = M_2_PI * thetaAdj; u *= std::exp(thetaAdj * qFastSin(theta) / beta); return u * xAdj; } double StableRand::integrandForAlphaEqualOne(double theta, double xAdj) const { double u = integrandAuxForAlphaEqualOne(theta, xAdj); return u * std::exp(-u); } double StableRand::integrandAuxForCommonAlpha(double theta, double xAdj, double xiAdj) const { double thetaAdj = alpha * (theta + xiAdj); double sinThetaAdj = qFastSin(thetaAdj); /// if theta ~ 0 if (std::fabs(sinThetaAdj) < MIN_POSITIVE) return 0.0; double cosTheta = qFastCos(theta); double y = cosTheta / sinThetaAdj; /// if theta ~ pi / 2 if (std::fabs(y) < MIN_POSITIVE) return 0.0; y = std::pow(y, alpha_alpham1); y *= qFastCos(thetaAdj - theta); y /= cosTheta; return integrandCoef * xAdj * y; } double StableRand::integrandForCommonAlpha(double theta, double xAdj, double xiAdj) const { double u = integrandAuxForCommonAlpha(theta, xAdj, xiAdj); return u * std::exp(-u); } double StableRand::F(double x) const { return cdfPtr(x); } <commit_msg>pashacommit<commit_after>#include "StableRand.h" #include <QDebug> StableRand::StableRand(double exponent, double skewness, double scale, double location) : U(-M_PI_2, M_PI_2), N(0, M_SQRT2) { setParameters(exponent, skewness, scale, location); } void StableRand::setParameters(double exponent, double skewness, double scale, double location) { alpha = std::min(exponent, 2.0); alpha = std::max(alpha, MIN_POSITIVE); alphaInv = 1.0 / alpha; alpha_alpham1 = alpha / (alpha - 1.0); alpham1Inv = alpha_alpham1 - 1.0; beta = std::min(skewness, 1.0); beta = std::max(beta, -1.0); sigma = std::max(scale, MIN_POSITIVE); mu = location; /// Should be cautious, known distributions in priority if (std::fabs(alpha - 2) < MIN_POSITIVE) alpha = 2; else if (std::fabs(alpha - 1) < MIN_POSITIVE) alpha = 1; else if (std::fabs(alpha - .5) < MIN_POSITIVE) alpha = .5; if (std::fabs(beta) < MIN_POSITIVE) beta = 0; else if (std::fabs(beta - 1) < MIN_POSITIVE) beta = 1; else if (std::fabs(beta + 1) < MIN_POSITIVE) beta = -1; if (alpha == 2) /// X ~ Normal(mu, 2sigma^2) { N.setMean(mu); N.setSigma(sigma * M_SQRT2); valuePtr = std::bind(&StableRand::valueNormal, this); pdfPtr = std::bind(&StableRand::pdfNormal, this, std::placeholders::_1); cdfPtr = std::bind(&StableRand::cdfNormal, this, std::placeholders::_1); } else if (alpha == 1) { if (beta == 0) /// X ~ Cauchy(mu, sigma) { C.setLocation(mu); C.setScale(sigma); valuePtr = std::bind(&StableRand::valueCauchy, this); pdfPtr = std::bind(&StableRand::pdfCauchy, this, std::placeholders::_1); cdfPtr = std::bind(&StableRand::cdfCauchy, this, std::placeholders::_1); } else /// just alpha == 1 { logSigma = std::log(sigma); pdfCoef = 0.5 / beta; valuePtr = std::bind(&StableRand::valueForAlphaEqualOne, this); pdfPtr = std::bind(&StableRand::pdfForAlphaEqualOne, this, std::placeholders::_1); cdfPtr = std::bind(&StableRand::cdfForAlphaEqualOne, this, std::placeholders::_1); } } else if (alpha == .5 && beta == 1) /// X ~ Levy(mu, sigma) { L.setLocation(mu); L.setScale(sigma); valuePtr = std::bind(&StableRand::valueLevy, this); pdfPtr = std::bind(&StableRand::pdfLevy, this, std::placeholders::_1); cdfPtr = std::bind(&StableRand::cdfLevy, this, std::placeholders::_1); } else if (alpha == .5 && beta == -1) /// -X ~ Levy(mu, sigma) { L.setLocation(mu); L.setScale(sigma); valuePtr = std::bind(&StableRand::valueLevyNegative, this); pdfPtr = std::bind(&StableRand::pdfLevyNegative, this, std::placeholders::_1); cdfPtr = std::bind(&StableRand::cdfLevyNegative, this, std::placeholders::_1); } else /// Common case: alpha != 1 { B = beta * std::tan(M_PI_2 * alpha); zeta = -B; S = std::pow(1 + B * B, .5 * alphaInv); B = std::atan(B); pdfCoef = M_1_PI * alpha / (std::fabs(1 - alpha) * sigma); xi = alphaInv * B; integrandCoef = std::pow(qFastCos(B), alpham1Inv); valuePtr = std::bind(&StableRand::valueForCommonAlpha, this); pdfPtr = std::bind(&StableRand::pdfForCommonAlpha, this, std::placeholders::_1); cdfPtr = std::bind(&StableRand::cdfForCommonAlpha, this, std::placeholders::_1); } } double StableRand::value() { /// Get standard value double rv = 0; int iter = 0; do { rv = valuePtr(); ++iter; } while ((std::isnan(rv) || std::isinf(rv)) && iter < 10); /// if we got nan 10 times - we have a problem, get out return rv; } double StableRand::valueForCommonAlpha() { double V = U.value(); double W = E.value(); double alphaVB = alpha * V + B; double rv = S * qFastSin(alphaVB); /// S * sin(alpha * V + B) double W_adj = W / qFastCos(V - alphaVB); rv *= W_adj; /// S * sin(alpha * V + B) * W / cos((1 - alpha) * V - B) rv *= std::pow(W_adj * qFastCos(V), -alphaInv);/// S * sin(alpha * V + B) * W / cos((1 - alpha) * V - B) / /// ((W * cos(V) / cos((1 - alpha) * V - B)) ^ (1 / alpha)) return mu + sigma * rv; } double StableRand::valueForAlphaEqualOne() { double V = U.value(); double W = E.value(); double pi_2BetaV = M_PI_2 + beta * V; double rv = logSigma; rv -= std::log(M_PI_2 * W * qFastCos(V) / pi_2BetaV); rv *= beta; rv += pi_2BetaV * std::tan(V); rv *= M_2_PI; return mu + sigma * rv; } double StableRand::f(double x) const { return pdfPtr(x); } double StableRand::pdfForCommonAlpha(double x) { x = (x - mu) / sigma; /// Standardize if (std::fabs(x) < 0.1) /// if we are close to 0 then we do interpolation avoiding dangerous values { double numen = std::tgamma(1 + alphaInv); numen *= qFastCos(xi); double denom = sigma * std::pow(1 + zeta * zeta, .5 * alphaInv); double y0 = M_1_PI * numen / denom; /// f(0) if (std::fabs(x) < 1e-6) return y0; double b = (x > 0) ? 0.11 : -0.11; double y1 = pdfForCommonAlpha(mu + sigma * b); return RandMath::linearInterpolation(0, b, y0, y1, x); } double xiAdj = xi; /// +- xi if (x > 0) { if (alpha < 1 && beta == -1) return 0; } else { if (alpha < 1 && beta == 1) return 0; x = -x; xiAdj = -xi; } double xAdj = std::pow(x, alpha_alpham1); /// find peak of integrand integrandPtr = std::bind(&StableRand::rootFunctionForCommonAlpha, this, std::placeholders::_1, xAdj, xiAdj); double theta0 = M_PI_4 - .5 * xiAdj; RandMath::findRoot(integrandPtr, -xiAdj, std::max(-xiAdj, 0.99 * M_PI_2), theta0); /// calculate two integrals integrandPtr = std::bind(&StableRand::integrandForCommonAlpha, this, std::placeholders::_1, xAdj, xiAdj); double int1 = RandMath::integral(integrandPtr, -xiAdj, theta0); double int2 = RandMath::integral(integrandPtr, theta0, M_PI_2); return pdfCoef * (int1 + int2) / x; } double StableRand::pdfForAlphaEqualOne(double x) { x = (x - mu) / sigma - M_2_PI * beta * logSigma; /// Standardize double xAdj = std::exp(-M_PI * x * pdfCoef); /// find peak of integrand integrandPtr = std::bind(&StableRand::rootFunctionForAlphaEqualOne, this, std::placeholders::_1, xAdj); double theta0 = 0; if (beta > 0) RandMath::findRoot(integrandPtr, -M_PI_2, 0.99 * M_PI_2, theta0); else RandMath::findRoot(integrandPtr, -0.99 * M_PI_2, M_PI_2, theta0); integrandPtr = std::bind(&StableRand::integrandForAlphaEqualOne, this, std::placeholders::_1, xAdj); double int1 = RandMath::integral(integrandPtr, -M_PI_2, theta0); double int2 = RandMath::integral(integrandPtr, theta0, M_PI_2); return std::fabs(pdfCoef) * (int1 + int2) / sigma; } double StableRand::integrandAuxForAlphaEqualOne(double theta, double xAdj) const { double cosTheta = qFastCos(theta); /// if theta ~ +-pi / 2 if (std::fabs(cosTheta) < MIN_POSITIVE) return 0.0; double thetaAdj = (M_PI_2 + beta * theta) / cosTheta; double u = M_2_PI * thetaAdj; u *= std::exp(thetaAdj * qFastSin(theta) / beta); return u * xAdj; } double StableRand::integrandForAlphaEqualOne(double theta, double xAdj) const { double u = integrandAuxForAlphaEqualOne(theta, xAdj); return u * std::exp(-u); } double StableRand::integrandAuxForCommonAlpha(double theta, double xAdj, double xiAdj) const { double thetaAdj = alpha * (theta + xiAdj); double sinThetaAdj = qFastSin(thetaAdj); /// if theta ~ 0 if (std::fabs(sinThetaAdj) < MIN_POSITIVE) return 0.0; double cosTheta = qFastCos(theta); double y = cosTheta / sinThetaAdj; /// if theta ~ pi / 2 if (std::fabs(y) < MIN_POSITIVE) return 0.0; y = std::pow(y, alpha_alpham1); y *= qFastCos(thetaAdj - theta); y /= cosTheta; return integrandCoef * xAdj * y; } double StableRand::integrandForCommonAlpha(double theta, double xAdj, double xiAdj) const { double u = integrandAuxForCommonAlpha(theta, xAdj, xiAdj); return u * std::exp(-u); } double StableRand::F(double x) const { return cdfPtr(x); } <|endoftext|>
<commit_before>#include "include/trikControl/mailbox.h" #include "src/mailboxServer.h" #include <QtCore/QEventLoop> using namespace trikControl; Mailbox::Mailbox(int port) : mWorker(new MailboxServer(port)) { QObject::connect(mWorker.data(), SIGNAL(newMessage(int, QString)), this, SIGNAL(newMessage(int, QString))); QObject::connect(mWorker.data(), SIGNAL(newMessage(int, QString)), this, SIGNAL(stopWaiting())); mWorker->moveToThread(&mWorkerThread); mWorkerThread.start(); } Mailbox::~Mailbox() { mWorkerThread.quit(); mWorkerThread.wait(); } void Mailbox::setHullNumber(int hullNumber) { QMetaObject::invokeMethod(mWorker.data(), "setHullNumber", Q_ARG(int, hullNumber)); } int Mailbox::myHullNumber() const { return mWorker->hullNumber(); } QHostAddress Mailbox::serverIp() const { return mWorker->serverIp(); } QHostAddress Mailbox::myIp() const { return mWorker->myIp(); } void Mailbox::connect(QString const &ip, int port) { QMetaObject::invokeMethod(mWorker.data(), "connect", Q_ARG(QString const &, ip), Q_ARG(int, port)); } void Mailbox::connect(QString const &ip) { QMetaObject::invokeMethod(mWorker.data(), "connect", Q_ARG(QString const &, ip)); } void Mailbox::send(int hullNumber, QString const &message) { QMetaObject::invokeMethod(mWorker.data(), "send", Q_ARG(int, hullNumber), Q_ARG(QString const &, message)); } void Mailbox::send(QString const &message) { QMetaObject::invokeMethod(mWorker.data(), "send", Q_ARG(QString const &, message)); } bool Mailbox::hasMessages() { return mWorker->hasMessages(); } QString Mailbox::receive() { QString result; QEventLoop loop; QObject::connect(this, SIGNAL(stopWaiting()), &loop, SLOT(quit())); loop.exec(); if (mWorker->hasMessages()) { result = mWorker->receive(); } return result; } <commit_msg>check for messages before waiting<commit_after>#include "include/trikControl/mailbox.h" #include "src/mailboxServer.h" #include <QtCore/QEventLoop> using namespace trikControl; Mailbox::Mailbox(int port) : mWorker(new MailboxServer(port)) { QObject::connect(mWorker.data(), SIGNAL(newMessage(int, QString)), this, SIGNAL(newMessage(int, QString))); QObject::connect(mWorker.data(), SIGNAL(newMessage(int, QString)), this, SIGNAL(stopWaiting())); mWorker->moveToThread(&mWorkerThread); mWorkerThread.start(); } Mailbox::~Mailbox() { mWorkerThread.quit(); mWorkerThread.wait(); } void Mailbox::setHullNumber(int hullNumber) { QMetaObject::invokeMethod(mWorker.data(), "setHullNumber", Q_ARG(int, hullNumber)); } int Mailbox::myHullNumber() const { return mWorker->hullNumber(); } QHostAddress Mailbox::serverIp() const { return mWorker->serverIp(); } QHostAddress Mailbox::myIp() const { return mWorker->myIp(); } void Mailbox::connect(QString const &ip, int port) { QMetaObject::invokeMethod(mWorker.data(), "connect", Q_ARG(QString const &, ip), Q_ARG(int, port)); } void Mailbox::connect(QString const &ip) { QMetaObject::invokeMethod(mWorker.data(), "connect", Q_ARG(QString const &, ip)); } void Mailbox::send(int hullNumber, QString const &message) { QMetaObject::invokeMethod(mWorker.data(), "send", Q_ARG(int, hullNumber), Q_ARG(QString const &, message)); } void Mailbox::send(QString const &message) { QMetaObject::invokeMethod(mWorker.data(), "send", Q_ARG(QString const &, message)); } bool Mailbox::hasMessages() { return mWorker->hasMessages(); } QString Mailbox::receive() { QString result; QEventLoop loop; QObject::connect(this, SIGNAL(stopWaiting()), &loop, SLOT(quit())); if (!mWorker->hasMessages()) { loop.exec(); } if (mWorker->hasMessages()) { result = mWorker->receive(); } return result; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Nokia Corporation and its Subsidiary(-ies) 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." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtDeclarative/QDeclarativeExtensionPlugin> #include <QtDeclarative/qdeclarative.h> #include <qapplication.h> #include "model.h" class QStockChartExampleQmlPlugin : public QDeclarativeExtensionPlugin { Q_OBJECT public: void registerTypes(const char *uri) { Q_ASSERT(uri == QLatin1String("com.nokia.StockChartExample")); qmlRegisterType<StockModel>(uri, 1, 0, "StockModel"); qmlRegisterType<StockPrice>(uri, 1, 0, "StockPrice"); } }; #include "plugin.moc" Q_EXPORT_PLUGIN2(qmlstockchartexampleplugin, QStockChartExampleQmlPlugin); <commit_msg>Fix build error for canvas stockchart example.<commit_after>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Nokia Corporation and its Subsidiary(-ies) 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." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtDeclarative/QDeclarativeExtensionPlugin> #include <QtDeclarative/qdeclarative.h> #include <QtGui/QGuiApplication> #include "model.h" class QStockChartExampleQmlPlugin : public QDeclarativeExtensionPlugin { Q_OBJECT public: void registerTypes(const char *uri) { Q_ASSERT(uri == QLatin1String("com.nokia.StockChartExample")); qmlRegisterType<StockModel>(uri, 1, 0, "StockModel"); qmlRegisterType<StockPrice>(uri, 1, 0, "StockPrice"); } }; #include "plugin.moc" Q_EXPORT_PLUGIN2(qmlstockchartexampleplugin, QStockChartExampleQmlPlugin); <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: admininvokationpage.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2003-03-25 16:00:47 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef EXTENSIONS_ABP_ADMINDIALOG_INVOKATION_PAGE_HXX #define EXTENSIONS_ABP_ADMINDIALOG_INVOKATION_PAGE_HXX #ifndef EXTENSIONS_ABP_ABSPAGE_HXX #include "abspage.hxx" #endif //......................................................................... namespace abp { //......................................................................... //===================================================================== //= AdminDialogInvokationPage //===================================================================== class AdminDialogInvokationPage : public AddressBookSourcePage { protected: FixedText m_aExplanation; PushButton m_aInvokeAdminDialog; FixedText m_aErrorMessage; sal_Bool m_bSuccessfullyExecutedDialog; public: AdminDialogInvokationPage( OAddessBookSourcePilot* _pParent ); protected: // TabDialog overridables virtual void ActivatePage(); virtual sal_Bool commitPage(COMMIT_REASON _eReason); virtual void initializePage(); // OImportPage overridables virtual sal_Bool determineNextButtonState(); private: DECL_LINK( OnInvokeAdminDialog, void* ); void implTryConnect(); void implUpdateErrorMessage(); }; //......................................................................... } // namespace abp //......................................................................... #endif // EXTENSIONS_ABP_ADMINDIALOG_INVOKATION_PAGE_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.3.504); FILE MERGED 2005/09/05 12:58:31 rt 1.3.504.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: admininvokationpage.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:06:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef EXTENSIONS_ABP_ADMINDIALOG_INVOKATION_PAGE_HXX #define EXTENSIONS_ABP_ADMINDIALOG_INVOKATION_PAGE_HXX #ifndef EXTENSIONS_ABP_ABSPAGE_HXX #include "abspage.hxx" #endif //......................................................................... namespace abp { //......................................................................... //===================================================================== //= AdminDialogInvokationPage //===================================================================== class AdminDialogInvokationPage : public AddressBookSourcePage { protected: FixedText m_aExplanation; PushButton m_aInvokeAdminDialog; FixedText m_aErrorMessage; sal_Bool m_bSuccessfullyExecutedDialog; public: AdminDialogInvokationPage( OAddessBookSourcePilot* _pParent ); protected: // TabDialog overridables virtual void ActivatePage(); virtual sal_Bool commitPage(COMMIT_REASON _eReason); virtual void initializePage(); // OImportPage overridables virtual sal_Bool determineNextButtonState(); private: DECL_LINK( OnInvokeAdminDialog, void* ); void implTryConnect(); void implUpdateErrorMessage(); }; //......................................................................... } // namespace abp //......................................................................... #endif // EXTENSIONS_ABP_ADMINDIALOG_INVOKATION_PAGE_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: selectlabeldialog.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2007-04-26 08:08:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_extensions.hxx" #ifndef _EXTENSIONS_PROPCTRLR_SELECTLABELDIALOG_HXX_ #include "selectlabeldialog.hxx" #endif #ifndef _EXTENSIONS_PROPCTRLR_FORMRESID_HRC_ #include "formresid.hrc" #endif #ifndef _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_ #include "formbrowsertools.hxx" #endif #ifndef _EXTENSIONS_FORMSCTRLR_FORMSTRINGS_HXX_ #include "formstrings.hxx" #endif #ifndef _COM_SUN_STAR_FORM_FORMCOMPONENTTYPE_HPP_ #include <com/sun/star/form/FormComponentType.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_ #include <com/sun/star/container/XChild.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif //............................................................................ namespace pcr { //............................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::form; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; //======================================================================== // OSelectLabelDialog //======================================================================== DBG_NAME(OSelectLabelDialog) //------------------------------------------------------------------------ OSelectLabelDialog::OSelectLabelDialog( Window* pParent, Reference< XPropertySet > _xControlModel ) :ModalDialog(pParent, PcrRes(RID_DLG_SELECTLABELCONTROL)) ,m_aMainDesc(this, PcrRes(1)) ,m_aControlTree(this, PcrRes(1)) ,m_aNoAssignment(this, PcrRes(1)) ,m_aSeparator(this, PcrRes(1)) ,m_aOk(this, PcrRes(1)) ,m_aCancel(this, PcrRes(1)) ,m_aModelImages(PcrRes(RID_IL_FORMEXPLORER)) ,m_xControlModel(_xControlModel) ,m_pInitialSelection(NULL) ,m_pLastSelected(NULL) ,m_bHaveAssignableControl(sal_False) { DBG_CTOR(OSelectLabelDialog,NULL); // initialize the TreeListBox m_aControlTree.SetSelectionMode( SINGLE_SELECTION ); m_aControlTree.SetDragDropMode( 0 ); m_aControlTree.EnableInplaceEditing( sal_False ); m_aControlTree.SetWindowBits(WB_BORDER | WB_HASLINES | WB_HASLINESATROOT | WB_HASBUTTONS | WB_HASBUTTONSATROOT | WB_HSCROLL); m_aControlTree.SetNodeBitmaps( m_aModelImages.GetImage( RID_SVXIMG_COLLAPSEDNODE ), m_aModelImages.GetImage( RID_SVXIMG_EXPANDEDNODE ) ); m_aControlTree.SetSelectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); m_aControlTree.SetDeselectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); // fill the description UniString sDescription = m_aMainDesc.GetText(); sal_Int16 nClassID = FormComponentType::CONTROL; if (::comphelper::hasProperty(PROPERTY_CLASSID, m_xControlModel)) nClassID = ::comphelper::getINT16(m_xControlModel->getPropertyValue(PROPERTY_CLASSID)); sDescription.SearchAndReplace(String::CreateFromAscii("$control_class$"), GetUIHeadlineName(nClassID, makeAny(m_xControlModel))); UniString sName = ::comphelper::getString(m_xControlModel->getPropertyValue(PROPERTY_NAME)).getStr(); sDescription.SearchAndReplace(String::CreateFromAscii("$control_name$"), sName); m_aMainDesc.SetText(sDescription); // search for the root of the form hierarchy Reference< XChild > xCont(m_xControlModel, UNO_QUERY); Reference< XInterface > xSearch( xCont.is() ? xCont->getParent() : Reference< XInterface > ()); Reference< XResultSet > xParentAsResultSet(xSearch, UNO_QUERY); while (xParentAsResultSet.is()) { xCont = Reference< XChild > (xSearch, UNO_QUERY); xSearch = xCont.is() ? xCont->getParent() : Reference< XInterface > (); xParentAsResultSet = Reference< XResultSet > (xSearch, UNO_QUERY); } // and insert all entries below this root into the listbox if (xSearch.is()) { // check wich service the allowed components must suppport sal_Int16 nClassId = 0; try { nClassId = ::comphelper::getINT16(m_xControlModel->getPropertyValue(PROPERTY_CLASSID)); } catch(...) { } m_sRequiredService = (FormComponentType::RADIOBUTTON == nClassId) ? SERVICE_COMPONENT_GROUPBOX : SERVICE_COMPONENT_FIXEDTEXT; m_aRequiredControlImage = m_aModelImages.GetImage((FormComponentType::RADIOBUTTON == nClassId) ? RID_SVXIMG_GROUPBOX : RID_SVXIMG_FIXEDTEXT); // calc the currently set label control (so InsertEntries can calc m_pInitialSelection) Any aCurrentLabelControl( m_xControlModel->getPropertyValue(PROPERTY_CONTROLLABEL) ); DBG_ASSERT((aCurrentLabelControl.getValueTypeClass() == TypeClass_INTERFACE) || !aCurrentLabelControl.hasValue(), "OSelectLabelDialog::OSelectLabelDialog : invalid ControlLabel property !"); if (aCurrentLabelControl.hasValue()) aCurrentLabelControl >>= m_xInitialLabelControl; // insert the root Image aRootImage = m_aModelImages.GetImage(RID_SVXIMG_FORMS); SvLBoxEntry* pRoot = m_aControlTree.InsertEntry(PcrRes(RID_STR_FORMS), aRootImage, aRootImage); // build the tree m_pInitialSelection = NULL; m_bHaveAssignableControl = sal_False; InsertEntries(xSearch, pRoot); m_aControlTree.Expand(pRoot); } if (m_pInitialSelection) { m_aControlTree.MakeVisible(m_pInitialSelection, sal_True); m_aControlTree.Select(m_pInitialSelection, sal_True); } else { m_aControlTree.MakeVisible(m_aControlTree.First(), sal_True); if (m_aControlTree.FirstSelected()) m_aControlTree.Select(m_aControlTree.FirstSelected(), sal_False); m_aNoAssignment.Check(sal_True); } if (!m_bHaveAssignableControl) { // no controls which can be assigned m_aNoAssignment.Check(sal_True); m_aNoAssignment.Enable(sal_False); } m_aNoAssignment.SetClickHdl(LINK(this, OSelectLabelDialog, OnNoAssignmentClicked)); m_aNoAssignment.GetClickHdl().Call(&m_aNoAssignment); FreeResource(); } //------------------------------------------------------------------------ OSelectLabelDialog::~OSelectLabelDialog() { // delete the entry datas of the listbox entries SvLBoxEntry* pLoop = m_aControlTree.First(); while (pLoop) { void* pData = pLoop->GetUserData(); if (pData) delete (Reference< XPropertySet > *)pData; pLoop = m_aControlTree.Next(pLoop); } DBG_DTOR(OSelectLabelDialog,NULL); } //------------------------------------------------------------------------ sal_Int32 OSelectLabelDialog::InsertEntries(const Reference< XInterface > & _xContainer, SvLBoxEntry* pContainerEntry) { Reference< XIndexAccess > xContainer(_xContainer, UNO_QUERY); if (!xContainer.is()) return 0; sal_Int32 nChildren = 0; UniString sName,sDisplayName; Reference< XPropertySet > xAsSet; for (sal_Int32 i=0; i<xContainer->getCount(); ++i) { xContainer->getByIndex(i) >>= xAsSet; if (!xAsSet.is()) { DBG_WARNING("OSelectLabelDialog::InsertEntries : strange : a form component which isn't a property set !"); continue; } if (!::comphelper::hasProperty(PROPERTY_NAME, xAsSet)) // we need at least a name for displaying ... continue; sName = ::comphelper::getString(xAsSet->getPropertyValue(PROPERTY_NAME)).getStr(); // we need to check if the control model supports the required service Reference< XServiceInfo > xInfo(xAsSet, UNO_QUERY); if (!xInfo.is()) continue; if (!xInfo->supportsService(m_sRequiredService)) { // perhaps it is a container Reference< XIndexAccess > xCont(xAsSet, UNO_QUERY); if (xCont.is() && xCont->getCount()) { // yes -> step down Image aFormImage = m_aModelImages.GetImage( RID_SVXIMG_FORM ); SvLBoxEntry* pCont = m_aControlTree.InsertEntry(sName, aFormImage, aFormImage, pContainerEntry); sal_Int32 nContChildren = InsertEntries(xCont, pCont); if (nContChildren) { m_aControlTree.Expand(pCont); ++nChildren; } else { // oops, no valid childs -> remove the entry m_aControlTree.ModelIsRemoving(pCont); m_aControlTree.GetModel()->Remove(pCont); m_aControlTree.ModelHasRemoved(pCont); } } continue; } // get the label if (!::comphelper::hasProperty(PROPERTY_LABEL, xAsSet)) continue; sDisplayName = ::comphelper::getString(xAsSet->getPropertyValue(PROPERTY_LABEL)).getStr(); sDisplayName += String::CreateFromAscii(" ("); sDisplayName += sName; sDisplayName += ')'; // all requirements met -> insert SvLBoxEntry* pCurrent = m_aControlTree.InsertEntry(sDisplayName, m_aRequiredControlImage, m_aRequiredControlImage, pContainerEntry); pCurrent->SetUserData(new Reference< XPropertySet > (xAsSet)); ++nChildren; if (m_xInitialLabelControl == xAsSet) m_pInitialSelection = pCurrent; m_bHaveAssignableControl = sal_True; } return nChildren; } //------------------------------------------------------------------------ IMPL_LINK(OSelectLabelDialog, OnEntrySelected, SvTreeListBox*, pLB) { DBG_ASSERT(pLB == &m_aControlTree, "OSelectLabelDialog::OnEntrySelected : where did this come from ?"); SvLBoxEntry* pSelected = m_aControlTree.FirstSelected(); void* pData = pSelected ? pSelected->GetUserData() : NULL; if (pData) m_xSelectedControl = Reference< XPropertySet > (*(Reference< XPropertySet > *)pData); m_aNoAssignment.SetClickHdl(Link()); m_aNoAssignment.Check(pData == NULL); m_aNoAssignment.SetClickHdl(LINK(this, OSelectLabelDialog, OnNoAssignmentClicked)); return 0L; } //------------------------------------------------------------------------ IMPL_LINK(OSelectLabelDialog, OnNoAssignmentClicked, Button*, pButton) { DBG_ASSERT(pButton == &m_aNoAssignment, "OSelectLabelDialog::OnNoAssignmentClicked : where did this come from ?"); if (m_aNoAssignment.IsChecked()) m_pLastSelected = m_aControlTree.FirstSelected(); else { DBG_ASSERT(m_bHaveAssignableControl, "OSelectLabelDialog::OnNoAssignmentClicked"); // search the first assignable entry SvLBoxEntry* pSearch = m_aControlTree.First(); while (pSearch) { if (pSearch->GetUserData()) break; pSearch = m_aControlTree.Next(pSearch); } // and select it if (pSearch) { m_aControlTree.Select(pSearch); m_pLastSelected = pSearch; } } if (m_pLastSelected) { m_aControlTree.SetSelectHdl(Link()); m_aControlTree.SetDeselectHdl(Link()); m_aControlTree.Select(m_pLastSelected, !m_aNoAssignment.IsChecked()); m_aControlTree.SetSelectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); m_aControlTree.SetDeselectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); } return 0L; } //............................................................................ } // namespace pcr //............................................................................ <commit_msg>INTEGRATION: CWS wae4extensions (1.8.78); FILE MERGED 2007/09/27 07:18:25 fs 1.8.78.1: #i81612# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: selectlabeldialog.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: ihi $ $Date: 2008-01-14 15:00:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_extensions.hxx" #ifndef _EXTENSIONS_PROPCTRLR_SELECTLABELDIALOG_HXX_ #include "selectlabeldialog.hxx" #endif #ifndef _EXTENSIONS_PROPCTRLR_FORMRESID_HRC_ #include "formresid.hrc" #endif #ifndef _EXTENSIONS_FORMSCTRLR_FORMBROWSERTOOLS_HXX_ #include "formbrowsertools.hxx" #endif #ifndef _EXTENSIONS_FORMSCTRLR_FORMSTRINGS_HXX_ #include "formstrings.hxx" #endif #ifndef _COM_SUN_STAR_FORM_FORMCOMPONENTTYPE_HPP_ #include <com/sun/star/form/FormComponentType.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_ #include <com/sun/star/container/XChild.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif //............................................................................ namespace pcr { //............................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::form; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::lang; //======================================================================== // OSelectLabelDialog //======================================================================== DBG_NAME(OSelectLabelDialog) //------------------------------------------------------------------------ OSelectLabelDialog::OSelectLabelDialog( Window* pParent, Reference< XPropertySet > _xControlModel ) :ModalDialog(pParent, PcrRes(RID_DLG_SELECTLABELCONTROL)) ,m_aMainDesc(this, PcrRes(1)) ,m_aControlTree(this, PcrRes(1)) ,m_aNoAssignment(this, PcrRes(1)) ,m_aSeparator(this, PcrRes(1)) ,m_aOk(this, PcrRes(1)) ,m_aCancel(this, PcrRes(1)) ,m_aModelImages(PcrRes(RID_IL_FORMEXPLORER)) ,m_xControlModel(_xControlModel) ,m_pInitialSelection(NULL) ,m_pLastSelected(NULL) ,m_bHaveAssignableControl(sal_False) { DBG_CTOR(OSelectLabelDialog,NULL); // initialize the TreeListBox m_aControlTree.SetSelectionMode( SINGLE_SELECTION ); m_aControlTree.SetDragDropMode( 0 ); m_aControlTree.EnableInplaceEditing( sal_False ); m_aControlTree.SetWindowBits(WB_BORDER | WB_HASLINES | WB_HASLINESATROOT | WB_HASBUTTONS | WB_HASBUTTONSATROOT | WB_HSCROLL); m_aControlTree.SetNodeBitmaps( m_aModelImages.GetImage( RID_SVXIMG_COLLAPSEDNODE ), m_aModelImages.GetImage( RID_SVXIMG_EXPANDEDNODE ) ); m_aControlTree.SetSelectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); m_aControlTree.SetDeselectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); // fill the description UniString sDescription = m_aMainDesc.GetText(); sal_Int16 nClassID = FormComponentType::CONTROL; if (::comphelper::hasProperty(PROPERTY_CLASSID, m_xControlModel)) nClassID = ::comphelper::getINT16(m_xControlModel->getPropertyValue(PROPERTY_CLASSID)); sDescription.SearchAndReplace(String::CreateFromAscii("$control_class$"), GetUIHeadlineName(nClassID, makeAny(m_xControlModel))); UniString sName = ::comphelper::getString(m_xControlModel->getPropertyValue(PROPERTY_NAME)).getStr(); sDescription.SearchAndReplace(String::CreateFromAscii("$control_name$"), sName); m_aMainDesc.SetText(sDescription); // search for the root of the form hierarchy Reference< XChild > xCont(m_xControlModel, UNO_QUERY); Reference< XInterface > xSearch( xCont.is() ? xCont->getParent() : Reference< XInterface > ()); Reference< XResultSet > xParentAsResultSet(xSearch, UNO_QUERY); while (xParentAsResultSet.is()) { xCont = Reference< XChild > (xSearch, UNO_QUERY); xSearch = xCont.is() ? xCont->getParent() : Reference< XInterface > (); xParentAsResultSet = Reference< XResultSet > (xSearch, UNO_QUERY); } // and insert all entries below this root into the listbox if (xSearch.is()) { // check wich service the allowed components must suppport sal_Int16 nClassId = 0; try { nClassId = ::comphelper::getINT16(m_xControlModel->getPropertyValue(PROPERTY_CLASSID)); } catch(...) { } m_sRequiredService = (FormComponentType::RADIOBUTTON == nClassId) ? SERVICE_COMPONENT_GROUPBOX : SERVICE_COMPONENT_FIXEDTEXT; m_aRequiredControlImage = m_aModelImages.GetImage((FormComponentType::RADIOBUTTON == nClassId) ? RID_SVXIMG_GROUPBOX : RID_SVXIMG_FIXEDTEXT); // calc the currently set label control (so InsertEntries can calc m_pInitialSelection) Any aCurrentLabelControl( m_xControlModel->getPropertyValue(PROPERTY_CONTROLLABEL) ); DBG_ASSERT((aCurrentLabelControl.getValueTypeClass() == TypeClass_INTERFACE) || !aCurrentLabelControl.hasValue(), "OSelectLabelDialog::OSelectLabelDialog : invalid ControlLabel property !"); if (aCurrentLabelControl.hasValue()) aCurrentLabelControl >>= m_xInitialLabelControl; // insert the root Image aRootImage = m_aModelImages.GetImage(RID_SVXIMG_FORMS); SvLBoxEntry* pRoot = m_aControlTree.InsertEntry(PcrRes(RID_STR_FORMS), aRootImage, aRootImage); // build the tree m_pInitialSelection = NULL; m_bHaveAssignableControl = sal_False; InsertEntries(xSearch, pRoot); m_aControlTree.Expand(pRoot); } if (m_pInitialSelection) { m_aControlTree.MakeVisible(m_pInitialSelection, sal_True); m_aControlTree.Select(m_pInitialSelection, sal_True); } else { m_aControlTree.MakeVisible(m_aControlTree.First(), sal_True); if (m_aControlTree.FirstSelected()) m_aControlTree.Select(m_aControlTree.FirstSelected(), sal_False); m_aNoAssignment.Check(sal_True); } if (!m_bHaveAssignableControl) { // no controls which can be assigned m_aNoAssignment.Check(sal_True); m_aNoAssignment.Enable(sal_False); } m_aNoAssignment.SetClickHdl(LINK(this, OSelectLabelDialog, OnNoAssignmentClicked)); m_aNoAssignment.GetClickHdl().Call(&m_aNoAssignment); FreeResource(); } //------------------------------------------------------------------------ OSelectLabelDialog::~OSelectLabelDialog() { // delete the entry datas of the listbox entries SvLBoxEntry* pLoop = m_aControlTree.First(); while (pLoop) { void* pData = pLoop->GetUserData(); if (pData) delete (Reference< XPropertySet > *)pData; pLoop = m_aControlTree.Next(pLoop); } DBG_DTOR(OSelectLabelDialog,NULL); } //------------------------------------------------------------------------ sal_Int32 OSelectLabelDialog::InsertEntries(const Reference< XInterface > & _xContainer, SvLBoxEntry* pContainerEntry) { Reference< XIndexAccess > xContainer(_xContainer, UNO_QUERY); if (!xContainer.is()) return 0; sal_Int32 nChildren = 0; UniString sName,sDisplayName; Reference< XPropertySet > xAsSet; for (sal_Int32 i=0; i<xContainer->getCount(); ++i) { xContainer->getByIndex(i) >>= xAsSet; if (!xAsSet.is()) { DBG_WARNING("OSelectLabelDialog::InsertEntries : strange : a form component which isn't a property set !"); continue; } if (!::comphelper::hasProperty(PROPERTY_NAME, xAsSet)) // we need at least a name for displaying ... continue; sName = ::comphelper::getString(xAsSet->getPropertyValue(PROPERTY_NAME)).getStr(); // we need to check if the control model supports the required service Reference< XServiceInfo > xInfo(xAsSet, UNO_QUERY); if (!xInfo.is()) continue; if (!xInfo->supportsService(m_sRequiredService)) { // perhaps it is a container Reference< XIndexAccess > xCont(xAsSet, UNO_QUERY); if (xCont.is() && xCont->getCount()) { // yes -> step down Image aFormImage = m_aModelImages.GetImage( RID_SVXIMG_FORM ); SvLBoxEntry* pCont = m_aControlTree.InsertEntry(sName, aFormImage, aFormImage, pContainerEntry); sal_Int32 nContChildren = InsertEntries(xCont, pCont); if (nContChildren) { m_aControlTree.Expand(pCont); ++nChildren; } else { // oops, no valid childs -> remove the entry m_aControlTree.ModelIsRemoving(pCont); m_aControlTree.GetModel()->Remove(pCont); m_aControlTree.ModelHasRemoved(pCont); } } continue; } // get the label if (!::comphelper::hasProperty(PROPERTY_LABEL, xAsSet)) continue; sDisplayName = ::comphelper::getString(xAsSet->getPropertyValue(PROPERTY_LABEL)).getStr(); sDisplayName += String::CreateFromAscii(" ("); sDisplayName += sName; sDisplayName += ')'; // all requirements met -> insert SvLBoxEntry* pCurrent = m_aControlTree.InsertEntry(sDisplayName, m_aRequiredControlImage, m_aRequiredControlImage, pContainerEntry); pCurrent->SetUserData(new Reference< XPropertySet > (xAsSet)); ++nChildren; if (m_xInitialLabelControl == xAsSet) m_pInitialSelection = pCurrent; m_bHaveAssignableControl = sal_True; } return nChildren; } //------------------------------------------------------------------------ IMPL_LINK(OSelectLabelDialog, OnEntrySelected, SvTreeListBox*, pLB) { DBG_ASSERT(pLB == &m_aControlTree, "OSelectLabelDialog::OnEntrySelected : where did this come from ?"); (void)pLB; SvLBoxEntry* pSelected = m_aControlTree.FirstSelected(); void* pData = pSelected ? pSelected->GetUserData() : NULL; if (pData) m_xSelectedControl = Reference< XPropertySet > (*(Reference< XPropertySet > *)pData); m_aNoAssignment.SetClickHdl(Link()); m_aNoAssignment.Check(pData == NULL); m_aNoAssignment.SetClickHdl(LINK(this, OSelectLabelDialog, OnNoAssignmentClicked)); return 0L; } //------------------------------------------------------------------------ IMPL_LINK(OSelectLabelDialog, OnNoAssignmentClicked, Button*, pButton) { DBG_ASSERT(pButton == &m_aNoAssignment, "OSelectLabelDialog::OnNoAssignmentClicked : where did this come from ?"); (void)pButton; if (m_aNoAssignment.IsChecked()) m_pLastSelected = m_aControlTree.FirstSelected(); else { DBG_ASSERT(m_bHaveAssignableControl, "OSelectLabelDialog::OnNoAssignmentClicked"); // search the first assignable entry SvLBoxEntry* pSearch = m_aControlTree.First(); while (pSearch) { if (pSearch->GetUserData()) break; pSearch = m_aControlTree.Next(pSearch); } // and select it if (pSearch) { m_aControlTree.Select(pSearch); m_pLastSelected = pSearch; } } if (m_pLastSelected) { m_aControlTree.SetSelectHdl(Link()); m_aControlTree.SetDeselectHdl(Link()); m_aControlTree.Select(m_pLastSelected, !m_aNoAssignment.IsChecked()); m_aControlTree.SetSelectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); m_aControlTree.SetDeselectHdl(LINK(this, OSelectLabelDialog, OnEntrySelected)); } return 0L; } //............................................................................ } // namespace pcr //............................................................................ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ucbcmds.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:16:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _UCBCMDS_HXX #define _UCBCMDS_HXX ////////////////////////////////////////////////////////////////////////// // // Definitions for the commands supported by the UCB. // ////////////////////////////////////////////////////////////////////////// #define GETCOMMANDINFO_NAME "getCommandInfo" #define GETCOMMANDINFO_HANDLE 1024 #define GLOBALTRANSFER_NAME "globalTransfer" #define GLOBALTRANSFER_HANDLE 1025 #endif /* !_UCBCMDS_HXX */ <commit_msg>INTEGRATION: CWS changefileheader (1.2.184); FILE MERGED 2008/03/31 15:30:14 rt 1.2.184.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ucbcmds.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _UCBCMDS_HXX #define _UCBCMDS_HXX ////////////////////////////////////////////////////////////////////////// // // Definitions for the commands supported by the UCB. // ////////////////////////////////////////////////////////////////////////// #define GETCOMMANDINFO_NAME "getCommandInfo" #define GETCOMMANDINFO_HANDLE 1024 #define GLOBALTRANSFER_NAME "globalTransfer" #define GLOBALTRANSFER_HANDLE 1025 #endif /* !_UCBCMDS_HXX */ <|endoftext|>
<commit_before>//===- llvm/unittest/VMCore/ConstantsTest.cpp - Constants unit tests ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "gtest/gtest.h" namespace llvm { namespace { TEST(ConstantsTest, Integer_i1) { const IntegerType* Int1 = IntegerType::get(1); Constant* One = ConstantInt::get(Int1, 1, true); Constant* Zero = ConstantInt::get(Int1, 0); Constant* NegOne = ConstantInt::get(Int1, static_cast<uint64_t>(-1), true); EXPECT_EQ(NegOne, ConstantInt::getSigned(Int1, -1)); Constant* Undef = UndefValue::get(Int1); // Input: @b = constant i1 add(i1 1 , i1 1) // Output: @b = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getAdd(One, One)); // @c = constant i1 add(i1 -1, i1 1) // @c = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getAdd(NegOne, One)); // @d = constant i1 add(i1 -1, i1 -1) // @d = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getAdd(NegOne, NegOne)); // @e = constant i1 sub(i1 -1, i1 1) // @e = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getSub(NegOne, One)); // @f = constant i1 sub(i1 1 , i1 -1) // @f = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getSub(One, NegOne)); // @g = constant i1 sub(i1 1 , i1 1) // @g = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getSub(One, One)); // @h = constant i1 shl(i1 1 , i1 1) ; undefined // @h = constant i1 undef EXPECT_EQ(Undef, ConstantExpr::getShl(One, One)); // @i = constant i1 shl(i1 1 , i1 0) // @i = constant i1 true EXPECT_EQ(One, ConstantExpr::getShl(One, Zero)); // @j = constant i1 lshr(i1 1, i1 1) ; undefined // @j = constant i1 undef EXPECT_EQ(Undef, ConstantExpr::getLShr(One, One)); // @m = constant i1 ashr(i1 1, i1 1) ; undefined // @m = constant i1 undef EXPECT_EQ(Undef, ConstantExpr::getAShr(One, One)); // @n = constant i1 mul(i1 -1, i1 1) // @n = constant i1 true EXPECT_EQ(One, ConstantExpr::getMul(NegOne, One)); // @o = constant i1 sdiv(i1 -1, i1 1) ; overflow // @o = constant i1 true EXPECT_EQ(One, ConstantExpr::getSDiv(NegOne, One)); // @p = constant i1 sdiv(i1 1 , i1 -1); overflow // @p = constant i1 true EXPECT_EQ(One, ConstantExpr::getSDiv(One, NegOne)); // @q = constant i1 udiv(i1 -1, i1 1) // @q = constant i1 true EXPECT_EQ(One, ConstantExpr::getUDiv(NegOne, One)); // @r = constant i1 udiv(i1 1, i1 -1) // @r = constant i1 true EXPECT_EQ(One, ConstantExpr::getUDiv(One, NegOne)); // @s = constant i1 srem(i1 -1, i1 1) ; overflow // @s = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getSRem(NegOne, One)); // @t = constant i1 urem(i1 -1, i1 1) // @t = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getURem(NegOne, One)); // @u = constant i1 srem(i1 1, i1 -1) ; overflow // @u = constant i1 false EXPECT_EQ(Zero, ConstantExpr::getSRem(One, NegOne)); } TEST(ConstantsTest, IntSigns) { const IntegerType* Int8Ty = Type::Int8Ty; EXPECT_EQ(100, ConstantInt::get(Int8Ty, 100, false)->getSExtValue()); EXPECT_EQ(100, ConstantInt::get(Int8Ty, 100, true)->getSExtValue()); EXPECT_EQ(100, ConstantInt::getSigned(Int8Ty, 100)->getSExtValue()); EXPECT_EQ(-50, ConstantInt::get(Int8Ty, 206)->getSExtValue()); EXPECT_EQ(-50, ConstantInt::getSigned(Int8Ty, -50)->getSExtValue()); EXPECT_EQ(206U, ConstantInt::getSigned(Int8Ty, -50)->getZExtValue()); // Overflow is handled by truncation. EXPECT_EQ(0x3b, ConstantInt::get(Int8Ty, 0x13b)->getSExtValue()); } } // end anonymous namespace } // end namespace llvm <commit_msg>Port this unittest to use LLVMContext.<commit_after>//===- llvm/unittest/VMCore/ConstantsTest.cpp - Constants unit tests ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/LLVMContext.h" #include "gtest/gtest.h" namespace llvm { namespace { TEST(ConstantsTest, Integer_i1) { const IntegerType* Int1 = IntegerType::get(1); Constant* One = getGlobalContext().getConstantInt(Int1, 1, true); Constant* Zero = getGlobalContext().getConstantInt(Int1, 0); Constant* NegOne = getGlobalContext().getConstantInt(Int1, static_cast<uint64_t>(-1), true); EXPECT_EQ(NegOne, getGlobalContext().getConstantIntSigned(Int1, -1)); Constant* Undef = getGlobalContext().getUndef(Int1); // Input: @b = constant i1 add(i1 1 , i1 1) // Output: @b = constant i1 false EXPECT_EQ(Zero, getGlobalContext().getConstantExprAdd(One, One)); // @c = constant i1 add(i1 -1, i1 1) // @c = constant i1 false EXPECT_EQ(Zero, getGlobalContext().getConstantExprAdd(NegOne, One)); // @d = constant i1 add(i1 -1, i1 -1) // @d = constant i1 false EXPECT_EQ(Zero, getGlobalContext().getConstantExprAdd(NegOne, NegOne)); // @e = constant i1 sub(i1 -1, i1 1) // @e = constant i1 false EXPECT_EQ(Zero, getGlobalContext().getConstantExprSub(NegOne, One)); // @f = constant i1 sub(i1 1 , i1 -1) // @f = constant i1 false EXPECT_EQ(Zero, getGlobalContext().getConstantExprSub(One, NegOne)); // @g = constant i1 sub(i1 1 , i1 1) // @g = constant i1 false EXPECT_EQ(Zero, getGlobalContext().getConstantExprSub(One, One)); // @h = constant i1 shl(i1 1 , i1 1) ; undefined // @h = constant i1 undef EXPECT_EQ(Undef, getGlobalContext().getConstantExprShl(One, One)); // @i = constant i1 shl(i1 1 , i1 0) // @i = constant i1 true EXPECT_EQ(One, getGlobalContext().getConstantExprShl(One, Zero)); // @j = constant i1 lshr(i1 1, i1 1) ; undefined // @j = constant i1 undef EXPECT_EQ(Undef, getGlobalContext().getConstantExprLShr(One, One)); // @m = constant i1 ashr(i1 1, i1 1) ; undefined // @m = constant i1 undef EXPECT_EQ(Undef, getGlobalContext().getConstantExprAShr(One, One)); // @n = constant i1 mul(i1 -1, i1 1) // @n = constant i1 true EXPECT_EQ(One, getGlobalContext().getConstantExprMul(NegOne, One)); // @o = constant i1 sdiv(i1 -1, i1 1) ; overflow // @o = constant i1 true EXPECT_EQ(One, getGlobalContext().getConstantExprSDiv(NegOne, One)); // @p = constant i1 sdiv(i1 1 , i1 -1); overflow // @p = constant i1 true EXPECT_EQ(One, getGlobalContext().getConstantExprSDiv(One, NegOne)); // @q = constant i1 udiv(i1 -1, i1 1) // @q = constant i1 true EXPECT_EQ(One, getGlobalContext().getConstantExprUDiv(NegOne, One)); // @r = constant i1 udiv(i1 1, i1 -1) // @r = constant i1 true EXPECT_EQ(One, getGlobalContext().getConstantExprUDiv(One, NegOne)); // @s = constant i1 srem(i1 -1, i1 1) ; overflow // @s = constant i1 false EXPECT_EQ(Zero, getGlobalContext().getConstantExprSRem(NegOne, One)); // @t = constant i1 urem(i1 -1, i1 1) // @t = constant i1 false EXPECT_EQ(Zero, getGlobalContext().getConstantExprURem(NegOne, One)); // @u = constant i1 srem(i1 1, i1 -1) ; overflow // @u = constant i1 false EXPECT_EQ(Zero, getGlobalContext().getConstantExprSRem(One, NegOne)); } TEST(ConstantsTest, IntSigns) { const IntegerType* Int8Ty = Type::Int8Ty; LLVMContext &Context = getGlobalContext(); EXPECT_EQ(100, Context.getConstantInt(Int8Ty, 100, false)->getSExtValue()); EXPECT_EQ(100, Context.getConstantInt(Int8Ty, 100, true)->getSExtValue()); EXPECT_EQ(100, Context.getConstantIntSigned(Int8Ty, 100)->getSExtValue()); EXPECT_EQ(-50, Context.getConstantInt(Int8Ty, 206)->getSExtValue()); EXPECT_EQ(-50, Context.getConstantIntSigned(Int8Ty, -50)->getSExtValue()); EXPECT_EQ(206U, Context.getConstantIntSigned(Int8Ty, -50)->getZExtValue()); // Overflow is handled by truncation. EXPECT_EQ(0x3b, Context.getConstantInt(Int8Ty, 0x13b)->getSExtValue()); } } // end anonymous namespace } // end namespace llvm <|endoftext|>
<commit_before>#include "testparams.h" #include "MPITestFixture.h" #include <algorithm> extern TestParams globalTestParams; using namespace clusterlib; using namespace std; const string appName = "processSlot-app"; class ClusterlibProcessSlot : public MPITestFixture { CPPUNIT_TEST_SUITE(ClusterlibProcessSlot); CPPUNIT_TEST(testProcessSlot1); CPPUNIT_TEST_SUITE_END(); public: ClusterlibProcessSlot() : MPITestFixture(globalTestParams), _factory(NULL), _client0(NULL), _app0(NULL), _group0(NULL), _node0(NULL), _processSlot0(NULL) {} /* Runs prior to each test */ virtual void setUp() { _factory = new Factory( globalTestParams.getZkServerPortList()); MPI_CPPUNIT_ASSERT(_factory != NULL); _client0 = _factory->createClient(); MPI_CPPUNIT_ASSERT(_client0 != NULL); _app0 = _client0->getRoot()->getApplication(appName, true); MPI_CPPUNIT_ASSERT(_app0 != NULL); _group0 = _app0->getGroup("processSlot-group-servers", true); MPI_CPPUNIT_ASSERT(_group0 != NULL); _node0 = _group0->getNode("server-0", true); MPI_CPPUNIT_ASSERT(_node0 != NULL); } /* Runs after each test */ virtual void tearDown() { cleanAndBarrierMPITest(_factory, true); delete _factory; _factory = NULL; } /* * Simple test to see if processSlot set by one process are read by * another (when 2 processes or more are available). If only one * process is available, runs as a single process test. */ void testProcessSlot1() { initializeAndBarrierMPITest(2, true, _factory, true, "testProcessSlot1"); string processSlotName = "slot0"; if (isMyRank(0)) { _processSlot0 = _node0->getProcessSlot( processSlotName, true); MPI_CPPUNIT_ASSERT(_processSlot0); _processSlot0->acquireLock(); vector<int32_t> portVec; portVec.push_back(1234); portVec.push_back(5678); _processSlot0->setPortVec(portVec); _processSlot0->releaseLock(); } waitsForOrder(0, 1, _factory, true); if (isMyRank(1)) { _processSlot0 = _node0->getProcessSlot(processSlotName); MPI_CPPUNIT_ASSERT(_processSlot0); vector<int32_t> portVec = _processSlot0->getPortVec(); _processSlot0->acquireLock(); MPI_CPPUNIT_ASSERT(portVec.size() == 2); if (portVec.size() == 2) { MPI_CPPUNIT_ASSERT(portVec[0] == 1234); MPI_CPPUNIT_ASSERT(portVec[1] == 5678); } portVec[0] = 12; portVec[1] = 56; _processSlot0->setPortVec(portVec); _processSlot0->releaseLock(); } waitsForOrder(1, 0, _factory, true); if (isMyRank(0)) { _processSlot0->acquireLock(); vector<int32_t> portVec = _processSlot0->getPortVec(); _processSlot0->releaseLock(); MPI_CPPUNIT_ASSERT(portVec.size() == 2); if (portVec.size() == 2) { MPI_CPPUNIT_ASSERT(portVec[0] == 12); MPI_CPPUNIT_ASSERT(portVec[1] == 56); } } } private: Factory *_factory; Client *_client0; Application *_app0; Group *_group0; Node *_node0; ProcessSlot *_processSlot0; }; /* Registers the fixture into the 'registry' */ CPPUNIT_TEST_SUITE_REGISTRATION(ClusterlibProcessSlot); <commit_msg>Didn't acquire the lock prior to setting the vector (hangs ydhudson under certain conditions).<commit_after>#include "testparams.h" #include "MPITestFixture.h" #include <algorithm> extern TestParams globalTestParams; using namespace clusterlib; using namespace std; const string appName = "processSlot-app"; class ClusterlibProcessSlot : public MPITestFixture { CPPUNIT_TEST_SUITE(ClusterlibProcessSlot); CPPUNIT_TEST(testProcessSlot1); CPPUNIT_TEST_SUITE_END(); public: ClusterlibProcessSlot() : MPITestFixture(globalTestParams), _factory(NULL), _client0(NULL), _app0(NULL), _group0(NULL), _node0(NULL), _processSlot0(NULL) {} /* Runs prior to each test */ virtual void setUp() { _factory = new Factory( globalTestParams.getZkServerPortList()); MPI_CPPUNIT_ASSERT(_factory != NULL); _client0 = _factory->createClient(); MPI_CPPUNIT_ASSERT(_client0 != NULL); _app0 = _client0->getRoot()->getApplication(appName, true); MPI_CPPUNIT_ASSERT(_app0 != NULL); _group0 = _app0->getGroup("processSlot-group-servers", true); MPI_CPPUNIT_ASSERT(_group0 != NULL); _node0 = _group0->getNode("server-0", true); MPI_CPPUNIT_ASSERT(_node0 != NULL); } /* Runs after each test */ virtual void tearDown() { cleanAndBarrierMPITest(_factory, true); delete _factory; _factory = NULL; } /* * Simple test to see if processSlot set by one process are read by * another (when 2 processes or more are available). If only one * process is available, runs as a single process test. */ void testProcessSlot1() { initializeAndBarrierMPITest(2, true, _factory, true, "testProcessSlot1"); string processSlotName = "slot0"; if (isMyRank(0)) { _processSlot0 = _node0->getProcessSlot( processSlotName, true); MPI_CPPUNIT_ASSERT(_processSlot0); _processSlot0->acquireLock(); vector<int32_t> portVec; portVec.push_back(1234); portVec.push_back(5678); _processSlot0->setPortVec(portVec); _processSlot0->releaseLock(); } waitsForOrder(0, 1, _factory, true); if (isMyRank(1)) { _processSlot0 = _node0->getProcessSlot(processSlotName); MPI_CPPUNIT_ASSERT(_processSlot0); _processSlot0->acquireLock(); vector<int32_t> portVec = _processSlot0->getPortVec(); MPI_CPPUNIT_ASSERT(portVec.size() == 2); if (portVec.size() == 2) { MPI_CPPUNIT_ASSERT(portVec[0] == 1234); MPI_CPPUNIT_ASSERT(portVec[1] == 5678); } portVec[0] = 12; portVec[1] = 56; _processSlot0->setPortVec(portVec); _processSlot0->releaseLock(); } waitsForOrder(1, 0, _factory, true); if (isMyRank(0)) { _processSlot0->acquireLock(); vector<int32_t> portVec = _processSlot0->getPortVec(); _processSlot0->releaseLock(); MPI_CPPUNIT_ASSERT(portVec.size() == 2); if (portVec.size() == 2) { MPI_CPPUNIT_ASSERT(portVec[0] == 12); MPI_CPPUNIT_ASSERT(portVec[1] == 56); } } } private: Factory *_factory; Client *_client0; Application *_app0; Group *_group0; Node *_node0; ProcessSlot *_processSlot0; }; /* Registers the fixture into the 'registry' */ CPPUNIT_TEST_SUITE_REGISTRATION(ClusterlibProcessSlot); <|endoftext|>
<commit_before>/************************************************************************** ** ** Copyright (c) 2014 BogDan Vatra <[email protected]> ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "androidpackageinstallationstep.h" #include <android/androidconstants.h> #include <projectexplorer/buildsteplist.h> #include <projectexplorer/target.h> #include <projectexplorer/buildconfiguration.h> #include <projectexplorer/toolchain.h> #include <projectexplorer/kitinformation.h> #include <projectexplorer/gnumakeparser.h> #include <utils/hostosinfo.h> #include <QDir> using namespace QmakeAndroidSupport::Internal; const Core::Id AndroidPackageInstallationStep::Id = Core::Id("Qt4ProjectManager.AndroidPackageInstallationStep"); namespace { const char ANDROIDDIRECTORY[] = "Android.AndroidPackageInstallationStep.AndroidDirectory"; } AndroidPackageInstallationStep::AndroidPackageInstallationStep(ProjectExplorer::BuildStepList *bsl) : AbstractProcessStep(bsl, Id) { const QString name = tr("Copy application data"); setDefaultDisplayName(name); setDisplayName(name); } AndroidPackageInstallationStep::AndroidPackageInstallationStep(ProjectExplorer::BuildStepList *bc, AndroidPackageInstallationStep *other) : AbstractProcessStep(bc, other) { } bool AndroidPackageInstallationStep::init() { ProjectExplorer::BuildConfiguration *bc = buildConfiguration(); QString dirPath = bc->buildDirectory().appendPath(QLatin1String(Android::Constants::ANDROID_BUILDDIRECTORY)).toString(); if (Utils::HostOsInfo::isWindowsHost()) if (bc->environment().searchInPath(QLatin1String("sh.exe")).isEmpty()) dirPath = QDir::toNativeSeparators(dirPath); ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(target()->kit()); ProjectExplorer::ProcessParameters *pp = processParameters(); pp->setMacroExpander(bc->macroExpander()); pp->setWorkingDirectory(bc->buildDirectory().toString()); pp->setCommand(tc->makeCommand(bc->environment())); Utils::Environment env = bc->environment(); // Force output to english for the parsers. Do this here and not in the toolchain's // addToEnvironment() to not screw up the users run environment. env.set(QLatin1String("LC_ALL"), QLatin1String("C")); pp->setEnvironment(env); pp->setArguments(QString::fromLatin1("INSTALL_ROOT=\"%1\" install").arg(dirPath)); pp->resolveAll(); setOutputParser(new ProjectExplorer::GnuMakeParser()); ProjectExplorer::IOutputParser *parser = target()->kit()->createOutputParser(); if (parser) appendOutputParser(parser); outputParser()->setWorkingDirectory(pp->effectiveWorkingDirectory()); m_androidDirToClean = dirPath; return AbstractProcessStep::init(); } void AndroidPackageInstallationStep::run(QFutureInterface<bool> &fi) { QString error; Utils::FileName androidDir = Utils::FileName::fromString(m_androidDirToClean); if (!m_androidDirToClean.isEmpty()&& androidDir.toFileInfo().exists()) { emit addOutput(tr("Removing directory %1").arg(m_androidDirToClean), MessageOutput); if (!Utils::FileUtils::removeRecursively(androidDir, &error)) { emit addOutput(error, ErrorOutput); fi.reportResult(false); emit finished(); return; } } AbstractProcessStep::run(fi); } ProjectExplorer::BuildStepConfigWidget *AndroidPackageInstallationStep::createConfigWidget() { return new AndroidPackageInstallationStepWidget(this); } bool AndroidPackageInstallationStep::immutable() const { return true; } // // AndroidPackageInstallationStepWidget // AndroidPackageInstallationStepWidget::AndroidPackageInstallationStepWidget(AndroidPackageInstallationStep *step) : m_step(step) { } QString AndroidPackageInstallationStepWidget::summaryText() const { return tr("<b>Make install</b>"); } QString AndroidPackageInstallationStepWidget::displayName() const { return tr("Make install"); } bool AndroidPackageInstallationStepWidget::showWidget() const { return false; } <commit_msg>Android: Remove some dead code<commit_after>/************************************************************************** ** ** Copyright (c) 2014 BogDan Vatra <[email protected]> ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "androidpackageinstallationstep.h" #include <android/androidconstants.h> #include <projectexplorer/buildsteplist.h> #include <projectexplorer/target.h> #include <projectexplorer/buildconfiguration.h> #include <projectexplorer/toolchain.h> #include <projectexplorer/kitinformation.h> #include <projectexplorer/gnumakeparser.h> #include <utils/hostosinfo.h> #include <QDir> using namespace QmakeAndroidSupport::Internal; const Core::Id AndroidPackageInstallationStep::Id = Core::Id("Qt4ProjectManager.AndroidPackageInstallationStep"); AndroidPackageInstallationStep::AndroidPackageInstallationStep(ProjectExplorer::BuildStepList *bsl) : AbstractProcessStep(bsl, Id) { const QString name = tr("Copy application data"); setDefaultDisplayName(name); setDisplayName(name); } AndroidPackageInstallationStep::AndroidPackageInstallationStep(ProjectExplorer::BuildStepList *bc, AndroidPackageInstallationStep *other) : AbstractProcessStep(bc, other) { } bool AndroidPackageInstallationStep::init() { ProjectExplorer::BuildConfiguration *bc = buildConfiguration(); QString dirPath = bc->buildDirectory().appendPath(QLatin1String(Android::Constants::ANDROID_BUILDDIRECTORY)).toString(); if (Utils::HostOsInfo::isWindowsHost()) if (bc->environment().searchInPath(QLatin1String("sh.exe")).isEmpty()) dirPath = QDir::toNativeSeparators(dirPath); ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(target()->kit()); ProjectExplorer::ProcessParameters *pp = processParameters(); pp->setMacroExpander(bc->macroExpander()); pp->setWorkingDirectory(bc->buildDirectory().toString()); pp->setCommand(tc->makeCommand(bc->environment())); Utils::Environment env = bc->environment(); // Force output to english for the parsers. Do this here and not in the toolchain's // addToEnvironment() to not screw up the users run environment. env.set(QLatin1String("LC_ALL"), QLatin1String("C")); pp->setEnvironment(env); pp->setArguments(QString::fromLatin1("INSTALL_ROOT=\"%1\" install").arg(dirPath)); pp->resolveAll(); setOutputParser(new ProjectExplorer::GnuMakeParser()); ProjectExplorer::IOutputParser *parser = target()->kit()->createOutputParser(); if (parser) appendOutputParser(parser); outputParser()->setWorkingDirectory(pp->effectiveWorkingDirectory()); m_androidDirToClean = dirPath; return AbstractProcessStep::init(); } void AndroidPackageInstallationStep::run(QFutureInterface<bool> &fi) { QString error; Utils::FileName androidDir = Utils::FileName::fromString(m_androidDirToClean); if (!m_androidDirToClean.isEmpty()&& androidDir.toFileInfo().exists()) { emit addOutput(tr("Removing directory %1").arg(m_androidDirToClean), MessageOutput); if (!Utils::FileUtils::removeRecursively(androidDir, &error)) { emit addOutput(error, ErrorOutput); fi.reportResult(false); emit finished(); return; } } AbstractProcessStep::run(fi); } ProjectExplorer::BuildStepConfigWidget *AndroidPackageInstallationStep::createConfigWidget() { return new AndroidPackageInstallationStepWidget(this); } bool AndroidPackageInstallationStep::immutable() const { return true; } // // AndroidPackageInstallationStepWidget // AndroidPackageInstallationStepWidget::AndroidPackageInstallationStepWidget(AndroidPackageInstallationStep *step) : m_step(step) { } QString AndroidPackageInstallationStepWidget::summaryText() const { return tr("<b>Make install</b>"); } QString AndroidPackageInstallationStepWidget::displayName() const { return tr("Make install"); } bool AndroidPackageInstallationStepWidget::showWidget() const { return false; } <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 "stdafx.h" #include <iostream> #include "diagnostics/xquery_diagnostics.h" #include "diagnostics/user_exception.h" #include "context/static_context.h" #include "runtime/errors_and_diagnostics/errors_and_diagnostics.h" #include "runtime/util/iterator_impl.h" #include "store/api/item.h" #include "store/api/item_factory.h" #include "store/api/store.h" #include "store/api/temp_seq.h" #include "system/globalenv.h" #include "zorbatypes/zstring.h" #include "api/serialization/serializer.h" #include "api/serializerimpl.h" namespace zorba { /******************************************************************************* 3.1.1 fn:error ********************************************************************************/ bool ErrorIterator::nextImpl(store::Item_t& result, PlanState& planState) const { static const char* err_ns = "http://www.w3.org/2005/xqt-errors"; store::Item_t err_qname; GENV_ITEMFACTORY->createQName(err_qname, err_ns, "err", "FOER0000"); store::Item_t lTmpQName; store::Item_t lTmpErrorObject; store::Item_t lTmpDescr; zstring description; UserException::error_object_type lErrorObject; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); if (theChildren.size() >= 1) { if (consumeNext(lTmpQName, theChildren[0].getp(), planState)) err_qname = lTmpQName; } if (theChildren.size() >= 2) { consumeNext(lTmpDescr, theChildren[1].getp(), planState); description = lTmpDescr->getStringValue(); } if (theChildren.size() == 3) { while (consumeNext(lTmpErrorObject, theChildren[2].getp(), planState)) { lErrorObject.push_back( Item( lTmpErrorObject.getp() ) ); } } throw USER_EXCEPTION( err_qname, description.c_str(), ERROR_LOC( loc ), &lErrorObject ); STACK_END(state); } /******************************************************************************* 3.2.1 fn:trace ********************************************************************************/ bool TraceIterator::nextImpl(store::Item_t& result, PlanState& planState) const { TraceIteratorState *state; DEFAULT_STACK_INIT(TraceIteratorState, state, planState); if (!consumeNext(state->theTagItem, theChildren[1], planState)) { throw XQUERY_EXCEPTION(err::FORG0006, ERROR_PARAMS(ZED(BadArgTypeForFn_2o34o), ZED(EmptySequence), "fn:trace"), ERROR_LOC( loc ) ); } if (state->theSerializer.get() == 0) { state->theSerializer.reset(new serializer(0)); Zorba_SerializerOptions options; options.omit_xml_declaration = ZORBA_OMIT_XML_DECLARATION_YES; SerializerImpl::setSerializationParameters( *(state->theSerializer), options); } state->theOS = theSctx->get_trace_stream(); while (consumeNext(result, theChildren[0], planState)) { (*state->theOS) << state->theTagItem->getStringValue() << " [" << state->theIndex << "]: "; { store::Item_t lTmp = result; store::TempSeq_t lSequence = GENV_STORE.createTempSeq(lTmp); store::Iterator_t seq_iter = lSequence->getIterator(); seq_iter->open(); state->theSerializer->serialize( seq_iter, (*state->theOS), true); seq_iter->close(); } (*state->theOS) << std::endl; ++state->theIndex; STACK_PUSH(true, state); } STACK_END(state); } } // namespace zorba /* vim:set et sw=2 ts=2: */ <commit_msg>fix for bug #898066 (Stringstream & fn:trace) - implicitly materialize streamable strings in fn:trace - start fn:trace sequence numbering at 1<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 "stdafx.h" #include <iostream> #include "diagnostics/xquery_diagnostics.h" #include "diagnostics/user_exception.h" #include "context/static_context.h" #include "runtime/errors_and_diagnostics/errors_and_diagnostics.h" #include "runtime/util/iterator_impl.h" #include "store/api/item.h" #include "store/api/item_factory.h" #include "store/api/store.h" #include "store/api/temp_seq.h" #include "system/globalenv.h" #include "zorbatypes/zstring.h" #include "api/serialization/serializer.h" #include "api/serializerimpl.h" namespace zorba { /******************************************************************************* 3.1.1 fn:error ********************************************************************************/ bool ErrorIterator::nextImpl(store::Item_t& result, PlanState& planState) const { static const char* err_ns = "http://www.w3.org/2005/xqt-errors"; store::Item_t err_qname; GENV_ITEMFACTORY->createQName(err_qname, err_ns, "err", "FOER0000"); store::Item_t lTmpQName; store::Item_t lTmpErrorObject; store::Item_t lTmpDescr; zstring description; UserException::error_object_type lErrorObject; PlanIteratorState* state; DEFAULT_STACK_INIT(PlanIteratorState, state, planState); if (theChildren.size() >= 1) { if (consumeNext(lTmpQName, theChildren[0].getp(), planState)) err_qname = lTmpQName; } if (theChildren.size() >= 2) { consumeNext(lTmpDescr, theChildren[1].getp(), planState); description = lTmpDescr->getStringValue(); } if (theChildren.size() == 3) { while (consumeNext(lTmpErrorObject, theChildren[2].getp(), planState)) { lErrorObject.push_back( Item( lTmpErrorObject.getp() ) ); } } throw USER_EXCEPTION( err_qname, description.c_str(), ERROR_LOC( loc ), &lErrorObject ); STACK_END(state); } /******************************************************************************* 3.2.1 fn:trace ********************************************************************************/ bool TraceIterator::nextImpl(store::Item_t& result, PlanState& planState) const { TraceIteratorState *state; DEFAULT_STACK_INIT(TraceIteratorState, state, planState); state->theIndex = 1; // XQuery sequences start with 1 if (!consumeNext(state->theTagItem, theChildren[1], planState)) { throw XQUERY_EXCEPTION(err::FORG0006, ERROR_PARAMS(ZED(BadArgTypeForFn_2o34o), ZED(EmptySequence), "fn:trace"), ERROR_LOC( loc ) ); } if (state->theSerializer.get() == 0) { state->theSerializer.reset(new serializer(0)); Zorba_SerializerOptions options; options.omit_xml_declaration = ZORBA_OMIT_XML_DECLARATION_YES; SerializerImpl::setSerializationParameters( *(state->theSerializer), options); } state->theOS = theSctx->get_trace_stream(); while (consumeNext(result, theChildren[0], planState)) { (*state->theOS) << state->theTagItem->getStringValue() << " [" << state->theIndex << "]: "; { store::Item_t lTmp = result; // implicitly materialize non-seekable streamable strings to // avoid nasty "streamable string has already been consumed" // errors during debugging if (lTmp->isStreamable() && !lTmp->isSeekable() && lTmp->getTypeCode() == store::XS_STRING) { zstring lString = lTmp->getString(); GENV_ITEMFACTORY->createString(lTmp, lString); result = lTmp; } store::TempSeq_t lSequence = GENV_STORE.createTempSeq(lTmp); store::Iterator_t seq_iter = lSequence->getIterator(); seq_iter->open(); state->theSerializer->serialize( seq_iter, (*state->theOS), true); seq_iter->close(); } (*state->theOS) << std::endl; ++state->theIndex; STACK_PUSH(true, state); } STACK_END(state); } } // namespace zorba /* vim:set et sw=2 ts=2: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: StyleSheetTable.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: vg $ $Date: 2007-10-29 15:27:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_STYLESHEETTABLE_HXX #define INCLUDED_STYLESHEETTABLE_HXX #ifndef INCLUDED_WRITERFILTERDLLAPI_H #include <WriterFilterDllApi.hxx> #endif #include <com/sun/star/lang/XComponent.hpp> #ifndef INCLUDED_DMAPPER_PROPERTYMAP_HXX #include <PropertyMap.hxx> #endif #ifndef INCLUDED_FONTTABLE_HXX #include <FontTable.hxx> #endif #ifndef INCLUDED_WW8_RESOURCE_MODEL_HXX #include <doctok/WW8ResourceModel.hxx> #endif namespace com{ namespace sun { namespace star { namespace text{ class XTextDocument; }}}} namespace dmapper { enum StyleType { STYLE_TYPE_UNKNOWN, STYLE_TYPE_PARA, STYLE_TYPE_CHAR, STYLE_TYPE_TABLE, STYLE_LIST }; struct StyleSheetTable_Impl; struct StyleSheetEntry { ::rtl::OUString sStyleIdentifierI; ::rtl::OUString sStyleIdentifierD; bool bIsDefaultStyle; bool bInvalidHeight; bool bHasUPE; //universal property expansion StyleType nStyleTypeCode; //sgc ::rtl::OUString sBaseStyleIdentifier; ::rtl::OUString sNextStyleIdentifier; ::rtl::OUString sStyleName; ::rtl::OUString sStyleName1; PropertyMapPtr pProperties; StyleSheetEntry(); }; class DomainMapper; class WRITERFILTER_DLLPRIVATE StyleSheetTable : public doctok::Properties, public doctok::Table { StyleSheetTable_Impl *m_pImpl; public: StyleSheetTable( DomainMapper& rDMapper ); virtual ~StyleSheetTable(); // Properties virtual void attribute(doctok::Id Name, doctok::Value & val); virtual void sprm(doctok::Sprm & sprm); // Table virtual void entry(int pos, doctok::Reference<Properties>::Pointer_t ref); void ApplyStyleSheets(::com::sun::star::uno::Reference< ::com::sun::star::text::XTextDocument> xTextDocument, FontTablePtr rFontTable); const StyleSheetEntry* FindStyleSheetByISTD(const ::rtl::OUString sIndex); // returns the parent of the one with the given name - if empty the parent of the current style sheet is returned const StyleSheetEntry* FindParentStyleSheet(::rtl::OUString sBaseStyle); ::rtl::OUString ConvertStyleName( const ::rtl::OUString& rWWName/*, bool bParagraphStyle*/ ); ::rtl::OUString GetStyleIdFromIndex(const sal_uInt32 sti); private: void resolveAttributeProperties(doctok::Value & val); void resolveSprmProps(doctok::Sprm & sprm_); }; } #endif // <commit_msg>INTEGRATION: CWS xmlfilter02 (1.11.12); FILE MERGED 2007/11/14 12:57:07 hbrinkm 1.11.12.3: namespace clean up 2007/10/18 09:35:12 hbrinkm 1.11.12.2: WW8ResourceModel.hxx moved to inc/resourcemodel 2007/10/01 10:10:55 os 1.11.12.1: integration of cws writerfilter3 into cws xmlfilter02<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: StyleSheetTable.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: obo $ $Date: 2008-01-10 11:41:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INCLUDED_STYLESHEETTABLE_HXX #define INCLUDED_STYLESHEETTABLE_HXX #ifndef INCLUDED_WRITERFILTERDLLAPI_H #include <WriterFilterDllApi.hxx> #endif #include <com/sun/star/lang/XComponent.hpp> #ifndef INCLUDED_DMAPPER_PROPERTYMAP_HXX #include <PropertyMap.hxx> #endif #ifndef INCLUDED_FONTTABLE_HXX #include <FontTable.hxx> #endif #ifndef INCLUDED_WW8_RESOURCE_MODEL_HXX #include <resourcemodel/WW8ResourceModel.hxx> #endif namespace com{ namespace sun { namespace star { namespace text{ class XTextDocument; }}}} namespace writerfilter { namespace dmapper { enum StyleType { STYLE_TYPE_UNKNOWN, STYLE_TYPE_PARA, STYLE_TYPE_CHAR, STYLE_TYPE_TABLE, STYLE_LIST }; struct StyleSheetTable_Impl; struct StyleSheetEntry { ::rtl::OUString sStyleIdentifierI; ::rtl::OUString sStyleIdentifierD; bool bIsDefaultStyle; bool bInvalidHeight; bool bHasUPE; //universal property expansion StyleType nStyleTypeCode; //sgc ::rtl::OUString sBaseStyleIdentifier; ::rtl::OUString sNextStyleIdentifier; ::rtl::OUString sStyleName; ::rtl::OUString sStyleName1; PropertyMapPtr pProperties; StyleSheetEntry(); }; class DomainMapper; class WRITERFILTER_DLLPRIVATE StyleSheetTable : public Properties, public Table { StyleSheetTable_Impl *m_pImpl; public: StyleSheetTable( DomainMapper& rDMapper ); virtual ~StyleSheetTable(); // Properties virtual void attribute(Id Name, Value & val); virtual void sprm(Sprm & sprm); // Table virtual void entry(int pos, writerfilter::Reference<Properties>::Pointer_t ref); void ApplyStyleSheets(::com::sun::star::uno::Reference< ::com::sun::star::text::XTextDocument> xTextDocument, FontTablePtr rFontTable); const StyleSheetEntry* FindStyleSheetByISTD(const ::rtl::OUString& sIndex); // returns the parent of the one with the given name - if empty the parent of the current style sheet is returned const StyleSheetEntry* FindParentStyleSheet(::rtl::OUString sBaseStyle); ::rtl::OUString ConvertStyleName( const ::rtl::OUString& rWWName, bool bExtendedSearch = false ); ::rtl::OUString GetStyleIdFromIndex(const sal_uInt32 sti); private: void resolveAttributeProperties(Value & val); void resolveSprmProps(Sprm & sprm_); void applyDefaults(bool bParaProperties); }; typedef boost::shared_ptr< StyleSheetTable > StyleSheetTablePtr; }} #endif // <|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // 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 // // https://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 "google/cloud/storage/internal/grpc_object_read_source.h" #include "google/cloud/storage/internal/grpc_object_metadata_parser.h" #include "absl/strings/string_view.h" #include <algorithm> #include <limits> namespace google { namespace cloud { namespace storage { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace internal { namespace { std::chrono::milliseconds DefaultDownloadStallTimeout( std::chrono::milliseconds value) { if (value != std::chrono::milliseconds(0)) return value; return std::chrono::seconds( std::numeric_limits<std::chrono::seconds::rep>::max()); } } // namespace GrpcObjectReadSource::GrpcObjectReadSource( std::unique_ptr<StreamingRpc> stream, std::chrono::milliseconds download_stall_timeout) : stream_(std::move(stream)), download_stall_timeout_( DefaultDownloadStallTimeout(download_stall_timeout)) {} StatusOr<HttpResponse> GrpcObjectReadSource::Close() { if (stream_) stream_ = nullptr; if (!status_.ok()) return status_; return HttpResponse{HttpStatusCode::kOk, {}, {}}; } /// Read more data from the download, returning any HTTP headers and error /// codes. StatusOr<ReadSourceResult> GrpcObjectReadSource::Read(char* buf, std::size_t n) { std::size_t offset = 0; auto update_buf = [&offset, buf, n](absl::string_view source) { if (source.empty()) return source; auto const nbytes = std::min(n - offset, source.size()); auto const* end = source.data() + nbytes; std::copy(source.data(), end, buf + offset); offset += nbytes; return absl::string_view(end, source.size() - nbytes); }; ReadSourceResult result; result.response.status_code = HttpStatusCode::kContinue; result.bytes_received = 0; auto update_result = [&](google::storage::v2::ReadObjectResponse response) { // The google.storage.v1.Storage documentation says this field can be // empty. if (response.has_checksummed_data()) { // Sometimes protobuf bytes are not strings, but the explicit conversion // always works. spill_ = std::string( std::move(*response.mutable_checksummed_data()->mutable_content())); spill_view_ = update_buf(spill_); result.bytes_received = offset; } if (response.has_object_checksums()) { auto const& checksums = response.object_checksums(); if (checksums.has_crc32c()) { result.hashes = Merge( std::move(result.hashes), HashValues{ GrpcObjectMetadataParser::Crc32cFromProto(checksums.crc32c()), {}}); } if (!checksums.md5_hash().empty()) { result.hashes = Merge(std::move(result.hashes), HashValues{{}, GrpcObjectMetadataParser::MD5FromProto( checksums.md5_hash())}); } } if (response.has_metadata()) { auto const& metadata = response.metadata(); result.generation = result.generation.value_or(metadata.generation()); result.metageneration = result.metageneration.value_or(metadata.metageneration()); result.storage_class = result.storage_class.value_or(metadata.storage_class()); result.size = result.size.value_or(metadata.size()); } }; spill_view_ = update_buf(spill_view_); result.bytes_received = offset; while (offset < n && stream_) { auto data_future = stream_->Read(); auto state = data_future.wait_for(download_stall_timeout_); if (state != std::future_status::ready) { status_ = Status(StatusCode::kDeadlineExceeded, "Deadline exceeded waiting for data in ReadObject"); stream_->Cancel(); // Schedule a call to `Finish()` to close the stream. gRPC requires the // `Read()` call to complete before calling `Finish()`, and we do not // want to block waiting for that here. using ::google::storage::v2::ReadObjectResponse; struct CaptureByMove { std::unique_ptr<StreamingRpc> stream; void operator()(future<absl::optional<ReadObjectResponse>>) { (void)stream->Finish(); stream.reset(); } }; (void)data_future.then(CaptureByMove{std::move(stream_)}); return status_; } auto data = data_future.get(); if (!data.has_value()) { status_ = stream_->Finish().get(); auto metadata = stream_->GetRequestMetadata(); result.response.headers.insert(metadata.begin(), metadata.end()); stream_.reset(); if (!status_.ok()) return status_; return result; } update_result(std::move(*data)); } return result; } } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage } // namespace cloud } // namespace google <commit_msg>fix(GCS+gRPC): streaming RPC lifetime was too short (#9096)<commit_after>// Copyright 2019 Google LLC // // 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 // // https://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 "google/cloud/storage/internal/grpc_object_read_source.h" #include "google/cloud/storage/internal/grpc_object_metadata_parser.h" #include "absl/strings/string_view.h" #include <algorithm> #include <limits> namespace google { namespace cloud { namespace storage { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace internal { namespace { std::chrono::milliseconds DefaultDownloadStallTimeout( std::chrono::milliseconds value) { if (value != std::chrono::milliseconds(0)) return value; return std::chrono::seconds( std::numeric_limits<std::chrono::seconds::rep>::max()); } } // namespace GrpcObjectReadSource::GrpcObjectReadSource( std::unique_ptr<StreamingRpc> stream, std::chrono::milliseconds download_stall_timeout) : stream_(std::move(stream)), download_stall_timeout_( DefaultDownloadStallTimeout(download_stall_timeout)) {} StatusOr<HttpResponse> GrpcObjectReadSource::Close() { if (stream_) stream_ = nullptr; if (!status_.ok()) return status_; return HttpResponse{HttpStatusCode::kOk, {}, {}}; } /// Read more data from the download, returning any HTTP headers and error /// codes. StatusOr<ReadSourceResult> GrpcObjectReadSource::Read(char* buf, std::size_t n) { std::size_t offset = 0; auto update_buf = [&offset, buf, n](absl::string_view source) { if (source.empty()) return source; auto const nbytes = std::min(n - offset, source.size()); auto const* end = source.data() + nbytes; std::copy(source.data(), end, buf + offset); offset += nbytes; return absl::string_view(end, source.size() - nbytes); }; ReadSourceResult result; result.response.status_code = HttpStatusCode::kContinue; result.bytes_received = 0; auto update_result = [&](google::storage::v2::ReadObjectResponse response) { // The google.storage.v1.Storage documentation says this field can be // empty. if (response.has_checksummed_data()) { // Sometimes protobuf bytes are not strings, but the explicit conversion // always works. spill_ = std::string( std::move(*response.mutable_checksummed_data()->mutable_content())); spill_view_ = update_buf(spill_); result.bytes_received = offset; } if (response.has_object_checksums()) { auto const& checksums = response.object_checksums(); if (checksums.has_crc32c()) { result.hashes = Merge( std::move(result.hashes), HashValues{ GrpcObjectMetadataParser::Crc32cFromProto(checksums.crc32c()), {}}); } if (!checksums.md5_hash().empty()) { result.hashes = Merge(std::move(result.hashes), HashValues{{}, GrpcObjectMetadataParser::MD5FromProto( checksums.md5_hash())}); } } if (response.has_metadata()) { auto const& metadata = response.metadata(); result.generation = result.generation.value_or(metadata.generation()); result.metageneration = result.metageneration.value_or(metadata.metageneration()); result.storage_class = result.storage_class.value_or(metadata.storage_class()); result.size = result.size.value_or(metadata.size()); } }; spill_view_ = update_buf(spill_view_); result.bytes_received = offset; while (offset < n && stream_) { auto data_future = stream_->Read(); auto state = data_future.wait_for(download_stall_timeout_); if (state != std::future_status::ready) { status_ = Status(StatusCode::kDeadlineExceeded, "Deadline exceeded waiting for data in ReadObject"); stream_->Cancel(); // Schedule a call to `Finish()` to close the stream. gRPC requires the // `Read()` call to complete before calling `Finish()`, and we do not // want to block waiting for that here. using ::google::storage::v2::ReadObjectResponse; struct WaitForFinish { std::unique_ptr<StreamingRpc> stream; void operator()(future<Status>) {} }; struct WaitForRead { std::unique_ptr<StreamingRpc> stream; void operator()(future<absl::optional<ReadObjectResponse>>) { auto finish = stream->Finish(); (void)finish.then(WaitForFinish{std::move(stream)}); } }; (void)data_future.then(WaitForRead{std::move(stream_)}); return status_; } auto data = data_future.get(); if (!data.has_value()) { status_ = stream_->Finish().get(); auto metadata = stream_->GetRequestMetadata(); result.response.headers.insert(metadata.begin(), metadata.end()); stream_.reset(); if (!status_.ok()) return status_; return result; } update_result(std::move(*data)); } return result; } } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage } // namespace cloud } // namespace google <|endoftext|>
<commit_before>#include "account_data_view_model.hpp" #include "account.hpp" #include "../decimal_variant_data.hpp" #include "phatbooks_exceptions.hpp" #include <boost/shared_ptr.hpp> #include <jewel/debug_log.hpp> #include <jewel/decimal.hpp> #include <wx/dataview.h> #include <wx/variant.h> #include <cassert> #include <vector> using boost::shared_ptr; using jewel::Decimal; using std::vector; namespace phatbooks { namespace gui { AccountDataViewModel::AccountDataViewModel ( vector<AugmentedAccount> const& p_accounts ) { for ( vector<AugmentedAccount>::const_iterator it = p_accounts.begin(), end = p_accounts.end(); it != end; ++it ) { AugmentedAccount* augmented_account = new AugmentedAccount(*it); m_accounts.push_back(augmented_account); } } AccountDataViewModel::~AccountDataViewModel() { for ( vector<AugmentedAccount*>::iterator it = m_accounts.begin(), end = m_accounts.end(); it != end; ++it ) { delete *it; *it = 0; } } bool AccountDataViewModel::IsContainer(wxDataViewItem const& item) const { (void)item; // Silence compiler warning re. unused parameter. return false; } wxDataViewItem AccountDataViewModel::GetParent(wxDataViewItem const& item) const { // Always returns an invalid wxDataViewItem since none // of the items have parents that are not the root (void)item; // Silence compiler warning re. unused parameter. return wxDataViewItem(0); } unsigned int AccountDataViewModel::GetChildren ( wxDataViewItem const& item, wxDataViewItemArray& children ) const { if (item == wxDataViewItem(0)) { assert (!item.IsOk()); // Then the item is the root and all the AugmentedAccounts are its // children. Deliberately start counting from 1, as 0 is for an // invalid wxDataViewItem. return get_all_items(children); } return 0; } unsigned int AccountDataViewModel::GetColumnCount() const { return s_num_columns; } wxString AccountDataViewModel::GetColumnType(unsigned int col) const { switch (col) { case s_name_column: // fall through case s_account_type_column: return wxString("string"); case s_opening_balance_column: return DecimalVariantData::GetTypeStatic(); default: throw AccountDataViewModelException("Invalid column number."); } } void AccountDataViewModel::GetValue ( wxVariant& variant, wxDataViewItem const& item, unsigned int col ) const { if (!item.IsOk()) { throw AccountDataViewModelException("Invalid wxDataViewItem."); } AugmentedAccount* augmented_account = static_cast<AugmentedAccount*>(item.GetID()); if (!augmented_account) { throw AccountDataViewModelException ( "Invalid pointer to AugmentedAccount." ); } wxVariantData* data = 0; switch (col) { case s_name_column: variant = bstring_to_wx(augmented_account->account.name()); return; case s_account_type_column: variant = bstring_to_wx ( account_type_to_string(augmented_account->account.account_type()) ); return; case s_opening_balance_column: data = new DecimalVariantData ( augmented_account->technical_opening_balance ); variant.SetData(data); return; default: throw AccountDataViewModelException("Invalid column number."); } } bool AccountDataViewModel::SetValue ( wxVariant const& variant, wxDataViewItem const& item, unsigned int col ) { if (!item.IsOk()) { throw AccountDataViewModelException("Invalid wxDataViewItem."); } AugmentedAccount* augmented_account = static_cast<AugmentedAccount*>(item.GetID()); if (!augmented_account) { throw AccountDataViewModelException ( "Invalid pointer to AugmentedAccount." ); } DecimalVariantData* dvd = 0; switch (col) { case s_name_column: augmented_account->account.set_name ( wx_to_bstring(variant.GetString()) ); return true; case s_account_type_column: augmented_account->account.set_account_type ( string_to_account_type(wx_to_bstring(variant.GetString())) ); return true; case s_opening_balance_column: dvd = dynamic_cast<DecimalVariantData*>(variant.GetData()); if (!dvd) { throw AccountDataViewModelException("Wrong wxVariant type."); } augmented_account->technical_opening_balance = dvd->decimal(); return true; default: throw AccountDataViewModelException("Invalid column number."); } return false; } unsigned int AccountDataViewModel::get_all_items(wxDataViewItemArray& items) const { for ( vector<AugmentedAccount*>::const_iterator it = m_accounts.begin(), end = m_accounts.end(); it != end; ++it ) { void* item = static_cast<void*>(*it); items.Add(wxDataViewItem(item)); } return m_accounts.size(); } } // namespace gui } // namespace phatbooks <commit_msg>Added some debugging statements to try to figure out why wxDataViewCtrl showing default Accounts in SetupWizard is not being properly displayed on Windows.<commit_after>#include "account_data_view_model.hpp" #include "account.hpp" #include "../decimal_variant_data.hpp" #include "phatbooks_exceptions.hpp" #include <boost/shared_ptr.hpp> #include <jewel/decimal.hpp> #include <wx/dataview.h> #include <wx/variant.h> #include <cassert> #include <vector> using boost::shared_ptr; using jewel::Decimal; using std::vector; // For debugging #include <jewel/debug_log.hpp> #include <iostream> using std::endl; namespace phatbooks { namespace gui { AccountDataViewModel::AccountDataViewModel ( vector<AugmentedAccount> const& p_accounts ) { for ( vector<AugmentedAccount>::const_iterator it = p_accounts.begin(), end = p_accounts.end(); it != end; ++it ) { JEWEL_DEBUG_LOG << "Adding AugmentedAccount* to AccountDataViewModel " << "with Account name " << it->account.name() << endl; AugmentedAccount* augmented_account = new AugmentedAccount(*it); m_accounts.push_back(augmented_account); } } AccountDataViewModel::~AccountDataViewModel() { for ( vector<AugmentedAccount*>::iterator it = m_accounts.begin(), end = m_accounts.end(); it != end; ++it ) { delete *it; *it = 0; } } bool AccountDataViewModel::IsContainer(wxDataViewItem const& item) const { (void)item; // Silence compiler warning re. unused parameter. return false; } wxDataViewItem AccountDataViewModel::GetParent(wxDataViewItem const& item) const { // Always returns an invalid wxDataViewItem since none // of the items have parents that are not the root (void)item; // Silence compiler warning re. unused parameter. return wxDataViewItem(0); } unsigned int AccountDataViewModel::GetChildren ( wxDataViewItem const& item, wxDataViewItemArray& children ) const { if (item == wxDataViewItem(0)) { assert (!item.IsOk()); JEWEL_DEBUG_LOG << "Calling AccountDataViewModel::GetChildren" << endl; // Then the item is the root and all the AugmentedAccounts are its // children. Deliberately start counting from 1, as 0 is for an // invalid wxDataViewItem. unsigned int const ret = get_all_items(children); JEWEL_DEBUG_LOG << "Number of children gotten: " << ret << endl; return ret; } return 0; } unsigned int AccountDataViewModel::GetColumnCount() const { return s_num_columns; } wxString AccountDataViewModel::GetColumnType(unsigned int col) const { switch (col) { case s_name_column: // fall through case s_account_type_column: return wxString("string"); case s_opening_balance_column: return DecimalVariantData::GetTypeStatic(); default: throw AccountDataViewModelException("Invalid column number."); } } void AccountDataViewModel::GetValue ( wxVariant& variant, wxDataViewItem const& item, unsigned int col ) const { if (!item.IsOk()) { throw AccountDataViewModelException("Invalid wxDataViewItem."); } AugmentedAccount* augmented_account = static_cast<AugmentedAccount*>(item.GetID()); if (!augmented_account) { throw AccountDataViewModelException ( "Invalid pointer to AugmentedAccount." ); } wxVariantData* data = 0; switch (col) { case s_name_column: variant = bstring_to_wx(augmented_account->account.name()); return; case s_account_type_column: variant = bstring_to_wx ( account_type_to_string(augmented_account->account.account_type()) ); return; case s_opening_balance_column: data = new DecimalVariantData ( augmented_account->technical_opening_balance ); variant.SetData(data); return; default: throw AccountDataViewModelException("Invalid column number."); } } bool AccountDataViewModel::SetValue ( wxVariant const& variant, wxDataViewItem const& item, unsigned int col ) { if (!item.IsOk()) { throw AccountDataViewModelException("Invalid wxDataViewItem."); } AugmentedAccount* augmented_account = static_cast<AugmentedAccount*>(item.GetID()); if (!augmented_account) { throw AccountDataViewModelException ( "Invalid pointer to AugmentedAccount." ); } DecimalVariantData* dvd = 0; switch (col) { case s_name_column: augmented_account->account.set_name ( wx_to_bstring(variant.GetString()) ); return true; case s_account_type_column: augmented_account->account.set_account_type ( string_to_account_type(wx_to_bstring(variant.GetString())) ); return true; case s_opening_balance_column: dvd = dynamic_cast<DecimalVariantData*>(variant.GetData()); if (!dvd) { throw AccountDataViewModelException("Wrong wxVariant type."); } augmented_account->technical_opening_balance = dvd->decimal(); return true; default: throw AccountDataViewModelException("Invalid column number."); } return false; } unsigned int AccountDataViewModel::get_all_items(wxDataViewItemArray& items) const { for ( vector<AugmentedAccount*>::const_iterator it = m_accounts.begin(), end = m_accounts.end(); it != end; ++it ) { void* item = static_cast<void*>(*it); items.Add(wxDataViewItem(item)); } return m_accounts.size(); } } // namespace gui } // namespace phatbooks <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLEventsImportContext.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: dvo $ $Date: 2001-08-02 18:51:34 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_XMLEVENTSIMPORTCONTEXT_HXX #include "XMLEventsImportContext.hxx" #endif #ifndef _XMLOFF_XMLEVENTIMPORTHELPER_HXX #include "XMLEventImportHelper.hxx" #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP #include <com/sun/star/document/XEventsSupplier.hpp> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif using namespace ::com::sun::star::uno; using namespace ::xmloff::token; using ::rtl::OUString; using ::com::sun::star::xml::sax::XAttributeList; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::container::XNameReplace; using ::com::sun::star::document::XEventsSupplier; TYPEINIT1(XMLEventsImportContext, SvXMLImportContext); XMLEventsImportContext::XMLEventsImportContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName) : SvXMLImportContext(rImport, nPrfx, rLocalName) { } XMLEventsImportContext::XMLEventsImportContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, const Reference<XEventsSupplier> & xEventsSupplier) : SvXMLImportContext(rImport, nPrfx, rLocalName), xEvents(xEventsSupplier->getEvents()) { } XMLEventsImportContext::XMLEventsImportContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, const Reference<XNameReplace> & xNameReplace) : SvXMLImportContext(rImport, nPrfx, rLocalName), xEvents(xNameReplace) { } XMLEventsImportContext::~XMLEventsImportContext() { // // if, for whatever reason, the object gets destroyed prematurely, // // we need to delete the collected events // EventsVector::iterator aEnd = aCollectEvents.end(); // for(EventsVector::iterator aIter = aCollectEvents.begin(); // aIter != aEnd; // aIter++) // { // EventNameValuesPair* pPair = &(*aIter); // delete pPair; // } // aCollectEvents.clear(); } void XMLEventsImportContext::StartElement( const Reference<XAttributeList> & xAttrList) { // nothing to be done } void XMLEventsImportContext::EndElement() { // nothing to be done } SvXMLImportContext* XMLEventsImportContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList ) { // a) search for script:language and script:event-name attribute // b) delegate to factory. The factory will: // 1) translate XML event name into API event name // 2) get proper event context factory from import // 3) instantiate context // a) search for script:language and script:event-name attribute OUString sLanguage; OUString sEventName; sal_Int16 nCount = xAttrList->getLength(); for (sal_Int16 nAttr = 0; nAttr < nCount; nAttr++) { OUString sLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName ); if (XML_NAMESPACE_SCRIPT == nPrefix) { if (IsXMLToken(sLocalName, XML_EVENT_NAME)) { sEventName = xAttrList->getValueByIndex(nAttr); } else if (IsXMLToken(sLocalName, XML_LANGUAGE)) { sLanguage = xAttrList->getValueByIndex(nAttr); } // else: ignore -> let child context handle this } // else: ignore -> let child context handle this } // b) delegate to factory return GetImport().GetEventImport().CreateContext( GetImport(), nPrefix, rLocalName, xAttrList, this, sEventName, sLanguage); } void XMLEventsImportContext::SetEvents( const Reference<XEventsSupplier> & xEventsSupplier) { if (xEventsSupplier.is()) { SetEvents(xEventsSupplier->getEvents()); } } void XMLEventsImportContext::SetEvents( const Reference<XNameReplace> & xNameRepl) { if (xNameRepl.is()) { xEvents = xNameRepl; // now iterate over vector and a) insert b) delete all elements EventsVector::iterator aEnd = aCollectEvents.end(); for(EventsVector::iterator aIter = aCollectEvents.begin(); aIter != aEnd; aIter++) { AddEventValues(aIter->first, aIter->second); // EventNameValuesPair* pPair = &(*aIter); // delete pPair; } aCollectEvents.clear(); } } sal_Bool XMLEventsImportContext::GetEventSequence( const OUString& rName, Sequence<PropertyValue> & rSequence ) { // search through the vector // (This shouldn't take a lot of time, since this method should only get // called if only one (or few) events are being expected) // iterate over vector until end or rName is found; EventsVector::iterator aIter = aCollectEvents.begin(); while( (aIter != aCollectEvents.end()) && (aIter->first != rName) ) { aIter++; } // if we're not at the end, set the sequence sal_Bool bRet = (aIter != aCollectEvents.end()); if (bRet) rSequence = aIter->second; return bRet; } void XMLEventsImportContext::AddEventValues( const OUString& rEventName, const Sequence<PropertyValue> & rValues ) { // if we already have the events, set them; else just collect if (xEvents.is()) { // set event (if name is known) if (xEvents->hasByName(rEventName)) { Any aAny; aAny <<= rValues; xEvents->replaceByName(rEventName, aAny); } } else { // EventNameValuesPair* aPair = new EventNameValuesPair(rEventName, // rValues); // aCollectEvents.push_back(*aPair); EventNameValuesPair aPair(rEventName, rValues); aCollectEvents.push_back(aPair); } } <commit_msg>#99838# catch IllegalArgumentException in XMLEventsImportContext::AddEventValues<commit_after>/************************************************************************* * * $RCSfile: XMLEventsImportContext.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hbrinkm $ $Date: 2002-11-19 13:03:15 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_XMLEVENTSIMPORTCONTEXT_HXX #include "XMLEventsImportContext.hxx" #endif #ifndef _XMLOFF_XMLEVENTIMPORTHELPER_HXX #include "XMLEventImportHelper.hxx" #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP #include <com/sun/star/document/XEventsSupplier.hpp> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLERROR_HXX #include "xmlerror.hxx" #endif // _XMLOFF_XMLERROR_HXX using namespace ::com::sun::star::uno; using namespace ::xmloff::token; using ::rtl::OUString; using ::com::sun::star::xml::sax::XAttributeList; using ::com::sun::star::beans::PropertyValue; using ::com::sun::star::container::XNameReplace; using ::com::sun::star::document::XEventsSupplier; using ::com::sun::star::lang::IllegalArgumentException; TYPEINIT1(XMLEventsImportContext, SvXMLImportContext); XMLEventsImportContext::XMLEventsImportContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName) : SvXMLImportContext(rImport, nPrfx, rLocalName) { } XMLEventsImportContext::XMLEventsImportContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, const Reference<XEventsSupplier> & xEventsSupplier) : SvXMLImportContext(rImport, nPrfx, rLocalName), xEvents(xEventsSupplier->getEvents()) { } XMLEventsImportContext::XMLEventsImportContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, const Reference<XNameReplace> & xNameReplace) : SvXMLImportContext(rImport, nPrfx, rLocalName), xEvents(xNameReplace) { } XMLEventsImportContext::~XMLEventsImportContext() { // // if, for whatever reason, the object gets destroyed prematurely, // // we need to delete the collected events // EventsVector::iterator aEnd = aCollectEvents.end(); // for(EventsVector::iterator aIter = aCollectEvents.begin(); // aIter != aEnd; // aIter++) // { // EventNameValuesPair* pPair = &(*aIter); // delete pPair; // } // aCollectEvents.clear(); } void XMLEventsImportContext::StartElement( const Reference<XAttributeList> & xAttrList) { // nothing to be done } void XMLEventsImportContext::EndElement() { // nothing to be done } SvXMLImportContext* XMLEventsImportContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList ) { // a) search for script:language and script:event-name attribute // b) delegate to factory. The factory will: // 1) translate XML event name into API event name // 2) get proper event context factory from import // 3) instantiate context // a) search for script:language and script:event-name attribute OUString sLanguage; OUString sEventName; sal_Int16 nCount = xAttrList->getLength(); for (sal_Int16 nAttr = 0; nAttr < nCount; nAttr++) { OUString sLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName ); if (XML_NAMESPACE_SCRIPT == nPrefix) { if (IsXMLToken(sLocalName, XML_EVENT_NAME)) { sEventName = xAttrList->getValueByIndex(nAttr); } else if (IsXMLToken(sLocalName, XML_LANGUAGE)) { sLanguage = xAttrList->getValueByIndex(nAttr); } // else: ignore -> let child context handle this } // else: ignore -> let child context handle this } // b) delegate to factory return GetImport().GetEventImport().CreateContext( GetImport(), nPrefix, rLocalName, xAttrList, this, sEventName, sLanguage); } void XMLEventsImportContext::SetEvents( const Reference<XEventsSupplier> & xEventsSupplier) { if (xEventsSupplier.is()) { SetEvents(xEventsSupplier->getEvents()); } } void XMLEventsImportContext::SetEvents( const Reference<XNameReplace> & xNameRepl) { if (xNameRepl.is()) { xEvents = xNameRepl; // now iterate over vector and a) insert b) delete all elements EventsVector::iterator aEnd = aCollectEvents.end(); for(EventsVector::iterator aIter = aCollectEvents.begin(); aIter != aEnd; aIter++) { AddEventValues(aIter->first, aIter->second); // EventNameValuesPair* pPair = &(*aIter); // delete pPair; } aCollectEvents.clear(); } } sal_Bool XMLEventsImportContext::GetEventSequence( const OUString& rName, Sequence<PropertyValue> & rSequence ) { // search through the vector // (This shouldn't take a lot of time, since this method should only get // called if only one (or few) events are being expected) // iterate over vector until end or rName is found; EventsVector::iterator aIter = aCollectEvents.begin(); while( (aIter != aCollectEvents.end()) && (aIter->first != rName) ) { aIter++; } // if we're not at the end, set the sequence sal_Bool bRet = (aIter != aCollectEvents.end()); if (bRet) rSequence = aIter->second; return bRet; } void XMLEventsImportContext::AddEventValues( const OUString& rEventName, const Sequence<PropertyValue> & rValues ) { // if we already have the events, set them; else just collect if (xEvents.is()) { // set event (if name is known) if (xEvents->hasByName(rEventName)) { Any aAny; aAny <<= rValues; try { xEvents->replaceByName(rEventName, aAny); } catch ( const IllegalArgumentException & rException ) { Sequence<OUString> aMsgParams(1); aMsgParams[0] = rEventName; GetImport().SetError(XMLERROR_FLAG_ERROR | XMLERROR_ILLEGAL_EVENT, aMsgParams, rException.Message, 0); } } } else { // EventNameValuesPair* aPair = new EventNameValuesPair(rEventName, // rValues); // aCollectEvents.push_back(*aPair); EventNameValuesPair aPair(rEventName, rValues); aCollectEvents.push_back(aPair); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PageMasterImportContext.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:26:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_PAGEMASTERIMPORTCONTEXT_HXX #include "PageMasterImportContext.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_PAGEMASTERPROPHDL_HXX_ #include "PageMasterPropHdl.hxx" #endif #ifndef _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX #include "PagePropertySetContext.hxx" #endif #ifndef _XMLOFF_PAGEPHEADERFOOTERCONTEXT_HXX #include "PageHeaderFooterContext.hxx" #endif #ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX #include "PageMasterPropMapper.hxx" #endif #ifndef _XMLOFF_PAGEMASTERIMPORTPROPMAPPER_HXX #include "PageMasterImportPropMapper.hxx" #endif #ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX #include <xmloff/PageMasterStyleMap.hxx> #endif using namespace ::com::sun::star; using namespace ::xmloff::token; void PageStyleContext::SetAttribute( sal_uInt16 nPrefixKey, const rtl::OUString& rLocalName, const rtl::OUString& rValue ) { // TODO: use a map here if( XML_NAMESPACE_STYLE == nPrefixKey && IsXMLToken( rLocalName, XML_PAGE_USAGE ) ) { sPageUsage = rValue; } else { XMLPropStyleContext::SetAttribute( nPrefixKey, rLocalName, rValue ); } } TYPEINIT1( PageStyleContext, XMLPropStyleContext ); PageStyleContext::PageStyleContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLName, const uno::Reference< xml::sax::XAttributeList > & xAttrList, SvXMLStylesContext& rStyles) : XMLPropStyleContext( rImport, nPrfx, rLName, xAttrList, rStyles, XML_STYLE_FAMILY_PAGE_MASTER ), sPageUsage() { } PageStyleContext::~PageStyleContext() { } SvXMLImportContext *PageStyleContext::CreateChildContext( sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const uno::Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = NULL; if( XML_NAMESPACE_STYLE == nPrefix && ((IsXMLToken(rLocalName, XML_HEADER_STYLE )) || (IsXMLToken(rLocalName, XML_FOOTER_STYLE )) ) ) { sal_Bool bHeader = IsXMLToken(rLocalName, XML_HEADER_STYLE); UniReference < SvXMLImportPropertyMapper > xImpPrMap = GetStyles()->GetImportPropertyMapper( GetFamily() ); if( xImpPrMap.is() ) { const UniReference< XMLPropertySetMapper >& rMapper = xImpPrMap->getPropertySetMapper(); sal_Int32 nFlag; if (bHeader) nFlag = CTF_PM_HEADERFLAG; else nFlag = CTF_PM_FOOTERFLAG; sal_Int32 nStartIndex (-1); sal_Int32 nEndIndex (-1); sal_Bool bFirst(sal_False); sal_Bool bEnd(sal_False); sal_Int32 nIndex = 0; while ( nIndex < rMapper->GetEntryCount() && !bEnd) { if ((rMapper->GetEntryContextId( nIndex ) & CTF_PM_FLAGMASK) == nFlag) { if (!bFirst) { bFirst = sal_True; nStartIndex = nIndex; } } else if (bFirst) { bEnd = sal_True; nEndIndex = nIndex; } nIndex++; } if (!bEnd) nEndIndex = nIndex; pContext = new PageHeaderFooterContext(GetImport(), nPrefix, rLocalName, xAttrList, GetProperties(), xImpPrMap, nStartIndex, nEndIndex, bHeader); } } if( XML_NAMESPACE_STYLE == nPrefix && IsXMLToken(rLocalName, XML_PAGE_LAYOUT_PROPERTIES) ) { UniReference < SvXMLImportPropertyMapper > xImpPrMap = GetStyles()->GetImportPropertyMapper( GetFamily() ); if( xImpPrMap.is() ) { const UniReference< XMLPropertySetMapper >& rMapper = xImpPrMap->getPropertySetMapper(); sal_Int32 nEndIndex (-1); sal_Bool bEnd(sal_False); sal_Int32 nIndex = 0; sal_Int16 nContextID; while ( nIndex < rMapper->GetEntryCount() && !bEnd) { nContextID = rMapper->GetEntryContextId( nIndex ); if (nContextID && ((nContextID & CTF_PM_FLAGMASK) != XML_PM_CTF_START)) { nEndIndex = nIndex; bEnd = sal_True; } nIndex++; } if (!bEnd) nEndIndex = nIndex; PageContextType aType = Page; pContext = new PagePropertySetContext( GetImport(), nPrefix, rLocalName, xAttrList, XML_TYPE_PROP_PAGE_LAYOUT, GetProperties(), xImpPrMap, 0, nEndIndex, aType); } } if (!pContext) pContext = XMLPropStyleContext::CreateChildContext( nPrefix, rLocalName, xAttrList ); return pContext; } void PageStyleContext::FillPropertySet( const uno::Reference<beans::XPropertySet > & rPropSet ) { XMLPropStyleContext::FillPropertySet(rPropSet); if (sPageUsage.getLength()) { uno::Any aPageUsage; XMLPMPropHdl_PageStyleLayout aPageUsageHdl; if (aPageUsageHdl.importXML(sPageUsage, aPageUsage, GetImport().GetMM100UnitConverter())) rPropSet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PageStyleLayout")), aPageUsage); } } <commit_msg>INTEGRATION: CWS cjksp1_DEV300 (1.12.112); FILE MERGED 2007/09/27 04:28:35 pflin 1.12.112.2: RESYNC: (1.12-1.13); FILE MERGED 2007/04/23 07:58:07 pflin 1.12.112.1: Text grid enhancement: support xml filter<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PageMasterImportContext.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: kz $ $Date: 2008-03-07 16:17:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_PAGEMASTERIMPORTCONTEXT_HXX #include "PageMasterImportContext.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_PAGEMASTERPROPHDL_HXX_ #include "PageMasterPropHdl.hxx" #endif #ifndef _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX #include "PagePropertySetContext.hxx" #endif #ifndef _XMLOFF_PAGEPHEADERFOOTERCONTEXT_HXX #include "PageHeaderFooterContext.hxx" #endif #ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX #include "PageMasterPropMapper.hxx" #endif #ifndef _XMLOFF_PAGEMASTERIMPORTPROPMAPPER_HXX #include "PageMasterImportPropMapper.hxx" #endif #ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX #include <xmloff/PageMasterStyleMap.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif using namespace ::com::sun::star; using namespace ::xmloff::token; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; void PageStyleContext::SetAttribute( sal_uInt16 nPrefixKey, const rtl::OUString& rLocalName, const rtl::OUString& rValue ) { // TODO: use a map here if( XML_NAMESPACE_STYLE == nPrefixKey && IsXMLToken( rLocalName, XML_PAGE_USAGE ) ) { sPageUsage = rValue; } else { XMLPropStyleContext::SetAttribute( nPrefixKey, rLocalName, rValue ); } } TYPEINIT1( PageStyleContext, XMLPropStyleContext ); PageStyleContext::PageStyleContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const rtl::OUString& rLName, const uno::Reference< xml::sax::XAttributeList > & xAttrList, SvXMLStylesContext& rStyles, sal_Bool bDefaultStyle) : XMLPropStyleContext( rImport, nPrfx, rLName, xAttrList, rStyles, XML_STYLE_FAMILY_PAGE_MASTER, bDefaultStyle), sPageUsage() { } PageStyleContext::~PageStyleContext() { } SvXMLImportContext *PageStyleContext::CreateChildContext( sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const uno::Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = NULL; if( XML_NAMESPACE_STYLE == nPrefix && ((IsXMLToken(rLocalName, XML_HEADER_STYLE )) || (IsXMLToken(rLocalName, XML_FOOTER_STYLE )) ) ) { sal_Bool bHeader = IsXMLToken(rLocalName, XML_HEADER_STYLE); UniReference < SvXMLImportPropertyMapper > xImpPrMap = GetStyles()->GetImportPropertyMapper( GetFamily() ); if( xImpPrMap.is() ) { const UniReference< XMLPropertySetMapper >& rMapper = xImpPrMap->getPropertySetMapper(); sal_Int32 nFlag; if (bHeader) nFlag = CTF_PM_HEADERFLAG; else nFlag = CTF_PM_FOOTERFLAG; sal_Int32 nStartIndex (-1); sal_Int32 nEndIndex (-1); sal_Bool bFirst(sal_False); sal_Bool bEnd(sal_False); sal_Int32 nIndex = 0; while ( nIndex < rMapper->GetEntryCount() && !bEnd) { if ((rMapper->GetEntryContextId( nIndex ) & CTF_PM_FLAGMASK) == nFlag) { if (!bFirst) { bFirst = sal_True; nStartIndex = nIndex; } } else if (bFirst) { bEnd = sal_True; nEndIndex = nIndex; } nIndex++; } if (!bEnd) nEndIndex = nIndex; pContext = new PageHeaderFooterContext(GetImport(), nPrefix, rLocalName, xAttrList, GetProperties(), xImpPrMap, nStartIndex, nEndIndex, bHeader); } } if( XML_NAMESPACE_STYLE == nPrefix && IsXMLToken(rLocalName, XML_PAGE_LAYOUT_PROPERTIES) ) { UniReference < SvXMLImportPropertyMapper > xImpPrMap = GetStyles()->GetImportPropertyMapper( GetFamily() ); if( xImpPrMap.is() ) { const UniReference< XMLPropertySetMapper >& rMapper = xImpPrMap->getPropertySetMapper(); sal_Int32 nEndIndex (-1); sal_Bool bEnd(sal_False); sal_Int32 nIndex = 0; sal_Int16 nContextID; while ( nIndex < rMapper->GetEntryCount() && !bEnd) { nContextID = rMapper->GetEntryContextId( nIndex ); if (nContextID && ((nContextID & CTF_PM_FLAGMASK) != XML_PM_CTF_START)) { nEndIndex = nIndex; bEnd = sal_True; } nIndex++; } if (!bEnd) nEndIndex = nIndex; PageContextType aType = Page; pContext = new PagePropertySetContext( GetImport(), nPrefix, rLocalName, xAttrList, XML_TYPE_PROP_PAGE_LAYOUT, GetProperties(), xImpPrMap, 0, nEndIndex, aType); } } if (!pContext) pContext = XMLPropStyleContext::CreateChildContext( nPrefix, rLocalName, xAttrList ); return pContext; } void PageStyleContext::FillPropertySet( const uno::Reference<beans::XPropertySet > & rPropSet ) { XMLPropStyleContext::FillPropertySet(rPropSet); if (sPageUsage.getLength()) { uno::Any aPageUsage; XMLPMPropHdl_PageStyleLayout aPageUsageHdl; if (aPageUsageHdl.importXML(sPageUsage, aPageUsage, GetImport().GetMM100UnitConverter())) rPropSet->setPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PageStyleLayout")), aPageUsage); } } // text grid enhancement for better CJK support //set default page layout style void PageStyleContext::SetDefaults( ) { Reference < XMultiServiceFactory > xFactory ( GetImport().GetModel(), UNO_QUERY); if (xFactory.is()) { Reference < XInterface > xInt = xFactory->createInstance ( rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.Defaults" ) ) ); Reference < beans::XPropertySet > xProperties ( xInt, UNO_QUERY ); if ( xProperties.is() ) FillPropertySet ( xProperties ); } } <|endoftext|>
<commit_before>#ifndef VIENNAGRID_ELEMENT_VIEW_HPP #define VIENNAGRID_ELEMENT_VIEW_HPP /* ======================================================================= Copyright (c) 2011-2012, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- Authors: Karl Rupp [email protected] Josef Weinbub [email protected] (A list of additional contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #include "viennagrid/element/element.hpp" #include "viennagrid/domain/geometric_domain.hpp" /** @file element.hpp @brief Provides the main n-cell type */ namespace viennagrid { namespace result_of { template <typename something, typename element_type_or_tag, typename view_container_tag = storage::std_deque_tag> struct element_view { typedef typename element_range<something, element_type_or_tag>::type::base_container_type base_container_type; typedef typename storage::result_of::view<base_container_type, view_container_tag>::type type; }; template <typename something, typename element_type_or_tag, typename view_container_tag = storage::std_deque_tag> struct const_element_view { typedef typename const_element_range<something, element_type_or_tag>::type::base_container_type base_container_type; typedef typename storage::result_of::view<const base_container_type, view_container_tag>::type type; }; } template<typename element_type_or_tag, typename something, typename functor> typename result_of::element_view<something, element_type_or_tag>::type element_view( something & s, functor f ) { typedef typename result_of::element_tag<element_type_or_tag>::type element_tag; typedef typename result_of::element<something, element_tag>::type ElementType; typedef typename result_of::element_range<something, element_tag>::type RangeType; typedef typename result_of::hook_iterator<RangeType>::type IteratorType; RangeType range = viennagrid::elements<element_tag>(s); typename result_of::element_view<something, element_tag>::type view; view.set_base_container( *range.get_base_container() ); for ( IteratorType it = range.begin(); it != range.end(); ++it ) { ElementType const & element = viennagrid::dereference_hook(s, *it); if ( f(element) ) view.insert_hook( *it ); } return view; } template<typename element_type_or_tag, typename something, typename functor> typename result_of::const_element_view<something, element_type_or_tag>::type element_view( something const & s, functor f ) { typedef typename result_of::element_tag<element_type_or_tag>::type element_tag; typedef typename result_of::element<something, element_tag>::type ElementType; typedef typename result_of::const_element_range<something, element_tag>::type RangeType; typedef typename result_of::hook_iterator<RangeType>::type IteratorType; RangeType range = viennagrid::elements<element_tag>(s); typename result_of::element_view<something, element_tag>::type view; view.set_base_container( *range.get_base_container() ); for ( IteratorType it = range.begin(); it != range.end(); ++it ) { ElementType const & element = viennagrid::dereference_hook(s, *it); if ( f(element) ) view.insert_hook( *it ); } return view; } } #endif <commit_msg>added element view without functor<commit_after>#ifndef VIENNAGRID_ELEMENT_VIEW_HPP #define VIENNAGRID_ELEMENT_VIEW_HPP /* ======================================================================= Copyright (c) 2011-2012, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- Authors: Karl Rupp [email protected] Josef Weinbub [email protected] (A list of additional contributors can be found in the PDF manual) License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #include "viennagrid/element/element.hpp" #include "viennagrid/domain/geometric_domain.hpp" /** @file element.hpp @brief Provides the main n-cell type */ namespace viennagrid { namespace result_of { template <typename something, typename element_type_or_tag, typename view_container_tag = storage::std_deque_tag> struct element_view { typedef typename element_range<something, element_type_or_tag>::type::base_container_type base_container_type; typedef typename storage::result_of::view<base_container_type, view_container_tag>::type type; }; template <typename something, typename element_type_or_tag, typename view_container_tag = storage::std_deque_tag> struct const_element_view { typedef typename const_element_range<something, element_type_or_tag>::type::base_container_type base_container_type; typedef typename storage::result_of::view<const base_container_type, view_container_tag>::type type; }; } template<typename element_type_or_tag, typename something> typename result_of::element_view<something, element_type_or_tag>::type element_view( something & s ) { typedef typename result_of::element_tag<element_type_or_tag>::type element_tag; typedef typename result_of::element<something, element_tag>::type element_type; typename result_of::element_view<something, element_tag>::type view; view.set_base_container( viennagrid::storage::collection::get<element_type>(viennagrid::container_collection(s)) ); return view; } template<typename element_type_or_tag, typename something, typename functor> typename result_of::element_view<something, element_type_or_tag>::type element_view( something & s, functor f ) { typedef typename result_of::element_tag<element_type_or_tag>::type element_tag; typedef typename result_of::element<something, element_tag>::type ElementType; typedef typename result_of::element_range<something, element_tag>::type RangeType; typedef typename result_of::hook_iterator<RangeType>::type IteratorType; RangeType range = viennagrid::elements<element_tag>(s); typename result_of::element_view<something, element_tag>::type view; view.set_base_container( *range.get_base_container() ); for ( IteratorType it = range.begin(); it != range.end(); ++it ) { ElementType const & element = viennagrid::dereference_hook(s, *it); if ( f(element) ) view.insert_hook( *it ); } return view; } template<typename element_type_or_tag, typename something, typename functor> typename result_of::const_element_view<something, element_type_or_tag>::type element_view( something const & s, functor f ) { typedef typename result_of::element_tag<element_type_or_tag>::type element_tag; typedef typename result_of::element<something, element_tag>::type ElementType; typedef typename result_of::const_element_range<something, element_tag>::type RangeType; typedef typename result_of::hook_iterator<RangeType>::type IteratorType; RangeType range = viennagrid::elements<element_tag>(s); typename result_of::element_view<something, element_tag>::type view; view.set_base_container( *range.get_base_container() ); for ( IteratorType it = range.begin(); it != range.end(); ++it ) { ElementType const & element = viennagrid::dereference_hook(s, *it); if ( f(element) ) view.insert_hook( *it ); } return view; } } #endif <|endoftext|>
<commit_before>/** @file @brief Implementation for class that tracks and identifies LEDs. @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. // Internal Includes #include "BeaconBasedPoseEstimator.h" // Library/third-party includes #include <osvr/Util/QuatlibInteropC.h> // Standard includes // - none namespace osvr { namespace vbtracker { // clang-format off // Default 3D locations for the beacons on an OSVR HDK face plate, in // millimeters const DoubleVecVec OsvrHdkLedLocations_SENSOR0 = { {-85, 3, 24.09}, { -83.2, -14.01, 13.89 }, { -47, 51, 24.09 }, { 47, 51, 24.09 }, { 86.6, 2.65, 24.09 }, { 85.5, -14.31, 13.89 }, { 85.2, 19.68, 13.89 }, { 21, 51, 24.09 }, // Original spec was 13.09, new position works better { -21, 51, 24.09 }, // Original spec was 13.09, new position works better { -84.2, 19.99, 13.89 }, { -60.41, 47.55, 44.6 }, { -80.42, 20.48, 42.9 }, { -82.01, 2.74, 42.4 }, { -80.42, -14.99, 42.9 }, { -60.41, -10.25, 48.1 }, { -60.41, 15.75, 48.1 }, { -30.41, 32.75, 50.5 }, { -31.41, 47.34, 47 }, { -0.41, -15.25, 51.3 }, { -30.41, -27.25, 50.5 }, { -60.44, -41.65, 45.1 }, { -22.41, -41.65, 47.8 }, { 21.59, -41.65, 47.8 }, { 59.59, -41.65, 45.1 }, { 79.63, -14.98, 42.9 }, { 29.59, -27.25, 50.5 }, { 81.19, 2.74, 42.4 }, { 79.61, 20.48, 42.9 }, { 59.59, 47.55, 44.6 }, { 30.59, 47.55, 47 }, { 29.59, 32.75, 50.5 }, { -0.41, 20.75, 51.3 }, { 59.59, 15.75, 48.1 }, { 59.59, -10.25, 48.1 } }; // Default 3D locations for the beacons on an OSVR HDK back plate, in // millimeters const DoubleVecVec OsvrHdkLedLocations_SENSOR1 = { {1, 23.8, 0}, { 11, 5.8, 0 }, { 9, -23.8, 0 }, { 0, -8.8, 0 }, { -9, -23.8, 0 }, { -12, 5.8, 0 } }; // clang-format on BeaconBasedPoseEstimator::BeaconBasedPoseEstimator( const DoubleVecVec &cameraMatrix, const std::vector<double> &distCoeffs, const DoubleVecVec &beacons, size_t requiredInliers, size_t permittedOutliers) { SetBeacons(beacons); SetCameraMatrix(cameraMatrix); SetDistCoeffs(distCoeffs); m_gotPose = false; m_requiredInliers = requiredInliers; m_permittedOutliers = permittedOutliers; } bool BeaconBasedPoseEstimator::SetBeacons(const DoubleVecVec &beacons) { // Our existing pose won't match anymore. m_gotPose = false; for (int i = 0; i < beacons.size(); i++) { if (beacons[i].size() != 3) { m_beacons.clear(); return false; } cv::Point3f p(static_cast<float>(beacons[i][0]), static_cast<float>(beacons[i][1]), static_cast<float>(beacons[i][2])); m_beacons.push_back(p); } return true; } bool BeaconBasedPoseEstimator::SetCameraMatrix( const DoubleVecVec &cameraMatrix) { // Our existing pose won't match anymore. m_gotPose = false; // Construct the camera matrix from the vectors we received. if (cameraMatrix.size() != 3) { return false; } for (size_t i = 0; i < cameraMatrix.size(); i++) { if (cameraMatrix[i].size() != 3) { return false; } } cv::Mat newCameraMatrix(static_cast<int>(cameraMatrix.size()), static_cast<int>(cameraMatrix[0].size()), CV_64F); for (int i = 0; i < cameraMatrix.size(); i++) { for (int j = 0; j < cameraMatrix[i].size(); j++) { newCameraMatrix.at<double>(i, j) = cameraMatrix[i][j]; } } m_cameraMatrix = newCameraMatrix; // std::cout << "XXX cameraMatrix =" << std::endl << m_cameraMatrix // << std::endl; return true; } bool BeaconBasedPoseEstimator::SetDistCoeffs( const std::vector<double> &distCoeffs) { // Our existing pose won't match anymore. m_gotPose = false; // Construct the distortion matrix from the vectors we received. if (distCoeffs.size() < 5) { return false; } cv::Mat newDistCoeffs(static_cast<int>(distCoeffs.size()), 1, CV_64F); for (int i = 0; i < distCoeffs.size(); i++) { newDistCoeffs.at<double>(i, 0) = distCoeffs[i]; } m_distCoeffs = newDistCoeffs; // std::cout << "XXX distCoeffs =" << std::endl << m_distCoeffs << // std::endl; return true; } bool BeaconBasedPoseEstimator::EstimatePoseFromLeds(const LedGroup &leds, OSVR_PoseState &outPose) { auto ret = m_estimatePoseFromLeds(leds, outPose); m_gotPose = ret; return ret; } bool BeaconBasedPoseEstimator::m_estimatePoseFromLeds(const LedGroup &leds, OSVR_PoseState &outPose) { // We need to get a pair of matched vectors of points: 2D locations // with in the image and 3D locations in model space. There needs to // be a correspondence between the points in these vectors, such that // the ith element in one matches the ith element in the other. We // make these by looking up the locations of LEDs with known identifiers // and pushing both onto the vectors at the same time. std::vector<cv::Point3f> objectPoints; std::vector<cv::Point2f> imagePoints; auto const beaconsSize = m_beacons.size(); for (auto const &led : leds) { if (!led.identified()) { continue; } auto id = led.getID(); if (id < beaconsSize) { imagePoints.push_back(led.getLocation()); objectPoints.push_back(m_beacons[id]); } } // Make sure we have enough points to do our estimation. if (objectPoints.size() < m_permittedOutliers + m_requiredInliers) { return false; } // Produce an estimate of the translation and rotation needed to take // points from model space into camera space. We allow for at most // m_permittedOutliers outliers. Even in simulation data, we sometimes // find duplicate IDs for LEDs, indicating that we are getting // mis-identified ones sometimes. // We tried using the previous guess to reduce the amount of computation // being done, but this got us stuck in infinite locations. We seem to // do okay without using it, so leaving it out. // @todo Make number of iterations into a parameter. bool usePreviousGuess = false; int iterationsCount = 5; cv::Mat inlierIndices; cv::solvePnPRansac( objectPoints, imagePoints, m_cameraMatrix, m_distCoeffs, m_rvec, m_tvec, usePreviousGuess, iterationsCount, 8.0f, static_cast<int>(objectPoints.size() - m_permittedOutliers), inlierIndices); //========================================================================== // Make sure we got all the inliers we needed. Otherwise, reject this // pose. if (inlierIndices.rows < m_requiredInliers) { return false; } //========================================================================== // Convert this into an OSVR representation of the transformation that // gives the pose of the HDK origin in the camera coordinate system, // switching units to meters and encoding the angle in a unit // quaternion. // The matrix described by rvec and tvec takes points in model space // (the space where the LEDs are defined, which is in mm away from an // implied origin) into a coordinate system where the center is at the // camera's origin, with X to the right, Y down, and Z in the direction // that the camera is facing (but still in the original units of mm): // |Xc| |r11 r12 r13 t1| |Xm| // |Yc| = |r21 r22 r23 t2|*|Ym| // |Zc| |r31 r32 r33 t3| |Zm| // |1 | // That is, it rotates into the camera coordinate system and then adds // the translation, which is in the camera coordinate system. // This is the transformation we want, since it reports the sensor's // position and orientation in camera space, except that we want to // convert // the units into meters and the orientation into a Quaternion. // NOTE: This is a right-handed coordinate system with X pointing // towards the right from the camera center of projection, Y pointing // down, and Z pointing along the camera viewing direction. // Compose the transform in original units. // We start by making a 3x3 rotation matrix out of the rvec, which // is done by a function that for some reason is named Rodrigues. cv::Mat rot; cv::Rodrigues(m_rvec, rot); // @todo: Replace this code with Eigen code. if (rot.type() != CV_64F) { return false; } // Get the forward transform q_xyz_quat_type forward; forward.xyz[Q_X] = m_tvec.at<double>(0); forward.xyz[Q_Y] = m_tvec.at<double>(1); forward.xyz[Q_Z] = m_tvec.at<double>(2); // Fill in a 4x4 matrix that starts as the identity // matrix with the 3x3 part from the rotation matrix. q_matrix_type rot4x4; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if ((i < 3) && (j < 3)) { rot4x4[i][j] = rot.at<double>(i, j); } else { if (i == j) { rot4x4[i][j] = 1; } else { rot4x4[i][j] = 0; } } } } q_from_row_matrix(forward.quat, rot4x4); // Scale to meters q_vec_scale(forward.xyz, 1e-3, forward.xyz); //============================================================== // Put into OSVR format. osvrPose3FromQuatlib(&outPose, &forward); return true; } bool BeaconBasedPoseEstimator::ProjectBeaconsToImage( std::vector<cv::Point2f> &out) { // Make sure we have a pose. Otherwise, we can't do anything. if (!m_gotPose) { return false; } cv::projectPoints(m_beacons, m_rvec, m_tvec, m_cameraMatrix, m_distCoeffs, out); return true; } } // End namespace vbtracker } // End namespace osvr <commit_msg>Converting the transformation from OpenCV into one that matches what we expect for the HDK in OSVR. This has the camera at the origin and the HDK looking straight at it.<commit_after>/** @file @brief Implementation for class that tracks and identifies LEDs. @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. // Internal Includes #include "BeaconBasedPoseEstimator.h" // Library/third-party includes #include <osvr/Util/QuatlibInteropC.h> // Standard includes // - none namespace osvr { namespace vbtracker { // clang-format off // Default 3D locations for the beacons on an OSVR HDK face plate, in // millimeters const DoubleVecVec OsvrHdkLedLocations_SENSOR0 = { {-85, 3, 24.09}, { -83.2, -14.01, 13.89 }, { -47, 51, 24.09 }, { 47, 51, 24.09 }, { 86.6, 2.65, 24.09 }, { 85.5, -14.31, 13.89 }, { 85.2, 19.68, 13.89 }, { 21, 51, 24.09 }, // Original spec was 13.09, new position works better { -21, 51, 24.09 }, // Original spec was 13.09, new position works better { -84.2, 19.99, 13.89 }, { -60.41, 47.55, 44.6 }, { -80.42, 20.48, 42.9 }, { -82.01, 2.74, 42.4 }, { -80.42, -14.99, 42.9 }, { -60.41, -10.25, 48.1 }, { -60.41, 15.75, 48.1 }, { -30.41, 32.75, 50.5 }, { -31.41, 47.34, 47 }, { -0.41, -15.25, 51.3 }, { -30.41, -27.25, 50.5 }, { -60.44, -41.65, 45.1 }, { -22.41, -41.65, 47.8 }, { 21.59, -41.65, 47.8 }, { 59.59, -41.65, 45.1 }, { 79.63, -14.98, 42.9 }, { 29.59, -27.25, 50.5 }, { 81.19, 2.74, 42.4 }, { 79.61, 20.48, 42.9 }, { 59.59, 47.55, 44.6 }, { 30.59, 47.55, 47 }, { 29.59, 32.75, 50.5 }, { -0.41, 20.75, 51.3 }, { 59.59, 15.75, 48.1 }, { 59.59, -10.25, 48.1 } }; // Default 3D locations for the beacons on an OSVR HDK back plate, in // millimeters const DoubleVecVec OsvrHdkLedLocations_SENSOR1 = { {1, 23.8, 0}, { 11, 5.8, 0 }, { 9, -23.8, 0 }, { 0, -8.8, 0 }, { -9, -23.8, 0 }, { -12, 5.8, 0 } }; // clang-format on BeaconBasedPoseEstimator::BeaconBasedPoseEstimator( const DoubleVecVec &cameraMatrix, const std::vector<double> &distCoeffs, const DoubleVecVec &beacons, size_t requiredInliers, size_t permittedOutliers) { SetBeacons(beacons); SetCameraMatrix(cameraMatrix); SetDistCoeffs(distCoeffs); m_gotPose = false; m_requiredInliers = requiredInliers; m_permittedOutliers = permittedOutliers; } bool BeaconBasedPoseEstimator::SetBeacons(const DoubleVecVec &beacons) { // Our existing pose won't match anymore. m_gotPose = false; for (int i = 0; i < beacons.size(); i++) { if (beacons[i].size() != 3) { m_beacons.clear(); return false; } cv::Point3f p(static_cast<float>(beacons[i][0]), static_cast<float>(beacons[i][1]), static_cast<float>(beacons[i][2])); m_beacons.push_back(p); } return true; } bool BeaconBasedPoseEstimator::SetCameraMatrix( const DoubleVecVec &cameraMatrix) { // Our existing pose won't match anymore. m_gotPose = false; // Construct the camera matrix from the vectors we received. if (cameraMatrix.size() != 3) { return false; } for (size_t i = 0; i < cameraMatrix.size(); i++) { if (cameraMatrix[i].size() != 3) { return false; } } cv::Mat newCameraMatrix(static_cast<int>(cameraMatrix.size()), static_cast<int>(cameraMatrix[0].size()), CV_64F); for (int i = 0; i < cameraMatrix.size(); i++) { for (int j = 0; j < cameraMatrix[i].size(); j++) { newCameraMatrix.at<double>(i, j) = cameraMatrix[i][j]; } } m_cameraMatrix = newCameraMatrix; // std::cout << "XXX cameraMatrix =" << std::endl << m_cameraMatrix // << std::endl; return true; } bool BeaconBasedPoseEstimator::SetDistCoeffs( const std::vector<double> &distCoeffs) { // Our existing pose won't match anymore. m_gotPose = false; // Construct the distortion matrix from the vectors we received. if (distCoeffs.size() < 5) { return false; } cv::Mat newDistCoeffs(static_cast<int>(distCoeffs.size()), 1, CV_64F); for (int i = 0; i < distCoeffs.size(); i++) { newDistCoeffs.at<double>(i, 0) = distCoeffs[i]; } m_distCoeffs = newDistCoeffs; // std::cout << "XXX distCoeffs =" << std::endl << m_distCoeffs << // std::endl; return true; } bool BeaconBasedPoseEstimator::EstimatePoseFromLeds(const LedGroup &leds, OSVR_PoseState &outPose) { auto ret = m_estimatePoseFromLeds(leds, outPose); m_gotPose = ret; return ret; } bool BeaconBasedPoseEstimator::m_estimatePoseFromLeds(const LedGroup &leds, OSVR_PoseState &outPose) { // We need to get a pair of matched vectors of points: 2D locations // with in the image and 3D locations in model space. There needs to // be a correspondence between the points in these vectors, such that // the ith element in one matches the ith element in the other. We // make these by looking up the locations of LEDs with known identifiers // and pushing both onto the vectors at the same time. std::vector<cv::Point3f> objectPoints; std::vector<cv::Point2f> imagePoints; auto const beaconsSize = m_beacons.size(); for (auto const &led : leds) { if (!led.identified()) { continue; } auto id = led.getID(); if (id < beaconsSize) { imagePoints.push_back(led.getLocation()); objectPoints.push_back(m_beacons[id]); } } // Make sure we have enough points to do our estimation. if (objectPoints.size() < m_permittedOutliers + m_requiredInliers) { return false; } // Produce an estimate of the translation and rotation needed to take // points from model space into camera space. We allow for at most // m_permittedOutliers outliers. Even in simulation data, we sometimes // find duplicate IDs for LEDs, indicating that we are getting // mis-identified ones sometimes. // We tried using the previous guess to reduce the amount of computation // being done, but this got us stuck in infinite locations. We seem to // do okay without using it, so leaving it out. // @todo Make number of iterations into a parameter. bool usePreviousGuess = false; int iterationsCount = 5; cv::Mat inlierIndices; cv::solvePnPRansac( objectPoints, imagePoints, m_cameraMatrix, m_distCoeffs, m_rvec, m_tvec, usePreviousGuess, iterationsCount, 8.0f, static_cast<int>(objectPoints.size() - m_permittedOutliers), inlierIndices); //========================================================================== // Make sure we got all the inliers we needed. Otherwise, reject this // pose. if (inlierIndices.rows < m_requiredInliers) { return false; } //========================================================================== // Reproject the inliers into the image and make sure they are actually // close to the expected location; otherwise, we have a bad pose. if (inlierIndices.rows > 0) { std::vector<cv::Point3f> inlierObjectPoints; std::vector<cv::Point2f> inlierImagePoints; for (int i = 0; i < inlierIndices.rows; i++) { inlierObjectPoints.push_back(objectPoints[i]); inlierImagePoints.push_back(imagePoints[i]); } std::vector<cv::Point2f> reprojectedPoints; cv::projectPoints(inlierObjectPoints, m_rvec, m_tvec, m_cameraMatrix, m_distCoeffs, reprojectedPoints); for (size_t i = 0; i < reprojectedPoints.size(); i++) { if (reprojectedPoints[i].x - inlierImagePoints[i].x > 4) { return false; } if (reprojectedPoints[i].y - inlierImagePoints[i].y > 4) { return false; } } } //========================================================================== // Convert this into an OSVR representation of the transformation that // gives the pose of the HDK origin in the camera coordinate system, // switching units to meters and encoding the angle in a unit // quaternion. // The matrix described by rvec and tvec takes points in model space // (the space where the LEDs are defined, which is in mm away from an // implied origin) into a coordinate system where the center is at the // camera's origin, with X to the right, Y down, and Z in the direction // that the camera is facing (but still in the original units of mm): // |Xc| |r11 r12 r13 t1| |Xm| // |Yc| = |r21 r22 r23 t2|*|Ym| // |Zc| |r31 r32 r33 t3| |Zm| // |1 | // That is, it rotates into the camera coordinate system and then adds // the translation, which is in the camera coordinate system. // This is the transformation we want, since it reports the sensor's // position and orientation in camera space, except that we want to // convert // the units into meters and the orientation into a Quaternion. // NOTE: This is a right-handed coordinate system with X pointing // towards the right from the camera center of projection, Y pointing // down, and Z pointing along the camera viewing direction. //========================================================================== // When we do what is described above, the X, Y, and Z axes are the inverse // of what we'd like to have (we'd like to have X right, Y up, and Z // into the screen for the basic HDK). So we invert the translation // and rotation, which is like switching the axes. m_tvec.at<double>(0) *= -1; m_tvec.at<double>(1) *= -1; m_tvec.at<double>(2) *= -1; m_rvec.at<double>(0) *= -1; m_rvec.at<double>(1) *= -1; m_rvec.at<double>(2) *= -1; // Compose the transform in original units. // We start by making a 3x3 rotation matrix out of the rvec, which // is done by a function that for some reason is named Rodrigues. cv::Mat rot; cv::Rodrigues(m_rvec, rot); // @todo: Replace this code with Eigen code. if (rot.type() != CV_64F) { return false; } // Get the forward transform // Scale to meters q_xyz_quat_type forward; forward.xyz[Q_X] = m_tvec.at<double>(0); forward.xyz[Q_Y] = m_tvec.at<double>(1); forward.xyz[Q_Z] = m_tvec.at<double>(2); q_vec_scale(forward.xyz, 1e-3, forward.xyz); // Fill in a 4x4 matrix that starts as the identity // matrix with the 3x3 part from the rotation matrix. q_matrix_type rot4x4; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if ((i < 3) && (j < 3)) { rot4x4[i][j] = rot.at<double>(i, j); } else { if (i == j) { rot4x4[i][j] = 1; } else { rot4x4[i][j] = 0; } } } } q_from_row_matrix(forward.quat, rot4x4); //============================================================== // When we do all of that, we end up with translation in Y // being backwards, and also rotations about X and Z being // backwards. Not sure why that is, but we correct it here. // @todo Figure out what is going on that this is wrong. forward.xyz[Q_Y] *= -1; forward.quat[Q_X] *= -1; forward.quat[Q_Z] *= -1; //============================================================== // Put into OSVR format. osvrPose3FromQuatlib(&outPose, &forward); return true; } bool BeaconBasedPoseEstimator::ProjectBeaconsToImage( std::vector<cv::Point2f> &out) { // Make sure we have a pose. Otherwise, we can't do anything. if (!m_gotPose) { return false; } cv::projectPoints(m_beacons, m_rvec, m_tvec, m_cameraMatrix, m_distCoeffs, out); return true; } } // End namespace vbtracker } // End namespace osvr <|endoftext|>
<commit_before><commit_msg>SingleSplitView: survive minimize / restore when resize changes leading bounds. BUG=16855<commit_after><|endoftext|>
<commit_before><commit_msg>a.cpp<commit_after>#include <iostream> <|endoftext|>
<commit_before>#include <pcl/ModelCoefficients.h> #include <pcl/sample_consensus/method_types.h> #include <pcl/sample_consensus/model_types.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/filters/extract_indices.h> #include <pcl/sample_consensus/ransac.h> #include <pcl/sample_consensus/sac_model_line.h> #include <pcl/sample_consensus/sac_model_plane.h> #include <pcl/features/normal_3d.h> #include <pcl/surface/gp3.h> #include "align.h" //using namespace std; int planeFitting (pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_raw, pcl::PointCloud<pcl::PointXYZRGB>::Ptr &final, float threshold) { //pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_raw(new pcl::PointCloud<pcl::PointXYZRGB>); //pcl::PointCloud<pcl::PointXYZRGB>::Ptr final (new pcl::PointCloud<pcl::PointXYZRGB>); pcl::PointCloud<pcl::PointXYZRGB>::Ptr filtered ( new pcl::PointCloud<pcl::PointXYZRGB> (*cloud_raw)); pcl::PointCloud<pcl::PointXYZRGB>::Ptr tmp1 ( new pcl::PointCloud<pcl::PointXYZRGB>); pcl::PointCloud<pcl::PointXYZRGB>::Ptr tmp2 ( new pcl::PointCloud<pcl::PointXYZRGB>); pcl::PointCloud<pcl::PointXYZRGB>::Ptr proj ( new pcl::PointCloud<pcl::PointXYZRGB>); vector<Eigen::VectorXf, Eigen::aligned_allocator<Eigen::VectorXf> > model_buffer; pcl::ExtractIndices<pcl::PointXYZRGB> extract; pcl::ExtractIndices<pcl::Normal> extract_n; std::vector<int> inliers; //filtered=cloud_raw; ///////////////////////////////////////////////////////// int points_num = cloud_raw->size (); // normal estimation pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne; ne.setInputCloud (cloud_raw); pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree ( new pcl::search::KdTree<pcl::PointXYZRGB> ()); ne.setSearchMethod (tree); pcl::PointCloud<pcl::Normal>::Ptr cloud_normals ( new pcl::PointCloud<pcl::Normal>); ne.setRadiusSearch (0.01); ne.compute (*cloud_normals); pcl::SampleConsensusModelPlane<pcl::PointXYZRGB>::Ptr model_q ( new pcl::SampleConsensusModelPlane<pcl::PointXYZRGB> (cloud_raw)); int count = 0; while (filtered->size () > 0.2 * points_num) { std::vector<int> inliers1; // ransac_plane model pcl::SampleConsensusModelPlane<pcl::PointXYZRGB>::Ptr model_p ( new pcl::SampleConsensusModelPlane<pcl::PointXYZRGB> (filtered)); pcl::RandomSampleConsensus<pcl::PointXYZRGB> ransac (model_p); ransac.setDistanceThreshold (threshold); ransac.computeModel (); ransac.getInliers (inliers); Eigen::VectorXf model_coefficients; ransac.getModelCoefficients (model_coefficients); // second selection of inliers //model_p->selectWithinDistance (model_coefficients, atof(argv[2]), inliers); //plane coefficients already normalized if (0) { cout << model_coefficients[0] << " " << model_coefficients[1] << " " << model_coefficients[2] << " " << model_coefficients[3] << endl; } //std::vector<int> inliers_true; // find the true inliers by using the norm check count++; // double check- norm check // TODO std::vector<int> inliers_true; for (int k = 0; k < inliers.size (); k++) { int i = inliers[k]; Eigen::Vector3f norm; norm[0] = cloud_normals->points[i].normal[0]; norm[1] = cloud_normals->points[i].normal[1]; norm[2] = cloud_normals->points[i].normal[2]; double test_cosine = norm.head<3> ().dot (model_coefficients.head<3> ()); double angular_tolerance = 0.15; double upper_limit = 1 + angular_tolerance; double lower_limit = 1 - angular_tolerance; // norm check if ( ( (test_cosine < upper_limit) && (test_cosine > lower_limit)) || ( (test_cosine > -upper_limit) && (test_cosine < -lower_limit))) inliers_true.push_back (i); } cout << inliers.size () << " " << inliers_true.size () << endl; //model_p->computeModelCoefficients (inliers_true, model_coefficients); model_p->optimizeModelCoefficients (inliers_true, model_coefficients, model_coefficients); model_buffer.push_back (model_coefficients); // projection //TODO /*for (int i=0;i<points_num;i++) { double distance=abs(model_coefficients[0]*(cloud_raw->points[i].x)+model_coefficients[1]*(cloud_raw->points[i].y) +model_coefficients[2]*(cloud_raw->points[i].z)+model_coefficients[3])/sqrt(model_coefficients[0]*model_coefficients[0]+ model_coefficients[1]*model_coefficients[1]+model_coefficients[2]*model_coefficients[2]); Eigen::Vector3f norm; norm[0]=cloud_normals->points[i].normal[0]; norm[1]=cloud_normals->points[i].normal[1]; norm[2]=cloud_normals->points[i].normal[2]; double test_cosine = norm.head<3>().dot(model_coefficients.head<3>()); double angular_tolerance=0.2; double upper_limit = 1 + angular_tolerance; double lower_limit = 1 - angular_tolerance; // norm check /*if (distance <0.005 || (distance<0.02 && (((test_cosine < upper_limit) && (test_cosine > lower_limit) ) || ((test_cosine > -upper_limit) && (test_cosine < -lower_limit)))) ) /*if ( distance<0.01 && (((test_cosine < upper_limit) && (test_cosine > lower_limit) ) || ((test_cosine > -upper_limit) && (test_cosine < -lower_limit))) ) inliers1.push_back(i); if (distance<0.008) inliers1.push_back(i); } //model_q->projectPoints (inliers1, model_coefficients, *proj, 0);*/ if (1) { cout << filtered->size () << " " << cloud_normals->size () << " " << cloud_raw->size () << endl; cout << "# of planes: " << count << endl; } // Extract the inliers boost::shared_ptr<vector<int> > indicesptr (new vector<int> (inliers)); extract.setInputCloud (filtered); extract.setIndices (indicesptr); extract.setNegative (false); extract.filter (*tmp1); extract.setNegative (true); extract.filter (*tmp2); filtered.swap (tmp2); // test the extracted inliers and write them into .cpd format /*pcl::PCDWriter writer; std::stringstream ss; ss << "plane" << count << ".pcd" ; writer.write<pcl::PointXYZRGB> (ss.str (), *tmp1, false);*/ // *final=*final+*proj; // plane projection //*final=*final+*tmp1; // no pojection // extract the inliers for the norm extract_n.setInputCloud (cloud_normals); extract_n.setIndices (indicesptr); extract_n.setNegative (true); extract_n.filter (*cloud_normals); } // projection 2 // TODO vector<vector<int> > inliers_proj; int s = model_buffer.size (); for (int j = 0; j < s; j++) { inliers_proj.push_back (vector<int> ()); } for (int i = 0; i < points_num; i++) { Eigen::VectorXf model_coefficients; double distance_min = 0.006; double distance[s]; int index_min = -1; for (int j = 0; j < s; j++) { distance[j] = abs ( model_buffer[j][0] * (cloud_raw->points[i].x) + model_buffer[j][1] * (cloud_raw->points[i].y) + model_buffer[j][2] * (cloud_raw->points[i].z) + model_buffer[j][3]) / sqrt ( model_buffer[j][0] * model_buffer[j][0] + model_buffer[j][1] * model_buffer[j][1] + model_buffer[j][2] * model_buffer[j][2]); if (distance[j] < distance_min) { distance_min = distance[j]; index_min = j; } } if (index_min >= 0) inliers_proj[index_min].push_back (i); /*if (index_min>=0) { for (int j=0;j<s;j++) { if (j!=index_min && (distance[j]-distance_min<0.0015)) inliers_proj[j].push_back(i); } }*/ } for (int j = 0; j < s; j++) { model_q->projectPoints (inliers_proj[j], model_buffer[j], *proj, 0); *final = *final + *proj; } return (0); } void meshFitting_RGB(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud, pcl::PolygonMesh &triangles) { pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>); pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne; ne.setInputCloud (cloud); pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB> ()); ne.setSearchMethod (tree); ne.setKSearch (20); ne.compute (*normals); //* normals should not contain the point normals + surface curvatures // Concatenate the XYZ and normal fields* pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloud_with_normals (new pcl::PointCloud<pcl::PointXYZRGBNormal>); //pcl::PointXYZRGBNormal pcl::concatenateFields (*cloud, *normals, *cloud_with_normals); // Create search tree pcl::search::KdTree<pcl::PointXYZRGBNormal>::Ptr tree2 (new pcl::search::KdTree<pcl::PointXYZRGBNormal>); tree2->setInputCloud (cloud_with_normals); // Initialize objects pcl::GreedyProjectionTriangulation<pcl::PointXYZRGBNormal> gp3; // Set the maximum distance between connected points (maximum edge length) // Set typical values for the parameters gp3.setSearchRadius (0.1); //0.025 gp3.setMu (10); gp3.setMaximumNearestNeighbors (300); gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees gp3.setMinimumAngle(M_PI/18); // 10 degrees gp3.setMaximumAngle(2*M_PI/3); // 120 degrees gp3.setNormalConsistency(false); // Get result gp3.setInputCloud (cloud_with_normals); gp3.setSearchMethod (tree2); gp3.reconstruct (triangles); } void meshFitting(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, pcl::PolygonMesh &triangles) { pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>); pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne; ne.setInputCloud (cloud); pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ> ()); ne.setSearchMethod (tree); ne.setKSearch (50); ne.compute (*normals); //* normals should not contain the point normals + surface curvatures // Concatenate the XYZ and normal fields* pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals (new pcl::PointCloud<pcl::PointNormal>); //pcl::PointXYZRGBNormal pcl::concatenateFields (*cloud, *normals, *cloud_with_normals); //* cloud_with_normals = cloud + normals // Create search tree* pcl::search::KdTree<pcl::PointNormal>::Ptr tree2 (new pcl::search::KdTree<pcl::PointNormal>); tree2->setInputCloud (cloud_with_normals); // Initialize objects pcl::GreedyProjectionTriangulation<pcl::PointNormal> gp3; //pcl::PolygonMesh triangles; // Set the maximum distance between connected points (maximum edge length) // Set typical values for the parameters gp3.setSearchRadius (0.2); //0.025 gp3.setMu (5); gp3.setMaximumNearestNeighbors (200); gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees gp3.setMinimumAngle(M_PI/18); // 10 degrees gp3.setMaximumAngle(2*M_PI/3); // 120 degrees gp3.setNormalConsistency(false); // Get result gp3.setInputCloud (cloud_with_normals); gp3.setSearchMethod (tree2); gp3.reconstruct (triangles); } <commit_msg>rm redundant files<commit_after><|endoftext|>
<commit_before>// // Created by Danni on 09.06.15. // #include "ZAssemblyGenerator.h" #include <sstream> #include <vector> using namespace std; using namespace experimental; static const string INST_START = "\t"; static const string INST_END = "\n"; static const string INST_LABEL_MARKER = "?"; static const string INST_JUMP_NEG_MARKER = "~"; static const string INST_STORE_TARGET_MARKER = "->"; static const string INST_SEPARATOR = " "; static const string ARGS_EQ = "="; static const string ARGS_SEPARATOR = ","; static const string LABEL_MARKER = ":"; static const string DIRECTIVE_START = "."; namespace directive { INST_TYPE ROUTINE = "FUNCT"; INST_TYPE GLOBAL_VAR = "GVAR"; } namespace instruction { INST_TYPE NEW_LINE_COMMAND = "new_line"; INST_TYPE PRINT_COMMAND = "print"; INST_TYPE JE_COMMAND = "je"; INST_TYPE JG_COMMAND = "jg"; INST_TYPE JL_COMMAND = "jl"; INST_TYPE JZ_COMMAND = "jz"; INST_TYPE QUIT_COMMAND = "quit"; INST_TYPE READ_CHAR_COMMAND = "read_char"; INST_TYPE PRINT_CHAR_COMMAND = "print_char"; INST_TYPE PRINT_NUM_COMMAND = "print_num"; INST_TYPE PRINT_ADDR_COMMAND = "print_addr"; INST_TYPE JUMP_COMMAND = "jump"; INST_TYPE RET_COMMAND = "ret"; INST_TYPE SET_TEXT_STYLE = "set_text_style"; INST_TYPE CALL_VS_COMMAND = "call_vs"; INST_TYPE CALL_1N_COMMAND = "call_1n"; INST_TYPE STORE_COMMAND = "store"; INST_TYPE LOAD_COMMAND = "load"; INST_TYPE ADD_COMMAND = "add"; INST_TYPE SUB_COMMAND = "sub"; INST_TYPE MUL_COMMAND = "mul"; INST_TYPE DIV_COMMAND = "div"; INST_TYPE AND_COMMAND = "and"; INST_TYPE OR_COMMAND = "or"; INST_TYPE NOT_COMMAND = "not"; INST_TYPE RET_TRUE_COMMAND = "rtrue"; INST_TYPE RET_FALSE_COMMAND = "rfalse"; INST_TYPE PRINT_RET_COMMAND = "print_ret"; INST_TYPE RESTART_COMMAND = "restart"; INST_TYPE RET_POPPED_COMMAND = "ret_popped"; INST_TYPE VERIFY_COMMAND = "verify"; INST_TYPE NOTHING = ""; } ZAssemblyGenerator::ZAssemblyGenerator(ostream &out) : out(out) { } const string ZAssemblyGenerator::STACK_POINTER = "sp"; const bool ZAssemblyGenerator::ZAPF_MODE = false; string ZAssemblyGenerator::makeArgs(initializer_list<string> args) { stringstream ss; for (auto arg = args.begin(); arg != args.end(); ++arg) { ss << *arg; if (arg != args.end() && arg + 1 != args.end()) { ss << INST_SEPARATOR; } } return ss.str(); } ZAssemblyGenerator &ZAssemblyGenerator::addLabel(string labelName) { out << labelName << LABEL_MARKER << INST_END; return *this; } #pragma mark - directives ZAssemblyGenerator &ZAssemblyGenerator::addDirective(string directiveName, experimental::optional<string> args) { out << DIRECTIVE_START << directiveName; if (args) { out << INST_SEPARATOR; out << *args; } out << INST_END; return *this; } ZAssemblyGenerator &ZAssemblyGenerator::addRoutine(string routineName, vector<ZRoutineArgument> args) { stringstream ss; ss << routineName << INST_SEPARATOR; for (auto it = args.begin(); it != args.end(); ++it) { ss << it->argName; if (it->value) { ss << ARGS_EQ << *(it->value); } if (it + 1 != args.end()) { ss << ARGS_SEPARATOR; } } addDirective(directive::ROUTINE, ss.str()); return *this; } ZAssemblyGenerator &ZAssemblyGenerator::addGlobal(string globalName) { addDirective(directive::GLOBAL_VAR, globalName); return *this; } #pragma mark - instructions ZAssemblyGenerator &ZAssemblyGenerator::addInstruction(INST_TYPE instruction, optional<string> args, optional<pair<string, bool>> targetLabelAndNeg, optional<string> storeTarget) { out << INST_START; out << instruction; if (args) { out << INST_SEPARATOR << *args; } if (targetLabelAndNeg) { out << INST_SEPARATOR << INST_LABEL_MARKER; if (targetLabelAndNeg->second) { out << INST_JUMP_NEG_MARKER; } out << targetLabelAndNeg->first; } if (storeTarget) { out << INST_SEPARATOR << INST_STORE_TARGET_MARKER << INST_SEPARATOR << *storeTarget; } out << INST_END; return *this; } ZAssemblyGenerator &ZAssemblyGenerator::jump(string targetLabel) { if (ZAPF_MODE) return addInstruction(instruction::JUMP_COMMAND, targetLabel, nullopt, nullopt); else return addInstruction(instruction::JUMP_COMMAND, nullopt, make_pair(targetLabel, false), nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::markStart() { if (ZAPF_MODE) { out << "START::" << INST_END; } return *this; } ZAssemblyGenerator &ZAssemblyGenerator::call(string routineName) { return addInstruction(instruction::CALL_VS_COMMAND, routineName, nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::call(string routineName, string storeTarget) { return addInstruction(instruction::CALL_VS_COMMAND, routineName, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::jumpEquals(string args, string targetLabel) { return addInstruction(instruction::JE_COMMAND, args, make_pair(targetLabel, false), nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::jumpGreater(string args, string targetLabel) { return addInstruction(instruction::JG_COMMAND, args, make_pair(targetLabel, false), nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::quit() { return addInstruction(instruction::QUIT_COMMAND, nullopt, nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::ret(string arg) { return addInstruction(instruction::RET_COMMAND, arg, nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::newline() { return addInstruction(instruction::NEW_LINE_COMMAND, nullopt, nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::print(string str) { return addInstruction(instruction::PRINT_COMMAND, string("\"") + str + string("\""), nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::setTextStyle(bool italic, bool bold, bool underlined) { string result; if (italic) { result += "i"; } if (bold) { result += "b"; } if (underlined) { result += "u"; } if (!(italic && bold && underlined)) { result = "r"; } return addInstruction(instruction::SET_TEXT_STYLE, result, nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::read_char(string storeTarget) { return addInstruction(instruction::READ_CHAR_COMMAND, string("1"), nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::println(string str) { return addInstruction(instruction::PRINT_COMMAND, string("\"") + str + string("\""), nullopt, nullopt).newline(); } ZAssemblyGenerator &ZAssemblyGenerator::variable(string variable) { return addInstruction(instruction::NOTHING, variable.substr(1), nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::load(std::string source, std::string target) { return addInstruction(instruction::LOAD_COMMAND, source, nullopt, target); } ZAssemblyGenerator &ZAssemblyGenerator::store(std::string target, std::string value) { return addInstruction(instruction::STORE_COMMAND, value, nullopt, target); } ZAssemblyGenerator &ZAssemblyGenerator::add(std::string left, std::string right, std::string storeTarget) { return addInstruction(instruction::ADD_COMMAND, left + " " + right, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::sub(std::string left, std::string right, std::string storeTarget) { return addInstruction(instruction::SUB_COMMAND, left + " " + right, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::mul(std::string left, std::string right, std::string storeTarget) { return addInstruction(instruction::MUL_COMMAND, left + " " + right, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::div(std::string left, std::string right, std::string storeTarget) { return addInstruction(instruction::DIV_COMMAND, left + " " + right, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::mod(std::string left, std::string right, std::string storeTarget) { } ZAssemblyGenerator &ZAssemblyGenerator::land(std::string left, std::string right, std::string storeTarget) { return addInstruction(instruction::AND_COMMAND, left + " " + right, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::lor(std::string left, std::string right, std::string storeTarget) { return addInstruction(instruction::OR_COMMAND, left + " " + right, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::lnot(std::string variable, std::string storeTarget) { return addInstruction(instruction::NOT_COMMAND, variable, nullopt, storeTarget); }<commit_msg>wrong set macro assembly generation<commit_after>// // Created by Danni on 09.06.15. // #include "ZAssemblyGenerator.h" #include <sstream> #include <vector> using namespace std; using namespace experimental; static const string INST_START = "\t"; static const string INST_END = "\n"; static const string INST_LABEL_MARKER = "?"; static const string INST_JUMP_NEG_MARKER = "~"; static const string INST_STORE_TARGET_MARKER = "->"; static const string INST_SEPARATOR = " "; static const string ARGS_EQ = "="; static const string ARGS_SEPARATOR = ","; static const string LABEL_MARKER = ":"; static const string DIRECTIVE_START = "."; namespace directive { INST_TYPE ROUTINE = "FUNCT"; INST_TYPE GLOBAL_VAR = "GVAR"; } namespace instruction { INST_TYPE NEW_LINE_COMMAND = "new_line"; INST_TYPE PRINT_COMMAND = "print"; INST_TYPE JE_COMMAND = "je"; INST_TYPE JG_COMMAND = "jg"; INST_TYPE JL_COMMAND = "jl"; INST_TYPE JZ_COMMAND = "jz"; INST_TYPE QUIT_COMMAND = "quit"; INST_TYPE READ_CHAR_COMMAND = "read_char"; INST_TYPE PRINT_CHAR_COMMAND = "print_char"; INST_TYPE PRINT_NUM_COMMAND = "print_num"; INST_TYPE PRINT_ADDR_COMMAND = "print_addr"; INST_TYPE JUMP_COMMAND = "jump"; INST_TYPE RET_COMMAND = "ret"; INST_TYPE SET_TEXT_STYLE = "set_text_style"; INST_TYPE CALL_VS_COMMAND = "call_vs"; INST_TYPE CALL_1N_COMMAND = "call_1n"; INST_TYPE STORE_COMMAND = "store"; INST_TYPE LOAD_COMMAND = "load"; INST_TYPE ADD_COMMAND = "add"; INST_TYPE SUB_COMMAND = "sub"; INST_TYPE MUL_COMMAND = "mul"; INST_TYPE DIV_COMMAND = "div"; INST_TYPE AND_COMMAND = "and"; INST_TYPE OR_COMMAND = "or"; INST_TYPE NOT_COMMAND = "not"; INST_TYPE RET_TRUE_COMMAND = "rtrue"; INST_TYPE RET_FALSE_COMMAND = "rfalse"; INST_TYPE PRINT_RET_COMMAND = "print_ret"; INST_TYPE RESTART_COMMAND = "restart"; INST_TYPE RET_POPPED_COMMAND = "ret_popped"; INST_TYPE VERIFY_COMMAND = "verify"; INST_TYPE NOTHING = ""; } ZAssemblyGenerator::ZAssemblyGenerator(ostream &out) : out(out) { } const string ZAssemblyGenerator::STACK_POINTER = "sp"; const bool ZAssemblyGenerator::ZAPF_MODE = false; string ZAssemblyGenerator::makeArgs(initializer_list<string> args) { stringstream ss; for (auto arg = args.begin(); arg != args.end(); ++arg) { ss << *arg; if (arg != args.end() && arg + 1 != args.end()) { ss << INST_SEPARATOR; } } return ss.str(); } ZAssemblyGenerator &ZAssemblyGenerator::addLabel(string labelName) { out << labelName << LABEL_MARKER << INST_END; return *this; } #pragma mark - directives ZAssemblyGenerator &ZAssemblyGenerator::addDirective(string directiveName, experimental::optional<string> args) { out << DIRECTIVE_START << directiveName; if (args) { out << INST_SEPARATOR; out << *args; } out << INST_END; return *this; } ZAssemblyGenerator &ZAssemblyGenerator::addRoutine(string routineName, vector<ZRoutineArgument> args) { stringstream ss; ss << routineName << INST_SEPARATOR; for (auto it = args.begin(); it != args.end(); ++it) { ss << it->argName; if (it->value) { ss << ARGS_EQ << *(it->value); } if (it + 1 != args.end()) { ss << ARGS_SEPARATOR; } } addDirective(directive::ROUTINE, ss.str()); return *this; } ZAssemblyGenerator &ZAssemblyGenerator::addGlobal(string globalName) { addDirective(directive::GLOBAL_VAR, globalName); return *this; } #pragma mark - instructions ZAssemblyGenerator &ZAssemblyGenerator::addInstruction(INST_TYPE instruction, optional<string> args, optional<pair<string, bool>> targetLabelAndNeg, optional<string> storeTarget) { out << INST_START; out << instruction; if (args) { out << INST_SEPARATOR << *args; } if (targetLabelAndNeg) { out << INST_SEPARATOR << INST_LABEL_MARKER; if (targetLabelAndNeg->second) { out << INST_JUMP_NEG_MARKER; } out << targetLabelAndNeg->first; } if (storeTarget) { out << INST_SEPARATOR << INST_STORE_TARGET_MARKER << INST_SEPARATOR << *storeTarget; } out << INST_END; return *this; } ZAssemblyGenerator &ZAssemblyGenerator::jump(string targetLabel) { if (ZAPF_MODE) return addInstruction(instruction::JUMP_COMMAND, targetLabel, nullopt, nullopt); else return addInstruction(instruction::JUMP_COMMAND, nullopt, make_pair(targetLabel, false), nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::markStart() { if (ZAPF_MODE) { out << "START::" << INST_END; } return *this; } ZAssemblyGenerator &ZAssemblyGenerator::call(string routineName) { return addInstruction(instruction::CALL_VS_COMMAND, routineName, nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::call(string routineName, string storeTarget) { return addInstruction(instruction::CALL_VS_COMMAND, routineName, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::jumpEquals(string args, string targetLabel) { return addInstruction(instruction::JE_COMMAND, args, make_pair(targetLabel, false), nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::jumpGreater(string args, string targetLabel) { return addInstruction(instruction::JG_COMMAND, args, make_pair(targetLabel, false), nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::quit() { return addInstruction(instruction::QUIT_COMMAND, nullopt, nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::ret(string arg) { return addInstruction(instruction::RET_COMMAND, arg, nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::newline() { return addInstruction(instruction::NEW_LINE_COMMAND, nullopt, nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::print(string str) { return addInstruction(instruction::PRINT_COMMAND, string("\"") + str + string("\""), nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::setTextStyle(bool italic, bool bold, bool underlined) { string result; if (italic) { result += "i"; } if (bold) { result += "b"; } if (underlined) { result += "u"; } if (!(italic && bold && underlined)) { result = "r"; } return addInstruction(instruction::SET_TEXT_STYLE, result, nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::read_char(string storeTarget) { return addInstruction(instruction::READ_CHAR_COMMAND, string("1"), nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::println(string str) { return addInstruction(instruction::PRINT_COMMAND, string("\"") + str + string("\""), nullopt, nullopt).newline(); } ZAssemblyGenerator &ZAssemblyGenerator::variable(string variable) { return addInstruction(instruction::NOTHING, variable.substr(1), nullopt, nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::load(std::string source, std::string target) { return addInstruction(instruction::LOAD_COMMAND, source, nullopt, target); } ZAssemblyGenerator &ZAssemblyGenerator::store(std::string target, std::string value) { return addInstruction(instruction::STORE_COMMAND,makeArgs({target, value}) ,nullopt,nullopt); } ZAssemblyGenerator &ZAssemblyGenerator::add(std::string left, std::string right, std::string storeTarget) { return addInstruction(instruction::ADD_COMMAND, left + " " + right, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::sub(std::string left, std::string right, std::string storeTarget) { return addInstruction(instruction::SUB_COMMAND, left + " " + right, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::mul(std::string left, std::string right, std::string storeTarget) { return addInstruction(instruction::MUL_COMMAND, left + " " + right, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::div(std::string left, std::string right, std::string storeTarget) { return addInstruction(instruction::DIV_COMMAND, left + " " + right, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::mod(std::string left, std::string right, std::string storeTarget) { } ZAssemblyGenerator &ZAssemblyGenerator::land(std::string left, std::string right, std::string storeTarget) { return addInstruction(instruction::AND_COMMAND, left + " " + right, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::lor(std::string left, std::string right, std::string storeTarget) { return addInstruction(instruction::OR_COMMAND, left + " " + right, nullopt, storeTarget); } ZAssemblyGenerator &ZAssemblyGenerator::lnot(std::string variable, std::string storeTarget) { return addInstruction(instruction::NOT_COMMAND, variable, nullopt, storeTarget); }<|endoftext|>
<commit_before>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen * * 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 "texture_manager.hpp" #include "device.hpp" #include "stb_image.h" #include "memory_mapped_texture.hpp" #include "texture_files.hpp" #ifdef GRANITE_VULKAN_MT #include "thread_group.hpp" #include "thread_id.hpp" #endif using namespace std; namespace Vulkan { bool Texture::init_texture() { if (!path.empty()) return init(); else return true; } Texture::Texture(Device *device_, const std::string &path_, VkFormat format_, const VkComponentMapping &swizzle_) : VolatileSource(path_), device(device_), format(format_), swizzle(swizzle_) { } Texture::Texture(Device *device_) : device(device_), format(VK_FORMAT_UNDEFINED) { } void Texture::set_path(const std::string &path_) { path = path_; } void Texture::update(std::unique_ptr<Granite::File> file) { auto *f = file.release(); auto work = [f, this]() { #ifdef GRANITE_VULKAN_MT LOGI("Loading texture in thread index: %u\n", get_current_thread_index()); #endif unique_ptr<Granite::File> updated_file{f}; auto size = updated_file->get_size(); void *mapped = updated_file->map(); if (size && mapped) { if (Granite::SceneFormats::MemoryMappedTexture::is_header(mapped, size)) update_gtx(move(updated_file), mapped); else update_other(mapped, size); device->get_texture_manager().notify_updated_texture(path, *this); } else { LOGE("Failed to map texture file ...\n"); update_checkerboard(); } }; #ifdef GRANITE_VULKAN_MT auto &workers = *Granite::Global::thread_group(); // Workaround, cannot copy the lambda because of owning a unique_ptr. auto task = workers.create_task(move(work)); task->flush(); #else work(); #endif } void Texture::update_checkerboard() { LOGE("Failed to load texture: %s, falling back to a checkerboard.\n", path.c_str()); ImageInitialData initial = {}; static const uint32_t checkerboard[] = { 0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u, 0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu, }; initial.data = checkerboard; auto info = ImageCreateInfo::immutable_2d_image(4, 4, VK_FORMAT_R8G8B8A8_UNORM, false); auto image = device->create_image(info, &initial); if (image) device->set_name(*image, path.c_str()); replace_image(image); } void Texture::update_gtx(const Granite::SceneFormats::MemoryMappedTexture &mapped_file) { if (mapped_file.empty()) { update_checkerboard(); return; } auto &layout = mapped_file.get_layout(); ImageCreateInfo info = {}; info.width = layout.get_width(); info.height = layout.get_height(); info.depth = layout.get_depth(); info.type = layout.get_image_type(); info.format = layout.get_format(); info.levels = layout.get_levels(); info.layers = layout.get_layers(); info.samples = VK_SAMPLE_COUNT_1_BIT; info.domain = ImageDomain::Physical; info.initial_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; info.usage = VK_IMAGE_USAGE_SAMPLED_BIT; info.swizzle = swizzle; info.flags = (mapped_file.get_flags() & Granite::SceneFormats::MEMORY_MAPPED_TEXTURE_CUBE_MAP_COMPATIBLE_BIT) ? VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : 0; info.misc = 0; mapped_file.remap_swizzle(info.swizzle); if (info.levels == 1 && (mapped_file.get_flags() & Granite::SceneFormats::MEMORY_MAPPED_TEXTURE_GENERATE_MIPMAP_ON_LOAD_BIT) != 0 && device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_BLIT_SRC_BIT) && device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_BLIT_DST_BIT)) { info.levels = 0; info.misc |= IMAGE_MISC_GENERATE_MIPS_BIT; } if (!device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) { LOGE("Format (%u) is not supported!\n", unsigned(info.format)); return; } auto staging = device->create_image_staging_buffer(layout); auto image = device->create_image_from_staging_buffer(info, &staging); if (image) device->set_name(*image, path.c_str()); replace_image(image); } void Texture::update_gtx(unique_ptr<Granite::File> file, void *mapped) { Granite::SceneFormats::MemoryMappedTexture mapped_file; if (!mapped_file.map_read(move(file), mapped)) { LOGE("Failed to read texture.\n"); return; } update_gtx(mapped_file); } void Texture::update_other(const void *data, size_t size) { auto tex = Granite::load_texture_from_memory(data, size, (format == VK_FORMAT_R8G8B8A8_SRGB || format == VK_FORMAT_UNDEFINED || format == VK_FORMAT_B8G8R8A8_SRGB || format == VK_FORMAT_A8B8G8R8_SRGB_PACK32) ? Granite::ColorSpace::sRGB : Granite::ColorSpace::Linear); update_gtx(tex); } void Texture::load() { if (!handle.get_nowait()) init(); } void Texture::unload() { deinit(); handle.reset(); } void Texture::replace_image(ImageHandle handle_) { auto old = this->handle.write_object(move(handle_)); if (old) device->keep_handle_alive(move(old)); if (enable_notification) device->get_texture_manager().notify_updated_texture(path, *this); } Image *Texture::get_image() { auto ret = handle.get(); VK_ASSERT(ret); return ret; } void Texture::set_enable_notification(bool enable) { enable_notification = enable; } TextureManager::TextureManager(Device *device_) : device(device_) { } Texture *TextureManager::request_texture(const std::string &path, VkFormat format, const VkComponentMapping &mapping) { Util::Hasher hasher; hasher.string(path); auto deferred_hash = hasher.get(); hasher.u32(format); hasher.u32(mapping.r); hasher.u32(mapping.g); hasher.u32(mapping.b); hasher.u32(mapping.a); auto hash = hasher.get(); auto *ret = deferred_textures.find(deferred_hash); if (ret) return ret; ret = textures.find(hash); if (ret) return ret; ret = textures.emplace_yield(hash, device, path, format, mapping); if (!ret->init_texture()) ret->update_checkerboard(); return ret; } void TextureManager::register_texture_update_notification(const std::string &modified_path, std::function<void(Texture &)> func) { Util::Hasher hasher; hasher.string(modified_path); auto hash = hasher.get(); auto *ret = deferred_textures.find(hash); if (ret) func(*ret); notifications[modified_path].push_back(move(func)); } void TextureManager::notify_updated_texture(const std::string &path, Vulkan::Texture &texture) { auto itr = notifications.find(path); if (itr != end(notifications)) for (auto &f : itr->second) if (f) f(texture); } Texture *TextureManager::register_deferred_texture(const std::string &path) { Util::Hasher hasher; hasher.string(path); auto hash = hasher.get(); auto *ret = deferred_textures.find(hash); if (!ret) { auto *texture = deferred_textures.allocate(device); texture->set_path(path); texture->set_enable_notification(false); ret = deferred_textures.insert_yield(hash, texture); } return ret; } } <commit_msg>Make images from texture manager available in all queues.<commit_after>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen * * 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 "texture_manager.hpp" #include "device.hpp" #include "stb_image.h" #include "memory_mapped_texture.hpp" #include "texture_files.hpp" #ifdef GRANITE_VULKAN_MT #include "thread_group.hpp" #include "thread_id.hpp" #endif using namespace std; namespace Vulkan { bool Texture::init_texture() { if (!path.empty()) return init(); else return true; } Texture::Texture(Device *device_, const std::string &path_, VkFormat format_, const VkComponentMapping &swizzle_) : VolatileSource(path_), device(device_), format(format_), swizzle(swizzle_) { } Texture::Texture(Device *device_) : device(device_), format(VK_FORMAT_UNDEFINED) { } void Texture::set_path(const std::string &path_) { path = path_; } void Texture::update(std::unique_ptr<Granite::File> file) { auto *f = file.release(); auto work = [f, this]() { #ifdef GRANITE_VULKAN_MT LOGI("Loading texture in thread index: %u\n", get_current_thread_index()); #endif unique_ptr<Granite::File> updated_file{f}; auto size = updated_file->get_size(); void *mapped = updated_file->map(); if (size && mapped) { if (Granite::SceneFormats::MemoryMappedTexture::is_header(mapped, size)) update_gtx(move(updated_file), mapped); else update_other(mapped, size); device->get_texture_manager().notify_updated_texture(path, *this); } else { LOGE("Failed to map texture file ...\n"); update_checkerboard(); } }; #ifdef GRANITE_VULKAN_MT auto &workers = *Granite::Global::thread_group(); // Workaround, cannot copy the lambda because of owning a unique_ptr. auto task = workers.create_task(move(work)); task->flush(); #else work(); #endif } void Texture::update_checkerboard() { LOGE("Failed to load texture: %s, falling back to a checkerboard.\n", path.c_str()); ImageInitialData initial = {}; static const uint32_t checkerboard[] = { 0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u, 0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu, }; initial.data = checkerboard; auto info = ImageCreateInfo::immutable_2d_image(4, 4, VK_FORMAT_R8G8B8A8_UNORM, false); info.misc = IMAGE_MISC_CONCURRENT_QUEUE_GRAPHICS_BIT | IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_GRAPHICS_BIT | IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_COMPUTE_BIT; auto image = device->create_image(info, &initial); if (image) device->set_name(*image, path.c_str()); replace_image(image); } void Texture::update_gtx(const Granite::SceneFormats::MemoryMappedTexture &mapped_file) { if (mapped_file.empty()) { update_checkerboard(); return; } auto &layout = mapped_file.get_layout(); ImageCreateInfo info = {}; info.width = layout.get_width(); info.height = layout.get_height(); info.depth = layout.get_depth(); info.type = layout.get_image_type(); info.format = layout.get_format(); info.levels = layout.get_levels(); info.layers = layout.get_layers(); info.samples = VK_SAMPLE_COUNT_1_BIT; info.domain = ImageDomain::Physical; info.initial_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; info.usage = VK_IMAGE_USAGE_SAMPLED_BIT; info.swizzle = swizzle; info.flags = (mapped_file.get_flags() & Granite::SceneFormats::MEMORY_MAPPED_TEXTURE_CUBE_MAP_COMPATIBLE_BIT) ? VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT : 0; info.misc = IMAGE_MISC_CONCURRENT_QUEUE_GRAPHICS_BIT | IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_GRAPHICS_BIT | IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_COMPUTE_BIT; mapped_file.remap_swizzle(info.swizzle); if (info.levels == 1 && (mapped_file.get_flags() & Granite::SceneFormats::MEMORY_MAPPED_TEXTURE_GENERATE_MIPMAP_ON_LOAD_BIT) != 0 && device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_BLIT_SRC_BIT) && device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_BLIT_DST_BIT)) { info.levels = 0; info.misc |= IMAGE_MISC_GENERATE_MIPS_BIT; } if (!device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) { LOGE("Format (%u) is not supported!\n", unsigned(info.format)); return; } auto staging = device->create_image_staging_buffer(layout); auto image = device->create_image_from_staging_buffer(info, &staging); if (image) device->set_name(*image, path.c_str()); replace_image(image); } void Texture::update_gtx(unique_ptr<Granite::File> file, void *mapped) { Granite::SceneFormats::MemoryMappedTexture mapped_file; if (!mapped_file.map_read(move(file), mapped)) { LOGE("Failed to read texture.\n"); return; } update_gtx(mapped_file); } void Texture::update_other(const void *data, size_t size) { auto tex = Granite::load_texture_from_memory(data, size, (format == VK_FORMAT_R8G8B8A8_SRGB || format == VK_FORMAT_UNDEFINED || format == VK_FORMAT_B8G8R8A8_SRGB || format == VK_FORMAT_A8B8G8R8_SRGB_PACK32) ? Granite::ColorSpace::sRGB : Granite::ColorSpace::Linear); update_gtx(tex); } void Texture::load() { if (!handle.get_nowait()) init(); } void Texture::unload() { deinit(); handle.reset(); } void Texture::replace_image(ImageHandle handle_) { auto old = this->handle.write_object(move(handle_)); if (old) device->keep_handle_alive(move(old)); if (enable_notification) device->get_texture_manager().notify_updated_texture(path, *this); } Image *Texture::get_image() { auto ret = handle.get(); VK_ASSERT(ret); return ret; } void Texture::set_enable_notification(bool enable) { enable_notification = enable; } TextureManager::TextureManager(Device *device_) : device(device_) { } Texture *TextureManager::request_texture(const std::string &path, VkFormat format, const VkComponentMapping &mapping) { Util::Hasher hasher; hasher.string(path); auto deferred_hash = hasher.get(); hasher.u32(format); hasher.u32(mapping.r); hasher.u32(mapping.g); hasher.u32(mapping.b); hasher.u32(mapping.a); auto hash = hasher.get(); auto *ret = deferred_textures.find(deferred_hash); if (ret) return ret; ret = textures.find(hash); if (ret) return ret; ret = textures.emplace_yield(hash, device, path, format, mapping); if (!ret->init_texture()) ret->update_checkerboard(); return ret; } void TextureManager::register_texture_update_notification(const std::string &modified_path, std::function<void(Texture &)> func) { Util::Hasher hasher; hasher.string(modified_path); auto hash = hasher.get(); auto *ret = deferred_textures.find(hash); if (ret) func(*ret); notifications[modified_path].push_back(move(func)); } void TextureManager::notify_updated_texture(const std::string &path, Vulkan::Texture &texture) { auto itr = notifications.find(path); if (itr != end(notifications)) for (auto &f : itr->second) if (f) f(texture); } Texture *TextureManager::register_deferred_texture(const std::string &path) { Util::Hasher hasher; hasher.string(path); auto hash = hasher.get(); auto *ret = deferred_textures.find(hash); if (!ret) { auto *texture = deferred_textures.allocate(device); texture->set_path(path); texture->set_enable_notification(false); ret = deferred_textures.insert_yield(hash, texture); } return ret; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "progressview.h" #include <QEvent> #include <QVBoxLayout> using namespace Core; using namespace Core::Internal; static const int PROGRESS_WIDTH = 100; ProgressView::ProgressView(QWidget *parent) : QWidget(parent), m_referenceWidget(0), m_hovered(false) { m_layout = new QVBoxLayout; setLayout(m_layout); m_layout->setContentsMargins(0, 0, 0, 1); m_layout->setSpacing(0); m_layout->setSizeConstraint(QLayout::SetFixedSize); setWindowTitle(tr("Processes")); } ProgressView::~ProgressView() { } void ProgressView::addProgressWidget(QWidget *widget) { m_layout->insertWidget(0, widget); } void ProgressView::removeProgressWidget(QWidget *widget) { m_layout->removeWidget(widget); } bool ProgressView::isHovered() const { return m_hovered; } void ProgressView::setReferenceWidget(QWidget *widget) { if (m_referenceWidget) removeEventFilter(this); m_referenceWidget = widget; if (m_referenceWidget) installEventFilter(this); reposition(); } bool ProgressView::event(QEvent *event) { if (event->type() == QEvent::ParentAboutToChange && parentWidget()) { parentWidget()->removeEventFilter(this); } else if (event->type() == QEvent::ParentChange && parentWidget()) { parentWidget()->installEventFilter(this); } else if (event->type() == QEvent::Resize) { reposition(); } else if (event->type() == QEvent::Enter) { m_hovered = true; emit hoveredChanged(m_hovered); } else if (event->type() == QEvent::Leave) { m_hovered = false; emit hoveredChanged(m_hovered); } return QWidget::event(event); } bool ProgressView::eventFilter(QObject *obj, QEvent *event) { if ((obj == parentWidget() || obj == m_referenceWidget) && event->type() == QEvent::Resize) reposition(); return false; } void ProgressView::reposition() { if (!parentWidget() || !m_referenceWidget) return; QPoint topRightReferenceInParent = m_referenceWidget->mapTo(parentWidget(), m_referenceWidget->rect().topRight()); move(topRightReferenceInParent - rect().bottomRight()); } <commit_msg>Core: Remove dead code<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "progressview.h" #include <QEvent> #include <QVBoxLayout> using namespace Core; using namespace Core::Internal; ProgressView::ProgressView(QWidget *parent) : QWidget(parent), m_referenceWidget(0), m_hovered(false) { m_layout = new QVBoxLayout; setLayout(m_layout); m_layout->setContentsMargins(0, 0, 0, 1); m_layout->setSpacing(0); m_layout->setSizeConstraint(QLayout::SetFixedSize); setWindowTitle(tr("Processes")); } ProgressView::~ProgressView() { } void ProgressView::addProgressWidget(QWidget *widget) { m_layout->insertWidget(0, widget); } void ProgressView::removeProgressWidget(QWidget *widget) { m_layout->removeWidget(widget); } bool ProgressView::isHovered() const { return m_hovered; } void ProgressView::setReferenceWidget(QWidget *widget) { if (m_referenceWidget) removeEventFilter(this); m_referenceWidget = widget; if (m_referenceWidget) installEventFilter(this); reposition(); } bool ProgressView::event(QEvent *event) { if (event->type() == QEvent::ParentAboutToChange && parentWidget()) { parentWidget()->removeEventFilter(this); } else if (event->type() == QEvent::ParentChange && parentWidget()) { parentWidget()->installEventFilter(this); } else if (event->type() == QEvent::Resize) { reposition(); } else if (event->type() == QEvent::Enter) { m_hovered = true; emit hoveredChanged(m_hovered); } else if (event->type() == QEvent::Leave) { m_hovered = false; emit hoveredChanged(m_hovered); } return QWidget::event(event); } bool ProgressView::eventFilter(QObject *obj, QEvent *event) { if ((obj == parentWidget() || obj == m_referenceWidget) && event->type() == QEvent::Resize) reposition(); return false; } void ProgressView::reposition() { if (!parentWidget() || !m_referenceWidget) return; QPoint topRightReferenceInParent = m_referenceWidget->mapTo(parentWidget(), m_referenceWidget->rect().topRight()); move(topRightReferenceInParent - rect().bottomRight()); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmlstate.h" #include "qmlmodelview.h" #include <nodelistproperty.h> #include <variantproperty.h> #include <metainfo.h> #include <invalidmodelnodeexception.h> #include "bindingproperty.h" namespace QmlDesigner { QmlModelState::QmlModelState() : QmlModelNodeFacade(), m_isBaseState(false) { } QmlModelState::QmlModelState(const ModelNode &modelNode) : QmlModelNodeFacade(modelNode), m_isBaseState(false) { } QmlPropertyChanges QmlModelState::propertyChanges(const ModelNode &node) { //### exception if not valid if (isBaseState()) return QmlPropertyChanges(); addChangeSetIfNotExists(node); foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) { //### exception if not valid QmlModelStateOperation if (QmlPropertyChanges(childNode).target().isValid() && QmlPropertyChanges(childNode).target() == node) return QmlPropertyChanges(childNode); //### exception if not valid(childNode); } return QmlPropertyChanges(); //not found } QList<QmlModelStateOperation> QmlModelState::stateOperations(const ModelNode &node) const { QList<QmlModelStateOperation> returnList; //### exception if not valid if (isBaseState()) return returnList; if (!modelNode().hasProperty("changes")) return returnList; Q_ASSERT(modelNode().property("changes").isNodeListProperty()); foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) { QmlModelStateOperation stateOperation(childNode); if (stateOperation.isValid()) { ModelNode targetNode = stateOperation.target(); if (targetNode.isValid() && targetNode == node) returnList.append(stateOperation); //### exception if not valid(childNode); } } return returnList; //not found } QList<QmlPropertyChanges> QmlModelState::propertyChanges() const { //### exception if not valid QList<QmlPropertyChanges> returnList; if (isBaseState()) return returnList; if (!modelNode().hasProperty("changes")) return returnList; Q_ASSERT(modelNode().property("changes").isNodeListProperty()); foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) { //### exception if not valid QmlModelStateOperation if (QmlPropertyChanges(childNode).isValid()) returnList.append(QmlPropertyChanges(childNode)); } return returnList; } bool QmlModelState::hasPropertyChanges(const ModelNode &node) const { //### exception if not valid if (isBaseState()) return false; foreach(const QmlPropertyChanges &changeSet, propertyChanges()) { if (changeSet.target().isValid() && changeSet.target() == node) return true; } return false; } bool QmlModelState::hasStateOperation(const ModelNode &node) const { //### exception if not valid if (isBaseState()) return false; foreach(const QmlModelStateOperation &stateOperation, stateOperations()) { if (stateOperation.target() == node) return true; } return false; } QList<QmlModelStateOperation> QmlModelState::stateOperations() const { //### exception if not valid QList<QmlModelStateOperation> returnList; if (isBaseState()) return returnList; if (!modelNode().hasProperty("changes")) return returnList; Q_ASSERT(modelNode().property("changes").isNodeListProperty()); foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) { //### exception if not valid QmlModelStateOperation if (QmlModelStateOperation(childNode).isValid()) returnList.append(QmlModelStateOperation(childNode)); } return returnList; } /*! \brief Add a ChangeSet for the specified ModelNode to this state The new ChangeSet if only added if no ChangeSet for the ModelNode does not exist, yet. */ void QmlModelState::addChangeSetIfNotExists(const ModelNode &node) { //### exception if not valid if (!isValid()) throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__); if (hasPropertyChanges(node)) { return; //changeSet already there } ModelNode newChangeSet = modelNode().view()->createModelNode("Qt/PropertyChanges", 4, 7); modelNode().nodeListProperty("changes").reparentHere(newChangeSet); QmlPropertyChanges(newChangeSet).setTarget(node); Q_ASSERT(QmlPropertyChanges(newChangeSet).isValid()); } void QmlModelState::removePropertyChanges(const ModelNode &node) { //### exception if not valid if (!isValid()) throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__); if (isBaseState()) return; QmlPropertyChanges theChangeSet(propertyChanges(node)); if (theChangeSet.isValid()) theChangeSet.modelNode().destroy(); } /*! \brief Returns if this state affects the specified ModelNode \return true if this state affects the specifigied ModelNode */ bool QmlModelState::affectsModelNode(const ModelNode &node) const { if (isBaseState()) return false; return !stateOperations(node).isEmpty(); } QList<QmlObjectNode> QmlModelState::allAffectedNodes() const { QList<QmlObjectNode> returnList; foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) { //### exception if not valid QmlModelStateOperation if (QmlModelStateOperation(childNode).isValid() && !returnList.contains(QmlModelStateOperation(childNode).target())) returnList.append(QmlModelStateOperation(childNode).target()); } return returnList; } QString QmlModelState::name() const { if (isBaseState()) return QString(""); return modelNode().variantProperty("name").value().toString(); } void QmlModelState::setName(const QString &name) { if ((!isBaseState()) && (modelNode().isValid())) modelNode().variantProperty("name").setValue(name); } bool QmlModelState::isValid() const { return QmlModelNodeFacade::isValid() && modelNode().metaInfo().isValid() && (modelNode().metaInfo().isSubclassOf("Qt/State", 4, 7) || isBaseState()); } /** Removes state node & all subnodes. */ void QmlModelState::destroy() { Q_ASSERT(isValid()); modelNode().destroy(); } /*! \brief Returns if this state is the base state \return true if this state is the base state */ bool QmlModelState::isBaseState() const { return m_isBaseState && modelNode().isRootNode(); } QmlModelState QmlModelState::duplicate(const QString &name) const { if (!isValid()) throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__); QmlItemNode parentNode(modelNode().parentProperty().parentModelNode()); if (!parentNode.isValid()) throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__); // QmlModelState newState(stateGroup().addState(name)); PropertyListType propertyList; propertyList.append(qMakePair(QString("name"), QVariant(name))); QmlModelState newState ( qmlModelView()->createModelNode("Qt/State", 4, 7, propertyList) ); foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) { ModelNode newModelNode(qmlModelView()->createModelNode(childNode.type(), childNode.majorVersion(), childNode.minorVersion())); foreach (const BindingProperty &bindingProperty, childNode.bindingProperties()) newModelNode.bindingProperty(bindingProperty.name()).setExpression(bindingProperty.expression()); foreach (const VariantProperty &variantProperty, childNode.variantProperties()) newModelNode.variantProperty(variantProperty.name()) = variantProperty.value(); newState.modelNode().nodeListProperty("changes").reparentHere(newModelNode); } modelNode().parentProperty().reparentHere(newState); return newState; } QmlModelStateGroup QmlModelState::stateGroup() const { QmlItemNode parentNode(modelNode().parentProperty().parentModelNode()); return parentNode.states(); } QmlModelState QmlModelState::createBaseState(const QmlModelView *view) { QmlModelState fxState(view->rootModelNode()); fxState.m_isBaseState = true; return fxState; } } // QmlDesigner <commit_msg>QmlDesigner.model: crash fix<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qmlstate.h" #include "qmlmodelview.h" #include <nodelistproperty.h> #include <variantproperty.h> #include <metainfo.h> #include <invalidmodelnodeexception.h> #include "bindingproperty.h" namespace QmlDesigner { QmlModelState::QmlModelState() : QmlModelNodeFacade(), m_isBaseState(false) { } QmlModelState::QmlModelState(const ModelNode &modelNode) : QmlModelNodeFacade(modelNode), m_isBaseState(false) { } QmlPropertyChanges QmlModelState::propertyChanges(const ModelNode &node) { //### exception if not valid if (isBaseState()) return QmlPropertyChanges(); addChangeSetIfNotExists(node); foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) { //### exception if not valid QmlModelStateOperation if (QmlPropertyChanges(childNode).target().isValid() && QmlPropertyChanges(childNode).target() == node && QmlPropertyChanges(childNode).isValid()) return QmlPropertyChanges(childNode); //### exception if not valid(childNode); } return QmlPropertyChanges(); //not found } QList<QmlModelStateOperation> QmlModelState::stateOperations(const ModelNode &node) const { QList<QmlModelStateOperation> returnList; //### exception if not valid if (isBaseState()) return returnList; if (!modelNode().hasProperty("changes")) return returnList; Q_ASSERT(modelNode().property("changes").isNodeListProperty()); foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) { QmlModelStateOperation stateOperation(childNode); if (stateOperation.isValid()) { ModelNode targetNode = stateOperation.target(); if (targetNode.isValid() && targetNode == node) returnList.append(stateOperation); //### exception if not valid(childNode); } } return returnList; //not found } QList<QmlPropertyChanges> QmlModelState::propertyChanges() const { //### exception if not valid QList<QmlPropertyChanges> returnList; if (isBaseState()) return returnList; if (!modelNode().hasProperty("changes")) return returnList; Q_ASSERT(modelNode().property("changes").isNodeListProperty()); foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) { //### exception if not valid QmlModelStateOperation if (QmlPropertyChanges(childNode).isValid()) returnList.append(QmlPropertyChanges(childNode)); } return returnList; } bool QmlModelState::hasPropertyChanges(const ModelNode &node) const { //### exception if not valid if (isBaseState()) return false; foreach(const QmlPropertyChanges &changeSet, propertyChanges()) { if (changeSet.target().isValid() && changeSet.target() == node) return true; } return false; } bool QmlModelState::hasStateOperation(const ModelNode &node) const { //### exception if not valid if (isBaseState()) return false; foreach(const QmlModelStateOperation &stateOperation, stateOperations()) { if (stateOperation.target() == node) return true; } return false; } QList<QmlModelStateOperation> QmlModelState::stateOperations() const { //### exception if not valid QList<QmlModelStateOperation> returnList; if (isBaseState()) return returnList; if (!modelNode().hasProperty("changes")) return returnList; Q_ASSERT(modelNode().property("changes").isNodeListProperty()); foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) { //### exception if not valid QmlModelStateOperation if (QmlModelStateOperation(childNode).isValid()) returnList.append(QmlModelStateOperation(childNode)); } return returnList; } /*! \brief Add a ChangeSet for the specified ModelNode to this state The new ChangeSet if only added if no ChangeSet for the ModelNode does not exist, yet. */ void QmlModelState::addChangeSetIfNotExists(const ModelNode &node) { //### exception if not valid if (!isValid()) throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__); if (hasPropertyChanges(node)) { return; //changeSet already there } ModelNode newChangeSet = modelNode().view()->createModelNode("Qt/PropertyChanges", 4, 7); modelNode().nodeListProperty("changes").reparentHere(newChangeSet); QmlPropertyChanges(newChangeSet).setTarget(node); Q_ASSERT(QmlPropertyChanges(newChangeSet).isValid()); } void QmlModelState::removePropertyChanges(const ModelNode &node) { //### exception if not valid if (!isValid()) throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__); if (isBaseState()) return; QmlPropertyChanges theChangeSet(propertyChanges(node)); if (theChangeSet.isValid()) theChangeSet.modelNode().destroy(); } /*! \brief Returns if this state affects the specified ModelNode \return true if this state affects the specifigied ModelNode */ bool QmlModelState::affectsModelNode(const ModelNode &node) const { if (isBaseState()) return false; return !stateOperations(node).isEmpty(); } QList<QmlObjectNode> QmlModelState::allAffectedNodes() const { QList<QmlObjectNode> returnList; foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) { //### exception if not valid QmlModelStateOperation if (QmlModelStateOperation(childNode).isValid() && !returnList.contains(QmlModelStateOperation(childNode).target())) returnList.append(QmlModelStateOperation(childNode).target()); } return returnList; } QString QmlModelState::name() const { if (isBaseState()) return QString(""); return modelNode().variantProperty("name").value().toString(); } void QmlModelState::setName(const QString &name) { if ((!isBaseState()) && (modelNode().isValid())) modelNode().variantProperty("name").setValue(name); } bool QmlModelState::isValid() const { return QmlModelNodeFacade::isValid() && modelNode().metaInfo().isValid() && (modelNode().metaInfo().isSubclassOf("Qt/State", 4, 7) || isBaseState()); } /** Removes state node & all subnodes. */ void QmlModelState::destroy() { Q_ASSERT(isValid()); modelNode().destroy(); } /*! \brief Returns if this state is the base state \return true if this state is the base state */ bool QmlModelState::isBaseState() const { return m_isBaseState && modelNode().isRootNode(); } QmlModelState QmlModelState::duplicate(const QString &name) const { if (!isValid()) throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__); QmlItemNode parentNode(modelNode().parentProperty().parentModelNode()); if (!parentNode.isValid()) throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__); // QmlModelState newState(stateGroup().addState(name)); PropertyListType propertyList; propertyList.append(qMakePair(QString("name"), QVariant(name))); QmlModelState newState ( qmlModelView()->createModelNode("Qt/State", 4, 7, propertyList) ); foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) { ModelNode newModelNode(qmlModelView()->createModelNode(childNode.type(), childNode.majorVersion(), childNode.minorVersion())); foreach (const BindingProperty &bindingProperty, childNode.bindingProperties()) newModelNode.bindingProperty(bindingProperty.name()).setExpression(bindingProperty.expression()); foreach (const VariantProperty &variantProperty, childNode.variantProperties()) newModelNode.variantProperty(variantProperty.name()) = variantProperty.value(); newState.modelNode().nodeListProperty("changes").reparentHere(newModelNode); } modelNode().parentProperty().reparentHere(newState); return newState; } QmlModelStateGroup QmlModelState::stateGroup() const { QmlItemNode parentNode(modelNode().parentProperty().parentModelNode()); return parentNode.states(); } QmlModelState QmlModelState::createBaseState(const QmlModelView *view) { QmlModelState fxState(view->rootModelNode()); fxState.m_isBaseState = true; return fxState; } } // QmlDesigner <|endoftext|>
<commit_before>#include <sstream> #include <iostream> #include <fstream> #include <vector> #include <cassert> #include <cmath> #include <tr1/memory> #include <boost/program_options.hpp> #include <boost/program_options/variables_map.hpp> #include "verbose.h" #include "hg.h" #include "prob.h" #include "inside_outside.h" #include "ff_register.h" #include "decoder.h" #include "filelib.h" #include "online_optimizer.h" #include "fdict.h" #include "weights.h" #include "sparse_vector.h" #include "sampler.h" #ifdef HAVE_MPI #include <boost/mpi/timer.hpp> #include <boost/mpi.hpp> namespace mpi = boost::mpi; #endif using namespace std; namespace po = boost::program_options; void SanityCheck(const vector<double>& w) { for (int i = 0; i < w.size(); ++i) { assert(!isnan(w[i])); assert(!isinf(w[i])); } } struct FComp { const vector<double>& w_; FComp(const vector<double>& w) : w_(w) {} bool operator()(int a, int b) const { return fabs(w_[a]) > fabs(w_[b]); } }; void ShowLargestFeatures(const vector<double>& w) { vector<int> fnums(w.size()); for (int i = 0; i < w.size(); ++i) fnums[i] = i; vector<int>::iterator mid = fnums.begin(); mid += (w.size() > 10 ? 10 : w.size()); partial_sort(fnums.begin(), mid, fnums.end(), FComp(w)); cerr << "TOP FEATURES:"; for (vector<int>::iterator i = fnums.begin(); i != mid; ++i) { cerr << ' ' << FD::Convert(*i) << '=' << w[*i]; } cerr << endl; } bool InitCommandLine(int argc, char** argv, po::variables_map* conf) { po::options_description opts("Configuration options"); opts.add_options() ("input_weights,w",po::value<string>(),"Input feature weights file") ("training_data,t",po::value<string>(),"Training data corpus") ("training_agenda,a",po::value<string>(), "Text file listing a series of configuration files and the number of iterations to train using each configuration successively") ("minibatch_size_per_proc,s", po::value<unsigned>()->default_value(5), "Number of training instances evaluated per processor in each minibatch") ("optimization_method,m", po::value<string>()->default_value("sgd"), "Optimization method (sgd)") ("random_seed,S", po::value<uint32_t>(), "Random seed (if not specified, /dev/random will be used)") ("eta_0,e", po::value<double>()->default_value(0.2), "Initial learning rate for SGD (eta_0)") ("L1,1","Use L1 regularization") ("regularization_strength,C", po::value<double>()->default_value(1.0), "Regularization strength (C)"); po::options_description clo("Command line options"); clo.add_options() ("config", po::value<string>(), "Configuration file") ("help,h", "Print this help message and exit"); po::options_description dconfig_options, dcmdline_options; dconfig_options.add(opts); dcmdline_options.add(opts).add(clo); po::store(parse_command_line(argc, argv, dcmdline_options), *conf); if (conf->count("config")) { ifstream config((*conf)["config"].as<string>().c_str()); po::store(po::parse_config_file(config, dconfig_options), *conf); } po::notify(*conf); if (conf->count("help") || !conf->count("training_data") || !conf->count("training_agenda")) { cerr << dcmdline_options << endl; return false; } return true; } void ReadTrainingCorpus(const string& fname, int rank, int size, vector<string>* c, vector<int>* order) { ReadFile rf(fname); istream& in = *rf.stream(); string line; int id = 0; while(in) { getline(in, line); if (!in) break; if (id % size == rank) { c->push_back(line); order->push_back(id); } ++id; } } static const double kMINUS_EPSILON = -1e-6; struct TrainingObserver : public DecoderObserver { void Reset() { acc_grad.clear(); acc_obj = 0; total_complete = 0; } void SetLocalGradientAndObjective(vector<double>* g, double* o) const { *o = acc_obj; for (SparseVector<prob_t>::const_iterator it = acc_grad.begin(); it != acc_grad.end(); ++it) (*g)[it->first] = it->second; } virtual void NotifyDecodingStart(const SentenceMetadata& smeta) { cur_model_exp.clear(); cur_obj = 0; state = 1; } // compute model expectations, denominator of objective virtual void NotifyTranslationForest(const SentenceMetadata& smeta, Hypergraph* hg) { assert(state == 1); state = 2; const prob_t z = InsideOutside<prob_t, EdgeProb, SparseVector<prob_t>, EdgeFeaturesAndProbWeightFunction>(*hg, &cur_model_exp); cur_obj = log(z); cur_model_exp /= z; } // compute "empirical" expectations, numerator of objective virtual void NotifyAlignmentForest(const SentenceMetadata& smeta, Hypergraph* hg) { assert(state == 2); state = 3; SparseVector<prob_t> ref_exp; const prob_t ref_z = InsideOutside<prob_t, EdgeProb, SparseVector<prob_t>, EdgeFeaturesAndProbWeightFunction>(*hg, &ref_exp); ref_exp /= ref_z; double log_ref_z; #if 0 if (crf_uniform_empirical) { log_ref_z = ref_exp.dot(feature_weights); } else { log_ref_z = log(ref_z); } #else log_ref_z = log(ref_z); #endif // rounding errors means that <0 is too strict if ((cur_obj - log_ref_z) < kMINUS_EPSILON) { cerr << "DIFF. ERR! log_model_z < log_ref_z: " << cur_obj << " " << log_ref_z << endl; exit(1); } assert(!isnan(log_ref_z)); ref_exp -= cur_model_exp; acc_grad += ref_exp; acc_obj += (cur_obj - log_ref_z); } virtual void NotifyDecodingComplete(const SentenceMetadata& smeta) { if (state == 3) { ++total_complete; } else { } } void GetGradient(SparseVector<double>* g) const { g->clear(); for (SparseVector<prob_t>::const_iterator it = acc_grad.begin(); it != acc_grad.end(); ++it) g->set_value(it->first, it->second); } int total_complete; SparseVector<prob_t> cur_model_exp; SparseVector<prob_t> acc_grad; double acc_obj; double cur_obj; int state; }; #ifdef HAVE_MPI namespace boost { namespace mpi { template<> struct is_commutative<std::plus<SparseVector<double> >, SparseVector<double> > : mpl::true_ { }; } } // end namespace boost::mpi #endif bool LoadAgenda(const string& file, vector<pair<string, int> >* a) { ReadFile rf(file); istream& in = *rf.stream(); string line; while(in) { getline(in, line); if (!in) break; if (line.empty()) continue; if (line[0] == '#') continue; int sc = 0; if (line.size() < 3) return false; for (int i = 0; i < line.size(); ++i) { if (line[i] == ' ') ++sc; } if (sc != 1) { cerr << "Too many spaces in line: " << line << endl; return false; } size_t d = line.find(" "); pair<string, int> x; x.first = line.substr(0,d); x.second = atoi(line.substr(d+1).c_str()); a->push_back(x); if (!FileExists(x.first)) { cerr << "Can't find file " << x.first << endl; return false; } } return true; } int main(int argc, char** argv) { #ifdef HAVE_MPI mpi::environment env(argc, argv); mpi::communicator world; const int size = world.size(); const int rank = world.rank(); #else const int size = 1; const int rank = 0; #endif if (size > 1) SetSilent(true); // turn off verbose decoder output register_feature_functions(); std::tr1::shared_ptr<MT19937> rng; po::variables_map conf; if (!InitCommandLine(argc, argv, &conf)) return 1; // load initial weights Weights weights; if (conf.count("input_weights")) weights.InitFromFile(conf["input_weights"].as<string>()); vector<string> corpus; vector<int> ids; ReadTrainingCorpus(conf["training_data"].as<string>(), rank, size, &corpus, &ids); assert(corpus.size() > 0); std::tr1::shared_ptr<OnlineOptimizer> o; std::tr1::shared_ptr<LearningRateSchedule> lr; const unsigned size_per_proc = conf["minibatch_size_per_proc"].as<unsigned>(); if (size_per_proc > corpus.size()) { cerr << "Minibatch size must be smaller than corpus size!\n"; return 1; } size_t total_corpus_size = 0; #ifdef HAVE_MPI reduce(world, corpus.size(), total_corpus_size, std::plus<size_t>(), 0); #else total_corpus_size = corpus.size(); #endif if (rank == 0) { cerr << "Total corpus size: " << total_corpus_size << endl; const unsigned batch_size = size_per_proc * size; // TODO config lr.reset(new ExponentialDecayLearningRate(batch_size, conf["eta_0"].as<double>())); const string omethod = conf["optimization_method"].as<string>(); if (omethod == "sgd") { const double C = conf["regularization_strength"].as<double>(); o.reset(new CumulativeL1OnlineOptimizer(lr, total_corpus_size, C)); } else { assert(!"fail"); } } if (conf.count("random_seed")) rng.reset(new MT19937(conf["random_seed"].as<uint32_t>())); else rng.reset(new MT19937); SparseVector<double> x; weights.InitSparseVector(&x); TrainingObserver observer; int write_weights_every_ith = 100; // TODO configure int titer = -1; vector<pair<string, int> > agenda; if (!LoadAgenda(conf["training_agenda"].as<string>(), &agenda)) return 1; if (rank == 0) cerr << "Loaded agenda defining " << agenda.size() << " training epochs\n"; vector<double> lambdas; for (int ai = 0; ai < agenda.size(); ++ai) { const string& cur_config = agenda[ai].first; const unsigned max_iteration = agenda[ai].second; if (rank == 0) cerr << "STARTING TRAINING EPOCH " << (ai+1) << ". CONFIG=" << cur_config << endl; // load cdec.ini and set up decoder ReadFile ini_rf(cur_config); Decoder decoder(ini_rf.stream()); if (rank == 0) o->ResetEpoch(); // resets the learning rate-- TODO is this good? int iter = -1; bool converged = false; while (!converged) { #ifdef HAVE_MPI mpi::timer timer; #endif weights.InitFromVector(x); weights.InitVector(&lambdas); ++iter; ++titer; observer.Reset(); decoder.SetWeights(lambdas); if (rank == 0) { converged = (iter == max_iteration); SanityCheck(lambdas); ShowLargestFeatures(lambdas); string fname = "weights.cur.gz"; if (iter % write_weights_every_ith == 0) { ostringstream o; o << "weights.epoch_" << (ai+1) << '.' << iter << ".gz"; fname = o.str(); } if (converged && ((ai+1)==agenda.size())) { fname = "weights.final.gz"; } ostringstream vv; vv << "total iter=" << titer << " (of current config iter=" << iter << ") minibatch=" << size_per_proc << " sentences/proc x " << size << " procs. num_feats=" << x.size() << '/' << FD::NumFeats() << " passes_thru_data=" << (titer * size_per_proc / static_cast<double>(corpus.size())) << " eta=" << lr->eta(titer); const string svv = vv.str(); cerr << svv << endl; weights.WriteToFile(fname, true, &svv); } for (int i = 0; i < size_per_proc; ++i) { int ei = corpus.size() * rng->next(); int id = ids[ei]; decoder.SetId(id); decoder.Decode(corpus[ei], &observer); } SparseVector<double> local_grad, g; observer.GetGradient(&local_grad); #ifdef HAVE_MPI reduce(world, local_grad, g, std::plus<SparseVector<double> >(), 0); #else g.swap(local_grad); #endif local_grad.clear(); if (rank == 0) { g /= (size_per_proc * size); o->UpdateWeights(g, FD::NumFeats(), &x); } #ifdef HAVE_MPI broadcast(world, x, 0); broadcast(world, converged, 0); world.barrier(); if (rank == 0) { cerr << " ELAPSED TIME THIS ITERATION=" << timer.elapsed() << endl; } #endif } } return 0; } <commit_msg>enable weights to be frozen during training<commit_after>#include <sstream> #include <iostream> #include <fstream> #include <vector> #include <cassert> #include <cmath> #include <tr1/memory> #include <boost/program_options.hpp> #include <boost/program_options/variables_map.hpp> #include "verbose.h" #include "hg.h" #include "prob.h" #include "inside_outside.h" #include "ff_register.h" #include "decoder.h" #include "filelib.h" #include "online_optimizer.h" #include "fdict.h" #include "weights.h" #include "sparse_vector.h" #include "sampler.h" #ifdef HAVE_MPI #include <boost/mpi/timer.hpp> #include <boost/mpi.hpp> namespace mpi = boost::mpi; #endif using namespace std; namespace po = boost::program_options; void SanityCheck(const vector<double>& w) { for (int i = 0; i < w.size(); ++i) { assert(!isnan(w[i])); assert(!isinf(w[i])); } } struct FComp { const vector<double>& w_; FComp(const vector<double>& w) : w_(w) {} bool operator()(int a, int b) const { return fabs(w_[a]) > fabs(w_[b]); } }; void ShowLargestFeatures(const vector<double>& w) { vector<int> fnums(w.size()); for (int i = 0; i < w.size(); ++i) fnums[i] = i; vector<int>::iterator mid = fnums.begin(); mid += (w.size() > 10 ? 10 : w.size()); partial_sort(fnums.begin(), mid, fnums.end(), FComp(w)); cerr << "TOP FEATURES:"; for (vector<int>::iterator i = fnums.begin(); i != mid; ++i) { cerr << ' ' << FD::Convert(*i) << '=' << w[*i]; } cerr << endl; } bool InitCommandLine(int argc, char** argv, po::variables_map* conf) { po::options_description opts("Configuration options"); opts.add_options() ("input_weights,w",po::value<string>(),"Input feature weights file") ("frozen_features,z",po::value<string>(), "List of features not to optimize") ("training_data,t",po::value<string>(),"Training data corpus") ("training_agenda,a",po::value<string>(), "Text file listing a series of configuration files and the number of iterations to train using each configuration successively") ("minibatch_size_per_proc,s", po::value<unsigned>()->default_value(5), "Number of training instances evaluated per processor in each minibatch") ("optimization_method,m", po::value<string>()->default_value("sgd"), "Optimization method (sgd)") ("random_seed,S", po::value<uint32_t>(), "Random seed (if not specified, /dev/random will be used)") ("eta_0,e", po::value<double>()->default_value(0.2), "Initial learning rate for SGD (eta_0)") ("L1,1","Use L1 regularization") ("regularization_strength,C", po::value<double>()->default_value(1.0), "Regularization strength (C)"); po::options_description clo("Command line options"); clo.add_options() ("config", po::value<string>(), "Configuration file") ("help,h", "Print this help message and exit"); po::options_description dconfig_options, dcmdline_options; dconfig_options.add(opts); dcmdline_options.add(opts).add(clo); po::store(parse_command_line(argc, argv, dcmdline_options), *conf); if (conf->count("config")) { ifstream config((*conf)["config"].as<string>().c_str()); po::store(po::parse_config_file(config, dconfig_options), *conf); } po::notify(*conf); if (conf->count("help") || !conf->count("training_data") || !conf->count("training_agenda")) { cerr << dcmdline_options << endl; return false; } return true; } void ReadTrainingCorpus(const string& fname, int rank, int size, vector<string>* c, vector<int>* order) { ReadFile rf(fname); istream& in = *rf.stream(); string line; int id = 0; while(in) { getline(in, line); if (!in) break; if (id % size == rank) { c->push_back(line); order->push_back(id); } ++id; } } static const double kMINUS_EPSILON = -1e-6; struct TrainingObserver : public DecoderObserver { void Reset() { acc_grad.clear(); acc_obj = 0; total_complete = 0; } void SetLocalGradientAndObjective(vector<double>* g, double* o) const { *o = acc_obj; for (SparseVector<prob_t>::const_iterator it = acc_grad.begin(); it != acc_grad.end(); ++it) (*g)[it->first] = it->second; } virtual void NotifyDecodingStart(const SentenceMetadata& smeta) { cur_model_exp.clear(); cur_obj = 0; state = 1; } // compute model expectations, denominator of objective virtual void NotifyTranslationForest(const SentenceMetadata& smeta, Hypergraph* hg) { assert(state == 1); state = 2; const prob_t z = InsideOutside<prob_t, EdgeProb, SparseVector<prob_t>, EdgeFeaturesAndProbWeightFunction>(*hg, &cur_model_exp); cur_obj = log(z); cur_model_exp /= z; } // compute "empirical" expectations, numerator of objective virtual void NotifyAlignmentForest(const SentenceMetadata& smeta, Hypergraph* hg) { assert(state == 2); state = 3; SparseVector<prob_t> ref_exp; const prob_t ref_z = InsideOutside<prob_t, EdgeProb, SparseVector<prob_t>, EdgeFeaturesAndProbWeightFunction>(*hg, &ref_exp); ref_exp /= ref_z; double log_ref_z; #if 0 if (crf_uniform_empirical) { log_ref_z = ref_exp.dot(feature_weights); } else { log_ref_z = log(ref_z); } #else log_ref_z = log(ref_z); #endif // rounding errors means that <0 is too strict if ((cur_obj - log_ref_z) < kMINUS_EPSILON) { cerr << "DIFF. ERR! log_model_z < log_ref_z: " << cur_obj << " " << log_ref_z << endl; exit(1); } assert(!isnan(log_ref_z)); ref_exp -= cur_model_exp; acc_grad += ref_exp; acc_obj += (cur_obj - log_ref_z); } virtual void NotifyDecodingComplete(const SentenceMetadata& smeta) { if (state == 3) { ++total_complete; } else { } } void GetGradient(SparseVector<double>* g) const { g->clear(); for (SparseVector<prob_t>::const_iterator it = acc_grad.begin(); it != acc_grad.end(); ++it) g->set_value(it->first, it->second); } int total_complete; SparseVector<prob_t> cur_model_exp; SparseVector<prob_t> acc_grad; double acc_obj; double cur_obj; int state; }; #ifdef HAVE_MPI namespace boost { namespace mpi { template<> struct is_commutative<std::plus<SparseVector<double> >, SparseVector<double> > : mpl::true_ { }; } } // end namespace boost::mpi #endif bool LoadAgenda(const string& file, vector<pair<string, int> >* a) { ReadFile rf(file); istream& in = *rf.stream(); string line; while(in) { getline(in, line); if (!in) break; if (line.empty()) continue; if (line[0] == '#') continue; int sc = 0; if (line.size() < 3) return false; for (int i = 0; i < line.size(); ++i) { if (line[i] == ' ') ++sc; } if (sc != 1) { cerr << "Too many spaces in line: " << line << endl; return false; } size_t d = line.find(" "); pair<string, int> x; x.first = line.substr(0,d); x.second = atoi(line.substr(d+1).c_str()); a->push_back(x); if (!FileExists(x.first)) { cerr << "Can't find file " << x.first << endl; return false; } } return true; } int main(int argc, char** argv) { #ifdef HAVE_MPI mpi::environment env(argc, argv); mpi::communicator world; const int size = world.size(); const int rank = world.rank(); #else const int size = 1; const int rank = 0; #endif if (size > 1) SetSilent(true); // turn off verbose decoder output register_feature_functions(); std::tr1::shared_ptr<MT19937> rng; po::variables_map conf; if (!InitCommandLine(argc, argv, &conf)) return 1; // load initial weights Weights weights; if (conf.count("input_weights")) weights.InitFromFile(conf["input_weights"].as<string>()); vector<int> frozen_fids; if (conf.count("frozen_features")) { ReadFile rf(conf["frozen_features"].as<string>()); istream& in = *rf.stream(); string line; while(in) { getline(in, line); if (line.empty()) continue; if (line[0] == ' ' || line[line.size() - 1] == ' ') { line = Trim(line); } frozen_fids.push_back(FD::Convert(line)); } if (rank == 0) cerr << "Freezing " << frozen_fids.size() << " features.\n"; } vector<string> corpus; vector<int> ids; ReadTrainingCorpus(conf["training_data"].as<string>(), rank, size, &corpus, &ids); assert(corpus.size() > 0); std::tr1::shared_ptr<OnlineOptimizer> o; std::tr1::shared_ptr<LearningRateSchedule> lr; const unsigned size_per_proc = conf["minibatch_size_per_proc"].as<unsigned>(); if (size_per_proc > corpus.size()) { cerr << "Minibatch size must be smaller than corpus size!\n"; return 1; } size_t total_corpus_size = 0; #ifdef HAVE_MPI reduce(world, corpus.size(), total_corpus_size, std::plus<size_t>(), 0); #else total_corpus_size = corpus.size(); #endif if (rank == 0) { cerr << "Total corpus size: " << total_corpus_size << endl; const unsigned batch_size = size_per_proc * size; // TODO config lr.reset(new ExponentialDecayLearningRate(batch_size, conf["eta_0"].as<double>())); const string omethod = conf["optimization_method"].as<string>(); if (omethod == "sgd") { const double C = conf["regularization_strength"].as<double>(); o.reset(new CumulativeL1OnlineOptimizer(lr, total_corpus_size, C)); } else { assert(!"fail"); } } if (conf.count("random_seed")) rng.reset(new MT19937(conf["random_seed"].as<uint32_t>())); else rng.reset(new MT19937); SparseVector<double> x; weights.InitSparseVector(&x); TrainingObserver observer; int write_weights_every_ith = 100; // TODO configure int titer = -1; vector<pair<string, int> > agenda; if (!LoadAgenda(conf["training_agenda"].as<string>(), &agenda)) return 1; if (rank == 0) cerr << "Loaded agenda defining " << agenda.size() << " training epochs\n"; vector<double> lambdas; for (int ai = 0; ai < agenda.size(); ++ai) { const string& cur_config = agenda[ai].first; const unsigned max_iteration = agenda[ai].second; if (rank == 0) cerr << "STARTING TRAINING EPOCH " << (ai+1) << ". CONFIG=" << cur_config << endl; // load cdec.ini and set up decoder ReadFile ini_rf(cur_config); Decoder decoder(ini_rf.stream()); if (rank == 0) o->ResetEpoch(); // resets the learning rate-- TODO is this good? int iter = -1; bool converged = false; while (!converged) { #ifdef HAVE_MPI mpi::timer timer; #endif weights.InitFromVector(x); weights.InitVector(&lambdas); ++iter; ++titer; observer.Reset(); decoder.SetWeights(lambdas); if (rank == 0) { converged = (iter == max_iteration); SanityCheck(lambdas); ShowLargestFeatures(lambdas); string fname = "weights.cur.gz"; if (iter % write_weights_every_ith == 0) { ostringstream o; o << "weights.epoch_" << (ai+1) << '.' << iter << ".gz"; fname = o.str(); } if (converged && ((ai+1)==agenda.size())) { fname = "weights.final.gz"; } ostringstream vv; vv << "total iter=" << titer << " (of current config iter=" << iter << ") minibatch=" << size_per_proc << " sentences/proc x " << size << " procs. num_feats=" << x.size() << '/' << FD::NumFeats() << " passes_thru_data=" << (titer * size_per_proc / static_cast<double>(corpus.size())) << " eta=" << lr->eta(titer); const string svv = vv.str(); cerr << svv << endl; weights.WriteToFile(fname, true, &svv); } for (int i = 0; i < size_per_proc; ++i) { int ei = corpus.size() * rng->next(); int id = ids[ei]; decoder.SetId(id); decoder.Decode(corpus[ei], &observer); } SparseVector<double> local_grad, g; observer.GetGradient(&local_grad); #ifdef HAVE_MPI reduce(world, local_grad, g, std::plus<SparseVector<double> >(), 0); #else g.swap(local_grad); #endif local_grad.clear(); for (int i = 0; i < frozen_fids.size(); ++i) g.erase(frozen_fids[i]); if (rank == 0) { g /= (size_per_proc * size); o->UpdateWeights(g, FD::NumFeats(), &x); } #ifdef HAVE_MPI broadcast(world, x, 0); broadcast(world, converged, 0); world.barrier(); if (rank == 0) { cerr << " ELAPSED TIME THIS ITERATION=" << timer.elapsed() << endl; } #endif } } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2016 Bitcoin Unlimited Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // All global variables that have construction/destruction dependencies // must be placed in this file so that the ctor/dtor order is correct. // Independent global variables may be placed here for organizational // purposes. #include "addrman.h" #include "chain.h" #include "chainparams.h" #include "clientversion.h" #include "consensus/consensus.h" #include "consensus/params.h" #include "consensus/validation.h" #include "leakybucket.h" #include "main.h" #include "miner.h" #include "net.h" #include "parallel.h" #include "policy/policy.h" #include "primitives/block.h" #include "rpc/server.h" #include "stat.h" #include "thinblock.h" #include "timedata.h" #include "tinyformat.h" #include "tweak.h" #include "txmempool.h" #include "ui_interface.h" #include "unlimited.h" #include "util.h" #include "utilstrencodings.h" #include "validationinterface.h" #include "version.h" #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <boost/thread.hpp> #include <inttypes.h> #include <iomanip> #include <queue> using namespace std; #ifdef DEBUG_LOCKORDER boost::mutex dd_mutex; std::map<std::pair<void *, void *>, LockStack> lockorders; boost::thread_specific_ptr<LockStack> lockstack; #endif atomic<bool> fIsInitialBlockDownload{false}; // main.cpp CriticalSections: CCriticalSection cs_LastBlockFile; CCriticalSection cs_nBlockSequenceId; CCriticalSection cs_nTimeOffset; int64_t nTimeOffset = 0; CCriticalSection cs_rpcWarmup; CCriticalSection cs_main; BlockMap mapBlockIndex; CChain chainActive; CWaitableCriticalSection csBestBlock; CConditionVariable cvBlockChange; proxyType proxyInfo[NET_MAX]; proxyType nameProxy; CCriticalSection cs_proxyInfos; set<uint256> setPreVerifiedTxHash; set<uint256> setUnVerifiedOrphanTxHash; CCriticalSection cs_xval; CCriticalSection cs_vNodes; CCriticalSection cs_mapLocalHost; map<CNetAddr, LocalServiceInfo> mapLocalHost; std::vector<CSubNet> CNode::vWhitelistedRange; CCriticalSection CNode::cs_vWhitelistedRange; CCriticalSection CNode::cs_setBanned; uint64_t CNode::nTotalBytesRecv = 0; uint64_t CNode::nTotalBytesSent = 0; CCriticalSection CNode::cs_totalBytesRecv; CCriticalSection CNode::cs_totalBytesSent; // critical sections from net.cpp CCriticalSection cs_setservAddNodeAddresses; CCriticalSection cs_vAddedNodes; CCriticalSection cs_vUseDNSSeeds; CCriticalSection cs_nLastNodeId; CCriticalSection cs_mapInboundConnectionTracker; CCriticalSection cs_vOneShots; CCriticalSection cs_statMap; // semaphore for parallel validation threads CCriticalSection cs_semPV; CSemaphore *semPV; deque<string> vOneShots; std::map<CNetAddr, ConnectionHistory> mapInboundConnectionTracker; vector<std::string> vUseDNSSeeds; vector<std::string> vAddedNodes; set<CNetAddr> setservAddNodeAddresses; uint64_t maxGeneratedBlock = DEFAULT_MAX_GENERATED_BLOCK_SIZE; unsigned int excessiveBlockSize = DEFAULT_EXCESSIVE_BLOCK_SIZE; unsigned int excessiveAcceptDepth = DEFAULT_EXCESSIVE_ACCEPT_DEPTH; unsigned int maxMessageSizeMultiplier = DEFAULT_MAX_MESSAGE_SIZE_MULTIPLIER; int nMaxOutConnections = DEFAULT_MAX_OUTBOUND_CONNECTIONS; uint32_t blockVersion = 0; // Overrides the mined block version if non-zero std::vector<std::string> BUComments = std::vector<std::string>(); std::string minerComment; // Variables for traffic shaping /** Default value for the maximum amount of data that can be received in a burst */ const int64_t DEFAULT_MAX_RECV_BURST = std::numeric_limits<long long>::max(); /** Default value for the maximum amount of data that can be sent in a burst */ const int64_t DEFAULT_MAX_SEND_BURST = std::numeric_limits<long long>::max(); /** Default value for the average amount of data received per second */ const int64_t DEFAULT_AVE_RECV = std::numeric_limits<long long>::max(); /** Default value for the average amount of data sent per second */ const int64_t DEFAULT_AVE_SEND = std::numeric_limits<long long>::max(); CLeakyBucket receiveShaper(DEFAULT_MAX_RECV_BURST, DEFAULT_AVE_RECV); CLeakyBucket sendShaper(DEFAULT_MAX_SEND_BURST, DEFAULT_AVE_SEND); boost::chrono::steady_clock CLeakyBucket::clock; // Variables for statistics tracking, must be before the "requester" singleton instantiation const char *sampleNames[] = {"sec10", "min5", "hourly", "daily", "monthly"}; int operateSampleCount[] = {30, 12, 24, 30}; int interruptIntervals[] = {30, 30 * 12, 30 * 12 * 24, 30 * 12 * 24 * 30}; CTxMemPool mempool(::minRelayTxFee); boost::posix_time::milliseconds statMinInterval(10000); boost::asio::io_service stat_io_service; CStatMap statistics; CTweakMap tweaks; map<CInv, CDataStream> mapRelay; deque<pair<int64_t, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; limitedmap<uint256, int64_t> mapAlreadyAskedFor(MAX_INV_SZ); vector<CNode *> vNodes; list<CNode *> vNodesDisconnected; CSemaphore *semOutbound = NULL; CSemaphore *semOutboundAddNode = NULL; // BU: separate semaphore for -addnodes CNodeSignals g_signals; CAddrMan addrman; // BU: change locking of orphan map from using cs_main to cs_orphancache. There is too much dependance on cs_main locks // which are generally too broad in scope. CCriticalSection cs_orphancache; map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_orphancache); map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_orphancache); CTweakRef<unsigned int> ebTweak("net.excessiveBlock", "Excessive block size in bytes", &excessiveBlockSize, &ExcessiveBlockValidator); CTweak<uint64_t> blockSigopsPerMb("net.excessiveSigopsPerMb", "Excessive effort per block, denoted in cost (# inputs * txsize) per MB", BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS); CTweak<uint64_t> blockMiningSigopsPerMb("mining.excessiveSigopsPerMb", "Excessive effort per block, denoted in cost (# inputs * txsize) per MB", BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS); CTweak<uint64_t> coinbaseReserve("mining.coinbaseReserve", "How much space to reserve for the coinbase transaction, in bytes", DEFAULT_COINBASE_RESERVE_SIZE); CTweakRef<std::string> miningCommentTweak("mining.comment", "Include text in a block's coinbase.", &minerComment); CTweakRef<uint64_t> miningBlockSize("mining.blockSize", "Maximum block size in bytes. The maximum block size returned from 'getblocktemplate' will be this value minus " "mining.coinbaseReserve.", &maxGeneratedBlock, &MiningBlockSizeValidator); CTweak<unsigned int> maxTxSize("net.excessiveTx", "Largest transaction size in bytes", DEFAULT_LARGEST_TRANSACTION); CTweakRef<unsigned int> eadTweak("net.excessiveAcceptDepth", "Excessive block chain acceptance depth in blocks", &excessiveAcceptDepth); CTweakRef<int> maxOutConnectionsTweak("net.maxOutboundConnections", "Maximum number of outbound connections", &nMaxOutConnections, &OutboundConnectionValidator); CTweakRef<int> maxConnectionsTweak("net.maxConnections", "Maximum number of connections", &nMaxConnections); CTweakRef<int> minXthinNodesTweak("net.minXthinNodes", "Minimum number of outbound xthin capable nodes to connect to", &nMinXthinNodes); // When should I request a tx from someone else (in microseconds). cmdline/bitcoin.conf: -txretryinterval CTweakRef<unsigned int> triTweak("net.txRetryInterval", "How long to wait in microseconds before requesting a transaction from another source", &MIN_TX_REQUEST_RETRY_INTERVAL); // When should I request a block from someone else (in microseconds). cmdline/bitcoin.conf: -blkretryinterval CTweakRef<unsigned int> briTweak("net.blockRetryInterval", "How long to wait in microseconds before requesting a block from another source", &MIN_BLK_REQUEST_RETRY_INTERVAL); CTweakRef<std::string> subverOverrideTweak("net.subversionOverride", "If set, this field will override the normal subversion field. This is useful if you need to hide your node.", &subverOverride, &SubverValidator); CTweak<CAmount> maxTxFee("wallet.maxTxFee", "Maximum total fees to use in a single wallet transaction or raw transaction; setting this too low may abort large " "transactions.", DEFAULT_TRANSACTION_MAXFEE); /** Number of blocks that can be requested at any given time from a single peer. */ CTweak<unsigned int> maxBlocksInTransitPerPeer("net.maxBlocksInTransitPerPeer", "Number of blocks that can be requested at any given time from a single peer. 0 means use algorithm.", 0); /** Size of the "block download window": how far ahead of our current height do we fetch? * Larger windows tolerate larger download speed differences between peer, but increase the potential * degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning * harder). We'll probably want to make this a per-peer adaptive value at some point. */ CTweak<unsigned int> blockDownloadWindow("net.blockDownloadWindow", "How far ahead of our current height do we fetch? 0 means use algorithm.", 0); /** This is the initial size of CFileBuffer's RAM buffer during reindex. A larger size will result in a tiny bit better performance if blocks are that size. The real purpose of this parameter is to exhaustively test dynamic buffer resizes during reindexing by allowing the size to be set to low and random values. */ CTweak<uint64_t> reindexTypicalBlockSize("reindex.typicalBlockSize", "Set larger than the typical block size. The block data file's RAM buffer will initally be 2x this size.", TYPICAL_BLOCK_SIZE); /** This is the initial size of CFileBuffer's RAM buffer during reindex. A larger size will result in a tiny bit better performance if blocks are that size. The real purpose of this parameter is to exhaustively test dynamic buffer resizes during reindexing by allowing the size to be set to low and random values. */ CTweak<uint64_t> checkScriptDays("blockchain.checkScriptDays", "The number of days in the past we check scripts during initial block download.", DEFAULT_CHECKPOINT_DAYS); CRequestManager requester; // after the maps nodes and tweaks // Parallel Validation Variables CParallelValidation PV; // Singleton class CAllScriptCheckQueues allScriptCheckQueues; // Singleton class CStatHistory<unsigned int> txAdded; //"memPool/txAdded"); CStatHistory<uint64_t, MinValMax<uint64_t> > poolSize; // "memPool/size",STAT_OP_AVE); CStatHistory<uint64_t> recvAmt; CStatHistory<uint64_t> sendAmt; CStatHistory<uint64_t> nTxValidationTime("txValidationTime", STAT_OP_MAX | STAT_INDIVIDUAL); CStatHistory<uint64_t> nBlockValidationTime("blockValidationTime", STAT_OP_MAX | STAT_INDIVIDUAL); CCriticalSection cs_blockvalidationtime; CThinBlockData thindata; // Singleton class // Expedited blocks std::vector<CNode *> xpeditedBlk; // (256,(CNode*)NULL); // Who requested expedited blocks from us std::vector<CNode *> xpeditedBlkUp; //(256,(CNode*)NULL); // Who we requested expedited blocks from std::vector<CNode *> xpeditedTxn; // (256,(CNode*)NULL); <commit_msg>Add <atomic> to the list of includes in globals.cpp<commit_after>// Copyright (c) 2016 Bitcoin Unlimited Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // All global variables that have construction/destruction dependencies // must be placed in this file so that the ctor/dtor order is correct. // Independent global variables may be placed here for organizational // purposes. #include "addrman.h" #include "chain.h" #include "chainparams.h" #include "clientversion.h" #include "consensus/consensus.h" #include "consensus/params.h" #include "consensus/validation.h" #include "leakybucket.h" #include "main.h" #include "miner.h" #include "net.h" #include "parallel.h" #include "policy/policy.h" #include "primitives/block.h" #include "rpc/server.h" #include "stat.h" #include "thinblock.h" #include "timedata.h" #include "tinyformat.h" #include "tweak.h" #include "txmempool.h" #include "ui_interface.h" #include "unlimited.h" #include "util.h" #include "utilstrencodings.h" #include "validationinterface.h" #include "version.h" #include <atomic> #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <boost/thread.hpp> #include <inttypes.h> #include <iomanip> #include <queue> using namespace std; #ifdef DEBUG_LOCKORDER boost::mutex dd_mutex; std::map<std::pair<void *, void *>, LockStack> lockorders; boost::thread_specific_ptr<LockStack> lockstack; #endif std::atomic<bool> fIsInitialBlockDownload{false}; // main.cpp CriticalSections: CCriticalSection cs_LastBlockFile; CCriticalSection cs_nBlockSequenceId; CCriticalSection cs_nTimeOffset; int64_t nTimeOffset = 0; CCriticalSection cs_rpcWarmup; CCriticalSection cs_main; BlockMap mapBlockIndex; CChain chainActive; CWaitableCriticalSection csBestBlock; CConditionVariable cvBlockChange; proxyType proxyInfo[NET_MAX]; proxyType nameProxy; CCriticalSection cs_proxyInfos; set<uint256> setPreVerifiedTxHash; set<uint256> setUnVerifiedOrphanTxHash; CCriticalSection cs_xval; CCriticalSection cs_vNodes; CCriticalSection cs_mapLocalHost; map<CNetAddr, LocalServiceInfo> mapLocalHost; std::vector<CSubNet> CNode::vWhitelistedRange; CCriticalSection CNode::cs_vWhitelistedRange; CCriticalSection CNode::cs_setBanned; uint64_t CNode::nTotalBytesRecv = 0; uint64_t CNode::nTotalBytesSent = 0; CCriticalSection CNode::cs_totalBytesRecv; CCriticalSection CNode::cs_totalBytesSent; // critical sections from net.cpp CCriticalSection cs_setservAddNodeAddresses; CCriticalSection cs_vAddedNodes; CCriticalSection cs_vUseDNSSeeds; CCriticalSection cs_nLastNodeId; CCriticalSection cs_mapInboundConnectionTracker; CCriticalSection cs_vOneShots; CCriticalSection cs_statMap; // semaphore for parallel validation threads CCriticalSection cs_semPV; CSemaphore *semPV; deque<string> vOneShots; std::map<CNetAddr, ConnectionHistory> mapInboundConnectionTracker; vector<std::string> vUseDNSSeeds; vector<std::string> vAddedNodes; set<CNetAddr> setservAddNodeAddresses; uint64_t maxGeneratedBlock = DEFAULT_MAX_GENERATED_BLOCK_SIZE; unsigned int excessiveBlockSize = DEFAULT_EXCESSIVE_BLOCK_SIZE; unsigned int excessiveAcceptDepth = DEFAULT_EXCESSIVE_ACCEPT_DEPTH; unsigned int maxMessageSizeMultiplier = DEFAULT_MAX_MESSAGE_SIZE_MULTIPLIER; int nMaxOutConnections = DEFAULT_MAX_OUTBOUND_CONNECTIONS; uint32_t blockVersion = 0; // Overrides the mined block version if non-zero std::vector<std::string> BUComments = std::vector<std::string>(); std::string minerComment; // Variables for traffic shaping /** Default value for the maximum amount of data that can be received in a burst */ const int64_t DEFAULT_MAX_RECV_BURST = std::numeric_limits<long long>::max(); /** Default value for the maximum amount of data that can be sent in a burst */ const int64_t DEFAULT_MAX_SEND_BURST = std::numeric_limits<long long>::max(); /** Default value for the average amount of data received per second */ const int64_t DEFAULT_AVE_RECV = std::numeric_limits<long long>::max(); /** Default value for the average amount of data sent per second */ const int64_t DEFAULT_AVE_SEND = std::numeric_limits<long long>::max(); CLeakyBucket receiveShaper(DEFAULT_MAX_RECV_BURST, DEFAULT_AVE_RECV); CLeakyBucket sendShaper(DEFAULT_MAX_SEND_BURST, DEFAULT_AVE_SEND); boost::chrono::steady_clock CLeakyBucket::clock; // Variables for statistics tracking, must be before the "requester" singleton instantiation const char *sampleNames[] = {"sec10", "min5", "hourly", "daily", "monthly"}; int operateSampleCount[] = {30, 12, 24, 30}; int interruptIntervals[] = {30, 30 * 12, 30 * 12 * 24, 30 * 12 * 24 * 30}; CTxMemPool mempool(::minRelayTxFee); boost::posix_time::milliseconds statMinInterval(10000); boost::asio::io_service stat_io_service; CStatMap statistics; CTweakMap tweaks; map<CInv, CDataStream> mapRelay; deque<pair<int64_t, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; limitedmap<uint256, int64_t> mapAlreadyAskedFor(MAX_INV_SZ); vector<CNode *> vNodes; list<CNode *> vNodesDisconnected; CSemaphore *semOutbound = NULL; CSemaphore *semOutboundAddNode = NULL; // BU: separate semaphore for -addnodes CNodeSignals g_signals; CAddrMan addrman; // BU: change locking of orphan map from using cs_main to cs_orphancache. There is too much dependance on cs_main locks // which are generally too broad in scope. CCriticalSection cs_orphancache; map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(cs_orphancache); map<uint256, set<uint256> > mapOrphanTransactionsByPrev GUARDED_BY(cs_orphancache); CTweakRef<unsigned int> ebTweak("net.excessiveBlock", "Excessive block size in bytes", &excessiveBlockSize, &ExcessiveBlockValidator); CTweak<uint64_t> blockSigopsPerMb("net.excessiveSigopsPerMb", "Excessive effort per block, denoted in cost (# inputs * txsize) per MB", BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS); CTweak<uint64_t> blockMiningSigopsPerMb("mining.excessiveSigopsPerMb", "Excessive effort per block, denoted in cost (# inputs * txsize) per MB", BLOCKSTREAM_CORE_MAX_BLOCK_SIGOPS); CTweak<uint64_t> coinbaseReserve("mining.coinbaseReserve", "How much space to reserve for the coinbase transaction, in bytes", DEFAULT_COINBASE_RESERVE_SIZE); CTweakRef<std::string> miningCommentTweak("mining.comment", "Include text in a block's coinbase.", &minerComment); CTweakRef<uint64_t> miningBlockSize("mining.blockSize", "Maximum block size in bytes. The maximum block size returned from 'getblocktemplate' will be this value minus " "mining.coinbaseReserve.", &maxGeneratedBlock, &MiningBlockSizeValidator); CTweak<unsigned int> maxTxSize("net.excessiveTx", "Largest transaction size in bytes", DEFAULT_LARGEST_TRANSACTION); CTweakRef<unsigned int> eadTweak("net.excessiveAcceptDepth", "Excessive block chain acceptance depth in blocks", &excessiveAcceptDepth); CTweakRef<int> maxOutConnectionsTweak("net.maxOutboundConnections", "Maximum number of outbound connections", &nMaxOutConnections, &OutboundConnectionValidator); CTweakRef<int> maxConnectionsTweak("net.maxConnections", "Maximum number of connections", &nMaxConnections); CTweakRef<int> minXthinNodesTweak("net.minXthinNodes", "Minimum number of outbound xthin capable nodes to connect to", &nMinXthinNodes); // When should I request a tx from someone else (in microseconds). cmdline/bitcoin.conf: -txretryinterval CTweakRef<unsigned int> triTweak("net.txRetryInterval", "How long to wait in microseconds before requesting a transaction from another source", &MIN_TX_REQUEST_RETRY_INTERVAL); // When should I request a block from someone else (in microseconds). cmdline/bitcoin.conf: -blkretryinterval CTweakRef<unsigned int> briTweak("net.blockRetryInterval", "How long to wait in microseconds before requesting a block from another source", &MIN_BLK_REQUEST_RETRY_INTERVAL); CTweakRef<std::string> subverOverrideTweak("net.subversionOverride", "If set, this field will override the normal subversion field. This is useful if you need to hide your node.", &subverOverride, &SubverValidator); CTweak<CAmount> maxTxFee("wallet.maxTxFee", "Maximum total fees to use in a single wallet transaction or raw transaction; setting this too low may abort large " "transactions.", DEFAULT_TRANSACTION_MAXFEE); /** Number of blocks that can be requested at any given time from a single peer. */ CTweak<unsigned int> maxBlocksInTransitPerPeer("net.maxBlocksInTransitPerPeer", "Number of blocks that can be requested at any given time from a single peer. 0 means use algorithm.", 0); /** Size of the "block download window": how far ahead of our current height do we fetch? * Larger windows tolerate larger download speed differences between peer, but increase the potential * degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning * harder). We'll probably want to make this a per-peer adaptive value at some point. */ CTweak<unsigned int> blockDownloadWindow("net.blockDownloadWindow", "How far ahead of our current height do we fetch? 0 means use algorithm.", 0); /** This is the initial size of CFileBuffer's RAM buffer during reindex. A larger size will result in a tiny bit better performance if blocks are that size. The real purpose of this parameter is to exhaustively test dynamic buffer resizes during reindexing by allowing the size to be set to low and random values. */ CTweak<uint64_t> reindexTypicalBlockSize("reindex.typicalBlockSize", "Set larger than the typical block size. The block data file's RAM buffer will initally be 2x this size.", TYPICAL_BLOCK_SIZE); /** This is the initial size of CFileBuffer's RAM buffer during reindex. A larger size will result in a tiny bit better performance if blocks are that size. The real purpose of this parameter is to exhaustively test dynamic buffer resizes during reindexing by allowing the size to be set to low and random values. */ CTweak<uint64_t> checkScriptDays("blockchain.checkScriptDays", "The number of days in the past we check scripts during initial block download.", DEFAULT_CHECKPOINT_DAYS); CRequestManager requester; // after the maps nodes and tweaks // Parallel Validation Variables CParallelValidation PV; // Singleton class CAllScriptCheckQueues allScriptCheckQueues; // Singleton class CStatHistory<unsigned int> txAdded; //"memPool/txAdded"); CStatHistory<uint64_t, MinValMax<uint64_t> > poolSize; // "memPool/size",STAT_OP_AVE); CStatHistory<uint64_t> recvAmt; CStatHistory<uint64_t> sendAmt; CStatHistory<uint64_t> nTxValidationTime("txValidationTime", STAT_OP_MAX | STAT_INDIVIDUAL); CStatHistory<uint64_t> nBlockValidationTime("blockValidationTime", STAT_OP_MAX | STAT_INDIVIDUAL); CCriticalSection cs_blockvalidationtime; CThinBlockData thindata; // Singleton class // Expedited blocks std::vector<CNode *> xpeditedBlk; // (256,(CNode*)NULL); // Who requested expedited blocks from us std::vector<CNode *> xpeditedBlkUp; //(256,(CNode*)NULL); // Who we requested expedited blocks from std::vector<CNode *> xpeditedTxn; // (256,(CNode*)NULL); <|endoftext|>
<commit_before> #include <GUIDOEngine/GUIDOEngine.h> #include <GUIDOEngine/GDeviceOSX.h> #include <GUIDOEngine/GFontOSX.h> #include <GUIDOEngine/GMemoryDeviceOSX.h> #include <GUIDOEngine/GPrinterDeviceOSX.h> #include <GUIDOEngine/GSystemOSX.h> #include <GUIDOEngine/SVGSystem.h> #include <guido-c.h> // const char *byte_to_binary(int x); const char* GuidoCGetVersion() { return "0.5.0"; } // System GuidoCGraphicSystem * GuidoCCreateSystem() { fprintf(stderr, "Creating system!\n"); // FIXME need to pass CGContextRef as first param here /* In a WX paint handler: wxPaintDC MyDC(this); CGContextRef context = ((wxMacCGContext*)MyDC.GetGraphicContext())->GetNativeContext(); */ GuidoCGraphicSystem * system = (GuidoCGraphicSystem*) new GSystemOSX(0,0); return system; } uint32_t* GuidoCNativePaint(GuidoCGraphicDevice * device) { CGContextRef context = CGContextRef(((VGDevice*) device)->GetNativeContext()); uint32_t* data = (uint32_t*)::CGBitmapContextGetData(context); return data; } void GuidoCPrintDeviceInfo(GuidoCGraphicDevice * device) { CGContextRef context = CGContextRef(((VGDevice*) device)->GetNativeContext()); uint32_t* data = (uint32_t*)::CGBitmapContextGetData(context); int m = CGBitmapContextGetBitsPerComponent(context); int n = CGBitmapContextGetBitsPerPixel(context); int w = CGBitmapContextGetWidth(context); int h = CGBitmapContextGetHeight(context); unsigned i = CGBitmapContextGetBitmapInfo(context); unsigned a = CGBitmapContextGetAlphaInfo(context); fprintf(stderr, "Data format: bitsPerComp=%d bitsPerPixel=%d width=%d height=%d\n", m, n, w, h); // fprintf(stderr, "Info: %s\n", byte_to_binary(i)); // fprintf(stderr, "Alpha info: %s\n", byte_to_binary(a)); if (i & kCGBitmapFloatComponents) fprintf(stderr, "The components are floats\n"); if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrderDefault) fprintf(stderr, "The byte order is the default\n"); if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder16Little) fprintf(stderr, "The byte order is 16LE\n"); if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Little) fprintf(stderr, "The byte order is 32LE\n"); if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder16Big) fprintf(stderr, "The byte order is 16BE\n"); if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Big) fprintf(stderr, "The byte order is 32BE\n"); if (a == kCGImageAlphaNone) fprintf(stderr, "Alpha: kCGImageAlphaNone\n"); if (a == kCGImageAlphaPremultipliedLast) fprintf(stderr, "Alpha: kCGImageAlphaPremultipliedLast\n"); if (a == kCGImageAlphaPremultipliedFirst) fprintf(stderr, "Alpha: kCGImageAlphaPremultipliedFirst\n"); if (a == kCGImageAlphaLast) fprintf(stderr, "Alpha: kCGImageAlphaLast\n"); if (a == kCGImageAlphaFirst) fprintf(stderr, "Alpha: kCGImageAlphaFirst\n"); if (a == kCGImageAlphaNoneSkipLast) fprintf(stderr, "Alpha: kCGImageAlphaNoneSkipLast\n"); if (a == kCGImageAlphaNoneSkipFirst) fprintf(stderr, "Alpha: kCGImageAlphaNoneSkipFirst\n"); } GuidoCGraphicSystem * GuidoCCreateSVGSystem() { GuidoCGraphicSystem * system = (GuidoCGraphicSystem*) new SVGSystem(); return system; } void GuidoCFreeSystem(GuidoCGraphicSystem * system) { delete (GSystemOSX*) system; } void GuidoCFreeSVGSystem(GuidoCGraphicSystem * system) { delete (SVGSystem*) system; } GuidoCGraphicDevice * GuidoCCreateDisplayDevice(GuidoCGraphicSystem * system) { return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreateDisplayDevice(); } GuidoCGraphicDevice * GuidoCCreateMemoryDevice(GuidoCGraphicSystem * system, int width, int height) { return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreateMemoryDevice(width, height); } GuidoCGraphicDevice * GuidoCCreateMemoryDevicePath(GuidoCGraphicSystem * system, const char* path) { return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreateMemoryDevice(path); } GuidoCGraphicDevice * GuidoCCreatePrinterDevice(GuidoCGraphicSystem * system) { return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreatePrinterDevice(); } // const char *byte_to_binary(int x) // { // static char b[9]; // b[0] = '\0'; // int z; // for (z = 128; z > 0; z >>= 1) // strcat(b, ((x & z) == z) ? "1" : "0"); // return b; // } <commit_msg>Cleaning<commit_after> #include <GUIDOEngine/GUIDOEngine.h> #include <GUIDOEngine/GDeviceOSX.h> #include <GUIDOEngine/GFontOSX.h> #include <GUIDOEngine/GMemoryDeviceOSX.h> #include <GUIDOEngine/GPrinterDeviceOSX.h> #include <GUIDOEngine/GSystemOSX.h> #include <GUIDOEngine/SVGSystem.h> #include <guido-c.h> // const char *byte_to_binary(int x); const char* GuidoCGetVersion() { return "0.5.0"; } // System GuidoCGraphicSystem * GuidoCCreateSystem() { fprintf(stderr, "Creating system!\n"); // FIXME need to pass CGContextRef as first param here /* In a WX paint handler: wxPaintDC MyDC(this); CGContextRef context = ((wxMacCGContext*)MyDC.GetGraphicContext())->GetNativeContext(); */ GuidoCGraphicSystem * system = (GuidoCGraphicSystem*) new GSystemOSX(0,0); return system; } uint32_t* GuidoCNativePaint(GuidoCGraphicDevice * device) { CGContextRef context = CGContextRef(((VGDevice*) device)->GetNativeContext()); uint32_t* data = (uint32_t*)::CGBitmapContextGetData(context); return data; } void GuidoCPrintDeviceInfo(GuidoCGraphicDevice * device) { CGContextRef context = CGContextRef(((VGDevice*) device)->GetNativeContext()); uint32_t* data = (uint32_t*)::CGBitmapContextGetData(context); int m = CGBitmapContextGetBitsPerComponent(context); int n = CGBitmapContextGetBitsPerPixel(context); int w = CGBitmapContextGetWidth(context); int h = CGBitmapContextGetHeight(context); unsigned i = CGBitmapContextGetBitmapInfo(context); unsigned a = CGBitmapContextGetAlphaInfo(context); fprintf(stderr, "Data format: bitsPerComp=%d bitsPerPixel=%d width=%d height=%d\n", m, n, w, h); // fprintf(stderr, "Info: %s\n", byte_to_binary(i)); // fprintf(stderr, "Alpha info: %s\n", byte_to_binary(a)); if (i & kCGBitmapFloatComponents) fprintf(stderr, "The components are floats\n"); if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrderDefault) fprintf(stderr, "The byte order is the default\n"); if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder16Little) fprintf(stderr, "The byte order is 16LE\n"); if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Little) fprintf(stderr, "The byte order is 32LE\n"); if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder16Big) fprintf(stderr, "The byte order is 16BE\n"); if ((i & kCGBitmapByteOrderMask) == kCGBitmapByteOrder32Big) fprintf(stderr, "The byte order is 32BE\n"); if (a == kCGImageAlphaNone) fprintf(stderr, "Alpha: kCGImageAlphaNone\n"); if (a == kCGImageAlphaPremultipliedLast) fprintf(stderr, "Alpha: kCGImageAlphaPremultipliedLast\n"); if (a == kCGImageAlphaPremultipliedFirst) fprintf(stderr, "Alpha: kCGImageAlphaPremultipliedFirst\n"); if (a == kCGImageAlphaLast) fprintf(stderr, "Alpha: kCGImageAlphaLast\n"); if (a == kCGImageAlphaFirst) fprintf(stderr, "Alpha: kCGImageAlphaFirst\n"); if (a == kCGImageAlphaNoneSkipLast) fprintf(stderr, "Alpha: kCGImageAlphaNoneSkipLast\n"); if (a == kCGImageAlphaNoneSkipFirst) fprintf(stderr, "Alpha: kCGImageAlphaNoneSkipFirst\n"); } GuidoCGraphicSystem * GuidoCCreateSVGSystem() { GuidoCGraphicSystem * system = (GuidoCGraphicSystem*) new SVGSystem(); return system; } void GuidoCFreeSystem(GuidoCGraphicSystem * system) { delete (GSystemOSX*) system; } void GuidoCFreeSVGSystem(GuidoCGraphicSystem * system) { delete (SVGSystem*) system; } GuidoCGraphicDevice * GuidoCCreateDisplayDevice(GuidoCGraphicSystem * system) { return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreateDisplayDevice(); } GuidoCGraphicDevice * GuidoCCreateMemoryDevice(GuidoCGraphicSystem * system, int width, int height) { return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreateMemoryDevice(width, height); } GuidoCGraphicDevice * GuidoCCreateMemoryDevicePath(GuidoCGraphicSystem * system, const char* path) { return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreateMemoryDevice(path); } GuidoCGraphicDevice * GuidoCCreatePrinterDevice(GuidoCGraphicSystem * system) { return (GuidoCGraphicDevice*) ((VGSystem*) system)->CreatePrinterDevice(); } // const char *byte_to_binary(int x) // { // static char b[9]; // b[0] = '\0'; // int z; // for (z = 128; z > 0; z >>= 1) // strcat(b, ((x & z) == z) ? "1" : "0"); // return b; // } <|endoftext|>
<commit_before>#include <stan/math/error_handling/check_finite.hpp> #include <gtest/gtest.h> using stan::math::check_finite; TEST(MathErrorHandling,CheckFinite) { const char* function = "check_finite(%1%)"; double x = 0; double result; EXPECT_TRUE(check_finite(function, x, "x", &result)) << "check_finite should be true with finite x: " << x; x = std::numeric_limits<double>::infinity(); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on Inf: " << x; x = -std::numeric_limits<double>::infinity(); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on -Inf: " << x; x = std::numeric_limits<double>::quiet_NaN(); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on NaN: " << x; } // ---------- check_finite: vector tests ---------- TEST(MathErrorHandling,CheckFinite_Vector) { const char* function = "check_finite(%1%)"; double result; std::vector<double> x; x.clear(); x.push_back (-1); x.push_back (0); x.push_back (1); ASSERT_TRUE(check_finite(function, x, "x", &result)) << "check_finite should be true with finite x"; x.clear(); x.push_back(-1); x.push_back(0); x.push_back(std::numeric_limits<double>::infinity()); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on Inf"; x.clear(); x.push_back(-1); x.push_back(0); x.push_back(-std::numeric_limits<double>::infinity()); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on -Inf"; x.clear(); x.push_back(-1); x.push_back(0); x.push_back(std::numeric_limits<double>::quiet_NaN()); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on NaN"; } // ---------- check_finite: matrix tests ---------- TEST(MathErrorHandling,CheckFinite_Matrix) { const char* function = "check_finite(%1%)"; double result; Eigen::Matrix<double,Eigen::Dynamic,1> x; result = 0; x.resize(3); x << -1, 0, 1; ASSERT_TRUE(check_finite(function, x, "x", &result)) << "check_finite should be true with finite x"; result = 0; x.resize(3); x << -1, 0, std::numeric_limits<double>::infinity(); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on Inf"; result = 0; x.resize(3); x << -1, 0, -std::numeric_limits<double>::infinity(); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on -Inf"; result = 0; x.resize(3); x << -1, 0, std::numeric_limits<double>::quiet_NaN(); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on NaN"; } TEST(MathErrorHandling,CheckFinite_Matrix_one_indexed_message) { const char* function = "check_finite(%1%)"; double result; Eigen::Matrix<double,Eigen::Dynamic,1> x; std::string message; result = 0; x.resize(3); x << -1, 0, std::numeric_limits<double>::infinity(); try { check_finite(function, x, "x", &result); FAIL() << "should have thrown"; } catch (std::domain_error& e) { message = e.what(); } catch (...) { FAIL() << "threw the wrong error"; } EXPECT_NE(std::string::npos, message.find("[3]")) << message; } <commit_msg>added NaN test for check_finite<commit_after>#include <stan/math/error_handling/check_finite.hpp> #include <gtest/gtest.h> using stan::math::check_finite; TEST(MathErrorHandling,CheckFinite) { const char* function = "check_finite(%1%)"; double x = 0; double result; EXPECT_TRUE(check_finite(function, x, "x", &result)) << "check_finite should be true with finite x: " << x; x = std::numeric_limits<double>::infinity(); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on Inf: " << x; x = -std::numeric_limits<double>::infinity(); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on -Inf: " << x; x = std::numeric_limits<double>::quiet_NaN(); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on NaN: " << x; } // ---------- check_finite: vector tests ---------- TEST(MathErrorHandling,CheckFinite_Vector) { const char* function = "check_finite(%1%)"; double result; std::vector<double> x; x.clear(); x.push_back (-1); x.push_back (0); x.push_back (1); ASSERT_TRUE(check_finite(function, x, "x", &result)) << "check_finite should be true with finite x"; x.clear(); x.push_back(-1); x.push_back(0); x.push_back(std::numeric_limits<double>::infinity()); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on Inf"; x.clear(); x.push_back(-1); x.push_back(0); x.push_back(-std::numeric_limits<double>::infinity()); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on -Inf"; x.clear(); x.push_back(-1); x.push_back(0); x.push_back(std::numeric_limits<double>::quiet_NaN()); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on NaN"; } // ---------- check_finite: matrix tests ---------- TEST(MathErrorHandling,CheckFinite_Matrix) { const char* function = "check_finite(%1%)"; double result; Eigen::Matrix<double,Eigen::Dynamic,1> x; result = 0; x.resize(3); x << -1, 0, 1; ASSERT_TRUE(check_finite(function, x, "x", &result)) << "check_finite should be true with finite x"; result = 0; x.resize(3); x << -1, 0, std::numeric_limits<double>::infinity(); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on Inf"; result = 0; x.resize(3); x << -1, 0, -std::numeric_limits<double>::infinity(); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on -Inf"; result = 0; x.resize(3); x << -1, 0, std::numeric_limits<double>::quiet_NaN(); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error) << "check_finite should throw exception on NaN"; } TEST(MathErrorHandling,CheckFinite_Matrix_one_indexed_message) { const char* function = "check_finite(%1%)"; double result; Eigen::Matrix<double,Eigen::Dynamic,1> x; std::string message; result = 0; x.resize(3); x << -1, 0, std::numeric_limits<double>::infinity(); try { check_finite(function, x, "x", &result); FAIL() << "should have thrown"; } catch (std::domain_error& e) { message = e.what(); } catch (...) { FAIL() << "threw the wrong error"; } EXPECT_NE(std::string::npos, message.find("[3]")) << message; } TEST(MathErrorHandling,CheckFinite_nan) { const char* function = "check_finite(%1%)"; double result; double nan = std::numeric_limits<double>::quiet_NaN(); EXPECT_THROW(check_finite(function, nan, "x", &result), std::domain_error); std::vector<double> x; x.push_back (nan); x.push_back (0); x.push_back (1); EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error); x[0] = 1.0; x[1] = nan; EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error); x[1] = 0.0; x[2] = nan; EXPECT_THROW(check_finite(function, x, "x", &result), std::domain_error); Eigen::Matrix<double,Eigen::Dynamic,1> x_mat(3); x_mat << nan, 0, 1; EXPECT_THROW(check_finite(function, x_mat, "x_mat", &result), std::domain_error); x_mat << 1, nan, 1; EXPECT_THROW(check_finite(function, x_mat, "x_mat", &result), std::domain_error); x_mat << 1, 0, nan; EXPECT_THROW(check_finite(function, x_mat, "x_mat", &result), std::domain_error); } <|endoftext|>
<commit_before>#include <stan/model/indexing/rvalue_index_size.hpp> #include <gtest/gtest.h> #include <vector> // error checking is during indexing, not during index construction // so no tests here for out of bounds TEST(modelIndexingRvalueIndexSize, multi) { using stan::model::index_multi; using stan::model::rvalue_index_size; std::vector<int> ns; ns.push_back(1); ns.push_back(2); index_multi idx(ns); EXPECT_EQ(2, rvalue_index_size(idx, 10)); } TEST(modelIndexingRvalueIndexSize, omni) { using stan::model::index_omni; using stan::model::rvalue_index_size; index_omni idx; EXPECT_EQ(10, rvalue_index_size(idx, 10)); } TEST(modelIndexingRvalueIndexSize, min) { using stan::model::index_min; using stan::model::rvalue_index_size; index_min idx(3); EXPECT_EQ(8, rvalue_index_size(idx, 10)); } TEST(modelIndexingRvalueIndexSize, max) { using stan::model::index_max; using stan::model::rvalue_index_size; index_max idx(5); EXPECT_EQ(5, rvalue_index_size(idx, 10)); } TEST(modelIndexingRvalueIndexSize, minMax) { using stan::model::index_min_max; using stan::model::rvalue_index_size; index_min_max mm(1, 3); EXPECT_EQ(3, rvalue_index_size(mm, 10)); index_min_max mm2(3, 3); EXPECT_EQ(1, rvalue_index_size(mm2, 10)); index_min_max mm3(3, 1); EXPECT_EQ(0, rvalue_index_size(mm3, 10)); index_min_max mm4(1, 0); EXPECT_EQ(0, rvalue_index_size(mm3, 10)); } <commit_msg>fix rvalue_index_size test<commit_after>#include <stan/model/indexing/rvalue_index_size.hpp> #include <gtest/gtest.h> #include <vector> // error checking is during indexing, not during index construction // so no tests here for out of bounds TEST(modelIndexingRvalueIndexSize, multi) { using stan::model::index_multi; using stan::model::rvalue_index_size; std::vector<int> ns; ns.push_back(1); ns.push_back(2); index_multi idx(ns); EXPECT_EQ(2, rvalue_index_size(idx, 10)); } TEST(modelIndexingRvalueIndexSize, omni) { using stan::model::index_omni; using stan::model::rvalue_index_size; index_omni idx; EXPECT_EQ(10, rvalue_index_size(idx, 10)); } TEST(modelIndexingRvalueIndexSize, min) { using stan::model::index_min; using stan::model::rvalue_index_size; index_min idx(3); EXPECT_EQ(8, rvalue_index_size(idx, 10)); } TEST(modelIndexingRvalueIndexSize, max) { using stan::model::index_max; using stan::model::rvalue_index_size; index_max idx(5); EXPECT_EQ(5, rvalue_index_size(idx, 10)); } TEST(modelIndexingRvalueIndexSize, minMax) { using stan::model::index_min_max; using stan::model::rvalue_index_size; index_min_max mm(1, 3); EXPECT_EQ(3, rvalue_index_size(mm, 10)); index_min_max mm2(3, 3); EXPECT_EQ(1, rvalue_index_size(mm2, 10)); index_min_max mm3(3, 1); EXPECT_EQ(3, rvalue_index_size(mm3, 10)); index_min_max mm4(1, 0); EXPECT_EQ(2, rvalue_index_size(mm4, 10)); } <|endoftext|>
<commit_before>// 11 may 2015 // TODO split out winapi includes #include "tablepriv.h" // before we start, why is this file C++? because the following is not a valid C header file! // namely, UIAutomationCoreApi.h forgets to typedef enum xxx { ... } xxx; and typedef struct xxx xxx; so it just uses xxx incorrectly // and because these are enums, we can't just do typedef enum xxx xxx; here ourselves, as that's illegal in both C and C++! // thanks, Microsoft! // (if it was just structs I would just typedef them here but even that's not really futureproof) #include <uiautomation.h> // TODOs // - make sure RPC_E_DISCONNECTED is correct; source it // - make sure E_POINTER is correct // well if we're stuck with C++, we might as well make the most of it class tableAcc : public IRawElementProviderSimple { struct table *t; ULONG refcount; public: tableAcc(struct table *); // internal methods void Invalidate(void); // IUnknown STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject); STDMETHODIMP_(ULONG) AddRef(void); STDMETHODIMP_(ULONG) Release(void); // IRawElementProviderSimple STDMETHODIMP GetPatternProvider(PATTERNID patternId, IUnknown **pRetVal); STDMETHODIMP GetPropertyValue(PROPERTYID propertyId, VARIANT *pRetVal); STDMETHODIMP get_HostRawElementProvider(IRawElementProviderSimple **pRetVal); STDMETHODIMP get_ProviderOptions(ProviderOptions *pRetVal); }; tableAcc::tableAcc(struct table *t) { this->t = t; this->refcount = 1; // first instance goes to the table } void tableAcc::Invalidate(void) { // this will always be called before the tableAcc is destroyed because there's one ref given to the table itself this->t = NULL; } // TODO are the static_casts necessary or will a good old C cast do? STDMETHODIMP tableAcc::QueryInterface(REFIID riid, void **ppvObject) { if (ppvObject == NULL) return E_POINTER; if (IsEqualIID(riid, IID_IUnknown)) { this->AddRef(); *ppvObject = static_cast<tableAcc *>(this); return S_OK; } if (IsEqualIID(riid, IID_IRawElementProviderSimple)) { this->AddRef(); *ppvObject = static_cast<IRawElementProviderSimple *>(this); return S_OK; } if (IsEqualIID(riid, IID_IGridProvider)) { this->AddRef(); *ppvObject = static_cast<IGridProvider *>(this); return S_OK; } return E_NOINTERFACE; } STDMETHODIMP_(ULONG) tableAcc::AddRef(void) { // http://blogs.msdn.com/b/oldnewthing/archive/2005/09/27/474384.aspx if (this->refcount == 0) logLastError("tableAcc::AddRef() called during destruction"); this->refcount++; return this->refcount; } STDMETHODIMP_(ULONG) tableAcc::Release(void) { this->refcount--; if (this->refcount == 0) { delete this; return 0; } return this->refcount; } // TODO again with static_casts STDMETHODIMP tableAcc::GetPatternProvider(PATTERNID patternId, IUnknown **pRetVal) { if (pRetVal == NULL) return E_POINTER; #if 0 // TODO if (patternId == UIA_ListPatternId) { this->AddRef(); *pRetVal = static_cast<IRawElementProviderSimple *>(this); return S_OK; } #endif // TODO datagrid pattern? *pRetVal = NULL; return S_OK; } STDMETHODIMP tableAcc::GetPropertyValue(PROPERTYID propertyId, VARIANT *pRetVal) { BSTR bstr; if (pRetVal == NULL) return E_POINTER; // TODO keep this on error? pRetVal->vt = VT_EMPTY; // behavior on unknown property is to keep it VT_EMPTY and return S_OK if (this->t == NULL) return RPC_E_DISCONNECTED; switch (propertyId) { case UIA_ControlTypePropertyId: pRetVal->vt = VT_I4; pRetVal->lVal = UIA_ListControlTypeId; break; case UIA_NamePropertyId: // TODO do we specify this ourselves? or let the parent window provide it? bstr = SysAllocString(L"test string"); if (bstr == NULL) return E_OUTOFMEMORY; pRetVal->vt = VT_BSTR; pRetVal->bstrVal = bstr; break; #if 0 case UIA_NativeWindowHandlePropertyId: // TODO the docs say VT_I4 // a window handle is a pointer // 64-bit issue? break; #endif } return S_OK; } STDMETHODIMP tableAcc::get_HostRawElementProvider(IRawElementProviderSimple **pRetVal) { if (this->t == NULL) { if (pRetVal == NULL) return E_POINTER; // TODO correct? *pRetVal = NULL; return RPC_E_DISCONNECTED; } // according to https://msdn.microsoft.com/en-us/library/windows/desktop/ee671597%28v=vs.85%29.aspx this is correct for the top-level provider return UiaHostProviderFromHwnd(this->t->hwnd, pRetVal); } STDMETHODIMP tableAcc::get_ProviderOptions(ProviderOptions *pRetVal) { if (pRetVal == NULL) return E_POINTER; // TODO ProviderOptions_UseClientCoordinates? *pRetVal = ProviderOptions_ServerSideProvider; return S_OK; } void initTableAcc(struct table *t) { tableAcc *a; a = new tableAcc(t); t->tableAcc = a; } void uninitTableAcc(struct table *t) { tableAcc *a; a = (tableAcc *) (t->tableAcc); a->Invalidate(); a->Release(); t->tableAcc = NULL; } HANDLER(accessibilityHandler) { if (uMsg != WM_GETOBJECT) return FALSE; // OBJID_CLIENT evaluates to an expression of type LONG // the documentation for WM_GETOBJECT says to cast "it" to a DWORD before comparing // https://msdn.microsoft.com/en-us/library/windows/desktop/dd373624%28v=vs.85%29.aspx casts them both to DWORDs; let's do that // its two siblings only cast lParam, resulting in an erroneous DWORD to LONG comparison // The Old New Thing book does not cast anything // Microsoft's MSAA sample casts lParam to LONG instead! // (As you can probably tell, the biggest problem with MSAA is that its documentation is ambiguous and/or self-contradictory...) // and https://msdn.microsoft.com/en-us/library/windows/desktop/ff625912%28v=vs.85%29.aspx casts them both to long! // Note that we're not using Active Accessibility, but the above applies even more, because UiaRootObjectId is *NEGATIVE*! if (((DWORD) lParam) != ((DWORD) UiaRootObjectId)) return FALSE; *lResult = UiaReturnRawElementProvider(t->hwnd, wParam, lParam, (IRawElementProviderSimple *) (t->tableAcc)); return TRUE; } <commit_msg>More UI Automation work.<commit_after>// 11 may 2015 // TODO split out winapi includes #include "tablepriv.h" // before we start, why is this file C++? because the following is not a valid C header file! // namely, UIAutomationCoreApi.h forgets to typedef enum xxx { ... } xxx; and typedef struct xxx xxx; so it just uses xxx incorrectly // and because these are enums, we can't just do typedef enum xxx xxx; here ourselves, as that's illegal in both C and C++! // thanks, Microsoft! // (if it was just structs I would just typedef them here but even that's not really futureproof) #include <uiautomation.h> // well if we're stuck with C++, we might as well make the most of it // For the top-level table, we implement the List control type because the standard Windows list view does so. // TODOs // - make sure E_POINTER is correct; examples use E_INVALIDARG // - children must implement IRawElementProviderFragment #define eDisconnected UIA_E_ELEMENTNOTAVAILABLE #define ePointer E_POINTER class tableAcc : public IRawElementProviderSimple, public IRawElementProviderFragmentRoot { struct table *t; ULONG refcount; public: tableAcc(struct table *); // internal methods void tDisconnect(void); // TODDO event support - see what events the host provider provides for us (from the same link that shows host properties?) // IUnknown STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject); STDMETHODIMP_(ULONG) AddRef(void); STDMETHODIMP_(ULONG) Release(void); // IRawElementProviderSimple STDMETHODIMP GetPatternProvider(PATTERNID patternId, IUnknown **pRetVal); STDMETHODIMP GetPropertyValue(PROPERTYID propertyId, VARIANT *pRetVal); STDMETHODIMP get_HostRawElementProvider(IRawElementProviderSimple **pRetVal); STDMETHODIMP get_ProviderOptions(ProviderOptions *pRetVal); // IRawElementProviderFragmentRoot STDMETHODIMP ElementProviderFromPoint(double x, double y, IRawElementProviderFragment **pRetVal); STDMETHODIMP GetFocus(IRawElementProviderFragment **pRetVal); }; tableAcc::tableAcc(struct table *t) { this->t = t; this->refcount = 1; // first instance goes to the table } // TODO are the static_casts necessary or will a good old C cast do? // note that this first one is not to IUnknown, as QueryInterface() requires us to always return the same pointer to IUnknown #define IU(x) (static_cast<tableAcc *>(x)) #define IREPS(x) (static_cast<IRawElementProviderSimple *>(x)) #define IREPFR(x) (static_cast<IRawElementProviderFragmentRoot *>(x)) // this will always be called before the tableAcc is destroyed because there's one ref given to the table itself void tableAcc::tDisconnect(void) { HRESULT hr; hr = UiaDisconnectProvider(IREPS(this)); if (hr != S_OK) logHRESULT("error disconnecting UI Automation root provider for table in tableAcc::tDisconnect()", hr); this->t = NULL; } STDMETHODIMP tableAcc::QueryInterface(REFIID riid, void **ppvObject) { if (ppvObject == NULL) return ePointer; if (IsEqualIID(riid, IID_IUnknown)) { this->AddRef(); *ppvObject = IU(this); return S_OK; } if (IsEqualIID(riid, IID_IRawElementProviderSimple)) { this->AddRef(); *ppvObject = IREPS(this); return S_OK; } if (IsEqualIID(riid, IID_IRawElementProviderFragmentRoot)) { this->AddRef(); *ppvObject = IREPFR(this); return S_OK; } return E_NOINTERFACE; } STDMETHODIMP_(ULONG) tableAcc::AddRef(void) { // http://blogs.msdn.com/b/oldnewthing/archive/2005/09/27/474384.aspx if (this->refcount == 0) logLastError("tableAcc::AddRef() called during destruction"); this->refcount++; return this->refcount; } STDMETHODIMP_(ULONG) tableAcc::Release(void) { this->refcount--; if (this->refcount == 0) { delete this; return 0; } return this->refcount; } STDMETHODIMP tableAcc::GetPatternProvider(PATTERNID patternId, IUnknown **pRetVal) { if (pRetVal == NULL) return ePointer; // TODO which patterns should we provide? inspect the listview control to find out *pRetVal = NULL; return S_OK; } // TODO https://msdn.microsoft.com/en-us/library/windows/desktop/ee671615%28v=vs.85%29.aspx specifies which properties we can ignore STDMETHODIMP tableAcc::GetPropertyValue(PROPERTYID propertyId, VARIANT *pRetVal) { BSTR bstr; if (pRetVal == NULL) return ePointer; // TODO keep this on error? pRetVal->vt = VT_EMPTY; // behavior on unknown property is to keep it VT_EMPTY and return S_OK if (this->t == NULL) return eDisconnected; switch (propertyId) { case UIA_ControlTypePropertyId: pRetVal->vt = VT_I4; //TODO pRetVal->lVal = UIA_ListControlTypeId; break; case UIA_NamePropertyId: // TODO remove this once everything works; we only use it to test bstr = SysAllocString(L"test string"); if (bstr == NULL) return E_OUTOFMEMORY; pRetVal->vt = VT_BSTR; pRetVal->bstrVal = bstr; break; #if 0 case UIA_NativeWindowHandlePropertyId: // TODO the docs say VT_I4 // a window handle is a pointer // 64-bit issue? break; #endif } return S_OK; } STDMETHODIMP tableAcc::get_HostRawElementProvider(IRawElementProviderSimple **pRetVal) { if (this->t == NULL) { if (pRetVal == NULL) return ePointer; // TODO correct? *pRetVal = NULL; return eDisconnected; } // according to https://msdn.microsoft.com/en-us/library/windows/desktop/ee671597%28v=vs.85%29.aspx this is correct for the top-level provider return UiaHostProviderFromHwnd(this->t->hwnd, pRetVal); } STDMETHODIMP tableAcc::get_ProviderOptions(ProviderOptions *pRetVal) { if (pRetVal == NULL) return ePointer; *pRetVal = ProviderOptions_ServerSideProvider; return S_OK; } STDMETHODIMP tableAcc::ElementProviderFromPoint(double x, double y, IRawElementProviderFragment **pRetVal) { // TODO return E_NOTIMPL; // note: x and y are in screen coordinates } STDMETHODIMP tableAcc::GetFocus(IRawElementProviderFragment **pRetVal) { // TODO return E_NOTIMPL; } void initTableAcc(struct table *t) { tableAcc *a; a = new tableAcc(t); t->tableAcc = a; } void uninitTableAcc(struct table *t) { tableAcc *a; a = (tableAcc *) (t->tableAcc); a->tDisconnect(); a->Release(); t->tableAcc = NULL; } HANDLER(accessibilityHandler) { if (uMsg != WM_GETOBJECT) return FALSE; // OBJID_CLIENT evaluates to an expression of type LONG // the documentation for WM_GETOBJECT says to cast "it" to a DWORD before comparing // https://msdn.microsoft.com/en-us/library/windows/desktop/dd373624%28v=vs.85%29.aspx casts them both to DWORDs; let's do that // its two siblings only cast lParam, resulting in an erroneous DWORD to LONG comparison // The Old New Thing book does not cast anything // Microsoft's MSAA sample casts lParam to LONG instead! // (As you can probably tell, the biggest problem with MSAA is that its documentation is ambiguous and/or self-contradictory...) // and https://msdn.microsoft.com/en-us/library/windows/desktop/ff625912%28v=vs.85%29.aspx casts them both to long! // Note that we're not using Active Accessibility, but the above applies even more, because UiaRootObjectId is *NEGATIVE*! if (((DWORD) lParam) != ((DWORD) UiaRootObjectId)) return FALSE; *lResult = UiaReturnRawElementProvider(t->hwnd, wParam, lParam, IREPS(t->tableAcc)); return TRUE; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems, * University of Southern California * Jan Issac ([email protected]) * Manuel Wuthrich ([email protected]) * * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * @date 2014 * @author Jan Issac ([email protected]) * @author Manuel Wuthrich ([email protected]) * Max-Planck-Institute for Intelligent Systems, University of Southern California */ #ifndef FAST_FILTERING_FILTERS_DETERMINISTIC_KALMAN_FILTER_HPP #define FAST_FILTERING_FILTERS_DETERMINISTIC_KALMAN_FILTER_HPP #include <fast_filtering/utils/traits.hpp> #include <boost/shared_ptr.hpp> #include <fast_filtering/distributions/gaussian.hpp> #include <fast_filtering/models/process_models/linear_process_model.hpp> #include <fast_filtering/models/observation_models/linear_observation_model.hpp> namespace ff { template <typename ProcessModel, typename ObservationModel> class KalmanFilter { public: typedef boost::shared_ptr<ProcessModel> ProcessModelPtr; typedef boost::shared_ptr<ObservationModel> ObservationModelPtr; typedef typename ProcessModel::Scalar Scalar; typedef typename ProcessModel::State State; typedef typename ProcessModel::Input Input; typedef typename ProcessModel::DynamicsMatrix DynamicsMatrix; typedef typename ProcessModel::Operator DynamicsCovariance; typedef typename ObservationModel::Observation Observation; typedef typename ObservationModel::SensorMatrix SensorMatrix; typedef typename ObservationModel::Operator SensorCovariance; typedef Gaussian<State> StateDistribution; public: KalmanFilter(const ProcessModelPtr& process_model, const ObservationModelPtr& observation_model): process_model_(process_model), observation_model_(observation_model) { } virtual ~KalmanFilter() { } void Predict(const double delta_time, const StateDistribution& prior, StateDistribution& predicted) { const DynamicsMatrix& A = process_model_->A(); const DynamicsCovariance Q = delta_time * process_model_->Covariance(); predicted.Mean(A * prior.Mean()); predicted.Covariance(A * prior.Covariance() * A.transpose() + Q); } void Update(const StateDistribution& predicted, const Observation& y, StateDistribution& posterior) { typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix; const SensorMatrix& H = observation_model_->H(); const SensorMatrix R = observation_model_->Covariance(); const Matrix S = H * predicted.Covariance() * H.transpose() + R; const Matrix K = predicted.Covariance() * H.transpose() * S.inverse(); posterior.Mean( predicted.Mean() + K * (y - H * predicted.Mean())); posterior.Covariance( predicted.Covariance() - K * H * predicted.Covariance()); } protected: ProcessModelPtr process_model_; ObservationModelPtr observation_model_; }; } #endif <commit_msg>fixed covariance R. intermediate matrices have a fixed size of using fixed size model dynamics.<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems, * University of Southern California * Jan Issac ([email protected]) * Manuel Wuthrich ([email protected]) * * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /** * @date 2014 * @author Jan Issac ([email protected]) * @author Manuel Wuthrich ([email protected]) * Max-Planck-Institute for Intelligent Systems, University of Southern California */ #ifndef FAST_FILTERING_FILTERS_DETERMINISTIC_KALMAN_FILTER_HPP #define FAST_FILTERING_FILTERS_DETERMINISTIC_KALMAN_FILTER_HPP #include <fast_filtering/utils/traits.hpp> #include <boost/shared_ptr.hpp> #include <fast_filtering/distributions/gaussian.hpp> #include <fast_filtering/models/process_models/linear_process_model.hpp> #include <fast_filtering/models/observation_models/linear_observation_model.hpp> namespace ff { template <typename ProcessModel, typename ObservationModel> class KalmanFilter { public: typedef boost::shared_ptr<ProcessModel> ProcessModelPtr; typedef boost::shared_ptr<ObservationModel> ObservationModelPtr; typedef typename ProcessModel::Scalar Scalar; typedef typename ProcessModel::State State; typedef typename ProcessModel::Input Input; typedef typename ProcessModel::DynamicsMatrix DynamicsMatrix; typedef typename ProcessModel::Operator DynamicsCovariance; typedef typename ObservationModel::Observation Observation; typedef typename ObservationModel::SensorMatrix SensorMatrix; typedef typename ObservationModel::Operator SensorCovariance; typedef Gaussian<State> StateDistribution; public: KalmanFilter(const ProcessModelPtr& process_model, const ObservationModelPtr& observation_model): process_model_(process_model), observation_model_(observation_model) { } virtual ~KalmanFilter() { } void Predict(const double delta_time, const StateDistribution& prior, StateDistribution& predicted) { const DynamicsMatrix& A = process_model_->A(); const DynamicsCovariance Q = delta_time * process_model_->Covariance(); predicted.Mean(A * prior.Mean()); predicted.Covariance(A * prior.Covariance() * A.transpose() + Q); } void Update(const StateDistribution& predicted, const Observation& y, StateDistribution& posterior) { const SensorMatrix& H = observation_model_->H(); const SensorCovariance R = observation_model_->Covariance(); typedef Eigen::Matrix< Scalar, SensorMatrix::RowsAtCompileTime, SensorCovariance::ColsAtCompileTime> SMatrix; typedef Eigen::Matrix< Scalar, DynamicsCovariance::RowsAtCompileTime, SMatrix::ColsAtCompileTime> KMatrix; const SMatrix S = H * predicted.Covariance() * H.transpose() + R; const KMatrix K = predicted.Covariance() * H.transpose() * S.inverse(); posterior.Mean( predicted.Mean() + K * (y - H * predicted.Mean())); posterior.Covariance( predicted.Covariance() - K * H * predicted.Covariance()); } protected: ProcessModelPtr process_model_; ObservationModelPtr observation_model_; }; } #endif <|endoftext|>
<commit_before>/** * \file FFT.cpp */ #include <cmath> #include <complex> #include <cstdlib> #include "FFT.h" namespace ATK { template<class DataType_> FFT<DataType_>::FFT() #if ATK_USE_FFTW == 1 :fft_plan(NULL), input_data(NULL), output_freqs(NULL) #endif #if ATK_USE_ACCELERATE == 1 :fftSetup(NULL), output_freqs(NULL) #endif { #if ATK_USE_ACCELERATE == 1 splitData.realp = NULL; splitData.imagp = NULL; #endif } template<class DataType_> FFT<DataType_>::~FFT() { #if ATK_USE_FFTW == 1 delete[] input_data; delete[] output_freqs; fftw_destroy_plan(fft_plan); #endif #if ATK_USE_ACCELERATE == 1 delete[] splitData.realp; delete[] splitData.imagp; vDSP_destroy_fftsetupD(fftSetup); delete[] output_freqs; #endif } template<class DataType_> void FFT<DataType_>::set_size(std::int64_t size) { this->size = size; log2n = std::log(size) / std::log(2.); #if ATK_USE_FFTW == 1 free(input_data); free(output_freqs); fftw_destroy_plan(fft_plan); input_data = fftw_alloc_complex(size); output_freqs = fftw_alloc_complex(size); fft_plan = fftw_plan_dft_1d(size, input_data, output_freqs, FFTW_FORWARD, FFTW_ESTIMATE); #endif #if ATK_USE_ACCELERATE == 1 delete[] splitData.realp; delete[] splitData.imagp; vDSP_destroy_fftsetupD(fftSetup); splitData.realp = new double[size/2]; splitData.imagp = new double[size/2]; fftSetup = vDSP_create_fftsetupD(log2n, FFT_RADIX2); delete[] output_freqs; output_freqs = new double[size/2]; #endif } template<class DataType_> void FFT<DataType_>::process(const DataType_* input, std::int64_t input_size) { #if ATK_USE_FFTW == 1 double factor = 1 << (log2n - 1); for(int j = 0; j < std::min(input_size, size); ++j) { input_data[j][0] = input[j] / factor; input_data[j][1] = 0; } fftw_execute(fft_plan); #endif #if ATK_USE_ACCELERATE == 1 double factor = input_sampling_rate; vDSP_ctozD(reinterpret_cast<DOUBLE_COMPLEX*>(input.data()), 2, &splitData, 1, std::min(input_size, size)/2); vDSP_fft_zripD(fftSetup, &splitData, 1, log2n, FFT_FORWARD); vDSP_zvabsD(&splitData, 1, output_freqs, 1, input_sampling_rate/2); vDSP_vsdivD(output_freqs, 1, &factor, output_freqs, 1, input_sampling_rate/2); #endif } template<class DataType_> void FFT<DataType_>::get_amp(std::vector<DataType_>& amp) const { amp.assign(size / 2, 0); for(std::int64_t i = 0; i < size / 2; ++i) { #if ATK_USE_FFTW == 1 amp[i] = output_freqs[i][0] * output_freqs[i][0]; amp[i] += output_freqs[i][1] * output_freqs[i][1]; amp[i] = std::sqrt(amp[i]); #endif #if ATK_USE_ACCELERATE == 1 amp[i] = output_freqs[i]; #endif } } template<class DataType_> void FFT<DataType_>::get_angle(std::vector<DataType_>& angle) const { angle.assign(size / 2, 0); for(std::int64_t i = 0; i < size/2; ++i) { #if ATK_USE_FFTW == 1 angle[i] = std::arg(std::complex<DataType_>(output_freqs[i][0], output_freqs[i][1])); #endif } } template class FFT<double>; } <commit_msg>Fixing FFT free calls<commit_after>/** * \file FFT.cpp */ #include <cmath> #include <complex> #include <cstdlib> #include "FFT.h" namespace ATK { template<class DataType_> FFT<DataType_>::FFT() #if ATK_USE_FFTW == 1 :size(0), fft_plan(NULL), input_data(NULL), output_freqs(NULL) #endif #if ATK_USE_ACCELERATE == 1 :fftSetup(NULL), output_freqs(NULL) #endif { #if ATK_USE_ACCELERATE == 1 splitData.realp = NULL; splitData.imagp = NULL; #endif } template<class DataType_> FFT<DataType_>::~FFT() { #if ATK_USE_FFTW == 1 fftw_free(input_data); fftw_free(output_freqs); fftw_destroy_plan(fft_plan); #endif #if ATK_USE_ACCELERATE == 1 delete[] splitData.realp; delete[] splitData.imagp; vDSP_destroy_fftsetupD(fftSetup); delete[] output_freqs; #endif } template<class DataType_> void FFT<DataType_>::set_size(std::int64_t size) { if(this->size == size) return; this->size = size; log2n = std::log(size) / std::log(2.); #if ATK_USE_FFTW == 1 fftw_free(input_data); fftw_free(output_freqs); fftw_destroy_plan(fft_plan); input_data = fftw_alloc_complex(size); output_freqs = fftw_alloc_complex(size); fft_plan = fftw_plan_dft_1d(size, input_data, output_freqs, FFTW_FORWARD, FFTW_ESTIMATE); #endif #if ATK_USE_ACCELERATE == 1 delete[] splitData.realp; delete[] splitData.imagp; vDSP_destroy_fftsetupD(fftSetup); splitData.realp = new double[size/2]; splitData.imagp = new double[size/2]; fftSetup = vDSP_create_fftsetupD(log2n, FFT_RADIX2); delete[] output_freqs; output_freqs = new double[size/2]; #endif } template<class DataType_> void FFT<DataType_>::process(const DataType_* input, std::int64_t input_size) { #if ATK_USE_FFTW == 1 double factor = 1 << (log2n - 1); for(int j = 0; j < std::min(input_size, size); ++j) { input_data[j][0] = input[j] / factor; input_data[j][1] = 0; } fftw_execute(fft_plan); #endif #if ATK_USE_ACCELERATE == 1 double factor = input_sampling_rate; vDSP_ctozD(reinterpret_cast<DOUBLE_COMPLEX*>(input.data()), 2, &splitData, 1, std::min(input_size, size)/2); vDSP_fft_zripD(fftSetup, &splitData, 1, log2n, FFT_FORWARD); vDSP_zvabsD(&splitData, 1, output_freqs, 1, input_sampling_rate/2); vDSP_vsdivD(output_freqs, 1, &factor, output_freqs, 1, input_sampling_rate/2); #endif } template<class DataType_> void FFT<DataType_>::get_amp(std::vector<DataType_>& amp) const { amp.assign(size / 2, 0); for(std::int64_t i = 0; i < size / 2; ++i) { #if ATK_USE_FFTW == 1 amp[i] = output_freqs[i][0] * output_freqs[i][0]; amp[i] += output_freqs[i][1] * output_freqs[i][1]; amp[i] = std::sqrt(amp[i]); #endif #if ATK_USE_ACCELERATE == 1 amp[i] = output_freqs[i]; #endif } } template<class DataType_> void FFT<DataType_>::get_angle(std::vector<DataType_>& angle) const { angle.assign(size / 2, 0); for(std::int64_t i = 0; i < size/2; ++i) { #if ATK_USE_FFTW == 1 angle[i] = std::arg(std::complex<DataType_>(output_freqs[i][0], output_freqs[i][1])); #endif } } template class FFT<double>; } <|endoftext|>
<commit_before>/*********************************************************************** cgi_jpeg.cpp - Example code showing how to fetch JPEG data from a BLOB column and send it back to a browser that requested it by ID. Use load_jpeg.cpp to load JPEG files into the database we query. Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and (c) 2004-2008 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <mysql++.h> #if defined(MYSQLPP_SSQLS_COMPATIBLE) #include <ssqls.h> #define IMG_DATABASE "mysql_cpp_data" #define IMG_HOST "localhost" #define IMG_USER "root" #define IMG_PASSWORD "nunyabinness" sql_create_2(images, 1, 2, mysqlpp::sql_int_unsigned, id, mysqlpp::sql_blob, data) int main() #else // !defined(MYSQLPP_SSQLS_COMPATIBLE) int main(int, char* argv[]) #endif { #if defined(MYSQLPP_SSQLS_COMPATIBLE) unsigned int img_id = 0; char* cgi_query = getenv("QUERY_STRING"); if (cgi_query) { if ((strlen(cgi_query) < 4) || memcmp(cgi_query, "id=", 3)) { std::cout << "Content-type: text/plain" << std::endl << std::endl; std::cout << "ERROR: Bad query string" << std::endl; return 1; } else { img_id = atoi(cgi_query + 3); } } else { std::cerr << "Put this program into a web server's cgi-bin " "directory, then" << std::endl; std::cerr << "invoke it with a URL like this:" << std::endl; std::cerr << std::endl; std::cerr << " http://server.name.com/cgi-bin/cgi_jpeg?id=2" << std::endl; std::cerr << std::endl; std::cerr << "This will retrieve the image with ID 2." << std::endl; std::cerr << std::endl; std::cerr << "You will probably have to change some of the #defines " "at the top of" << std::endl; std::cerr << "examples/cgi_jpeg.cpp to allow the lookup to work." << std::endl; return 1; } mysqlpp::Connection con(use_exceptions); try { con.connect(IMG_DATABASE, IMG_HOST, IMG_USER, IMG_PASSWORD); mysqlpp::Query query = con.query(); query << "SELECT * FROM images WHERE id = " << img_id; mysqlpp::UseQueryResult res = query.use(); if (res) { images img = res.fetch_row(); std::cout << "Content-type: image/jpeg" << std::endl; std::cout << "Content-length: " << img.data.length() << "\n\n"; std::cout << img.data; } else { std::cout << "Content-type: text/plain" << std::endl << std::endl; std::cout << "ERROR: No such image with ID " << img_id << std::endl; } } catch (const mysqlpp::BadQuery& er) { // Handle any query errors std::cout << "Content-type: text/plain" << std::endl << std::endl; std::cout << "QUERY ERROR: " << er.what() << std::endl; return 1; } catch (const mysqlpp::Exception& er) { // Catch-all for any other MySQL++ exceptions std::cout << "Content-type: text/plain" << std::endl << std::endl; std::cout << "GENERAL ERROR: " << er.what() << std::endl; return 1; } #else // MySQL++ works under Visual C++ 2003 with only one excpetion, // SSQLS, so we have to stub out the examples to avoid build errors. std::cout << argv[0] << " requires Visual C++ 2005 or newer." << std::endl; #endif return 0; } <commit_msg>Fix to the recent VC++ 2003 fix, which broke cgi_jpeg example for everyone else.<commit_after>/*********************************************************************** cgi_jpeg.cpp - Example code showing how to fetch JPEG data from a BLOB column and send it back to a browser that requested it by ID. Use load_jpeg.cpp to load JPEG files into the database we query. Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and (c) 2004-2008 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <mysql++.h> #if defined(MYSQLPP_SSQLS_COMPATIBLE) #include <ssqls.h> #define IMG_DATABASE "mysql_cpp_data" #define IMG_HOST "localhost" #define IMG_USER "root" #define IMG_PASSWORD "nunyabinness" sql_create_2(images, 1, 2, mysqlpp::sql_int_unsigned, id, mysqlpp::sql_blob, data) int main() #else // !defined(MYSQLPP_SSQLS_COMPATIBLE) int main(int, char* argv[]) #endif { #if defined(MYSQLPP_SSQLS_COMPATIBLE) unsigned int img_id = 0; char* cgi_query = getenv("QUERY_STRING"); if (cgi_query) { if ((strlen(cgi_query) < 4) || memcmp(cgi_query, "id=", 3)) { std::cout << "Content-type: text/plain" << std::endl << std::endl; std::cout << "ERROR: Bad query string" << std::endl; return 1; } else { img_id = atoi(cgi_query + 3); } } else { std::cerr << "Put this program into a web server's cgi-bin " "directory, then" << std::endl; std::cerr << "invoke it with a URL like this:" << std::endl; std::cerr << std::endl; std::cerr << " http://server.name.com/cgi-bin/cgi_jpeg?id=2" << std::endl; std::cerr << std::endl; std::cerr << "This will retrieve the image with ID 2." << std::endl; std::cerr << std::endl; std::cerr << "You will probably have to change some of the #defines " "at the top of" << std::endl; std::cerr << "examples/cgi_jpeg.cpp to allow the lookup to work." << std::endl; return 1; } try { mysqlpp::Connection con(IMG_DATABASE, IMG_HOST, IMG_USER, IMG_PASSWORD); mysqlpp::Query query = con.query(); query << "SELECT * FROM images WHERE id = " << img_id; mysqlpp::UseQueryResult res = query.use(); if (res) { images img = res.fetch_row(); std::cout << "Content-type: image/jpeg" << std::endl; std::cout << "Content-length: " << img.data.length() << "\n\n"; std::cout << img.data; } else { std::cout << "Content-type: text/plain" << std::endl << std::endl; std::cout << "ERROR: No such image with ID " << img_id << std::endl; } } catch (const mysqlpp::BadQuery& er) { // Handle any query errors std::cout << "Content-type: text/plain" << std::endl << std::endl; std::cout << "QUERY ERROR: " << er.what() << std::endl; return 1; } catch (const mysqlpp::Exception& er) { // Catch-all for any other MySQL++ exceptions std::cout << "Content-type: text/plain" << std::endl << std::endl; std::cout << "GENERAL ERROR: " << er.what() << std::endl; return 1; } #else // MySQL++ works under Visual C++ 2003 with only one excpetion, // SSQLS, so we have to stub out the examples to avoid build errors. std::cout << argv[0] << " requires Visual C++ 2005 or newer." << std::endl; #endif return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2019-2022, Hossein Moein 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 Hossein Moein and/or the DataFrame 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 Hossein Moein 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 <DataFrame/DataFrame.h> #include <DataFrame/DataFrameStatsVisitors.h> #include <DataFrame/RandGen.h> #include <iostream> using namespace hmdf; typedef StdDataFrame<time_t> MyDataFrame; // ----------------------------------------------------------------------------- int main(int argc, char *argv[]) { MyDataFrame df; const size_t index_sz = df.load_index( MyDataFrame::gen_datetime_index("01/01/1970", "08/15/2019", time_frequency::secondly, 1, DT_TIME_ZONE::EU_BERLIN)); RandGenParams<double> p; p.mean = 1.0; // Default p.std = 0.005; df.load_column("normal", gen_normal_dist<double>(index_sz, p)); df.load_column("log_normal", gen_lognormal_dist<double>(index_sz)); p.lambda = 1.5; df.load_column("exponential", gen_exponential_dist<double>(index_sz, p)); std::cout << "All memory allocations are done. Calculating means ..." << std::endl; MeanVisitor<double, time_t> n_mv; MeanVisitor<double, time_t> ln_mv; MeanVisitor<double, time_t> e_mv; auto fut1 = df.visit_async<double>("normal", n_mv); auto fut2 = df.visit_async<double>("log_normal", ln_mv); auto fut3 = df.visit_async<double>("exponential", e_mv); fut1.get(); fut2.get(); fut3.get(); // std::cout << "Normal mean " << n_mv.get_result() << std::endl; // std::cout << "Log Normal mean " << ln_mv.get_result() << std::endl; // std::cout << "Exponential mean " << e_mv.get_result() << std::endl; return (0); } // ----------------------------------------------------------------------------- // Local Variables: // mode:C++ // tab-width:4 // c-basic-offset:4 // End: <commit_msg>Removed a test code<commit_after>/* Copyright (c) 2019-2022, Hossein Moein 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 Hossein Moein and/or the DataFrame 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 Hossein Moein 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 <DataFrame/DataFrame.h> #include <DataFrame/DataFrameStatsVisitors.h> #include <DataFrame/RandGen.h> #include <iostream> using namespace hmdf; typedef StdDataFrame<time_t> MyDataFrame; // ----------------------------------------------------------------------------- int main(int argc, char *argv[]) { MyDataFrame df; const size_t index_sz = df.load_index( MyDataFrame::gen_datetime_index("01/01/1970", "08/15/2019", time_frequency::secondly, 1)); RandGenParams<double> p; p.mean = 1.0; // Default p.std = 0.005; df.load_column("normal", gen_normal_dist<double>(index_sz, p)); df.load_column("log_normal", gen_lognormal_dist<double>(index_sz)); p.lambda = 1.5; df.load_column("exponential", gen_exponential_dist<double>(index_sz, p)); std::cout << "All memory allocations are done. Calculating means ..." << std::endl; MeanVisitor<double, time_t> n_mv; MeanVisitor<double, time_t> ln_mv; MeanVisitor<double, time_t> e_mv; auto fut1 = df.visit_async<double>("normal", n_mv); auto fut2 = df.visit_async<double>("log_normal", ln_mv); auto fut3 = df.visit_async<double>("exponential", e_mv); fut1.get(); fut2.get(); fut3.get(); // std::cout << "Normal mean " << n_mv.get_result() << std::endl; // std::cout << "Log Normal mean " << ln_mv.get_result() << std::endl; // std::cout << "Exponential mean " << e_mv.get_result() << std::endl; return (0); } // ----------------------------------------------------------------------------- // Local Variables: // mode:C++ // tab-width:4 // c-basic-offset:4 // End: <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/predictor/vehicle/lane_sequence_predictor.h" #include <cmath> #include "Eigen/Dense" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/common/math/math_utils.h" #include "modules/common/log.h" namespace apollo { namespace prediction { using ::apollo::common::PathPoint; using ::apollo::common::TrajectoryPoint; using ::apollo::common::math::KalmanFilter; void LaneSequencePredictor::Predict(Obstacle* obstacle) { prediction_obstacle_.Clear(); CHECK_NOTNULL(obstacle); CHECK_GT(obstacle->history_size(), 0); const Feature& feature = obstacle->latest_feature(); if (!feature.has_lane() || !feature.lane().has_lane_graph()) { AERROR << "Obstacle [" << obstacle->id() << " has no lane graph."; return; } std::string lane_id = ""; if (feature.lane().has_lane_feature()) { lane_id = feature.lane().lane_feature().lane_id(); } int num_lane_sequence = feature.lane().lane_graph().lane_sequence_size(); std::vector<bool> enable_lane_sequence(num_lane_sequence, true); FilterLaneSequences(feature.lane().lane_graph(), lane_id, &enable_lane_sequence); for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = feature.lane().lane_graph().lane_sequence(i); if (sequence.lane_segment_size() == 0) { AERROR << "Empty lane segments."; continue; } if (!enable_lane_sequence[i]) { ADEBUG << "Lane sequence [" << ToString(sequence) << "] with probability [" <<sequence.probability() << "] is disqualified."; continue; } std::string curr_lane_id = sequence.lane_segment(0).lane_id(); std::vector<TrajectoryPoint> points; DrawLaneSequenceTrajectoryPoints( obstacle->kf_lane_tracker(curr_lane_id), sequence, FLAGS_prediction_duration, FLAGS_prediction_freq, &points); Trajectory trajectory; GenerateTrajectory(points, &trajectory); trajectory.set_probability(sequence.probability()); prediction_obstacle_.set_predicted_period(FLAGS_prediction_duration); prediction_obstacle_.add_trajectory()->CopyFrom(trajectory); ADEBUG << "Obstacle [" << obstacle->id() << "] has " << prediction_obstacle_.trajectory_size() << " trajectories."; } } void LaneSequencePredictor::FilterLaneSequences( const LaneGraph& lane_graph, const std::string& lane_id, std::vector<bool> *enable_lane_sequence) { int num_lane_sequence = lane_graph.lane_sequence_size(); std::vector<int> lane_change_type(num_lane_sequence, -1); std::pair<int, double> change(-1, -1.0); std::pair<int, double> all(-1, -1.0); for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); // Get lane change type int lane_change = GetLaneChangeType(lane_id, sequence); lane_change_type[i] = lane_change; double probability = sequence.probability(); if (::apollo::common::math::DoubleCompare(probability, all.second) > 0 || (::apollo::common::math::DoubleCompare(probability, all.second) == 0 && lane_change_type[i] == 0)) { all.first = i; all.second = probability; } if (lane_change_type[i] > 0 && ::apollo::common::math::DoubleCompare(probability, change.second) > 0) { change.first = i; change.second = probability; } } for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); double probability = sequence.probability(); if (::apollo::common::math::DoubleCompare( probability, FLAGS_lane_sequence_threshold) < 0 && i != all.first) { (*enable_lane_sequence)[i] = false; } else if (lane_change_type[i] > 0 && lane_change_type[i] != change.first) { (*enable_lane_sequence)[i] = false; } } } int LaneSequencePredictor::GetLaneChangeType( const std::string& lane_id, const LaneSequence& lane_sequence) { PredictionMap *map = PredictionMap::instance(); CHECK_NOTNULL(map); std::string lane_change_id = lane_sequence.lane_segment(0).lane_id(); if (lane_id == lane_change_id) { return 0; } else { if (map->IsLeftNeighborLane(map->LaneById(lane_change_id), map->LaneById(lane_id))) { return 1; } else if (map->IsRightNeighborLane( map->LaneById(lane_change_id), map->LaneById(lane_id))) { return 2; } } return -1; } void LaneSequencePredictor::DrawLaneSequenceTrajectoryPoints( const KalmanFilter<double, 4, 2, 0>& kf, const LaneSequence& sequence, double total_time, double freq, std::vector<TrajectoryPoint> *points) { PredictionMap *map = PredictionMap::instance(); CHECK_NOTNULL(map); Eigen::Matrix<double, 4, 1> state(kf.GetStateEstimate()); double lane_s = state(0, 0); double lane_l = state(1, 0); double lane_speed = state(2, 0); double lane_acc = state(3, 0); Eigen::Matrix<double, 4, 4> transition(kf.GetTransitionMatrix()); transition(0, 2) = freq; transition(0, 3) = 0.5 * freq * freq; transition(2, 3) = freq; int lane_segment_index = 0; std::string lane_id = sequence.lane_segment(lane_segment_index).lane_id(); for (size_t i = 0; i < static_cast<size_t>(total_time / freq); ++i) { Eigen::Vector2d point; double theta = M_PI; if (map->SmoothPointFromLane( map->id(lane_id), lane_s, lane_l, &point, &theta) != 0) { AERROR << "Unable to get smooth point from lane [" << lane_id << "] with s [" << lane_s << "] and l [" << lane_l << "]"; continue; } if (points->size() > 0) { PathPoint *prev_point = points->back().mutable_path_point(); double x_diff = point.x() - prev_point->x(); double y_diff = point.y() - prev_point->y(); if (::apollo::common::math::DoubleCompare(x_diff, 0.0) != 0 || ::apollo::common::math::DoubleCompare(y_diff, 0.0) != 0) { theta = std::atan2(y_diff, x_diff); prev_point->set_theta(theta); } else { theta = prev_point->theta(); } } // add trajectory point TrajectoryPoint trajectory_point; PathPoint path_point; path_point.set_x(point.x()); path_point.set_y(point.y()); path_point.set_z(0.0); path_point.set_theta(theta); trajectory_point.mutable_path_point()->CopyFrom(path_point); trajectory_point.set_v(lane_speed); trajectory_point.set_a(lane_acc); trajectory_point.set_relative_time(static_cast<double>(i) * freq); points->emplace_back(std::move(trajectory_point)); // update state if (::apollo::common::math::DoubleCompare(lane_speed, 0.0) <= 0) { lane_speed = 0.0; lane_acc = 0.0; transition(1, 1) = 1.0; } else if (::apollo::common::math::DoubleCompare( lane_speed, FLAGS_max_speed) >= 0) { lane_speed = FLAGS_max_speed; lane_acc = 0.0; } state(2, 0) = lane_speed; state(3, 0) = lane_acc; state = transition * state; if (::apollo::common::math::DoubleCompare(lane_s, state(0, 0)) >= 0) { state(0, 0) = lane_s; state(1, 0) = lane_l; state(2, 0) = 0.0; state(3, 0) = 0.0; transition(1, 1) = 1.0; } lane_s = state(0, 0); lane_l = state(1, 0); lane_speed = state(2, 0); lane_acc = state(3, 0); // find next lane id while (lane_s > map->LaneById(lane_id)->total_length() && lane_segment_index < sequence.lane_segment_size()) { lane_s = lane_s - map->LaneById(lane_id)->total_length(); lane_segment_index += 1; lane_id = sequence.lane_segment(lane_segment_index).lane_id(); } } } std::string LaneSequencePredictor::ToString(const LaneSequence& sequence) { std::string str_lane_sequence = ""; if (sequence.lane_segment_size() > 0) { str_lane_sequence += sequence.lane_segment(0).lane_id(); } for (int i = 1; i < sequence.lane_segment_size(); ++i) { str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id()); } return str_lane_sequence; } } // prediction } // apollo <commit_msg>Updated debug logging<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/predictor/vehicle/lane_sequence_predictor.h" #include <cmath> #include "Eigen/Dense" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/common/math/math_utils.h" #include "modules/common/log.h" namespace apollo { namespace prediction { using ::apollo::common::PathPoint; using ::apollo::common::TrajectoryPoint; using ::apollo::common::math::KalmanFilter; void LaneSequencePredictor::Predict(Obstacle* obstacle) { prediction_obstacle_.Clear(); CHECK_NOTNULL(obstacle); CHECK_GT(obstacle->history_size(), 0); const Feature& feature = obstacle->latest_feature(); if (!feature.has_lane() || !feature.lane().has_lane_graph()) { AERROR << "Obstacle [" << obstacle->id() << " has no lane graph."; return; } std::string lane_id = ""; if (feature.lane().has_lane_feature()) { lane_id = feature.lane().lane_feature().lane_id(); } int num_lane_sequence = feature.lane().lane_graph().lane_sequence_size(); std::vector<bool> enable_lane_sequence(num_lane_sequence, true); FilterLaneSequences(feature.lane().lane_graph(), lane_id, &enable_lane_sequence); for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = feature.lane().lane_graph().lane_sequence(i); if (sequence.lane_segment_size() == 0) { AERROR << "Empty lane segments."; continue; } if (!enable_lane_sequence[i]) { ADEBUG << "Lane sequence [" << ToString(sequence) << "] with probability [" <<sequence.probability() << "] is disqualified."; continue; } ADEBUG << "Obstacle [" << obstacle->id() << "] will draw a lane sequence trajectory [" << ToString(sequence) << "] with probability [" << sequence.probability() << "]."; std::string curr_lane_id = sequence.lane_segment(0).lane_id(); std::vector<TrajectoryPoint> points; DrawLaneSequenceTrajectoryPoints( obstacle->kf_lane_tracker(curr_lane_id), sequence, FLAGS_prediction_duration, FLAGS_prediction_freq, &points); Trajectory trajectory; GenerateTrajectory(points, &trajectory); trajectory.set_probability(sequence.probability()); prediction_obstacle_.set_predicted_period(FLAGS_prediction_duration); prediction_obstacle_.add_trajectory()->CopyFrom(trajectory); } ADEBUG << "Obstacle [" << obstacle->id() << "] has total " << prediction_obstacle_.trajectory_size() << " trajectories."; } void LaneSequencePredictor::FilterLaneSequences( const LaneGraph& lane_graph, const std::string& lane_id, std::vector<bool> *enable_lane_sequence) { int num_lane_sequence = lane_graph.lane_sequence_size(); std::vector<int> lane_change_type(num_lane_sequence, -1); std::pair<int, double> change(-1, -1.0); std::pair<int, double> all(-1, -1.0); for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); // Get lane change type int lane_change = GetLaneChangeType(lane_id, sequence); lane_change_type[i] = lane_change; double probability = sequence.probability(); if (::apollo::common::math::DoubleCompare(probability, all.second) > 0 || (::apollo::common::math::DoubleCompare(probability, all.second) == 0 && lane_change_type[i] == 0)) { all.first = i; all.second = probability; } if (lane_change_type[i] > 0 && ::apollo::common::math::DoubleCompare(probability, change.second) > 0) { change.first = i; change.second = probability; } } for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); double probability = sequence.probability(); if (::apollo::common::math::DoubleCompare( probability, FLAGS_lane_sequence_threshold) < 0 && i != all.first) { (*enable_lane_sequence)[i] = false; } else if (lane_change_type[i] > 0 && lane_change_type[i] != change.first) { (*enable_lane_sequence)[i] = false; } } } int LaneSequencePredictor::GetLaneChangeType( const std::string& lane_id, const LaneSequence& lane_sequence) { PredictionMap *map = PredictionMap::instance(); CHECK_NOTNULL(map); std::string lane_change_id = lane_sequence.lane_segment(0).lane_id(); if (lane_id == lane_change_id) { return 0; } else { if (map->IsLeftNeighborLane(map->LaneById(lane_change_id), map->LaneById(lane_id))) { return 1; } else if (map->IsRightNeighborLane( map->LaneById(lane_change_id), map->LaneById(lane_id))) { return 2; } } return -1; } void LaneSequencePredictor::DrawLaneSequenceTrajectoryPoints( const KalmanFilter<double, 4, 2, 0>& kf, const LaneSequence& sequence, double total_time, double freq, std::vector<TrajectoryPoint> *points) { PredictionMap *map = PredictionMap::instance(); CHECK_NOTNULL(map); Eigen::Matrix<double, 4, 1> state(kf.GetStateEstimate()); double lane_s = state(0, 0); double lane_l = state(1, 0); double lane_speed = state(2, 0); double lane_acc = state(3, 0); Eigen::Matrix<double, 4, 4> transition(kf.GetTransitionMatrix()); transition(0, 2) = freq; transition(0, 3) = 0.5 * freq * freq; transition(2, 3) = freq; int lane_segment_index = 0; std::string lane_id = sequence.lane_segment(lane_segment_index).lane_id(); for (size_t i = 0; i < static_cast<size_t>(total_time / freq); ++i) { Eigen::Vector2d point; double theta = M_PI; if (map->SmoothPointFromLane( map->id(lane_id), lane_s, lane_l, &point, &theta) != 0) { AERROR << "Unable to get smooth point from lane [" << lane_id << "] with s [" << lane_s << "] and l [" << lane_l << "]"; continue; } if (points->size() > 0) { PathPoint *prev_point = points->back().mutable_path_point(); double x_diff = point.x() - prev_point->x(); double y_diff = point.y() - prev_point->y(); if (::apollo::common::math::DoubleCompare(x_diff, 0.0) != 0 || ::apollo::common::math::DoubleCompare(y_diff, 0.0) != 0) { theta = std::atan2(y_diff, x_diff); prev_point->set_theta(theta); } else { theta = prev_point->theta(); } } // add trajectory point TrajectoryPoint trajectory_point; PathPoint path_point; path_point.set_x(point.x()); path_point.set_y(point.y()); path_point.set_z(0.0); path_point.set_theta(theta); trajectory_point.mutable_path_point()->CopyFrom(path_point); trajectory_point.set_v(lane_speed); trajectory_point.set_a(lane_acc); trajectory_point.set_relative_time(static_cast<double>(i) * freq); points->emplace_back(std::move(trajectory_point)); // update state if (::apollo::common::math::DoubleCompare(lane_speed, 0.0) <= 0) { lane_speed = 0.0; lane_acc = 0.0; transition(1, 1) = 1.0; } else if (::apollo::common::math::DoubleCompare( lane_speed, FLAGS_max_speed) >= 0) { lane_speed = FLAGS_max_speed; lane_acc = 0.0; } state(2, 0) = lane_speed; state(3, 0) = lane_acc; state = transition * state; if (::apollo::common::math::DoubleCompare(lane_s, state(0, 0)) >= 0) { state(0, 0) = lane_s; state(1, 0) = lane_l; state(2, 0) = 0.0; state(3, 0) = 0.0; transition(1, 1) = 1.0; } lane_s = state(0, 0); lane_l = state(1, 0); lane_speed = state(2, 0); lane_acc = state(3, 0); // find next lane id while (lane_s > map->LaneById(lane_id)->total_length() && lane_segment_index < sequence.lane_segment_size()) { lane_s = lane_s - map->LaneById(lane_id)->total_length(); lane_segment_index += 1; lane_id = sequence.lane_segment(lane_segment_index).lane_id(); } } } std::string LaneSequencePredictor::ToString(const LaneSequence& sequence) { std::string str_lane_sequence = ""; if (sequence.lane_segment_size() > 0) { str_lane_sequence += sequence.lane_segment(0).lane_id(); } for (int i = 1; i < sequence.lane_segment_size(); ++i) { str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id()); } return str_lane_sequence; } } // prediction } // apollo <|endoftext|>
<commit_before>/*------------ant.cpp---------------------------------------------------------// * * ants -- We have them * * Purpose: Figure out ant pathing to food. I want food. * *-----------------------------------------------------------------------------*/ #include <array> #include <iostream> #include <vector> #include <random> /*----------------------------------------------------------------------------// * STRUCTS *-----------------------------------------------------------------------------*/ // grid size const int n = 5; // structs for ant movement struct coord{ int x, y; }; // Template for 2d boolean arrays template <typename T, size_t rows, size_t cols> using array2d = std::array<std::array<T, cols>, rows>; // defines operators for definitions above inline bool operator==(const coord& lhs, const coord& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } inline bool operator!=(const coord& lhs, const coord& rhs) { return !(lhs == rhs); } struct ant{ array2d<bool, n, n> phetus; coord pos; std::vector<coord> phepath, antpath; int step, phenum, pernum; }; struct grid{ array2d<bool, n, n> wall; coord prize; }; // Functions for ant movement // Chooses step ant step(ant curr, grid landscape, coord spawn_point, int gen_flag); // Generates ants std::vector<ant> gen_ants(coord spawn_point); // Moves simulation every timestep std::vector<ant> move(std::vector <ant> ants, grid landscape); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(){ } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // Chooses step ant step(ant curr, grid landscape, coord spawn_point, int gen_flag){ coord next_step[3]; coord up, down, left, right, next; int pcount = 0; up.x = curr.pos.x; up.y = curr.pos.y + 1; down.x = curr.pos.x; down.y = curr.pos.y - 1; left.x = curr.pos.x - 1; left.y = curr.pos.y; right.x = curr.pos.x + 1; right.y = curr.pos.y; coord last = curr.antpath.back(); // determine possible movement // up case if (last != up) { if (landscape.wall[up.x][up.y] == 0){ next_step[pcount] = up; pcount++; } } // down case if (last != down) { if (landscape.wall[down.x][down.y] == 0){ next_step[pcount] = up; pcount++; } } if (last != left) { if (landscape.wall[left.x][left.y] == 0){ next_step[pcount] = up; pcount++; } } // right case if (last != right) { if (landscape.wall[right.x][right.y] == 0){ next_step[pcount] = up; pcount++; } } static std::random_device rd; auto seed = rd(); static std::mt19937 gen(seed); if (gen_flag == 0 && curr.phetus[curr.pos.x][curr.pos.y] == 0){ std::uniform_int_distribution<int> ant_distribution(0,pcount); next = next_step[ant_distribution(gen)]; curr.antpath.push_back(curr.pos); curr.pos = next; } else{ double prob = curr.pernum / curr.phenum, aprob[pcount], rn, psum = 0; int choice = -1, cthulu; std::uniform_real_distribution<double> ant_distribution(0,1); // search through phepath to find ant's curr location for (size_t q = 0; q < curr.phepath.size(); q++){ if (curr.pos.x == curr.phepath[q].x && curr.pos.y == curr.phepath[q].y){ cthulu = q; } } std::uniform_real_distribution<double> ant_ddist(0,1); rn = ant_ddist(gen); for (size_t q = 0; q < pcount; q++){ if (next_step[q].x == curr.phepath[cthulu +1].x && next_step[q].y == curr.phepath[cthulu +1].y){ aprob[q] = prob; } else{ aprob[q] = (1 - prob) / (pcount - 1); } psum += aprob[q]; if (rn < psum && choice < 0){ choice = q; } } next = next_step[choice]; curr.antpath.push_back(curr.pos); curr.pos = next; } return curr; } <commit_msg>adding for dbugging purposes. fixed soon.<commit_after>/*------------ant.cpp---------------------------------------------------------// * * ants -- We have them * * Purpose: Figure out ant pathing to food. I want food. * *-----------------------------------------------------------------------------*/ #include <array> #include <iostream> #include <vector> #include <random> #include <fstream> /*----------------------------------------------------------------------------// * STRUCTS *-----------------------------------------------------------------------------*/ // grid size const int n = 5; // structs for ant movement struct coord{ int x, y; }; // Template for 2d boolean arrays template <typename T, size_t rows, size_t cols> using array2d = std::array<std::array<T, cols>, rows>; // defines operators for definitions above inline bool operator==(const coord& lhs, const coord& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } inline bool operator!=(const coord& lhs, const coord& rhs) { return !(lhs == rhs); } struct ant{ array2d<bool, n, n> phetus; coord pos; std::vector<coord> phepath, antpath; int stepnum, phenum, pernum; }; struct grid{ array2d<bool, n, n> wall; coord prize; }; // Functions for ant movement // Chooses step ant step(ant curr, grid landscape, int gen_flag); // Generates ants std::vector<ant> gen_ants(std::vector<ant> ants, ant plate); // Changes template ant ant plate_toss(ant winner); // Moves simulation every timestep std::vector<ant> move(std::vector <ant> ants, grid landscape, coord spawn, int pernum, int final_time, std::ofstream &output); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(){ // defining output file std::ofstream output("out.dat", std::ofstream::out); // defining initial ant vector and grid std::vector<ant> ants; grid landscape; landscape.wall = {}; landscape.prize.x = n; landscape.prize.y = n; // defining spawn point coord spawn; spawn.x = n; spawn.y = 0; // defining misc characters int final_time = 10; int pernum = 10; move(ants, landscape, spawn, pernum, final_time, output); //output.close(); } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // Chooses step ant step(ant curr, grid landscape, int gen_flag){ coord next_step[3]; coord up, down, left, right, next; int pcount = 0; up.x = curr.pos.x; up.y = curr.pos.y + 1; down.x = curr.pos.x; down.y = curr.pos.y - 1; left.x = curr.pos.x - 1; left.y = curr.pos.y; right.x = curr.pos.x + 1; right.y = curr.pos.y; std::cout << up.x << '\n' << up.y << '\n'; coord last; if (curr.stepnum == 0){ last.x = -1; last.y = -1; } else{ last = curr.antpath.back(); } // determine possible movement // up case if (last != up) { if (landscape.wall[up.x][up.y] == 0){ next_step[pcount] = up; pcount++; } } // down case if (last != down) { if (landscape.wall[down.x][down.y] == 0){ next_step[pcount] = up; pcount++; } } if (last != left) { if (landscape.wall[left.x][left.y] == 0){ next_step[pcount] = up; pcount++; } } // right case if (last != right) { if (landscape.wall[right.x][right.y] == 0){ next_step[pcount] = up; pcount++; } } static std::random_device rd; auto seed = rd(); static std::mt19937 gen(seed); if (gen_flag == 0 && curr.phetus[curr.pos.x][curr.pos.y] == 0){ std::uniform_int_distribution<int> ant_distribution(0,pcount); next = next_step[ant_distribution(gen)]; curr.antpath.push_back(curr.pos); curr.pos = next; } else{ double prob = curr.pernum / curr.phenum, aprob[pcount], rn, psum = 0; int choice = -1, cthulu; std::uniform_real_distribution<double> ant_distribution(0,1); // search through phepath to find ant's curr location for (size_t q = 0; q < curr.phepath.size(); q++){ if (curr.pos.x == curr.phepath[q].x && curr.pos.y == curr.phepath[q].y){ cthulu = q; } } std::uniform_real_distribution<double> ant_ddist(0,1); rn = ant_ddist(gen); for (size_t q = 0; q < pcount; q++){ if (next_step[q].x == curr.phepath[cthulu +1].x && next_step[q].y == curr.phepath[cthulu +1].y){ aprob[q] = prob; } else{ aprob[q] = (1 - prob) / (pcount - 1); } psum += aprob[q]; if (rn < psum && choice < 0){ choice = q; } } next = next_step[choice]; curr.antpath.push_back(curr.pos); curr.pos = next; } curr.stepnum++; return curr; } // Generates ants std::vector<ant> gen_ants(std::vector<ant> ants, ant plate){ ant curr; curr = plate; ants.push_back(curr); return ants; } // Changes template ant ant plate_toss(ant winner){ ant plate = winner; plate.phenum = winner.stepnum; plate.stepnum = 0; // generate a new phetus plate.phetus = {}; for (size_t i = 0; i < winner.antpath.size(); i++){ plate.phetus[winner.antpath[i].x][winner.antpath[i].y] = 1; } plate.antpath = {}; return plate; } // Moves simulation every timestep // step 1: create ants // step 2: move ants // step 3: profit? // redefine all paths = to shortest path std::vector<ant> move(std::vector <ant> ants, grid landscape, coord spawn, int pernum, int final_time, std::ofstream &output){ std::vector<int> killlist; // Time loop // setting template for first generate ant plate; plate.pos.x = spawn.x; plate.pos.y = spawn.y; plate.stepnum = 0; plate.phenum = n*n; plate.phetus = {}; // to be defined later plate.pernum = pernum; /* // define walls and prize at random spot grid landscape; landscape.wall = {}; landscape.prize.x = n; landscape.prize.y = n; */ for (size_t i = 0; i < final_time; i++){ std::cout << i << '\n'; int flag = 0; // step 1: generate ant ants = gen_ants(ants, plate); // step 2: Move ants for (size_t j = 0; j < ants.size(); j++){ ants[j] = step(ants[j], landscape, flag); if (ants[j].stepnum > ants[j].phenum){ killlist.push_back(j); } if (ants[j].pos.x == landscape.prize.x && ants[j].pos.y == landscape.prize.y){ plate = plate_toss(ants[j]); } } for (size_t k = 0; k < killlist.size(); k++){ ants.erase(ants.begin() + killlist[k]); } for (size_t l = 0; l < ants[0].phepath.size(); l++){ output << ants[0].phepath[l].x << '\t' << ants[0].phepath[l].y << '\n'; } output << '\n' << '\n'; } return ants; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2016 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 * *****************************************************************************/ #ifndef MAPNIK_JSON_EXTRACT_BOUNDING_BOXES_CONFIG_HPP #define MAPNIK_JSON_EXTRACT_BOUNDING_BOXES_CONFIG_HPP #include <mapnik/json/json_grammar_config.hpp> #include <mapnik/box2d.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/spirit/home/x3.hpp> #pragma GCC diagnostic pop //auto feature_collection_impl = x3::with<mapnik::json::grammar::bracket_tag>(std::ref(bracket_counter)) // [x3::with<mapnik::json::grammar::keys_tag>(std::ref(keys)) // [x3::with<mapnik::json::grammar::feature_callback_tag>(std::ref(callback)) // [mapnik::json::grammar::feature_collection] // ]]; namespace mapnik { namespace json { template <typename Iterator, typename Boxes> struct extract_positions { using boxes_type = Boxes; using box_type = typename boxes_type::value_type::first_type; extract_positions(Iterator start, Boxes & boxes) : start_(start), boxes_(boxes) {} template <typename T> void operator() (T const& val) const { auto const& r = std::get<0>(val); auto const& b = std::get<1>(val); auto offset = std::distance(start_, r.begin()); auto size = std::distance(r.begin(), r.end()); boxes_.emplace_back(std::make_pair(box_type(b.minx(), b.miny(), b.maxx(), b.maxy()), std::make_pair(offset, size))); //boxes_.emplace_back(std::make_tuple(bbox,offset, size)); } Iterator start_; Boxes & boxes_; }; using box_type = mapnik::box2d<double>; using boxes_type = std::vector<std::pair<box_type, std::pair<std::size_t, std::size_t>>>; using callback_type = extract_positions<grammar::iterator_type, boxes_type>; using box_type_f = mapnik::box2d<float>; using boxes_type_f = std::vector<std::pair<box_type_f, std::pair<std::size_t, std::size_t>>>; using callback_type_f = extract_positions<grammar::iterator_type, boxes_type_f>; namespace grammar { struct bracket_tag; struct feature_callback_tag; namespace x3 = boost::spirit::x3; using space_type = x3::standard::space_type; //using iterator_type = char const*; using phrase_parse_context_type = x3::phrase_parse_context<space_type>::type; using context_type = x3::with_context<keys_tag, std::reference_wrapper<keys_map> const, phrase_parse_context_type>::type; using extract_bounding_boxes_context_type = x3::with_context<bracket_tag, std::reference_wrapper<std::size_t> const, x3::with_context<feature_callback_tag, std::reference_wrapper<callback_type> const, context_type>::type>::type; using extract_bounding_boxes_reverse_context_type = x3::with_context<keys_tag, std::reference_wrapper<keys_map> const, x3::with_context<feature_callback_tag, std::reference_wrapper<callback_type> const, x3::with_context<bracket_tag, std::reference_wrapper<std::size_t> const, phrase_parse_context_type>::type>::type>::type; using extract_bounding_boxes_context_type_f = x3::with_context<bracket_tag, std::reference_wrapper<std::size_t> const, x3::with_context<feature_callback_tag, std::reference_wrapper<callback_type_f> const, context_type>::type>::type; using extract_bounding_boxes_reverse_context_type_f = x3::with_context<keys_tag, std::reference_wrapper<keys_map> const, x3::with_context<feature_callback_tag, std::reference_wrapper<callback_type_f> const, x3::with_context<bracket_tag, std::reference_wrapper<std::size_t> const, phrase_parse_context_type>::type>::type>::type; }}} #endif // MAPNIK_JSON_EXTRACT_BOUNDING_BOXES_CONFIG_HPP <commit_msg>only add `valid` bounding boxes (make backward compatible)<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2016 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 * *****************************************************************************/ #ifndef MAPNIK_JSON_EXTRACT_BOUNDING_BOXES_CONFIG_HPP #define MAPNIK_JSON_EXTRACT_BOUNDING_BOXES_CONFIG_HPP #include <mapnik/json/json_grammar_config.hpp> #include <mapnik/box2d.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/spirit/home/x3.hpp> #pragma GCC diagnostic pop //auto feature_collection_impl = x3::with<mapnik::json::grammar::bracket_tag>(std::ref(bracket_counter)) // [x3::with<mapnik::json::grammar::keys_tag>(std::ref(keys)) // [x3::with<mapnik::json::grammar::feature_callback_tag>(std::ref(callback)) // [mapnik::json::grammar::feature_collection] // ]]; namespace mapnik { namespace json { template <typename Iterator, typename Boxes> struct extract_positions { using boxes_type = Boxes; using box_type = typename boxes_type::value_type::first_type; extract_positions(Iterator start, Boxes & boxes) : start_(start), boxes_(boxes) {} template <typename T> void operator() (T const& val) const { auto const& r = std::get<0>(val); auto const& b = std::get<1>(val); if (b.valid()) { auto offset = std::distance(start_, r.begin()); auto size = std::distance(r.begin(), r.end()); boxes_.emplace_back(std::make_pair(box_type(b.minx(), b.miny(), b.maxx(), b.maxy()), std::make_pair(offset, size))); //boxes_.emplace_back(std::make_tuple(bbox,offset, size)); } } Iterator start_; Boxes & boxes_; }; using box_type = mapnik::box2d<double>; using boxes_type = std::vector<std::pair<box_type, std::pair<std::size_t, std::size_t>>>; using callback_type = extract_positions<grammar::iterator_type, boxes_type>; using box_type_f = mapnik::box2d<float>; using boxes_type_f = std::vector<std::pair<box_type_f, std::pair<std::size_t, std::size_t>>>; using callback_type_f = extract_positions<grammar::iterator_type, boxes_type_f>; namespace grammar { struct bracket_tag; struct feature_callback_tag; namespace x3 = boost::spirit::x3; using space_type = x3::standard::space_type; //using iterator_type = char const*; using phrase_parse_context_type = x3::phrase_parse_context<space_type>::type; using context_type = x3::with_context<keys_tag, std::reference_wrapper<keys_map> const, phrase_parse_context_type>::type; using extract_bounding_boxes_context_type = x3::with_context<bracket_tag, std::reference_wrapper<std::size_t> const, x3::with_context<feature_callback_tag, std::reference_wrapper<callback_type> const, context_type>::type>::type; using extract_bounding_boxes_reverse_context_type = x3::with_context<keys_tag, std::reference_wrapper<keys_map> const, x3::with_context<feature_callback_tag, std::reference_wrapper<callback_type> const, x3::with_context<bracket_tag, std::reference_wrapper<std::size_t> const, phrase_parse_context_type>::type>::type>::type; using extract_bounding_boxes_context_type_f = x3::with_context<bracket_tag, std::reference_wrapper<std::size_t> const, x3::with_context<feature_callback_tag, std::reference_wrapper<callback_type_f> const, context_type>::type>::type; using extract_bounding_boxes_reverse_context_type_f = x3::with_context<keys_tag, std::reference_wrapper<keys_map> const, x3::with_context<feature_callback_tag, std::reference_wrapper<callback_type_f> const, x3::with_context<bracket_tag, std::reference_wrapper<std::size_t> const, phrase_parse_context_type>::type>::type>::type; }}} #endif // MAPNIK_JSON_EXTRACT_BOUNDING_BOXES_CONFIG_HPP <|endoftext|>
<commit_before>/* * sanitize - rewrite a string to a suitable (secure) one - implementation * Copyright(c) 2003-2004 of wave++ (Yuri D'Elia) * Distributed under GNU LGPL without ANY warranty. */ // interface #include "sanitize.hh" using std::string; // system headers #include <algorithm> using std::remove_copy_if; // c system headers #include <ctype.h> // implementation string sanitize_file(const string& src) { string r; // discard initial dots string::const_iterator it(src.begin()); while(it != src.end() && *it == '.') ++it; while(it != src.end()) { if(!isascii(*it) || (isprint(*it) && *it != '/')) r += *it; else r += '_'; ++it; } return r; } string sanitize_esc(const string& src) { string r; remove_copy_if(src.begin(), src.end(), r.begin(), iscntrl); return r; } <commit_msg>remove_copy_if had problems even with std::ptr_fun. Now using a simple loop.<commit_after>/* * sanitize - rewrite a string to a suitable (secure) one - implementation * Copyright(c) 2003-2004 of wave++ (Yuri D'Elia) * Distributed under GNU LGPL without ANY warranty. */ // interface #include "sanitize.hh" using std::string; // system headers #include <algorithm> using std::remove_copy_if; // c system headers #include <ctype.h> // implementation string sanitize_file(const string& src) { string r; // discard initial dots string::const_iterator it(src.begin()); while(it != src.end() && *it == '.') ++it; while(it != src.end()) { // non-ascii data is preserved (assumed to be locale-specific) if(!isascii(*it) || (isprint(*it) && *it != '/')) r += *it; else r += '_'; ++it; } return r; } string sanitize_esc(const string& src) { string r; for(string::const_iterator it = src.begin(); it != src.end(); ++it) if(!iscntrl(*it)) r += *it; return r; } <|endoftext|>
<commit_before><commit_msg>Revert "[DF] Work around TTree::GetLeaf bug in GetBranchOrLeafTypeName"<commit_after><|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkString.h" #include "SkTypeface.h" #include "SkTypes.h" static const char* gFaces[] = { "Times Roman", "Hiragino Maru Gothic Pro", "Papyrus", "Helvetica", "Courier New" }; class TypefaceGM : public skiagm::GM { public: TypefaceGM() { fFaces = new SkTypeface*[SK_ARRAY_COUNT(gFaces)]; for (size_t i = 0; i < SK_ARRAY_COUNT(gFaces); i++) { fFaces[i] = SkTypeface::CreateFromName(gFaces[i], SkTypeface::kNormal); } } virtual ~TypefaceGM() { for (size_t i = 0; i < SK_ARRAY_COUNT(gFaces); i++) { fFaces[i]->unref(); } delete [] fFaces; } protected: virtual SkString onShortName() SK_OVERRIDE { return SkString("typeface"); } virtual SkISize onISize() SK_OVERRIDE { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { SkString text("Typefaces are fun!"); SkScalar y = 0; SkPaint paint; paint.setAntiAlias(true); for (size_t i = 0; i < SK_ARRAY_COUNT(gFaces); i++) { this->drawWithFace(text, i, y, paint, canvas); } // Now go backwards for (int i = SK_ARRAY_COUNT(gFaces) - 1; i >= 0; i--) { this->drawWithFace(text, i, y, paint, canvas); } } private: void drawWithFace(const SkString& text, int i, SkScalar& y, SkPaint& paint, SkCanvas* canvas) { paint.setTypeface(fFaces[i]); y += paint.getFontMetrics(NULL); canvas->drawText(text.c_str(), text.size(), 0, y, paint); } SkTypeface** fFaces; typedef skiagm::GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static const struct { const char* fName; SkTypeface::Style fStyle; } gFaceStyles[] = { { "sans-serif", SkTypeface::kNormal }, { "sans-serif", SkTypeface::kBold }, { "sans-serif", SkTypeface::kItalic }, { "sans-serif", SkTypeface::kBoldItalic }, { "serif", SkTypeface::kNormal }, { "serif", SkTypeface::kBold }, { "serif", SkTypeface::kItalic }, { "serif", SkTypeface::kBoldItalic }, { "monospace", SkTypeface::kNormal }, { "monospace", SkTypeface::kBold }, { "monospace", SkTypeface::kItalic }, { "monospace", SkTypeface::kBoldItalic }, }; static const int gFaceStylesCount = SK_ARRAY_COUNT(gFaceStyles); class TypefaceStylesGM : public skiagm::GM { SkTypeface* fFaces[gFaceStylesCount]; public: TypefaceStylesGM() { for (int i = 0; i < gFaceStylesCount; i++) { fFaces[i] = SkTypeface::CreateFromName(gFaceStyles[i].fName, gFaceStyles[i].fStyle); } } virtual ~TypefaceStylesGM() { for (int i = 0; i < gFaceStylesCount; i++) { SkSafeUnref(fFaces[i]); } } protected: virtual SkString onShortName() SK_OVERRIDE { return SkString("typefacestyles"); } virtual SkISize onISize() SK_OVERRIDE { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(SkIntToScalar(30)); const char* text = "Hamburgefons"; const size_t textLen = strlen(text); SkScalar x = SkIntToScalar(10); SkScalar dy = paint.getFontMetrics(NULL); SkScalar y = dy; paint.setLinearText(true); for (int i = 0; i < gFaceStylesCount; i++) { paint.setTypeface(fFaces[i]); canvas->drawText(text, textLen, x, y, paint); y += dy; } } private: typedef skiagm::GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// DEF_GM( return new TypefaceGM; ) DEF_GM( return new TypefaceStylesGM; ) <commit_msg><commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkString.h" #include "SkTypeface.h" #include "SkTypes.h" static const char* gFaces[] = { "Times Roman", "Hiragino Maru Gothic Pro", "Papyrus", "Helvetica", "Courier New" }; class TypefaceGM : public skiagm::GM { public: TypefaceGM() { fFaces = new SkTypeface*[SK_ARRAY_COUNT(gFaces)]; for (size_t i = 0; i < SK_ARRAY_COUNT(gFaces); i++) { fFaces[i] = SkTypeface::CreateFromName(gFaces[i], SkTypeface::kNormal); } } virtual ~TypefaceGM() { for (size_t i = 0; i < SK_ARRAY_COUNT(gFaces); i++) { SkSafeUnref(fFaces[i]); } delete [] fFaces; } protected: virtual SkString onShortName() SK_OVERRIDE { return SkString("typeface"); } virtual SkISize onISize() SK_OVERRIDE { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { SkString text("Typefaces are fun!"); SkScalar y = 0; SkPaint paint; paint.setAntiAlias(true); for (size_t i = 0; i < SK_ARRAY_COUNT(gFaces); i++) { this->drawWithFace(text, i, y, paint, canvas); } // Now go backwards for (int i = SK_ARRAY_COUNT(gFaces) - 1; i >= 0; i--) { this->drawWithFace(text, i, y, paint, canvas); } } private: void drawWithFace(const SkString& text, int i, SkScalar& y, SkPaint& paint, SkCanvas* canvas) { paint.setTypeface(fFaces[i]); y += paint.getFontMetrics(NULL); canvas->drawText(text.c_str(), text.size(), 0, y, paint); } SkTypeface** fFaces; typedef skiagm::GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static const struct { const char* fName; SkTypeface::Style fStyle; } gFaceStyles[] = { { "sans-serif", SkTypeface::kNormal }, { "sans-serif", SkTypeface::kBold }, { "sans-serif", SkTypeface::kItalic }, { "sans-serif", SkTypeface::kBoldItalic }, { "serif", SkTypeface::kNormal }, { "serif", SkTypeface::kBold }, { "serif", SkTypeface::kItalic }, { "serif", SkTypeface::kBoldItalic }, { "monospace", SkTypeface::kNormal }, { "monospace", SkTypeface::kBold }, { "monospace", SkTypeface::kItalic }, { "monospace", SkTypeface::kBoldItalic }, }; static const int gFaceStylesCount = SK_ARRAY_COUNT(gFaceStyles); class TypefaceStylesGM : public skiagm::GM { SkTypeface* fFaces[gFaceStylesCount]; public: TypefaceStylesGM() { for (int i = 0; i < gFaceStylesCount; i++) { fFaces[i] = SkTypeface::CreateFromName(gFaceStyles[i].fName, gFaceStyles[i].fStyle); } } virtual ~TypefaceStylesGM() { for (int i = 0; i < gFaceStylesCount; i++) { SkSafeUnref(fFaces[i]); } } protected: virtual SkString onShortName() SK_OVERRIDE { return SkString("typefacestyles"); } virtual SkISize onISize() SK_OVERRIDE { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(SkIntToScalar(30)); const char* text = "Hamburgefons"; const size_t textLen = strlen(text); SkScalar x = SkIntToScalar(10); SkScalar dy = paint.getFontMetrics(NULL); SkScalar y = dy; paint.setLinearText(true); for (int i = 0; i < gFaceStylesCount; i++) { paint.setTypeface(fFaces[i]); canvas->drawText(text, textLen, x, y, paint); y += dy; } } private: typedef skiagm::GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// DEF_GM( return new TypefaceGM; ) DEF_GM( return new TypefaceStylesGM; ) <|endoftext|>
<commit_before>// Hello World example // This example shows basic usage of DOM-style API. #include "rapidjson/document.h" // rapidjson's DOM-style API #include "rapidjson/prettywriter.h" // for stringify JSON #include "rapidjson/filestream.h" // wrapper of C stream for prettywriter as output #include <cstdio> using namespace rapidjson; int main(int, char*[]) { //////////////////////////////////////////////////////////////////////////// // 1. Parse a JSON text string to a document. const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; printf("Original JSON:\n %s\n", json); Document document; // Default template parameter uses UTF8 and MemoryPoolAllocator. #if 0 // "normal" parsing, decode strings to new buffers. Can use other input stream via ParseStream(). if (document.Parse(json).HasParseError()) return 1; #else // In-situ parsing, decode strings directly in the source string. Source must be string. { char buffer[sizeof(json)]; memcpy(buffer, json, sizeof(json)); if (document.ParseInsitu(buffer).HasParseError()) return 1; } #endif printf("\nParsing to document succeeded.\n"); //////////////////////////////////////////////////////////////////////////// // 2. Access values in document. printf("\nAccess values in document:\n"); assert(document.IsObject()); // Document is a JSON value represents the root of DOM. Root can be either an object or array. assert(document.HasMember("hello")); assert(document["hello"].IsString()); printf("hello = %s\n", document["hello"].GetString()); // Since version 0.2, you can use single lookup to check the existing of member and its value: Value::Member* hello = document.FindMember("hello"); assert(hello != 0); assert(hello->value.IsString()); assert(strcmp("world", hello->value.GetString()) == 0); (void)hello; assert(document["t"].IsBool()); // JSON true/false are bool. Can also uses more specific function IsTrue(). printf("t = %s\n", document["t"].GetBool() ? "true" : "false"); assert(document["f"].IsBool()); printf("f = %s\n", document["f"].GetBool() ? "true" : "false"); printf("n = %s\n", document["n"].IsNull() ? "null" : "?"); assert(document["i"].IsNumber()); // Number is a JSON type, but C++ needs more specific type. assert(document["i"].IsInt()); // In this case, IsUint()/IsInt64()/IsUInt64() also return true. printf("i = %d\n", document["i"].GetInt()); // Alternative (int)document["i"] assert(document["pi"].IsNumber()); assert(document["pi"].IsDouble()); printf("pi = %g\n", document["pi"].GetDouble()); { const Value& a = document["a"]; // Using a reference for consecutive access is handy and faster. assert(a.IsArray()); for (SizeType i = 0; i < a.Size(); i++) // rapidjson uses SizeType instead of size_t. printf("a[%d] = %d\n", i, a[i].GetInt()); // Note: //int x = a[0].GetInt(); // Error: operator[ is ambiguous, as 0 also mean a null pointer of const char* type. int y = a[SizeType(0)].GetInt(); // Cast to SizeType will work. int z = a[0u].GetInt(); // This works too. (void)y; (void)z; // Iterating array with iterators printf("a = "); for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) printf("%d ", itr->GetInt()); printf("\n"); } // Iterating object members static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" }; for (Value::ConstMemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr) printf("Type of member %s is %s\n", itr->name.GetString(), kTypeNames[itr->value.GetType()]); //////////////////////////////////////////////////////////////////////////// // 3. Modify values in document. // Change i to a bigger number { uint64_t f20 = 1; // compute factorial of 20 for (uint64_t j = 1; j <= 20; j++) f20 *= j; document["i"] = f20; // Alternate form: document["i"].SetUint64(f20) assert(!document["i"].IsInt()); // No longer can be cast as int or uint. } // Adding values to array. { Value& a = document["a"]; // This time we uses non-const reference. Document::AllocatorType& allocator = document.GetAllocator(); for (int i = 5; i <= 10; i++) a.PushBack(i, allocator); // May look a bit strange, allocator is needed for potentially realloc. We normally uses the document's. // Fluent API a.PushBack("Lua", allocator).PushBack("Mio", allocator); } // Making string values. // This version of SetString() just store the pointer to the string. // So it is for literal and string that exists within value's life-cycle. { document["hello"] = "rapidjson"; // This will invoke strlen() // Faster version: // document["hello"].SetString("rapidjson", 9); } // This version of SetString() needs an allocator, which means it will allocate a new buffer and copy the the string into the buffer. Value author; { char buffer[10]; int len = sprintf(buffer, "%s %s", "Milo", "Yip"); // synthetic example of dynamically created string. author.SetString(buffer, static_cast<size_t>(len), document.GetAllocator()); // Shorter but slower version: // document["hello"].SetString(buffer, document.GetAllocator()); // Constructor version: // Value author(buffer, len, document.GetAllocator()); // Value author(buffer, document.GetAllocator()); memset(buffer, 0, sizeof(buffer)); // For demonstration purpose. } // Variable 'buffer' is unusable now but 'author' has already made a copy. document.AddMember("author", author, document.GetAllocator()); assert(author.IsNull()); // Move semantic for assignment. After this variable is assigned as a member, the variable becomes null. //////////////////////////////////////////////////////////////////////////// // 4. Stringify JSON printf("\nModified JSON with reformatting:\n"); FileStream f(stdout); PrettyWriter<FileStream> writer(f); document.Accept(writer); // Accept() traverses the DOM and generates Handler events. return 0; } <commit_msg>tutorial.cpp: update for FindMember change<commit_after>// Hello World example // This example shows basic usage of DOM-style API. #include "rapidjson/document.h" // rapidjson's DOM-style API #include "rapidjson/prettywriter.h" // for stringify JSON #include "rapidjson/filestream.h" // wrapper of C stream for prettywriter as output #include <cstdio> using namespace rapidjson; int main(int, char*[]) { //////////////////////////////////////////////////////////////////////////// // 1. Parse a JSON text string to a document. const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } "; printf("Original JSON:\n %s\n", json); Document document; // Default template parameter uses UTF8 and MemoryPoolAllocator. #if 0 // "normal" parsing, decode strings to new buffers. Can use other input stream via ParseStream(). if (document.Parse(json).HasParseError()) return 1; #else // In-situ parsing, decode strings directly in the source string. Source must be string. { char buffer[sizeof(json)]; memcpy(buffer, json, sizeof(json)); if (document.ParseInsitu(buffer).HasParseError()) return 1; } #endif printf("\nParsing to document succeeded.\n"); //////////////////////////////////////////////////////////////////////////// // 2. Access values in document. printf("\nAccess values in document:\n"); assert(document.IsObject()); // Document is a JSON value represents the root of DOM. Root can be either an object or array. assert(document.HasMember("hello")); assert(document["hello"].IsString()); printf("hello = %s\n", document["hello"].GetString()); // Since version 0.2, you can use single lookup to check the existing of member and its value: Value::MemberIterator hello = document.FindMember("hello"); assert(hello != document.MemberEnd()); assert(hello->value.IsString()); assert(strcmp("world", hello->value.GetString()) == 0); (void)hello; assert(document["t"].IsBool()); // JSON true/false are bool. Can also uses more specific function IsTrue(). printf("t = %s\n", document["t"].GetBool() ? "true" : "false"); assert(document["f"].IsBool()); printf("f = %s\n", document["f"].GetBool() ? "true" : "false"); printf("n = %s\n", document["n"].IsNull() ? "null" : "?"); assert(document["i"].IsNumber()); // Number is a JSON type, but C++ needs more specific type. assert(document["i"].IsInt()); // In this case, IsUint()/IsInt64()/IsUInt64() also return true. printf("i = %d\n", document["i"].GetInt()); // Alternative (int)document["i"] assert(document["pi"].IsNumber()); assert(document["pi"].IsDouble()); printf("pi = %g\n", document["pi"].GetDouble()); { const Value& a = document["a"]; // Using a reference for consecutive access is handy and faster. assert(a.IsArray()); for (SizeType i = 0; i < a.Size(); i++) // rapidjson uses SizeType instead of size_t. printf("a[%d] = %d\n", i, a[i].GetInt()); // Note: //int x = a[0].GetInt(); // Error: operator[ is ambiguous, as 0 also mean a null pointer of const char* type. int y = a[SizeType(0)].GetInt(); // Cast to SizeType will work. int z = a[0u].GetInt(); // This works too. (void)y; (void)z; // Iterating array with iterators printf("a = "); for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr) printf("%d ", itr->GetInt()); printf("\n"); } // Iterating object members static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" }; for (Value::ConstMemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr) printf("Type of member %s is %s\n", itr->name.GetString(), kTypeNames[itr->value.GetType()]); //////////////////////////////////////////////////////////////////////////// // 3. Modify values in document. // Change i to a bigger number { uint64_t f20 = 1; // compute factorial of 20 for (uint64_t j = 1; j <= 20; j++) f20 *= j; document["i"] = f20; // Alternate form: document["i"].SetUint64(f20) assert(!document["i"].IsInt()); // No longer can be cast as int or uint. } // Adding values to array. { Value& a = document["a"]; // This time we uses non-const reference. Document::AllocatorType& allocator = document.GetAllocator(); for (int i = 5; i <= 10; i++) a.PushBack(i, allocator); // May look a bit strange, allocator is needed for potentially realloc. We normally uses the document's. // Fluent API a.PushBack("Lua", allocator).PushBack("Mio", allocator); } // Making string values. // This version of SetString() just store the pointer to the string. // So it is for literal and string that exists within value's life-cycle. { document["hello"] = "rapidjson"; // This will invoke strlen() // Faster version: // document["hello"].SetString("rapidjson", 9); } // This version of SetString() needs an allocator, which means it will allocate a new buffer and copy the the string into the buffer. Value author; { char buffer[10]; int len = sprintf(buffer, "%s %s", "Milo", "Yip"); // synthetic example of dynamically created string. author.SetString(buffer, static_cast<size_t>(len), document.GetAllocator()); // Shorter but slower version: // document["hello"].SetString(buffer, document.GetAllocator()); // Constructor version: // Value author(buffer, len, document.GetAllocator()); // Value author(buffer, document.GetAllocator()); memset(buffer, 0, sizeof(buffer)); // For demonstration purpose. } // Variable 'buffer' is unusable now but 'author' has already made a copy. document.AddMember("author", author, document.GetAllocator()); assert(author.IsNull()); // Move semantic for assignment. After this variable is assigned as a member, the variable becomes null. //////////////////////////////////////////////////////////////////////////// // 4. Stringify JSON printf("\nModified JSON with reformatting:\n"); FileStream f(stdout); PrettyWriter<FileStream> writer(f); document.Accept(writer); // Accept() traverses the DOM and generates Handler events. return 0; } <|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // 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 // // https://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 "iree/compiler/Dialect/Shape/Plugins/XLA/XlaHloShapeBuilder.h" #include "iree/compiler/Dialect/Shape/IR/Builders.h" #include "iree/compiler/Dialect/Shape/IR/ShapeInterface.h" #include "iree/compiler/Dialect/Shape/IR/ShapeOps.h" #include "llvm/ADT/Optional.h" #include "mlir/IR/Value.h" #include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h" using llvm::None; using llvm::Optional; using llvm::SmallVector; using namespace mlir::iree_compiler::Shape; namespace mlir { namespace xla_hlo { template <typename HloOp> Value rewriteXlaBinaryElementwiseOpShape(RankedShapeType resultShape, HloOp op, OpBuilder &builder) { if (!op) return nullptr; if (op.broadcast_dimensions()) { // Has implicit broadcast - ignore for now. return nullptr; } // No implicit broadcast. Tread as same element type. SmallVector<Value, 4> inputOperands(op.getOperands()); return buildCastInputsToResultShape(op.getLoc(), resultShape, inputOperands, builder); } Value rewriteXlaDotOpShape(RankedShapeType resultRs, DotOp dotOp, OpBuilder &builder) { auto lhsType = dotOp.lhs().getType().dyn_cast<RankedTensorType>(); auto rhsType = dotOp.rhs().getType().dyn_cast<RankedTensorType>(); auto resultType = dotOp.getResult().getType().dyn_cast<RankedTensorType>(); if (!lhsType || !rhsType || !resultType) return nullptr; // Shape transfer function: // [n] dot [n] -> scalar // [m x k] dot [k] -> [m] // [m x k] dot [k x n] -> [m x n] auto lhsRank = lhsType.getRank(); auto rhsRank = rhsType.getRank(); auto resultRank = resultType.getRank(); auto dimType = resultRs.getDimType(); auto loc = dotOp.getLoc(); if (lhsRank == 1 && rhsRank == 1 && resultRank == 0) { auto scalarShape = RankedShapeType::getChecked({}, dimType, loc); return builder.create<ConstRankedShapeOp>(dotOp.getLoc(), scalarShape); } else if (lhsRank == 2 && rhsRank == 1 && resultRank == 1) { SmallVector<Value, 1> dynamicDims; if (resultRs.isDimDynamic(0)) { auto lhsGetShape = builder.create<GetRankedShapeOp>( loc, RankedShapeType::get(lhsType.getShape(), dimType), dotOp.lhs()); auto getMDim = builder.create<RankedDimOp>(loc, dimType, lhsGetShape, builder.getI64IntegerAttr(0)); dynamicDims.push_back(getMDim); } return builder.create<MakeRankedShapeOp>(loc, resultRs, dynamicDims); } else if (lhsRank == 2 && rhsRank == 2 && resultRank == 2) { SmallVector<Value, 2> dynamicDims; if (resultRs.isDimDynamic(0)) { auto lhsGetShape = builder.create<GetRankedShapeOp>( loc, RankedShapeType::get(lhsType.getShape(), dimType), dotOp.lhs()); auto getMDim = builder.create<RankedDimOp>(loc, dimType, lhsGetShape, builder.getI64IntegerAttr(0)); dynamicDims.push_back(getMDim); } if (resultRs.isDimDynamic(1)) { auto rhsGetShape = builder.create<GetRankedShapeOp>( loc, RankedShapeType::get(rhsType.getShape(), dimType), dotOp.rhs()); auto getNDim = builder.create<RankedDimOp>(loc, dimType, rhsGetShape, builder.getI64IntegerAttr(1)); dynamicDims.push_back(getNDim); } return builder.create<MakeRankedShapeOp>(loc, resultRs, dynamicDims); } else { return nullptr; } } // NOTE: This op is an HLO interloper and is just here until a corresponding // HLO is created. As such, it is included in this file even though not HLO // currently. Value rewriteShapexRankedBroadcastInDim(RankedShapeType resultShape, RankedBroadcastInDimOp bidOp, OpBuilder &builder) { if (!bidOp) return nullptr; return bidOp.result_shape(); } // Creates a custom op shape builder for XLA-HLO ops that are not otherwise // supported through traits or other declarative means. void populateXlaHloCustomOpShapeBuilder(CustomOpShapeBuilderList &builders) { auto &b = builders.make<CallbackCustomOpShapeBuilder>(); // NOTE: Most of these *should not* be "custom ops". They should be coming // from declarative shape information, but that doesn't exist yet. #define INSERT_EW_OP(OpTy) \ b.insertOpRankedShapeBuilder<OpTy>(rewriteXlaBinaryElementwiseOpShape<OpTy>); INSERT_EW_OP(AddOp); INSERT_EW_OP(Atan2Op); INSERT_EW_OP(DivOp); INSERT_EW_OP(MaxOp); INSERT_EW_OP(MinOp); INSERT_EW_OP(MulOp); INSERT_EW_OP(PowOp); INSERT_EW_OP(RemOp); INSERT_EW_OP(ShiftLeftOp); INSERT_EW_OP(ShiftRightArithmeticOp); INSERT_EW_OP(ShiftRightLogicalOp); INSERT_EW_OP(SubOp); b.insertOpRankedShapeBuilder<DotOp>(rewriteXlaDotOpShape); b.insertOpRankedShapeBuilder<RankedBroadcastInDimOp>( rewriteShapexRankedBroadcastInDim); } } // namespace xla_hlo } // namespace mlir <commit_msg>Hand-code a shape function for xla_hlo.reduce.<commit_after>// Copyright 2020 Google LLC // // 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 // // https://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 "iree/compiler/Dialect/Shape/Plugins/XLA/XlaHloShapeBuilder.h" #include "iree/compiler/Dialect/Shape/IR/Builders.h" #include "iree/compiler/Dialect/Shape/IR/ShapeInterface.h" #include "iree/compiler/Dialect/Shape/IR/ShapeOps.h" #include "llvm/ADT/Optional.h" #include "mlir/IR/Value.h" #include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h" using llvm::None; using llvm::Optional; using llvm::SmallVector; using namespace mlir::iree_compiler::Shape; namespace mlir { namespace xla_hlo { namespace { template <typename HloOp> Value rewriteXlaBinaryElementwiseOpShape(RankedShapeType resultShape, HloOp op, OpBuilder &builder) { if (!op) return nullptr; if (op.broadcast_dimensions()) { // Has implicit broadcast - ignore for now. return nullptr; } // No implicit broadcast. Tread as same element type. SmallVector<Value, 4> inputOperands(op.getOperands()); return buildCastInputsToResultShape(op.getLoc(), resultShape, inputOperands, builder); } Value rewriteXlaDotOpShape(RankedShapeType resultRs, DotOp dotOp, OpBuilder &builder) { auto lhsType = dotOp.lhs().getType().dyn_cast<RankedTensorType>(); auto rhsType = dotOp.rhs().getType().dyn_cast<RankedTensorType>(); auto resultType = dotOp.getResult().getType().dyn_cast<RankedTensorType>(); if (!lhsType || !rhsType || !resultType) return nullptr; // Shape transfer function: // [n] dot [n] -> scalar // [m x k] dot [k] -> [m] // [m x k] dot [k x n] -> [m x n] auto lhsRank = lhsType.getRank(); auto rhsRank = rhsType.getRank(); auto resultRank = resultType.getRank(); auto dimType = resultRs.getDimType(); auto loc = dotOp.getLoc(); if (lhsRank == 1 && rhsRank == 1 && resultRank == 0) { auto scalarShape = RankedShapeType::getChecked({}, dimType, loc); return builder.create<ConstRankedShapeOp>(dotOp.getLoc(), scalarShape); } else if (lhsRank == 2 && rhsRank == 1 && resultRank == 1) { SmallVector<Value, 1> dynamicDims; if (resultRs.isDimDynamic(0)) { auto lhsGetShape = builder.create<GetRankedShapeOp>( loc, RankedShapeType::get(lhsType.getShape(), dimType), dotOp.lhs()); auto getMDim = builder.create<RankedDimOp>(loc, dimType, lhsGetShape, builder.getI64IntegerAttr(0)); dynamicDims.push_back(getMDim); } return builder.create<MakeRankedShapeOp>(loc, resultRs, dynamicDims); } else if (lhsRank == 2 && rhsRank == 2 && resultRank == 2) { SmallVector<Value, 2> dynamicDims; if (resultRs.isDimDynamic(0)) { auto lhsGetShape = builder.create<GetRankedShapeOp>( loc, RankedShapeType::get(lhsType.getShape(), dimType), dotOp.lhs()); auto getMDim = builder.create<RankedDimOp>(loc, dimType, lhsGetShape, builder.getI64IntegerAttr(0)); dynamicDims.push_back(getMDim); } if (resultRs.isDimDynamic(1)) { auto rhsGetShape = builder.create<GetRankedShapeOp>( loc, RankedShapeType::get(rhsType.getShape(), dimType), dotOp.rhs()); auto getNDim = builder.create<RankedDimOp>(loc, dimType, rhsGetShape, builder.getI64IntegerAttr(1)); dynamicDims.push_back(getNDim); } return builder.create<MakeRankedShapeOp>(loc, resultRs, dynamicDims); } else { return nullptr; } } Value rewriteReduce(RankedShapeType resultShape, ReduceOp reduceOp, OpBuilder &builder) { Location loc = reduceOp.getLoc(); // Get a common operand shape. Value operandShape; SmallVector<Value, 4> operandShapes; RankedShapeType operandRs; for (auto operand : reduceOp.operands()) { auto shape = builder.create<GetRankedShapeOp>(loc, operand); operandRs = shape.getRankedShape(); operandShapes.push_back(shape); } assert(!operandShapes.empty()); if (operandShapes.size() == 1) { // Single operand. operandShape = operandShapes.front(); } else { // Multiple operands must be compatible. operandShape = builder.create<CastCompatibleShapeOp>(loc, operandRs, operandShapes); } // Map reduction dims onto operand dimensions. SmallVector<bool, 4> isDimReduced; isDimReduced.resize(operandRs.getRank()); for (auto apIntValue : reduceOp.dimensions().getIntValues()) { auto intValue = apIntValue.getZExtValue(); assert(intValue < isDimReduced.size()); isDimReduced[intValue] = true; } // Map operand -> result dynamic dims. assert(resultShape.getRank() == (operandRs.getRank() - reduceOp.dimensions().getNumElements())); SmallVector<Value, 4> resultDims; for (unsigned operandDimIndex = 0, e = isDimReduced.size(); operandDimIndex < e; ++operandDimIndex) { unsigned resultDimIndex = resultDims.size(); // Skip reduced operand indices and non-dynamic result indices. if (isDimReduced[operandDimIndex] || !resultShape.isDimDynamic(resultDimIndex)) continue; resultDims.push_back( builder.create<RankedDimOp>(loc, operandShape, operandDimIndex)); } return builder.create<MakeRankedShapeOp>(loc, resultShape, resultDims); } // NOTE: This op is an HLO interloper and is just here until a corresponding // HLO is created. As such, it is included in this file even though not HLO // currently. Value rewriteShapexRankedBroadcastInDim(RankedShapeType resultShape, RankedBroadcastInDimOp bidOp, OpBuilder &builder) { if (!bidOp) return nullptr; return bidOp.result_shape(); } } // namespace // Creates a custom op shape builder for XLA-HLO ops that are not otherwise // supported through traits or other declarative means. void populateXlaHloCustomOpShapeBuilder(CustomOpShapeBuilderList &builders) { auto &b = builders.make<CallbackCustomOpShapeBuilder>(); // NOTE: Most of these *should not* be "custom ops". They should be coming // from declarative shape information, but that doesn't exist yet. #define INSERT_EW_OP(OpTy) \ b.insertOpRankedShapeBuilder<OpTy>(rewriteXlaBinaryElementwiseOpShape<OpTy>); INSERT_EW_OP(AddOp); INSERT_EW_OP(Atan2Op); INSERT_EW_OP(DivOp); INSERT_EW_OP(MaxOp); INSERT_EW_OP(MinOp); INSERT_EW_OP(MulOp); INSERT_EW_OP(PowOp); INSERT_EW_OP(RemOp); INSERT_EW_OP(ShiftLeftOp); INSERT_EW_OP(ShiftRightArithmeticOp); INSERT_EW_OP(ShiftRightLogicalOp); INSERT_EW_OP(SubOp); b.insertOpRankedShapeBuilder<DotOp>(rewriteXlaDotOpShape); b.insertOpRankedShapeBuilder<RankedBroadcastInDimOp>( rewriteShapexRankedBroadcastInDim); b.insertOpRankedShapeBuilder<ReduceOp>(rewriteReduce); } } // namespace xla_hlo } // namespace mlir <|endoftext|>
<commit_before># Based on https://github.com/NaaS/system/blob/master/naasferatu/front-end/hadoop*.naas type hadoop_wc : record # FIXME not sure what a "vlen" is in that example -- i can understand that # it's a variable length integer, so shall we just call it an integer? key_len : integer { signed = false, endianness = big, # "size" in bytes size = 2 } key : string { size = "hadoop_wc.key_len" } value : integer { signed = false, endianness = big, size = 4 } # Remainder is based on https://github.com/NaaS/system/blob/master/crisp/flick/examples.fk # FIXME iron the semicolon out -- shouldnt be needed when have no parameters fun AllReady : ([type hadoop_wc/-] chans;) -> (boolean) for i in unordered chans initially acc = True: acc and not (peek(chans[i]) = None) fun prepend_x_if_must : (acc : [<integer * type hadoop_wc>], b : boolean, x : <integer * type hadoop_wc>) -> ([<integer * type hadoop_wc>]) if b: acc else: x :: acc type indexed_wc : [<integer * type hadoop_wc>] fun sort_on_word : (l : type indexed_wc) -> (type indexed_wc) # NOTE below rely on ">" to be extended in the obvious way to life the # ">" over words (strings) to work on values of type idx*wc. # FIXME make the above lifting explicit to get a full example. for x in l initially acc = []: if acc = []: [x] else: let sub_sorted = for y in acc initially sub_acc = <[], False, x>: # NOTE this is how i avoid using pattern matching let ys = sub_acc.ys let b = sub_acc.b let x = sub_acc.x if not b: if x > y: <y :: x :: ys, True, x> else: <y :: ys, b, x> else: <y :: ys, b, x> prepend_x_if_must (sub_sorted, x) proc WordCount : ([type hadoop_wc/-] input, -/type hadoop_wc output) if AllReady(input): input.peek().sort_on_word().combine().consume(input) => output else: <> # Sum together the occurrences of the smallest word fun combine : (l : type indexed_wc) -> (<[integer] * type hadoop_wc>) let initial_value = let smallest_value = head (sorted) <[smallest_value.1], smallest_value.2> for p in tail (sorted) initially acc = initial_value: let idx = p.1 let wc' = p.2 if wc'.word = wc.word : let wc'' = wc with count = wc.count + wc'.count <idx :: idxs, wc''> else: <idxs, wc> # We project out the word-count element in the tuple, and return it. # As a side-effect, we consume a value from each input channel which # contributed to the result we produce. fun consume : ([type hadoop_wc/-] input; ans : <[integer] * type hadoop_wc>) -> (type hadoop_wc) let idxs = l.1 let wc = l.2 for i in idxs: read(input[i]) wc <commit_msg>refactored, since it's quite a big example;<commit_after>## Main type definition # Based on https://github.com/NaaS/system/blob/master/naasferatu/front-end/hadoop*.naas type hadoop_wc : record # FIXME not sure what a "vlen" is in that example -- i can understand that # it's a variable length integer, so shall we just call it an integer? key_len : integer { signed = false, endianness = big, # "size" in bytes size = 2 } key : string { size = "hadoop_wc.key_len" } value : integer { signed = false, endianness = big, size = 4 } ## Main process # Remainder is based on https://github.com/NaaS/system/blob/master/crisp/flick/examples.fk # This is the process; the auxiliary functions are defined below. proc WordCount : ([type hadoop_wc/-] input, -/type hadoop_wc output) if AllReady(input): input.peek().sort_on_word().combine().consume(input) => output else: <> ## Support functions # Sum together the occurrences of the smallest word fun combine : (l : type indexed_wc) -> (<[integer] * type hadoop_wc>) let initial_value = let smallest_value = head (sorted) <[smallest_value.1], smallest_value.2> for p in tail (sorted) initially acc = initial_value: let idx = p.1 let wc' = p.2 if wc'.word = wc.word : let wc'' = wc with count = wc.count + wc'.count <idx :: idxs, wc''> else: <idxs, wc> # We project out the word-count element in the tuple, and return it. # As a side-effect, we consume a value from each input channel which # contributed to the result we produce. fun consume : ([type hadoop_wc/-] input; ans : <[integer] * type hadoop_wc>) -> (type hadoop_wc) let idxs = l.1 let wc = l.2 for i in idxs: read(input[i]) wc # Returns true if all channels are able to provide an input. # FIXME iron the semicolon out -- shouldnt be needed when have no parameters fun AllReady : ([type hadoop_wc/-] chans;) -> (boolean) for i in unordered chans initially acc = True: acc and not (peek(chans[i]) = None) ## Sorting-related definitions. fun prepend_x_if_must : (acc : [<integer * type hadoop_wc>], b : boolean, x : <integer * type hadoop_wc>) -> ([<integer * type hadoop_wc>]) if b: acc else: x :: acc type indexed_wc : [<integer * type hadoop_wc>] fun sort_on_word : (l : type indexed_wc) -> (type indexed_wc) # NOTE below rely on ">" to be extended in the obvious way to life the # ">" over words (strings) to work on values of type idx*wc. # FIXME make the above lifting explicit to get a full example. for x in l initially acc = []: if acc = []: [x] else: let sub_sorted = for y in acc initially sub_acc = <[], False, x>: # NOTE this is how i avoid using pattern matching let ys = sub_acc.ys let b = sub_acc.b let x = sub_acc.x if not b: if x > y: <y :: x :: ys, True, x> else: <y :: ys, b, x> else: <y :: ys, b, x> prepend_x_if_must (sub_sorted, x) <|endoftext|>
<commit_before>/* * heap.hpp * * Created on: 2012-11-21 * Author: kevin */ #ifndef HEAP_HPP__ #define HEAP_HPP__ #include "vector.hpp" namespace zl { template<class T> class Heap { public: Heap() { } ~Heap() { } Heap(const CSimpleVector<T>& array) { m_array = array; } protected: void Swap(T& x, T& y) { T tmp = x; x = y; y = tmp; } void AdjustHeap(int i, int nLenth) { int nChild = i*2 + 1; while(nChild < nLenth) { //nChildָСĽڵ if(nChild < nLenth - 1 && m_array[nChild+1] < m_array[nChild]) nChild++; if(m_array[nChild] < m_array[i]) { Swap(m_array[nChild], m_array[i]); i = nChild; nChild = i*2 + 1; } else break; } } public: int Size() const { return m_array.GetSize(); } void push(T value) { m_array.Add(value); int n = m_array.GetSize(); if(n > 2) { AdjustHeap(n/2 - 1, n); } //print_heap(); } bool pop(T& ret) { int n = m_array.GetSize(); if (n == 1) { ret = m_array[0]; m_array.RemoveAll(); return true; } else if(n > 1) { ret = m_array[0]; Swap(m_array[0], m_array[n-1]); m_array.RemoveAt(n-1); if(n > 2) AdjustHeap(0, n-1); return true; } return false; } // void print_heap() // { // for(int i = 0; i < m_array.GetSize(); i++) // { // printf("%d ", m_array[i]); // } // printf("\n"); // } private: CSimpleVector<T> m_array; }; } #endif // HEAP_HPP__<commit_msg>small err<commit_after>/* * heap.hpp * * Created on: 2012-11-21 * Author: kevin */ #ifndef HEAP_HPP__ #define HEAP_HPP__ #include "vector.hpp" namespace zl { template<class T> class Heap { public: Heap() { } ~Heap() { } Heap(const CSimpleVector<T>& array) { m_array = array; } protected: void Swap(T& x, T& y) { T tmp = x; x = y; y = tmp; } void AdjustHeap(int i, int nLenth) { int nChild = i*2 + 1; while(nChild < nLenth) { //nChildָСĽڵ if(nChild < nLenth - 1 && m_array[nChild+1] < m_array[nChild]) nChild++; if(m_array[nChild] < m_array[i]) { Swap(m_array[nChild], m_array[i]); i = nChild; nChild = i*2 + 1; } else break; } } public: int Size() const { return m_array.GetSize(); } void push(T value) { m_array.Add(value); int n = m_array.GetSize(); if(n > 2) { AdjustHeap(n/2 - 1, n); } //print_heap(); } bool pop(T& ret) { int n = m_array.GetSize(); if (n == 1) { ret = m_array[0]; m_array.RemoveData(); return true; } else if(n > 1) { ret = m_array[0]; Swap(m_array[0], m_array[n-1]); m_array.RemoveAt(n-1); if(n > 2) AdjustHeap(0, n-1); return true; } return false; } // void print_heap() // { // for(int i = 0; i < m_array.GetSize(); i++) // { // printf("%d ", m_array[i]); // } // printf("\n"); // } private: CSimpleVector<T> m_array; }; } #endif // HEAP_HPP__<|endoftext|>