text stringlengths 54 60.6k |
|---|
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich 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 "CppExporter.h"
#include "../visitors/header_visitors/DeclarationVisitorHeader.h"
#include "../visitors/source_visitors/DeclarationVisitorSource.h"
#include "OOModel/src/declarations/Project.h"
#include "Export/src/writer/Exporter.h"
#include "Export/src/writer/FragmentLayouter.h"
#include "ModelBase/src/model/TreeManager.h"
#include "../CodeUnit.h"
#include "../CodeComposite.h"
#include "../Config.h"
namespace CppExport {
QList<ExportError> CppExporter::exportTree(Model::TreeManager* treeManager,
const QString& pathToProjectContainerDirectory)
{
QList<CodeUnit*> codeUnits;
units(treeManager->root(), "", codeUnits);
QList<CodeUnitPart*> allHeaderParts;
for (auto unit : codeUnits)
{
unit->calculateSourceFragments();
allHeaderParts.append(unit->headerPart());
}
for (auto unit : codeUnits) unit->calculateDependencies(allHeaderParts);
auto directory = new Export::SourceDir(nullptr, pathToProjectContainerDirectory + "/src");
for (auto codeComposite : mergeUnits(codeUnits))
{
codeComposite->sortUnits();
createFileFromFragment(directory, codeComposite->name() + ".h", codeComposite->headerFragment());
createFileFromFragment(directory, codeComposite->name() + ".cpp", codeComposite->sourceFragment());
}
auto layout = layouter();
Export::Exporter::exportToFileSystem("", directory, &layout);
return {};
}
void CppExporter::createFileFromFragment(Export::SourceDir* directory, const QString& fileName,
Export::SourceFragment* sourceFragment)
{
auto file = &directory->file(fileName);
file->append(sourceFragment);
}
void CppExporter::units(Model::Node* current, QString namespaceName, QList<CodeUnit*>& result)
{
if (auto ooModule = DCast<OOModel::Module>(current))
{
if (ooModule->classes()->size() > 0)
namespaceName = ooModule->name();
else
{
// macro file
// TODO: handle non class units
//result.append(new CodeUnit((namespaceName.isEmpty() ? "" : namespaceName + "/") + ooModule->name(), current));
return;
}
}
else if (auto ooClass = DCast<OOModel::Class>(current))
{
result.append(new CodeUnit((namespaceName.isEmpty() ? "" : namespaceName + "/") + ooClass->name(), current));
return;
}
for (auto child : current->children())
units(child, namespaceName, result);
}
QList<CodeComposite*> CppExporter::mergeUnits(QList<CodeUnit*>& units)
{
QHash<QString, QString> mergeMap = Config::instance().dependencyUnitMergeMap();
QHash<QString, CodeComposite*> nameToCompositeMap;
for (auto unit : units)
{
auto it = mergeMap.find(unit->name());
auto compositeName = it != mergeMap.end() ? *it : unit->name();
auto cIt = nameToCompositeMap.find(compositeName);
if (cIt != nameToCompositeMap.end())
// case A: the composite that unit is a part of already exists => merge
(*cIt)->addUnit(unit);
else
{
// case B: the composite that unit is a part of does not yet exist
auto composite = new CodeComposite(compositeName);
composite->addUnit(unit);
nameToCompositeMap.insert(composite->name(), composite);
}
}
return nameToCompositeMap.values();
}
Export::FragmentLayouter CppExporter::layouter()
{
auto result = Export::FragmentLayouter{"\t"};
result.addRule("enumerators", Export::FragmentLayouter::SpaceAfterSeparator, "", ",", "");
result.addRule("vertical", Export::FragmentLayouter::NoIndentation, "", "\n", "");
result.addRule("sections", Export::FragmentLayouter::NoIndentation, "", "\n", "");
result.addRule("accessorSections", Export::FragmentLayouter::IndentChildFragments, "", "\n", "");
result.addRule("bodySections", Export::FragmentLayouter::NewLineBefore
| Export::FragmentLayouter::IndentChildFragments | Export::FragmentLayouter::NewLineAfterPrefix
| Export::FragmentLayouter::NewLineBeforePostfix, "{", "\n", "}");
result.addRule("space", Export::FragmentLayouter::SpaceAtEnd, "", " ", "");
result.addRule("comma", Export::FragmentLayouter::SpaceAfterSeparator, "", ",", "");
result.addRule("baseClasses", Export::FragmentLayouter::SpaceAfterSeparator, "public: ", ",", "");
result.addRule("initializerList", Export::FragmentLayouter::SpaceAfterSeparator, "{", ",", "}");
result.addRule("argsList", Export::FragmentLayouter::SpaceAfterSeparator, "(", ",", ")");
result.addRule("typeArgsList", Export::FragmentLayouter::SpaceAfterSeparator, "<", ",", ">");
result.addRule("body", Export::FragmentLayouter::NewLineBefore | Export::FragmentLayouter::IndentChildFragments
| Export::FragmentLayouter::NewLineAfterPrefix | Export::FragmentLayouter::NewLineBeforePostfix,
"{", "\n", "}");
return result;
}
Export::ExportMapContainer& CppExporter::exportMaps()
{
static Export::ExportMapContainer* container = new Export::ExportMapContainer();
return *container;
}
}
<commit_msg>fix base class export style<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich 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 "CppExporter.h"
#include "../visitors/header_visitors/DeclarationVisitorHeader.h"
#include "../visitors/source_visitors/DeclarationVisitorSource.h"
#include "OOModel/src/declarations/Project.h"
#include "Export/src/writer/Exporter.h"
#include "Export/src/writer/FragmentLayouter.h"
#include "ModelBase/src/model/TreeManager.h"
#include "../CodeUnit.h"
#include "../CodeComposite.h"
#include "../Config.h"
namespace CppExport {
QList<ExportError> CppExporter::exportTree(Model::TreeManager* treeManager,
const QString& pathToProjectContainerDirectory)
{
QList<CodeUnit*> codeUnits;
units(treeManager->root(), "", codeUnits);
QList<CodeUnitPart*> allHeaderParts;
for (auto unit : codeUnits)
{
unit->calculateSourceFragments();
allHeaderParts.append(unit->headerPart());
}
for (auto unit : codeUnits) unit->calculateDependencies(allHeaderParts);
auto directory = new Export::SourceDir(nullptr, pathToProjectContainerDirectory + "/src");
for (auto codeComposite : mergeUnits(codeUnits))
{
codeComposite->sortUnits();
createFileFromFragment(directory, codeComposite->name() + ".h", codeComposite->headerFragment());
createFileFromFragment(directory, codeComposite->name() + ".cpp", codeComposite->sourceFragment());
}
auto layout = layouter();
Export::Exporter::exportToFileSystem("", directory, &layout);
return {};
}
void CppExporter::createFileFromFragment(Export::SourceDir* directory, const QString& fileName,
Export::SourceFragment* sourceFragment)
{
auto file = &directory->file(fileName);
file->append(sourceFragment);
}
void CppExporter::units(Model::Node* current, QString namespaceName, QList<CodeUnit*>& result)
{
if (auto ooModule = DCast<OOModel::Module>(current))
{
if (ooModule->classes()->size() > 0)
namespaceName = ooModule->name();
else
{
// macro file
// TODO: handle non class units
//result.append(new CodeUnit((namespaceName.isEmpty() ? "" : namespaceName + "/") + ooModule->name(), current));
return;
}
}
else if (auto ooClass = DCast<OOModel::Class>(current))
{
result.append(new CodeUnit((namespaceName.isEmpty() ? "" : namespaceName + "/") + ooClass->name(), current));
return;
}
for (auto child : current->children())
units(child, namespaceName, result);
}
QList<CodeComposite*> CppExporter::mergeUnits(QList<CodeUnit*>& units)
{
QHash<QString, QString> mergeMap = Config::instance().dependencyUnitMergeMap();
QHash<QString, CodeComposite*> nameToCompositeMap;
for (auto unit : units)
{
auto it = mergeMap.find(unit->name());
auto compositeName = it != mergeMap.end() ? *it : unit->name();
auto cIt = nameToCompositeMap.find(compositeName);
if (cIt != nameToCompositeMap.end())
// case A: the composite that unit is a part of already exists => merge
(*cIt)->addUnit(unit);
else
{
// case B: the composite that unit is a part of does not yet exist
auto composite = new CodeComposite(compositeName);
composite->addUnit(unit);
nameToCompositeMap.insert(composite->name(), composite);
}
}
return nameToCompositeMap.values();
}
Export::FragmentLayouter CppExporter::layouter()
{
auto result = Export::FragmentLayouter{"\t"};
result.addRule("enumerators", Export::FragmentLayouter::SpaceAfterSeparator, "", ",", "");
result.addRule("vertical", Export::FragmentLayouter::NoIndentation, "", "\n", "");
result.addRule("sections", Export::FragmentLayouter::NoIndentation, "", "\n", "");
result.addRule("accessorSections", Export::FragmentLayouter::IndentChildFragments, "", "\n", "");
result.addRule("bodySections", Export::FragmentLayouter::NewLineBefore
| Export::FragmentLayouter::IndentChildFragments | Export::FragmentLayouter::NewLineAfterPrefix
| Export::FragmentLayouter::NewLineBeforePostfix, "{", "\n", "}");
result.addRule("space", Export::FragmentLayouter::SpaceAtEnd, "", " ", "");
result.addRule("comma", Export::FragmentLayouter::SpaceAfterSeparator, "", ",", "");
result.addRule("baseClasses", Export::FragmentLayouter::SpaceAfterSeparator, " : public ", ",", "");
result.addRule("initializerList", Export::FragmentLayouter::SpaceAfterSeparator, "{", ",", "}");
result.addRule("argsList", Export::FragmentLayouter::SpaceAfterSeparator, "(", ",", ")");
result.addRule("typeArgsList", Export::FragmentLayouter::SpaceAfterSeparator, "<", ",", ">");
result.addRule("body", Export::FragmentLayouter::NewLineBefore | Export::FragmentLayouter::IndentChildFragments
| Export::FragmentLayouter::NewLineAfterPrefix | Export::FragmentLayouter::NewLineBeforePostfix,
"{", "\n", "}");
return result;
}
Export::ExportMapContainer& CppExporter::exportMaps()
{
static Export::ExportMapContainer* container = new Export::ExportMapContainer();
return *container;
}
}
<|endoftext|> |
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "compressor.h"
#include <vespa/vespalib/util/memory.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <stdexcept>
#include <lz4.h>
#include <lz4hc.h>
using vespalib::alloc::Alloc;
using vespalib::ConstBufferRef;
using vespalib::DataBuffer;
using vespalib::make_string;
namespace document
{
size_t LZ4Compressor::adjustProcessLen(uint16_t, size_t len) const { return LZ4_compressBound(len); }
size_t LZ4Compressor::adjustUnProcessLen(uint16_t, size_t len) const { return len; }
bool
LZ4Compressor::process(const CompressionConfig& config, const void * inputV, size_t inputLen, void * outputV, size_t & outputLenV)
{
const char * input(static_cast<const char *>(inputV));
char * output(static_cast<char *>(outputV));
int sz(-1);
if (config.compressionLevel > 6) {
Alloc state = Alloc::alloc(LZ4_sizeofStateHC());
int maxOutputLen = LZ4_compressBound(inputLen);
sz = LZ4_compress_HC_extStateHC(state.get(), input, output, inputLen, maxOutputLen, config.compressionLevel);
} else {
Alloc state = Alloc::alloc(LZ4_sizeofState());
sz = LZ4_compress_withState(state.get(), input, output, inputLen);
}
if (sz != 0) {
outputLenV = sz;
}
assert(sz != 0);
return (sz != 0);
}
bool
LZ4Compressor::unprocess(const void * inputV, size_t inputLen, void * outputV, size_t & outputLenV)
{
const char * input(static_cast<const char *>(inputV));
char * output(static_cast<char *>(outputV));
int sz = LZ4_decompress_safe(input, output, inputLen, outputLenV);
if (sz > 0) {
outputLenV = sz;
}
assert(sz > 0);
return (sz > 0);
}
CompressionConfig::Type
compress(ICompressor & compressor, const CompressionConfig & compression, const ConstBufferRef & org, DataBuffer & dest)
{
CompressionConfig::Type type(CompressionConfig::NONE);
dest.ensureFree(compressor.adjustProcessLen(0, org.size()));
size_t compressedSize(dest.getFreeLen());
if (compressor.process(compression, org.c_str(), org.size(), dest.getFree(), compressedSize)) {
if (compressedSize < ((org.size() * compression.threshold)/100)) {
dest.moveFreeToData(compressedSize);
type = compression.type;
}
}
return type;
}
CompressionConfig::Type
docompress(const CompressionConfig & compression, const ConstBufferRef & org, DataBuffer & dest)
{
CompressionConfig::Type type(CompressionConfig::NONE);
switch (compression.type) {
case CompressionConfig::LZ4:
{
LZ4Compressor lz4;
type = compress(lz4, compression, org, dest);
}
break;
case CompressionConfig::NONE:
default:
break;
}
return type;
}
CompressionConfig::Type
compress(const CompressionConfig & compression, const ConstBufferRef & org, DataBuffer & dest, bool allowSwap)
{
CompressionConfig::Type type(CompressionConfig::NONE);
if (org.size() >= compression.minSize) {
type = docompress(compression, org, dest);
}
if (type == CompressionConfig::NONE) {
if (allowSwap) {
DataBuffer tmp(const_cast<char *>(org.c_str()), org.size());
tmp.moveFreeToData(org.size());
dest.swap(tmp);
} else {
dest.writeBytes(org.c_str(), org.size());
}
}
return type;
}
void
decompress(ICompressor & decompressor, size_t uncompressedLen, const ConstBufferRef & org, DataBuffer & dest, bool allowSwap)
{
dest.ensureFree(uncompressedLen);
size_t realUncompressedLen(dest.getFreeLen());
if ( ! decompressor.unprocess(org.c_str(), org.size(), dest.getFree(), realUncompressedLen) ) {
if ( uncompressedLen < realUncompressedLen) {
if (allowSwap) {
DataBuffer tmp(const_cast<char *>(org.c_str()), org.size());
tmp.moveFreeToData(org.size());
dest.swap(tmp);
} else {
dest.writeBytes(org.c_str(), org.size());
}
} else {
throw std::runtime_error(make_string("unprocess failed had %" PRIu64 ", wanted %" PRId64 ", got %" PRIu64,
org.size(), uncompressedLen, realUncompressedLen));
}
} else {
dest.moveFreeToData(realUncompressedLen);
}
}
void
decompress(const CompressionConfig::Type & type, size_t uncompressedLen, const ConstBufferRef & org, DataBuffer & dest, bool allowSwap)
{
switch (type) {
case CompressionConfig::LZ4:
{
LZ4Compressor lz4;
decompress(lz4, uncompressedLen, org, dest, allowSwap);
}
break;
case CompressionConfig::NONE:
case CompressionConfig::UNCOMPRESSABLE:
if (allowSwap) {
DataBuffer tmp(const_cast<char *>(org.c_str()), org.size());
tmp.moveFreeToData(org.size());
dest.swap(tmp);
} else {
dest.writeBytes(org.c_str(), org.size());
}
break;
default:
throw std::runtime_error(make_string("Unable to handle decompression of type '%d'", type));
break;
}
}
}
<commit_msg>Avoid using deprecated compression method. LZ4_compress_withState -> LZ4_compress_fast_extState.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "compressor.h"
#include <vespa/vespalib/util/memory.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <stdexcept>
#include <lz4.h>
#include <lz4hc.h>
using vespalib::alloc::Alloc;
using vespalib::ConstBufferRef;
using vespalib::DataBuffer;
using vespalib::make_string;
namespace document
{
size_t LZ4Compressor::adjustProcessLen(uint16_t, size_t len) const { return LZ4_compressBound(len); }
size_t LZ4Compressor::adjustUnProcessLen(uint16_t, size_t len) const { return len; }
bool
LZ4Compressor::process(const CompressionConfig& config, const void * inputV, size_t inputLen, void * outputV, size_t & outputLenV)
{
const char * input(static_cast<const char *>(inputV));
char * output(static_cast<char *>(outputV));
int sz(-1);
int maxOutputLen = LZ4_compressBound(inputLen);
if (config.compressionLevel > 6) {
Alloc state = Alloc::alloc(LZ4_sizeofStateHC());
sz = LZ4_compress_HC_extStateHC(state.get(), input, output, inputLen, maxOutputLen, config.compressionLevel);
} else {
Alloc state = Alloc::alloc(LZ4_sizeofState());
sz = LZ4_compress_fast_extState(state.get(), input, output, inputLen, maxOutputLen, 1);
}
if (sz != 0) {
outputLenV = sz;
}
assert(sz != 0);
return (sz != 0);
}
bool
LZ4Compressor::unprocess(const void * inputV, size_t inputLen, void * outputV, size_t & outputLenV)
{
const char * input(static_cast<const char *>(inputV));
char * output(static_cast<char *>(outputV));
int sz = LZ4_decompress_safe(input, output, inputLen, outputLenV);
if (sz > 0) {
outputLenV = sz;
}
assert(sz > 0);
return (sz > 0);
}
CompressionConfig::Type
compress(ICompressor & compressor, const CompressionConfig & compression, const ConstBufferRef & org, DataBuffer & dest)
{
CompressionConfig::Type type(CompressionConfig::NONE);
dest.ensureFree(compressor.adjustProcessLen(0, org.size()));
size_t compressedSize(dest.getFreeLen());
if (compressor.process(compression, org.c_str(), org.size(), dest.getFree(), compressedSize)) {
if (compressedSize < ((org.size() * compression.threshold)/100)) {
dest.moveFreeToData(compressedSize);
type = compression.type;
}
}
return type;
}
CompressionConfig::Type
docompress(const CompressionConfig & compression, const ConstBufferRef & org, DataBuffer & dest)
{
CompressionConfig::Type type(CompressionConfig::NONE);
switch (compression.type) {
case CompressionConfig::LZ4:
{
LZ4Compressor lz4;
type = compress(lz4, compression, org, dest);
}
break;
case CompressionConfig::NONE:
default:
break;
}
return type;
}
CompressionConfig::Type
compress(const CompressionConfig & compression, const ConstBufferRef & org, DataBuffer & dest, bool allowSwap)
{
CompressionConfig::Type type(CompressionConfig::NONE);
if (org.size() >= compression.minSize) {
type = docompress(compression, org, dest);
}
if (type == CompressionConfig::NONE) {
if (allowSwap) {
DataBuffer tmp(const_cast<char *>(org.c_str()), org.size());
tmp.moveFreeToData(org.size());
dest.swap(tmp);
} else {
dest.writeBytes(org.c_str(), org.size());
}
}
return type;
}
void
decompress(ICompressor & decompressor, size_t uncompressedLen, const ConstBufferRef & org, DataBuffer & dest, bool allowSwap)
{
dest.ensureFree(uncompressedLen);
size_t realUncompressedLen(dest.getFreeLen());
if ( ! decompressor.unprocess(org.c_str(), org.size(), dest.getFree(), realUncompressedLen) ) {
if ( uncompressedLen < realUncompressedLen) {
if (allowSwap) {
DataBuffer tmp(const_cast<char *>(org.c_str()), org.size());
tmp.moveFreeToData(org.size());
dest.swap(tmp);
} else {
dest.writeBytes(org.c_str(), org.size());
}
} else {
throw std::runtime_error(make_string("unprocess failed had %" PRIu64 ", wanted %" PRId64 ", got %" PRIu64,
org.size(), uncompressedLen, realUncompressedLen));
}
} else {
dest.moveFreeToData(realUncompressedLen);
}
}
void
decompress(const CompressionConfig::Type & type, size_t uncompressedLen, const ConstBufferRef & org, DataBuffer & dest, bool allowSwap)
{
switch (type) {
case CompressionConfig::LZ4:
{
LZ4Compressor lz4;
decompress(lz4, uncompressedLen, org, dest, allowSwap);
}
break;
case CompressionConfig::NONE:
case CompressionConfig::UNCOMPRESSABLE:
if (allowSwap) {
DataBuffer tmp(const_cast<char *>(org.c_str()), org.size());
tmp.moveFreeToData(org.size());
dest.swap(tmp);
} else {
dest.writeBytes(org.c_str(), org.size());
}
break;
default:
throw std::runtime_error(make_string("Unable to handle decompression of type '%d'", type));
break;
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, 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.
*
*/
#include <string>
#include <unordered_map>
#include <gtest/gtest.h>
#include <folly/experimental/TestUtil.h>
#include <folly/File.h>
#include <folly/FileUtil.h>
#include "mcrouter/flavor.h"
#include "mcrouter/lib/fbi/cpp/util.h"
using folly::test::TemporaryFile;
using facebook::memcache::mcrouter::readFlavor;
std::string eraseStr(std::string str, const std::string& substr) {
return str.erase(str.find(substr), substr.size());
}
TEST(Flavor, readStandaloneFlavor) {
// Write temporary flavor file to test.
TemporaryFile flavorFile("web-standalone");
std::string flavorContents =
"{"
"\"libmcrouter_options\": {"
"\"default_route\": \"abc\""
"},"
"\"standalone_options\": {"
"\"port\": \"11001\", "
"\"log_file\": \"mcrouter.log\""
"}"
"}";
std::string flavorPath(flavorFile.path().string());
EXPECT_EQ(folly::writeFull(flavorFile.fd(), flavorContents.data(),
flavorContents.size()), flavorContents.size());
// Reads the flavor file to test.
std::unordered_map<std::string, std::string> libmcrouter_opts;
std::unordered_map<std::string, std::string> standalone_opts;
std::string flavor = eraseStr(flavorPath, "-standalone");
EXPECT_TRUE(readFlavor(flavor, standalone_opts, libmcrouter_opts));
EXPECT_EQ(3, libmcrouter_opts.size());
EXPECT_EQ(1, libmcrouter_opts.count("default_route"));
EXPECT_EQ("abc", libmcrouter_opts["default_route"]);
EXPECT_EQ(1, libmcrouter_opts.count("router_name"));
EXPECT_EQ("web", libmcrouter_opts["router_name"]);
EXPECT_EQ(1, libmcrouter_opts.count("flavor_name"));
EXPECT_EQ("web", libmcrouter_opts["flavor_name"]);
EXPECT_EQ(2, standalone_opts.size());
EXPECT_EQ(1, standalone_opts.count("port"));
EXPECT_EQ("11001", standalone_opts["port"]);
EXPECT_EQ(1, standalone_opts.count("log_file"));
EXPECT_EQ("mcrouter.log", standalone_opts["log_file"]);
}
TEST(Flavor, readLibmcrouterFlavor) {
// Write temporary libmcrouter flavor file to test.
TemporaryFile flavorFile("web");
std::string flavorContents =
"{"
"\"options\": {"
"\"default_route\": \"abc\""
"}"
"}";
std::string flavorPath(flavorFile.path().string());
EXPECT_EQ(folly::writeFull(flavorFile.fd(),
flavorContents.data(), flavorContents.size()), flavorContents.size());
// Reads the flavor file to test.
std::unordered_map<std::string, std::string> libmcrouter_opts;
std::unordered_map<std::string, std::string> standalone_opts;
EXPECT_TRUE(readFlavor(flavorPath, standalone_opts, libmcrouter_opts));
EXPECT_EQ(0, standalone_opts.size());
EXPECT_EQ(3, libmcrouter_opts.size());
EXPECT_EQ(1, libmcrouter_opts.count("default_route"));
EXPECT_EQ("abc", libmcrouter_opts["default_route"]);
EXPECT_EQ(1, libmcrouter_opts.count("router_name"));
EXPECT_EQ("web", libmcrouter_opts["router_name"]);
EXPECT_EQ(1, libmcrouter_opts.count("flavor_name"));
EXPECT_EQ("web", libmcrouter_opts["flavor_name"]);
}
TEST(Flavor, readFlavorFromTwoFiles) {
// Write temporary standalone flavor file to test.
TemporaryFile flavorStandaloneFile("web-standalone");
std::string flavorStandaloneContents =
"{"
"\"standalone_options\": {"
"\"port\": \"11001\", "
"\"log_file\": \"mcrouter.log\""
"}"
"}";
std::string flavorStandalonePath(flavorStandaloneFile.path().string());
EXPECT_EQ(folly::writeFull(flavorStandaloneFile.fd(),
flavorStandaloneContents.data(), flavorStandaloneContents.size()),
flavorStandaloneContents.size());
// Write temporary libmcrouter flavor file to test.
std::string flavorPath(eraseStr(flavorStandalonePath, "-standalone"));
folly::File flavorFile(flavorPath.data(), O_RDWR | O_CREAT);
std::string flavorContents =
"{"
"\"options\": {"
"\"default_route\": \"abc\""
"}"
"}";
EXPECT_EQ(folly::writeFull(flavorFile.fd(),
flavorContents.data(), flavorContents.size()), flavorContents.size());
// Reads the flavor file to test. Expects that we read from both files.
std::unordered_map<std::string, std::string> libmcrouter_opts;
std::unordered_map<std::string, std::string> standalone_opts;
EXPECT_TRUE(readFlavor(flavorPath, standalone_opts, libmcrouter_opts));
EXPECT_EQ(3, libmcrouter_opts.size());
EXPECT_EQ(1, libmcrouter_opts.count("default_route"));
EXPECT_EQ("abc", libmcrouter_opts["default_route"]);
EXPECT_EQ(1, libmcrouter_opts.count("router_name"));
EXPECT_EQ("web", libmcrouter_opts["router_name"]);
EXPECT_EQ(1, libmcrouter_opts.count("flavor_name"));
EXPECT_EQ("web", libmcrouter_opts["flavor_name"]);
EXPECT_EQ(2, standalone_opts.size());
EXPECT_EQ(1, standalone_opts.count("port"));
EXPECT_EQ("11001", standalone_opts["port"]);
EXPECT_EQ(1, standalone_opts.count("log_file"));
EXPECT_EQ("mcrouter.log", standalone_opts["log_file"]);
}
TEST(Flavor, readFlavorFromTwoFilesShouldOverrideLibmcrouterOptions) {
// Write temporary standalone flavor file to test.
TemporaryFile flavorStandaloneFile("web-standalone");
std::string flavorStandaloneContents =
"{"
"\"libmcrouter_options\": {"
"\"default_route\": \"def\""
"},"
"\"standalone_options\": {"
"\"port\": \"11001\", "
"\"log_file\": \"mcrouter.log\""
"}"
"}";
std::string flavorStandalonePath(flavorStandaloneFile.path().string());
EXPECT_EQ(folly::writeFull(flavorStandaloneFile.fd(),
flavorStandaloneContents.data(), flavorStandaloneContents.size()),
flavorStandaloneContents.size());
// Write temporary libmcrouter flavor file to test.
std::string flavorPath(eraseStr(flavorStandalonePath, "-standalone"));
folly::File flavorFile(flavorPath.data(), O_RDWR | O_CREAT);
std::string flavorContents =
"{"
"\"options\": {"
"\"default_route\": \"abc\""
"}"
"}";
EXPECT_EQ(folly::writeFull(flavorFile.fd(),
flavorContents.data(), flavorContents.size()), flavorContents.size());
// Reads the flavor file to test. Expects that we read from both files.
std::unordered_map<std::string, std::string> libmcrouter_opts;
std::unordered_map<std::string, std::string> standalone_opts;
EXPECT_TRUE(readFlavor(flavorPath, standalone_opts, libmcrouter_opts));
EXPECT_EQ(3, libmcrouter_opts.size());
EXPECT_EQ(1, libmcrouter_opts.count("default_route"));
EXPECT_EQ("def", libmcrouter_opts["default_route"]);
EXPECT_EQ(1, libmcrouter_opts.count("router_name"));
EXPECT_EQ("web", libmcrouter_opts["router_name"]);
EXPECT_EQ(1, libmcrouter_opts.count("flavor_name"));
EXPECT_EQ("web", libmcrouter_opts["flavor_name"]);
EXPECT_EQ(2, standalone_opts.size());
EXPECT_EQ(1, standalone_opts.count("port"));
EXPECT_EQ("11001", standalone_opts["port"]);
EXPECT_EQ(1, standalone_opts.count("log_file"));
EXPECT_EQ("mcrouter.log", standalone_opts["log_file"]);
}
TEST(Flavor, readFlavorShouldReportMalformedStandaloneFlavor) {
// Write temporary standalone flavor file to test.
TemporaryFile flavorStandaloneFile("web-standalone");
std::string flavorStandaloneContents =
"{"
"\"standalone_options\": {"
"\"port\": \"11001\", "
"\"log_file\": \"mcrouter.log\""
"},"
"\"libmcrouter_options\": ["
"--i-have-no-idea-what-i'm-doing"
"]"
"}";
std::string flavorStandalonePath(flavorStandaloneFile.path().string());
EXPECT_EQ(folly::writeFull(flavorStandaloneFile.fd(),
flavorStandaloneContents.data(), flavorStandaloneContents.size()),
flavorStandaloneContents.size());
// Write temporary libmcrouter flavor file to test.
std::string flavorPath(eraseStr(flavorStandalonePath, "-standalone"));
folly::File flavorFile(flavorPath.data(), O_RDWR | O_CREAT);
std::string flavorContents =
"{"
"\"options\": {"
"\"default_route\": \"abc\""
"}"
"}";
EXPECT_EQ(folly::writeFull(flavorFile.fd(),
flavorContents.data(), flavorContents.size()), flavorContents.size());
// Reads the flavor file to test. Expects that we read from both files.
std::unordered_map<std::string, std::string> libmcrouter_opts;
std::unordered_map<std::string, std::string> standalone_opts;
EXPECT_FALSE(readFlavor(flavorPath, standalone_opts, libmcrouter_opts));
}
TEST(Flavor, readFlavorShouldReportMalformedLibmcrouterFlavor) {
// Write temporary standalone flavor file to test.
TemporaryFile flavorStandaloneFile("web-standalone");
std::string flavorStandaloneContents =
"{"
"\"standalone_options\": {"
"\"port\": \"11001\", "
"\"log_file\": \"mcrouter.log\""
"}"
"}";
std::string flavorStandalonePath(flavorStandaloneFile.path().string());
EXPECT_EQ(folly::writeFull(flavorStandaloneFile.fd(),
flavorStandaloneContents.data(), flavorStandaloneContents.size()),
flavorStandaloneContents.size());
// Write temporary libmcrouter flavor file to test.
std::string flavorPath(eraseStr(flavorStandalonePath, "-standalone"));
folly::File flavorFile(flavorPath.data(), O_RDWR | O_CREAT);
std::string flavorContents =
"{"
"\"libmcrouter_options\": {"
"\"default_route\": \"abc\""
"}"
"}";
EXPECT_EQ(folly::writeFull(flavorFile.fd(),
flavorContents.data(), flavorContents.size()), flavorContents.size());
// Reads the flavor file to test. Expects that we read from both files.
std::unordered_map<std::string, std::string> libmcrouter_opts;
std::unordered_map<std::string, std::string> standalone_opts;
EXPECT_FALSE(readFlavor(flavorPath, standalone_opts, libmcrouter_opts));
}
<commit_msg>Fix flavor unit tests<commit_after>/*
* Copyright (c) 2015, 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.
*
*/
#include <string>
#include <unordered_map>
#include <gtest/gtest.h>
#include <folly/experimental/TestUtil.h>
#include <folly/File.h>
#include <folly/FileUtil.h>
#include "mcrouter/flavor.h"
#include "mcrouter/lib/fbi/cpp/util.h"
using folly::test::TemporaryFile;
using facebook::memcache::mcrouter::readFlavor;
std::string eraseStr(std::string str, const std::string& substr) {
return str.erase(str.find(substr), substr.size());
}
TEST(Flavor, readStandaloneFlavor) {
// Write temporary flavor file to test.
TemporaryFile flavorFile("web-standalone");
std::string flavorContents =
"{"
"\"libmcrouter_options\": {"
"\"default_route\": \"abc\""
"},"
"\"standalone_options\": {"
"\"port\": \"11001\", "
"\"log_file\": \"mcrouter.log\""
"}"
"}";
std::string flavorPath(flavorFile.path().string());
EXPECT_EQ(folly::writeFull(flavorFile.fd(), flavorContents.data(),
flavorContents.size()), flavorContents.size());
// Reads the flavor file to test.
std::unordered_map<std::string, std::string> libmcrouter_opts;
std::unordered_map<std::string, std::string> standalone_opts;
std::string flavor = eraseStr(flavorPath, "-standalone");
EXPECT_TRUE(readFlavor(flavor, standalone_opts, libmcrouter_opts));
EXPECT_EQ(3, libmcrouter_opts.size());
EXPECT_EQ(1, libmcrouter_opts.count("default_route"));
EXPECT_EQ("abc", libmcrouter_opts["default_route"]);
EXPECT_EQ(1, libmcrouter_opts.count("router_name"));
EXPECT_EQ("web", libmcrouter_opts["router_name"]);
EXPECT_EQ(1, libmcrouter_opts.count("flavor_name"));
EXPECT_EQ(flavor, libmcrouter_opts["flavor_name"]);
EXPECT_EQ(2, standalone_opts.size());
EXPECT_EQ(1, standalone_opts.count("port"));
EXPECT_EQ("11001", standalone_opts["port"]);
EXPECT_EQ(1, standalone_opts.count("log_file"));
EXPECT_EQ("mcrouter.log", standalone_opts["log_file"]);
}
TEST(Flavor, readLibmcrouterFlavor) {
// Write temporary libmcrouter flavor file to test.
TemporaryFile flavorFile("web");
std::string flavorContents =
"{"
"\"options\": {"
"\"default_route\": \"abc\""
"}"
"}";
std::string flavorPath(flavorFile.path().string());
EXPECT_EQ(folly::writeFull(flavorFile.fd(),
flavorContents.data(), flavorContents.size()), flavorContents.size());
// Reads the flavor file to test.
std::unordered_map<std::string, std::string> libmcrouter_opts;
std::unordered_map<std::string, std::string> standalone_opts;
EXPECT_TRUE(readFlavor(flavorPath, standalone_opts, libmcrouter_opts));
EXPECT_EQ(0, standalone_opts.size());
EXPECT_EQ(3, libmcrouter_opts.size());
EXPECT_EQ(1, libmcrouter_opts.count("default_route"));
EXPECT_EQ("abc", libmcrouter_opts["default_route"]);
EXPECT_EQ(1, libmcrouter_opts.count("router_name"));
EXPECT_EQ("web", libmcrouter_opts["router_name"]);
EXPECT_EQ(1, libmcrouter_opts.count("flavor_name"));
EXPECT_EQ(flavorPath, libmcrouter_opts["flavor_name"]);
}
TEST(Flavor, readFlavorFromTwoFiles) {
// Write temporary standalone flavor file to test.
TemporaryFile flavorStandaloneFile("web-standalone");
std::string flavorStandaloneContents =
"{"
"\"standalone_options\": {"
"\"port\": \"11001\", "
"\"log_file\": \"mcrouter.log\""
"}"
"}";
std::string flavorStandalonePath(flavorStandaloneFile.path().string());
EXPECT_EQ(folly::writeFull(flavorStandaloneFile.fd(),
flavorStandaloneContents.data(), flavorStandaloneContents.size()),
flavorStandaloneContents.size());
// Write temporary libmcrouter flavor file to test.
std::string flavorPath(eraseStr(flavorStandalonePath, "-standalone"));
folly::File flavorFile(flavorPath.data(), O_RDWR | O_CREAT);
std::string flavorContents =
"{"
"\"options\": {"
"\"default_route\": \"abc\""
"}"
"}";
EXPECT_EQ(folly::writeFull(flavorFile.fd(),
flavorContents.data(), flavorContents.size()), flavorContents.size());
// Reads the flavor file to test. Expects that we read from both files.
std::unordered_map<std::string, std::string> libmcrouter_opts;
std::unordered_map<std::string, std::string> standalone_opts;
EXPECT_TRUE(readFlavor(flavorPath, standalone_opts, libmcrouter_opts));
EXPECT_EQ(3, libmcrouter_opts.size());
EXPECT_EQ(1, libmcrouter_opts.count("default_route"));
EXPECT_EQ("abc", libmcrouter_opts["default_route"]);
EXPECT_EQ(1, libmcrouter_opts.count("router_name"));
EXPECT_EQ("web", libmcrouter_opts["router_name"]);
EXPECT_EQ(1, libmcrouter_opts.count("flavor_name"));
EXPECT_EQ(flavorPath, libmcrouter_opts["flavor_name"]);
EXPECT_EQ(2, standalone_opts.size());
EXPECT_EQ(1, standalone_opts.count("port"));
EXPECT_EQ("11001", standalone_opts["port"]);
EXPECT_EQ(1, standalone_opts.count("log_file"));
EXPECT_EQ("mcrouter.log", standalone_opts["log_file"]);
}
TEST(Flavor, readFlavorFromTwoFilesShouldOverrideLibmcrouterOptions) {
// Write temporary standalone flavor file to test.
TemporaryFile flavorStandaloneFile("web-standalone");
std::string flavorStandaloneContents =
"{"
"\"libmcrouter_options\": {"
"\"default_route\": \"def\""
"},"
"\"standalone_options\": {"
"\"port\": \"11001\", "
"\"log_file\": \"mcrouter.log\""
"}"
"}";
std::string flavorStandalonePath(flavorStandaloneFile.path().string());
EXPECT_EQ(folly::writeFull(flavorStandaloneFile.fd(),
flavorStandaloneContents.data(), flavorStandaloneContents.size()),
flavorStandaloneContents.size());
// Write temporary libmcrouter flavor file to test.
std::string flavorPath(eraseStr(flavorStandalonePath, "-standalone"));
folly::File flavorFile(flavorPath.data(), O_RDWR | O_CREAT);
std::string flavorContents =
"{"
"\"options\": {"
"\"default_route\": \"abc\""
"}"
"}";
EXPECT_EQ(folly::writeFull(flavorFile.fd(),
flavorContents.data(), flavorContents.size()), flavorContents.size());
// Reads the flavor file to test. Expects that we read from both files.
std::unordered_map<std::string, std::string> libmcrouter_opts;
std::unordered_map<std::string, std::string> standalone_opts;
EXPECT_TRUE(readFlavor(flavorPath, standalone_opts, libmcrouter_opts));
EXPECT_EQ(3, libmcrouter_opts.size());
EXPECT_EQ(1, libmcrouter_opts.count("default_route"));
EXPECT_EQ("def", libmcrouter_opts["default_route"]);
EXPECT_EQ(1, libmcrouter_opts.count("router_name"));
EXPECT_EQ("web", libmcrouter_opts["router_name"]);
EXPECT_EQ(1, libmcrouter_opts.count("flavor_name"));
EXPECT_EQ(flavorPath, libmcrouter_opts["flavor_name"]);
EXPECT_EQ(2, standalone_opts.size());
EXPECT_EQ(1, standalone_opts.count("port"));
EXPECT_EQ("11001", standalone_opts["port"]);
EXPECT_EQ(1, standalone_opts.count("log_file"));
EXPECT_EQ("mcrouter.log", standalone_opts["log_file"]);
}
TEST(Flavor, readFlavorShouldReportMalformedStandaloneFlavor) {
// Write temporary standalone flavor file to test.
TemporaryFile flavorStandaloneFile("web-standalone");
std::string flavorStandaloneContents =
"{"
"\"standalone_options\": {"
"\"port\": \"11001\", "
"\"log_file\": \"mcrouter.log\""
"},"
"\"libmcrouter_options\": ["
"--i-have-no-idea-what-i'm-doing"
"]"
"}";
std::string flavorStandalonePath(flavorStandaloneFile.path().string());
EXPECT_EQ(folly::writeFull(flavorStandaloneFile.fd(),
flavorStandaloneContents.data(), flavorStandaloneContents.size()),
flavorStandaloneContents.size());
// Write temporary libmcrouter flavor file to test.
std::string flavorPath(eraseStr(flavorStandalonePath, "-standalone"));
folly::File flavorFile(flavorPath.data(), O_RDWR | O_CREAT);
std::string flavorContents =
"{"
"\"options\": {"
"\"default_route\": \"abc\""
"}"
"}";
EXPECT_EQ(folly::writeFull(flavorFile.fd(),
flavorContents.data(), flavorContents.size()), flavorContents.size());
// Reads the flavor file to test. Expects that we read from both files.
std::unordered_map<std::string, std::string> libmcrouter_opts;
std::unordered_map<std::string, std::string> standalone_opts;
EXPECT_FALSE(readFlavor(flavorPath, standalone_opts, libmcrouter_opts));
}
TEST(Flavor, readFlavorShouldReportMalformedLibmcrouterFlavor) {
// Write temporary standalone flavor file to test.
TemporaryFile flavorStandaloneFile("web-standalone");
std::string flavorStandaloneContents =
"{"
"\"standalone_options\": {"
"\"port\": \"11001\", "
"\"log_file\": \"mcrouter.log\""
"}"
"}";
std::string flavorStandalonePath(flavorStandaloneFile.path().string());
EXPECT_EQ(folly::writeFull(flavorStandaloneFile.fd(),
flavorStandaloneContents.data(), flavorStandaloneContents.size()),
flavorStandaloneContents.size());
// Write temporary libmcrouter flavor file to test.
std::string flavorPath(eraseStr(flavorStandalonePath, "-standalone"));
folly::File flavorFile(flavorPath.data(), O_RDWR | O_CREAT);
std::string flavorContents =
"{"
"\"libmcrouter_options\": {"
"\"default_route\": \"abc\""
"}"
"}";
EXPECT_EQ(folly::writeFull(flavorFile.fd(),
flavorContents.data(), flavorContents.size()), flavorContents.size());
// Reads the flavor file to test. Expects that we read from both files.
std::unordered_map<std::string, std::string> libmcrouter_opts;
std::unordered_map<std::string, std::string> standalone_opts;
EXPECT_FALSE(readFlavor(flavorPath, standalone_opts, libmcrouter_opts));
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: fuoltext.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: dl $ $Date: 2001-06-12 12:42:25 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _OUTLINER_HXX
#include <svx/outliner.hxx>
#endif
#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#define ITEMID_FIELD EE_FEATURE_FIELD
#ifndef _SVX_FLDITEM_HXX //autogen
#include <svx/flditem.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef _SFXDISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#include <svx/svxids.hrc>
#include "app.hrc"
#include "fuoltext.hxx"
#include "outlview.hxx"
#include "sdwindow.hxx"
#include "docshell.hxx"
#include "viewshel.hxx"
#include <stdio.h> // Fuer SlotFilter-Listing
static USHORT SidArray[] = {
SID_STYLE_FAMILY2,
SID_STYLE_FAMILY5,
SID_STYLE_UPDATE_BY_EXAMPLE,
SID_CUT,
SID_COPY,
SID_PASTE,
SID_SELECTALL,
SID_ATTR_CHAR_FONT,
SID_ATTR_CHAR_POSTURE,
SID_ATTR_CHAR_WEIGHT,
SID_ATTR_CHAR_UNDERLINE,
SID_ATTR_CHAR_FONTHEIGHT,
SID_ATTR_CHAR_COLOR,
SID_OUTLINE_UP,
SID_OUTLINE_DOWN,
SID_OUTLINE_LEFT,
SID_OUTLINE_RIGHT,
//SID_OUTLINE_FORMAT,
SID_OUTLINE_COLLAPSE_ALL,
//SID_OUTLINE_BULLET,
SID_OUTLINE_COLLAPSE,
SID_OUTLINE_EXPAND_ALL,
SID_OUTLINE_EXPAND,
SID_SET_SUPER_SCRIPT,
SID_SET_SUB_SCRIPT,
SID_HYPERLINK_GETLINK,
SID_PRESENTATION_TEMPLATES,
SID_STATUS_PAGE,
SID_STATUS_LAYOUT,
SID_EXPAND_PAGE,
SID_SUMMARY_PAGE,
SID_PARASPACE_INCREASE,
SID_PARASPACE_DECREASE,
0 };
TYPEINIT1( FuOutlineText, FuOutline );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuOutlineText::FuOutlineText(SdViewShell* pViewShell, SdWindow* pWindow,
SdView* pView, SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuOutline(pViewShell, pWindow, pView, pDoc, rReq)
{
// ERSTELLT SLOTFILTER-LISTING
// FILE* pFile = fopen("menu.dat", "w");
// fprintf(pFile, "SID_STYLE_FAMILY2, %6d\n", SID_STYLE_FAMILY2);
// fprintf(pFile, "SID_STYLE_FAMILY5, %6d\n", SID_STYLE_FAMILY5);
// fprintf(pFile, "SID_STYLE_UPDATE_BY_EXAMPLE, %6d\n", SID_STYLE_UPDATE_BY_EXAMPLE);
// fprintf(pFile, "SID_CUT, %6d\n", SID_CUT);
// fprintf(pFile, "SID_COPY, %6d\n", SID_COPY);
// fprintf(pFile, "SID_PASTE, %6d\n", SID_PASTE);
// fprintf(pFile, "SID_SELECTALL, %6d\n", SID_SELECTALL);
// fprintf(pFile, "SID_ATTR_CHAR_FONT, %6d\n", SID_ATTR_CHAR_FONT);
// fprintf(pFile, "SID_ATTR_CHAR_POSTURE, %6d\n", SID_ATTR_CHAR_POSTURE);
// fprintf(pFile, "SID_ATTR_CHAR_WEIGHT, %6d\n", SID_ATTR_CHAR_WEIGHT);
// fprintf(pFile, "SID_ATTR_CHAR_UNDERLINE, %6d\n", SID_ATTR_CHAR_UNDERLINE);
// fprintf(pFile, "SID_ATTR_CHAR_FONTHEIGHT, %6d\n", SID_ATTR_CHAR_FONTHEIGHT);
// fprintf(pFile, "SID_ATTR_CHAR_COLOR, %6d\n", SID_ATTR_CHAR_COLOR);
// fprintf(pFile, "SID_OUTLINE_UP, %6d\n", SID_OUTLINE_UP);
// fprintf(pFile, "SID_OUTLINE_DOWN, %6d\n", SID_OUTLINE_DOWN);
// fprintf(pFile, "SID_OUTLINE_LEFT, %6d\n", SID_OUTLINE_LEFT);
// fprintf(pFile, "SID_OUTLINE_RIGHT, %6d\n", SID_OUTLINE_RIGHT);
// fprintf(pFile, "SID_OUTLINE_COLLAPSE_ALL, %6d\n", SID_OUTLINE_COLLAPSE_ALL);
// fprintf(pFile, "SID_OUTLINE_COLLAPSE, %6d\n", SID_OUTLINE_COLLAPSE);
// fprintf(pFile, "SID_OUTLINE_EXPAND_ALL, %6d\n", SID_OUTLINE_EXPAND_ALL);
// fprintf(pFile, "SID_OUTLINE_EXPAND, %6d\n", SID_OUTLINE_EXPAND);
// fprintf(pFile, "SID_SET_SUPER_SCRIPT, %6d\n", SID_SET_SUPER_SCRIPT);
// fprintf(pFile, "SID_SET_SUB_SCRIPT, %6d\n", SID_SET_SUB_SCRIPT);
// fprintf(pFile, "SID_PRESENTATION_TEMPLATES, %6d\n", SID_PRESENTATION_TEMPLATES);
// fprintf(pFile, "SID_STATUS_PAGE, %6d\n", SID_STATUS_PAGE);
// fprintf(pFile, "SID_STATUS_LAYOUT, %6d\n", SID_STATUS_LAYOUT);
// fprintf(pFile, "SID_HYPERLINK_GETLINK, %6d\n", SID_HYPERLINK_GETLINK);
// fclose(pFile);
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuOutlineText::~FuOutlineText()
{
}
/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/
BOOL FuOutlineText::MouseButtonDown(const MouseEvent& rMEvt)
{
BOOL bReturn = FALSE;
pWindow->GrabFocus();
bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseButtonDown(rMEvt);
if (bReturn)
{
// Attributierung der akt. Textstelle kann jetzt anders sein
pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );
}
else
{
bReturn = FuOutline::MouseButtonDown(rMEvt);
}
return (bReturn);
}
/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/
BOOL FuOutlineText::MouseMove(const MouseEvent& rMEvt)
{
BOOL bReturn = FALSE;
bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseMove(rMEvt);
if (!bReturn)
{
bReturn = FuOutline::MouseMove(rMEvt);
}
const SvxFieldItem* pFieldItem = pOutlineView->GetViewByWindow( pWindow )->
GetFieldUnderMousePointer();
const SvxFieldData* pField = NULL;
if( pFieldItem )
pField = pFieldItem->GetField();
if( pField && pField->ISA( SvxURLField ) )
{
pWindow->SetPointer( Pointer( POINTER_REFHAND ) );
}
else
pWindow->SetPointer( Pointer( POINTER_TEXT ) );
return (bReturn);
}
/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/
BOOL FuOutlineText::MouseButtonUp(const MouseEvent& rMEvt)
{
BOOL bReturn = FALSE;
bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseButtonUp(rMEvt);
if (bReturn)
{
// Attributierung der akt. Textstelle kann jetzt anders sein
pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );
}
else
{
const SvxFieldItem* pFieldItem = pOutlineView->GetViewByWindow( pWindow )->GetFieldUnderMousePointer();
if( pFieldItem )
{
const SvxFieldData* pField = pFieldItem->GetField();
if( pField && pField->ISA( SvxURLField ) )
{
bReturn = TRUE;
pWindow->ReleaseMouse();
SfxStringItem aStrItem( SID_FILE_NAME, ( (SvxURLField*) pField)->GetURL() );
SfxStringItem aReferer( SID_REFERER, pDocSh->GetMedium()->GetName() );
SfxBoolItem aBrowseItem( SID_BROWSE, TRUE );
SfxViewFrame* pFrame = pViewShell->GetViewFrame();
if ( rMEvt.IsMod1() )
{
// Im neuen Frame oeffnen
pFrame->GetDispatcher()->Execute(SID_OPENDOC, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,
&aStrItem, &aBrowseItem, &aReferer, 0L);
}
else
{
// Im aktuellen Frame oeffnen
SfxFrameItem aFrameItem( SID_DOCFRAME, pFrame );
pFrame->GetDispatcher()->Execute(SID_OPENDOC, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,
&aStrItem, &aFrameItem, &aBrowseItem, &aReferer, 0L);
}
}
}
}
if( !bReturn )
bReturn = FuOutline::MouseButtonUp(rMEvt);
return (bReturn);
}
/*************************************************************************
|*
|* Tastaturereignisse bearbeiten
|*
|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls
|* FALSE.
|*
\************************************************************************/
BOOL FuOutlineText::KeyInput(const KeyEvent& rKEvt)
{
BOOL bReturn = FALSE;
if( !pDocSh->IsReadOnly() ||
rKEvt.GetKeyCode().GetGroup() == KEYGROUP_CURSOR )
{
pWindow->GrabFocus();
bReturn = pOutlineView->GetViewByWindow(pWindow)->PostKeyEvent(rKEvt);
if (bReturn)
{
// Attributierung der akt. Textstelle kann jetzt anders sein
pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );
}
else
{
bReturn = FuOutline::KeyInput(rKEvt);
}
}
return (bReturn);
}
/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/
void FuOutlineText::Activate()
{
FuOutline::Activate();
}
/*************************************************************************
|*
|* Function deaktivieren
|*
\************************************************************************/
void FuOutlineText::Deactivate()
{
FuOutline::Deactivate();
}
/*************************************************************************
|*
|* Cut object to clipboard
|*
\************************************************************************/
void FuOutlineText::DoCut()
{
pOutlineView->GetViewByWindow(pWindow)->Cut();
}
/*************************************************************************
|*
|* Copy object to clipboard
|*
\************************************************************************/
void FuOutlineText::DoCopy()
{
pOutlineView->GetViewByWindow(pWindow)->Copy();
}
/*************************************************************************
|*
|* Paste object from clipboard
|*
\************************************************************************/
void FuOutlineText::DoPaste()
{
pOutlineView->GetViewByWindow(pWindow)->PasteSpecial();
}
<commit_msg>#101117# Don't set mouse pointer, Outliner can do better...<commit_after>/*************************************************************************
*
* $RCSfile: fuoltext.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: mt $ $Date: 2002-07-24 14:04:41 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _OUTLINER_HXX
#include <svx/outliner.hxx>
#endif
#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#define ITEMID_FIELD EE_FEATURE_FIELD
#ifndef _SVX_FLDITEM_HXX //autogen
#include <svx/flditem.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef _SFXDISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#include <svx/svxids.hrc>
#include "app.hrc"
#include "fuoltext.hxx"
#include "outlview.hxx"
#include "sdwindow.hxx"
#include "docshell.hxx"
#include "viewshel.hxx"
#include <stdio.h> // Fuer SlotFilter-Listing
static USHORT SidArray[] = {
SID_STYLE_FAMILY2,
SID_STYLE_FAMILY5,
SID_STYLE_UPDATE_BY_EXAMPLE,
SID_CUT,
SID_COPY,
SID_PASTE,
SID_SELECTALL,
SID_ATTR_CHAR_FONT,
SID_ATTR_CHAR_POSTURE,
SID_ATTR_CHAR_WEIGHT,
SID_ATTR_CHAR_UNDERLINE,
SID_ATTR_CHAR_FONTHEIGHT,
SID_ATTR_CHAR_COLOR,
SID_OUTLINE_UP,
SID_OUTLINE_DOWN,
SID_OUTLINE_LEFT,
SID_OUTLINE_RIGHT,
//SID_OUTLINE_FORMAT,
SID_OUTLINE_COLLAPSE_ALL,
//SID_OUTLINE_BULLET,
SID_OUTLINE_COLLAPSE,
SID_OUTLINE_EXPAND_ALL,
SID_OUTLINE_EXPAND,
SID_SET_SUPER_SCRIPT,
SID_SET_SUB_SCRIPT,
SID_HYPERLINK_GETLINK,
SID_PRESENTATION_TEMPLATES,
SID_STATUS_PAGE,
SID_STATUS_LAYOUT,
SID_EXPAND_PAGE,
SID_SUMMARY_PAGE,
SID_PARASPACE_INCREASE,
SID_PARASPACE_DECREASE,
0 };
TYPEINIT1( FuOutlineText, FuOutline );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuOutlineText::FuOutlineText(SdViewShell* pViewShell, SdWindow* pWindow,
SdView* pView, SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuOutline(pViewShell, pWindow, pView, pDoc, rReq)
{
// ERSTELLT SLOTFILTER-LISTING
// FILE* pFile = fopen("menu.dat", "w");
// fprintf(pFile, "SID_STYLE_FAMILY2, %6d\n", SID_STYLE_FAMILY2);
// fprintf(pFile, "SID_STYLE_FAMILY5, %6d\n", SID_STYLE_FAMILY5);
// fprintf(pFile, "SID_STYLE_UPDATE_BY_EXAMPLE, %6d\n", SID_STYLE_UPDATE_BY_EXAMPLE);
// fprintf(pFile, "SID_CUT, %6d\n", SID_CUT);
// fprintf(pFile, "SID_COPY, %6d\n", SID_COPY);
// fprintf(pFile, "SID_PASTE, %6d\n", SID_PASTE);
// fprintf(pFile, "SID_SELECTALL, %6d\n", SID_SELECTALL);
// fprintf(pFile, "SID_ATTR_CHAR_FONT, %6d\n", SID_ATTR_CHAR_FONT);
// fprintf(pFile, "SID_ATTR_CHAR_POSTURE, %6d\n", SID_ATTR_CHAR_POSTURE);
// fprintf(pFile, "SID_ATTR_CHAR_WEIGHT, %6d\n", SID_ATTR_CHAR_WEIGHT);
// fprintf(pFile, "SID_ATTR_CHAR_UNDERLINE, %6d\n", SID_ATTR_CHAR_UNDERLINE);
// fprintf(pFile, "SID_ATTR_CHAR_FONTHEIGHT, %6d\n", SID_ATTR_CHAR_FONTHEIGHT);
// fprintf(pFile, "SID_ATTR_CHAR_COLOR, %6d\n", SID_ATTR_CHAR_COLOR);
// fprintf(pFile, "SID_OUTLINE_UP, %6d\n", SID_OUTLINE_UP);
// fprintf(pFile, "SID_OUTLINE_DOWN, %6d\n", SID_OUTLINE_DOWN);
// fprintf(pFile, "SID_OUTLINE_LEFT, %6d\n", SID_OUTLINE_LEFT);
// fprintf(pFile, "SID_OUTLINE_RIGHT, %6d\n", SID_OUTLINE_RIGHT);
// fprintf(pFile, "SID_OUTLINE_COLLAPSE_ALL, %6d\n", SID_OUTLINE_COLLAPSE_ALL);
// fprintf(pFile, "SID_OUTLINE_COLLAPSE, %6d\n", SID_OUTLINE_COLLAPSE);
// fprintf(pFile, "SID_OUTLINE_EXPAND_ALL, %6d\n", SID_OUTLINE_EXPAND_ALL);
// fprintf(pFile, "SID_OUTLINE_EXPAND, %6d\n", SID_OUTLINE_EXPAND);
// fprintf(pFile, "SID_SET_SUPER_SCRIPT, %6d\n", SID_SET_SUPER_SCRIPT);
// fprintf(pFile, "SID_SET_SUB_SCRIPT, %6d\n", SID_SET_SUB_SCRIPT);
// fprintf(pFile, "SID_PRESENTATION_TEMPLATES, %6d\n", SID_PRESENTATION_TEMPLATES);
// fprintf(pFile, "SID_STATUS_PAGE, %6d\n", SID_STATUS_PAGE);
// fprintf(pFile, "SID_STATUS_LAYOUT, %6d\n", SID_STATUS_LAYOUT);
// fprintf(pFile, "SID_HYPERLINK_GETLINK, %6d\n", SID_HYPERLINK_GETLINK);
// fclose(pFile);
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuOutlineText::~FuOutlineText()
{
}
/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/
BOOL FuOutlineText::MouseButtonDown(const MouseEvent& rMEvt)
{
BOOL bReturn = FALSE;
pWindow->GrabFocus();
bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseButtonDown(rMEvt);
if (bReturn)
{
// Attributierung der akt. Textstelle kann jetzt anders sein
pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );
}
else
{
bReturn = FuOutline::MouseButtonDown(rMEvt);
}
return (bReturn);
}
/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/
BOOL FuOutlineText::MouseMove(const MouseEvent& rMEvt)
{
BOOL bReturn = FALSE;
bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseMove(rMEvt);
if (!bReturn)
{
bReturn = FuOutline::MouseMove(rMEvt);
}
// MT 07/2002: Done in OutlinerView::MouseMove
/*
const SvxFieldItem* pFieldItem = pOutlineView->GetViewByWindow( pWindow )->
GetFieldUnderMousePointer();
const SvxFieldData* pField = NULL;
if( pFieldItem )
pField = pFieldItem->GetField();
if( pField && pField->ISA( SvxURLField ) )
{
pWindow->SetPointer( Pointer( POINTER_REFHAND ) );
}
else
pWindow->SetPointer( Pointer( POINTER_TEXT ) );
*/
return (bReturn);
}
/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/
BOOL FuOutlineText::MouseButtonUp(const MouseEvent& rMEvt)
{
BOOL bReturn = FALSE;
bReturn = pOutlineView->GetViewByWindow(pWindow)->MouseButtonUp(rMEvt);
if (bReturn)
{
// Attributierung der akt. Textstelle kann jetzt anders sein
pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );
}
else
{
const SvxFieldItem* pFieldItem = pOutlineView->GetViewByWindow( pWindow )->GetFieldUnderMousePointer();
if( pFieldItem )
{
const SvxFieldData* pField = pFieldItem->GetField();
if( pField && pField->ISA( SvxURLField ) )
{
bReturn = TRUE;
pWindow->ReleaseMouse();
SfxStringItem aStrItem( SID_FILE_NAME, ( (SvxURLField*) pField)->GetURL() );
SfxStringItem aReferer( SID_REFERER, pDocSh->GetMedium()->GetName() );
SfxBoolItem aBrowseItem( SID_BROWSE, TRUE );
SfxViewFrame* pFrame = pViewShell->GetViewFrame();
if ( rMEvt.IsMod1() )
{
// Im neuen Frame oeffnen
pFrame->GetDispatcher()->Execute(SID_OPENDOC, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,
&aStrItem, &aBrowseItem, &aReferer, 0L);
}
else
{
// Im aktuellen Frame oeffnen
SfxFrameItem aFrameItem( SID_DOCFRAME, pFrame );
pFrame->GetDispatcher()->Execute(SID_OPENDOC, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD,
&aStrItem, &aFrameItem, &aBrowseItem, &aReferer, 0L);
}
}
}
}
if( !bReturn )
bReturn = FuOutline::MouseButtonUp(rMEvt);
return (bReturn);
}
/*************************************************************************
|*
|* Tastaturereignisse bearbeiten
|*
|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls
|* FALSE.
|*
\************************************************************************/
BOOL FuOutlineText::KeyInput(const KeyEvent& rKEvt)
{
BOOL bReturn = FALSE;
if( !pDocSh->IsReadOnly() ||
rKEvt.GetKeyCode().GetGroup() == KEYGROUP_CURSOR )
{
pWindow->GrabFocus();
bReturn = pOutlineView->GetViewByWindow(pWindow)->PostKeyEvent(rKEvt);
if (bReturn)
{
// Attributierung der akt. Textstelle kann jetzt anders sein
pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );
}
else
{
bReturn = FuOutline::KeyInput(rKEvt);
}
}
return (bReturn);
}
/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/
void FuOutlineText::Activate()
{
FuOutline::Activate();
}
/*************************************************************************
|*
|* Function deaktivieren
|*
\************************************************************************/
void FuOutlineText::Deactivate()
{
FuOutline::Deactivate();
}
/*************************************************************************
|*
|* Cut object to clipboard
|*
\************************************************************************/
void FuOutlineText::DoCut()
{
pOutlineView->GetViewByWindow(pWindow)->Cut();
}
/*************************************************************************
|*
|* Copy object to clipboard
|*
\************************************************************************/
void FuOutlineText::DoCopy()
{
pOutlineView->GetViewByWindow(pWindow)->Copy();
}
/*************************************************************************
|*
|* Paste object from clipboard
|*
\************************************************************************/
void FuOutlineText::DoPaste()
{
pOutlineView->GetViewByWindow(pWindow)->PasteSpecial();
}
<|endoftext|> |
<commit_before>/**
* Extract features and score statistics from nvest file, optionally merging with
* those from the previous iteration.
* Developed during the 2nd MT marathon.
**/
#include <iostream>
#include <string>
#include <vector>
#include <getopt.h>
#include <boost/scoped_ptr.hpp>
#include "Data.h"
#include "Scorer.h"
#include "ScorerFactory.h"
#include "Timer.h"
#include "Util.h"
using namespace std;
using namespace MosesTuning;
namespace {
void usage()
{
cerr << "usage: extractor [options])" << endl;
cerr << "[--sctype|-s] the scorer type (default BLEU)" << endl;
cerr << "[--scconfig|-c] configuration string passed to scorer" << endl;
cerr << "\tThis is of the form NAME1:VAL1,NAME2:VAL2 etc " << endl;
cerr << "[--reference|-r] comma separated list of reference files" << endl;
cerr << "[--binary|-b] use binary output format (default to text )" << endl;
cerr << "[--nbest|-n] the nbest file" << endl;
cerr << "[--scfile|-S] the scorer data output file" << endl;
cerr << "[--ffile|-F] the feature data output file" << endl;
cerr << "[--prev-ffile|-E] comma separated list of previous feature data" << endl;
cerr << "[--prev-scfile|-R] comma separated list of previous scorer data" << endl;
cerr << "[--factors|-f] list of factors passed to the scorer (e.g. 0|2)" << endl;
cerr << "[--filter|-l] filter command used to preprocess the sentences" << endl;
cerr << "[-v] verbose level" << endl;
cerr << "[--help|-h] print this message and exit" << endl;
exit(1);
}
static struct option long_options[] = {
{"sctype", required_argument, 0, 's'},
{"scconfig", required_argument,0, 'c'},
{"factors", required_argument,0, 'f'},
{"filter", required_argument,0, 'l'},
{"reference", required_argument, 0, 'r'},
{"binary", no_argument, 0, 'b'},
{"nbest", required_argument, 0, 'n'},
{"scfile", required_argument, 0, 'S'},
{"ffile", required_argument, 0, 'F'},
{"prev-scfile", required_argument, 0, 'R'},
{"prev-ffile", required_argument, 0, 'E'},
{"verbose", required_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
// Command line options used in extractor.
struct ProgramOption {
string scorerType;
string scorerConfig;
string scorerFactors;
string scorerFilter;
string referenceFile;
string nbestFile;
string scoreDataFile;
string featureDataFile;
string prevScoreDataFile;
string prevFeatureDataFile;
bool binmode;
int verbosity;
ProgramOption()
: scorerType("BLEU"),
scorerConfig(""),
scorerFactors(""),
scorerFilter(""),
referenceFile(""),
nbestFile(""),
scoreDataFile("statscore.data"),
featureDataFile("features.data"),
prevScoreDataFile(""),
prevFeatureDataFile(""),
binmode(false),
verbosity(0) { }
};
void ParseCommandOptions(int argc, char** argv, ProgramOption* opt) {
int c;
int option_index;
while ((c = getopt_long(argc, argv, "s:r:f:l:n:S:F:R:E:v:hb", long_options, &option_index)) != -1) {
switch (c) {
case 's':
opt->scorerType = string(optarg);
break;
case 'c':
opt->scorerConfig = string(optarg);
break;
case 'f':
opt->scorerFactors = string(optarg);
break;
case 'l':
opt->scorerFilter = string(optarg);
break;
case 'r':
opt->referenceFile = string(optarg);
break;
case 'b':
opt->binmode = true;
break;
case 'n':
opt->nbestFile = string(optarg);
break;
case 'S':
opt->scoreDataFile = string(optarg);
break;
case 'F':
opt->featureDataFile = string(optarg);
break;
case 'E':
opt->prevFeatureDataFile = string(optarg);
break;
case 'R':
opt->prevScoreDataFile = string(optarg);
break;
case 'v':
opt->verbosity = atoi(optarg);
break;
default:
usage();
}
}
}
} // anonymous namespace
int main(int argc, char** argv)
{
ResetUserTime();
ProgramOption option;
ParseCommandOptions(argc, argv, &option);
try {
// check whether score statistics file is specified
if (option.scoreDataFile.length() == 0) {
throw runtime_error("Error: output score statistics file is not specified");
}
// check wheter feature file is specified
if (option.featureDataFile.length() == 0) {
throw runtime_error("Error: output feature file is not specified");
}
// check whether reference file is specified when nbest is specified
if ((option.nbestFile.length() > 0 && option.referenceFile.length() == 0)) {
throw runtime_error("Error: reference file is not specified; you can not score the nbest");
}
vector<string> nbestFiles;
if (option.nbestFile.length() > 0) {
Tokenize(option.nbestFile.c_str(), ',', &nbestFiles);
}
vector<string> referenceFiles;
if (option.referenceFile.length() > 0) {
Tokenize(option.referenceFile.c_str(), ',', &referenceFiles);
}
vector<string> prevScoreDataFiles;
if (option.prevScoreDataFile.length() > 0) {
Tokenize(option.prevScoreDataFile.c_str(), ',', &prevScoreDataFiles);
}
vector<string> prevFeatureDataFiles;
if (option.prevFeatureDataFile.length() > 0) {
Tokenize(option.prevFeatureDataFile.c_str(), ',', &prevFeatureDataFiles);
}
if (prevScoreDataFiles.size() != prevFeatureDataFiles.size()) {
throw runtime_error("Error: there is a different number of previous score and feature files");
}
if (option.binmode) {
cerr << "Binary write mode is selected" << endl;
} else {
cerr << "Binary write mode is NOT selected" << endl;
}
TRACE_ERR("Scorer type: " << option.scorerType << endl);
boost::scoped_ptr<Scorer> scorer(
ScorerFactory::getScorer(option.scorerType, option.scorerConfig));
// set Factors and Filter used to preprocess the sentences
scorer->setFactors(option.scorerFactors);
scorer->setFilter(option.scorerFilter);
// load references
if (referenceFiles.size() > 0)
scorer->setReferenceFiles(referenceFiles);
PrintUserTime("References loaded");
Data data(scorer.get());
// load old data
for (size_t i = 0; i < prevScoreDataFiles.size(); i++) {
data.load(prevFeatureDataFiles.at(i), prevScoreDataFiles.at(i));
}
PrintUserTime("Previous data loaded");
// computing score statistics of each nbest file
for (size_t i = 0; i < nbestFiles.size(); i++) {
data.loadNBest(nbestFiles.at(i));
}
PrintUserTime("Nbest entries loaded and scored");
//ADDED_BY_TS
data.removeDuplicates();
//END_ADDED
data.save(option.featureDataFile, option.scoreDataFile, option.binmode);
PrintUserTime("Stopping...");
return EXIT_SUCCESS;
} catch (const exception& e) {
cerr << "Exception: " << e.what() << endl;
return EXIT_FAILURE;
}
}
<commit_msg>option to skip duplicate removal<commit_after>/**
* Extract features and score statistics from nvest file, optionally merging with
* those from the previous iteration.
* Developed during the 2nd MT marathon.
**/
#include <iostream>
#include <string>
#include <vector>
#include <getopt.h>
#include <boost/scoped_ptr.hpp>
#include "Data.h"
#include "Scorer.h"
#include "ScorerFactory.h"
#include "Timer.h"
#include "Util.h"
using namespace std;
using namespace MosesTuning;
namespace {
void usage()
{
cerr << "usage: extractor [options])" << endl;
cerr << "[--sctype|-s] the scorer type (default BLEU)" << endl;
cerr << "[--scconfig|-c] configuration string passed to scorer" << endl;
cerr << "\tThis is of the form NAME1:VAL1,NAME2:VAL2 etc " << endl;
cerr << "[--reference|-r] comma separated list of reference files" << endl;
cerr << "[--binary|-b] use binary output format (default to text )" << endl;
cerr << "[--nbest|-n] the nbest file" << endl;
cerr << "[--scfile|-S] the scorer data output file" << endl;
cerr << "[--ffile|-F] the feature data output file" << endl;
cerr << "[--prev-ffile|-E] comma separated list of previous feature data" << endl;
cerr << "[--prev-scfile|-R] comma separated list of previous scorer data" << endl;
cerr << "[--factors|-f] list of factors passed to the scorer (e.g. 0|2)" << endl;
cerr << "[--filter|-l] filter command used to preprocess the sentences" << endl;
cerr << "[--allow-duplicates|-d] omit the duplicate removal step" << endl;
cerr << "[-v] verbose level" << endl;
cerr << "[--help|-h] print this message and exit" << endl;
exit(1);
}
static struct option long_options[] = {
{"sctype", required_argument, 0, 's'},
{"scconfig", required_argument,0, 'c'},
{"factors", required_argument,0, 'f'},
{"filter", required_argument,0, 'l'},
{"reference", required_argument, 0, 'r'},
{"binary", no_argument, 0, 'b'},
{"nbest", required_argument, 0, 'n'},
{"scfile", required_argument, 0, 'S'},
{"ffile", required_argument, 0, 'F'},
{"prev-scfile", required_argument, 0, 'R'},
{"prev-ffile", required_argument, 0, 'E'},
{"verbose", required_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
{"allow-duplicates", no_argument, 0, 'd'},
{0, 0, 0, 0}
};
// Command line options used in extractor.
struct ProgramOption {
string scorerType;
string scorerConfig;
string scorerFactors;
string scorerFilter;
string referenceFile;
string nbestFile;
string scoreDataFile;
string featureDataFile;
string prevScoreDataFile;
string prevFeatureDataFile;
bool binmode;
bool allowDuplicates;
int verbosity;
ProgramOption()
: scorerType("BLEU"),
scorerConfig(""),
scorerFactors(""),
scorerFilter(""),
referenceFile(""),
nbestFile(""),
scoreDataFile("statscore.data"),
featureDataFile("features.data"),
prevScoreDataFile(""),
prevFeatureDataFile(""),
binmode(false),
allowDuplicates(false),
verbosity(0) { }
};
void ParseCommandOptions(int argc, char** argv, ProgramOption* opt) {
int c;
int option_index;
while ((c = getopt_long(argc, argv, "s:r:f:l:n:S:F:R:E:v:hb", long_options, &option_index)) != -1) {
switch (c) {
case 's':
opt->scorerType = string(optarg);
break;
case 'c':
opt->scorerConfig = string(optarg);
break;
case 'f':
opt->scorerFactors = string(optarg);
break;
case 'l':
opt->scorerFilter = string(optarg);
break;
case 'r':
opt->referenceFile = string(optarg);
break;
case 'b':
opt->binmode = true;
break;
case 'n':
opt->nbestFile = string(optarg);
break;
case 'S':
opt->scoreDataFile = string(optarg);
break;
case 'F':
opt->featureDataFile = string(optarg);
break;
case 'E':
opt->prevFeatureDataFile = string(optarg);
break;
case 'R':
opt->prevScoreDataFile = string(optarg);
break;
case 'v':
opt->verbosity = atoi(optarg);
break;
case 'd':
opt->allowDuplicates = true;
break;
default:
usage();
}
}
}
} // anonymous namespace
int main(int argc, char** argv)
{
ResetUserTime();
ProgramOption option;
ParseCommandOptions(argc, argv, &option);
try {
// check whether score statistics file is specified
if (option.scoreDataFile.length() == 0) {
throw runtime_error("Error: output score statistics file is not specified");
}
// check wheter feature file is specified
if (option.featureDataFile.length() == 0) {
throw runtime_error("Error: output feature file is not specified");
}
// check whether reference file is specified when nbest is specified
if ((option.nbestFile.length() > 0 && option.referenceFile.length() == 0)) {
throw runtime_error("Error: reference file is not specified; you can not score the nbest");
}
vector<string> nbestFiles;
if (option.nbestFile.length() > 0) {
Tokenize(option.nbestFile.c_str(), ',', &nbestFiles);
}
vector<string> referenceFiles;
if (option.referenceFile.length() > 0) {
Tokenize(option.referenceFile.c_str(), ',', &referenceFiles);
}
vector<string> prevScoreDataFiles;
if (option.prevScoreDataFile.length() > 0) {
Tokenize(option.prevScoreDataFile.c_str(), ',', &prevScoreDataFiles);
}
vector<string> prevFeatureDataFiles;
if (option.prevFeatureDataFile.length() > 0) {
Tokenize(option.prevFeatureDataFile.c_str(), ',', &prevFeatureDataFiles);
}
if (prevScoreDataFiles.size() != prevFeatureDataFiles.size()) {
throw runtime_error("Error: there is a different number of previous score and feature files");
}
if (option.binmode) {
cerr << "Binary write mode is selected" << endl;
} else {
cerr << "Binary write mode is NOT selected" << endl;
}
TRACE_ERR("Scorer type: " << option.scorerType << endl);
boost::scoped_ptr<Scorer> scorer(
ScorerFactory::getScorer(option.scorerType, option.scorerConfig));
// set Factors and Filter used to preprocess the sentences
scorer->setFactors(option.scorerFactors);
scorer->setFilter(option.scorerFilter);
// load references
if (referenceFiles.size() > 0)
scorer->setReferenceFiles(referenceFiles);
PrintUserTime("References loaded");
Data data(scorer.get());
// load old data
for (size_t i = 0; i < prevScoreDataFiles.size(); i++) {
data.load(prevFeatureDataFiles.at(i), prevScoreDataFiles.at(i));
}
PrintUserTime("Previous data loaded");
// computing score statistics of each nbest file
for (size_t i = 0; i < nbestFiles.size(); i++) {
data.loadNBest(nbestFiles.at(i));
}
PrintUserTime("Nbest entries loaded and scored");
//ADDED_BY_TS
if (!option.allowDuplicates) {
data.removeDuplicates();
}
//END_ADDED
data.save(option.featureDataFile, option.scoreDataFile, option.binmode);
PrintUserTime("Stopping...");
return EXIT_SUCCESS;
} catch (const exception& e) {
cerr << "Exception: " << e.what() << endl;
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: unoobj.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2005-03-01 17:35: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: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _UNOOBJ_HXX
#define _UNOOBJ_HXX
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.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 _COM_SUN_STAR_DRAWING_XSHAPE_HPP_
#include <com/sun/star/drawing/XShape.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _SVDPOOL_HXX //autogen
#include <svx/svdpool.hxx>
#endif
#ifndef _SVX_UNOMASTER_HXX
#include <svx/unomaster.hxx>
#endif
#include <svx/unoipset.hxx>
#include <cppuhelper/implbase2.hxx>
class SdrObject;
class SdXImpressDocument;
class SdAnimationInfo;
class SdXShape : public SvxShapeMaster,
public ::com::sun::star::document::XEventsSupplier
{
friend class SdUnoEventsAccess;
private:
SvxShape* mpShape;
SvxItemPropertySet maPropSet;
const SfxItemPropertyMap* mpMap;
SdXImpressDocument* mpModel;
void SetStyleSheet( const ::com::sun::star::uno::Any& rAny ) throw( ::com::sun::star::lang::IllegalArgumentException );
::com::sun::star::uno::Any GetStyleSheet() const throw( ::com::sun::star::beans::UnknownPropertyException );
// Intern
SdAnimationInfo* GetAnimationInfo( sal_Bool bCreate = sal_False ) const throw();
sal_Bool IsPresObj() const throw();
void SetPresObj( sal_Bool bPresObj ) throw();
sal_Bool IsEmptyPresObj() const throw();
void SetEmptyPresObj( sal_Bool bEmpty ) throw();
sal_Bool IsMasterDepend() const throw();
void SetMasterDepend( sal_Bool bDepend ) throw();
SdrObject* GetSdrObject() const throw();
sal_Int32 GetPresentationOrderPos() const throw();
void SetPresentationOrderPos( sal_Int32 nPos ) throw();
com::sun::star::uno::Sequence< sal_Int8 >* mpImplementationId;
public:
SdXShape() throw();
SdXShape(SvxShape* pShape, SdXImpressDocument* pModel) throw();
virtual ~SdXShape() throw();
virtual sal_Bool queryAggregation( const com::sun::star::uno::Type & rType, com::sun::star::uno::Any& aAny );
virtual void dispose();
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
// XServiceInfo
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
//XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
//XPropertyState
virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);
// XEventsSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > SAL_CALL getEvents( ) throw(::com::sun::star::uno::RuntimeException);
private:
void setOldEffect( const com::sun::star::uno::Any& aValue );
void setOldTextEffect( const com::sun::star::uno::Any& aValue );
void setOldSpeed( const com::sun::star::uno::Any& aValue );
void setOldDimColor( const com::sun::star::uno::Any& aValue );
void setOldDimHide( const com::sun::star::uno::Any& aValue );
void setOldDimPrevious( const com::sun::star::uno::Any& aValue );
void setOldPresOrder( const com::sun::star::uno::Any& aValue );
void updateOldSoundEffect( SdAnimationInfo* pInfo );
};
struct SvEventDescription;
const SvEventDescription* ImplGetSupportedMacroItems();
#endif
<commit_msg>INTEGRATION: CWS impress36 (1.8.108); FILE MERGED 2005/02/25 15:25:55 cl 1.8.108.1: #i42737# added MigrateEffect framework for petter effect import and removed unused code<commit_after>/*************************************************************************
*
* $RCSfile: unoobj.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: kz $ $Date: 2005-03-18 17:03:54 $
*
* 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 _UNOOBJ_HXX
#define _UNOOBJ_HXX
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.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 _COM_SUN_STAR_DRAWING_XSHAPE_HPP_
#include <com/sun/star/drawing/XShape.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _SVDPOOL_HXX //autogen
#include <svx/svdpool.hxx>
#endif
#ifndef _SVX_UNOMASTER_HXX
#include <svx/unomaster.hxx>
#endif
#include <svx/unoipset.hxx>
#include <cppuhelper/implbase2.hxx>
class SdrObject;
class SdXImpressDocument;
class SdAnimationInfo;
class SdXShape : public SvxShapeMaster,
public ::com::sun::star::document::XEventsSupplier
{
friend class SdUnoEventsAccess;
private:
SvxShape* mpShape;
SvxItemPropertySet maPropSet;
const SfxItemPropertyMap* mpMap;
SdXImpressDocument* mpModel;
void SetStyleSheet( const ::com::sun::star::uno::Any& rAny ) throw( ::com::sun::star::lang::IllegalArgumentException );
::com::sun::star::uno::Any GetStyleSheet() const throw( ::com::sun::star::beans::UnknownPropertyException );
// Intern
SdAnimationInfo* GetAnimationInfo( sal_Bool bCreate = sal_False ) const throw();
sal_Bool IsPresObj() const throw();
void SetPresObj( sal_Bool bPresObj ) throw();
sal_Bool IsEmptyPresObj() const throw();
void SetEmptyPresObj( sal_Bool bEmpty ) throw();
sal_Bool IsMasterDepend() const throw();
void SetMasterDepend( sal_Bool bDepend ) throw();
SdrObject* GetSdrObject() const throw();
com::sun::star::uno::Sequence< sal_Int8 >* mpImplementationId;
public:
SdXShape() throw();
SdXShape(SvxShape* pShape, SdXImpressDocument* pModel) throw();
virtual ~SdXShape() throw();
virtual sal_Bool queryAggregation( const com::sun::star::uno::Type & rType, com::sun::star::uno::Any& aAny );
virtual void dispose();
// XInterface
virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
// XServiceInfo
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
//XPropertySet
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
//XPropertyState
virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
// XTypeProvider
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);
// XEventsSupplier
virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameReplace > SAL_CALL getEvents( ) throw(::com::sun::star::uno::RuntimeException);
private:
void setOldEffect( const com::sun::star::uno::Any& aValue );
void setOldTextEffect( const com::sun::star::uno::Any& aValue );
void setOldSpeed( const com::sun::star::uno::Any& aValue );
void setOldDimColor( const com::sun::star::uno::Any& aValue );
void setOldDimHide( const com::sun::star::uno::Any& aValue );
void setOldDimPrevious( const com::sun::star::uno::Any& aValue );
void setOldPresOrder( const com::sun::star::uno::Any& aValue );
void updateOldSoundEffect( SdAnimationInfo* pInfo );
void getOldEffect( com::sun::star::uno::Any& rValue ) const;
void getOldTextEffect( com::sun::star::uno::Any& rValue ) const;
void getOldSpeed( com::sun::star::uno::Any& rValue ) const;
void getOldSoundFile( com::sun::star::uno::Any& rValue ) const;
void getOldSoundOn( com::sun::star::uno::Any& rValue ) const;
void getOldDimColor( com::sun::star::uno::Any& rValue ) const;
void getOldDimHide( com::sun::star::uno::Any& rValue ) const;
void getOldDimPrev( com::sun::star::uno::Any& rValue ) const;
void getOldPresOrder( com::sun::star::uno::Any& rValue ) const;
};
struct SvEventDescription;
const SvEventDescription* ImplGetSupportedMacroItems();
#endif
<|endoftext|> |
<commit_before>#include "cinder/Cinder.h"
#if defined( CINDER_COCOA_TOUCH )
#include "cinder/app/AppCocoaTouch.h"
typedef ci::app::AppCocoaTouch AppNative;
#else
#include "cinder/app/AppBasic.h"
typedef ci::app::AppBasic AppNative;
#endif
#include "cinder/gl/gl.h"
#include "cinder/Clipboard.h"
#include "cinder/gl/Texture.h"
#include "cinder/Utilities.h"
#include "Resources.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class ClipboardBasicApp : public AppNative {
public:
void keyDown( KeyEvent event );
void draw();
};
void ClipboardBasicApp::keyDown( KeyEvent event )
{
if( event.getChar() == 'c' && event.isAccelDown() ) {
Clipboard::setImage( loadImage( loadResource( RES_CINDER_LOGO ) ) );
// to copy the contents of the window, you might do something like
// Clipboard::setImage( copyWindowSurface() );
}
}
void ClipboardBasicApp::draw()
{
gl::clear( Color( 0.5f, 0.5f, 0.5f ) );
gl::enableAlphaBlending( true );
gl::setMatricesWindow( getWindowSize() );
if( Clipboard::hasImage() )
gl::draw( gl::Texture( Clipboard::getImage() ) );
else if( Clipboard::hasString() )
gl::drawString( Clipboard::getString(), Vec2f( 0, getWindowCenter().y ) );
else
gl::drawString( "Clipboard contents unknown", Vec2f( 0, getWindowCenter().y ) );
}
#if defined( CINDER_COCOA_TOUCH )
CINDER_APP_COCOA_TOUCH( ClipboardBasicApp, RendererGl )
#else
CINDER_APP_BASIC( ClipboardBasicApp, RendererGl )
#endif<commit_msg>Moved ClipboardBasic to AppNative<commit_after>#include "cinder/Cinder.h"
#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/Clipboard.h"
#include "cinder/gl/Texture.h"
#include "cinder/Utilities.h"
#include "Resources.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class ClipboardBasicApp : public AppNative {
public:
void keyDown( KeyEvent event );
void draw();
};
void ClipboardBasicApp::keyDown( KeyEvent event )
{
if( event.getChar() == 'c' && event.isAccelDown() ) {
Clipboard::setImage( loadImage( loadResource( RES_CINDER_LOGO ) ) );
// to copy the contents of the window, you might do something like
// Clipboard::setImage( copyWindowSurface() );
}
}
void ClipboardBasicApp::draw()
{
gl::clear( Color( 0.5f, 0.5f, 0.5f ) );
gl::setMatricesWindow( getWindowSize() );
if( Clipboard::hasImage() )
gl::draw( gl::Texture( Clipboard::getImage() ) );
else if( Clipboard::hasString() )
gl::drawString( Clipboard::getString(), Vec2f( 0, getWindowCenter().y ) );
else
gl::drawString( "Clipboard contents unknown", Vec2f( 0, getWindowCenter().y ) );
}
CINDER_APP_NATIVE( ClipboardBasicApp, RendererGl )
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: grviewsh.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-01-20 12:50:36 $
*
* 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 "GraphicViewShell.hxx"
namespace sd {
/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
FrameView* pFrameView)
: DrawViewShell (pFrame, rViewShellBase, PK_STANDARD, pFrameView)
{
//Construct( pDocSh );
meShellType = ST_DRAW;
}
/*************************************************************************
|*
|* Copy-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell(SfxViewFrame* pFrame,
const DrawViewShell& rShell) :
DrawViewShell( pFrame, rShell )
{
//Construct( pDocSh );
meShellType = ST_DRAW;
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
GraphicViewShell::~GraphicViewShell()
{
}
/*************************************************************************
|*
|* gemeinsamer Initialisierungsanteil der beiden Konstruktoren
|*
\************************************************************************/
void GraphicViewShell::Construct()
{
// Shells fuer Object Bars erzeugen
//SfxShell* pObjBarShell = new SdDrawStdObjectBar(this, pDrView);
//aShellTable.Insert(RID_DRAW_OBJ_TOOLBOX, pObjBarShell);
// ObjectBar einschalten
//SwitchObjectBar(RID_DRAW_OBJ_TOOLBOX);
aPageBtn.Hide();
aMasterPageBtn.Hide();
aLayerBtn.Hide();
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS impress2 (1.3.26); FILE MERGED 2004/06/30 12:05:54 af 1.3.26.3: #i22705# Added Construct(), ChangeEditMode(), and ArrangeGUIElements() methods. 2004/04/23 11:52:23 af 1.3.26.2: #i22705# Removed edit-, master-,and layer button. 2004/02/19 15:49:17 af 1.3.26.1: #i22705# Added argument to constructors.<commit_after>/*************************************************************************
*
* $RCSfile: grviewsh.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2004-07-13 14:59:19 $
*
* 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 "GraphicViewShell.hxx"
#include "LayerTabBar.hxx"
#include "FrameView.hxx"
#include <sfx2/viewfrm.hxx>
#include <vcl/scrbar.hxx>
namespace sd {
static const int TABCONTROL_INITIAL_SIZE = 350;
/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
::Window* pParentWindow,
FrameView* pFrameView)
: DrawViewShell (
pFrame,
rViewShellBase,
pParentWindow,
PK_STANDARD,
pFrameView)
{
Construct ();
}
/*************************************************************************
|*
|* Copy-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell (
SfxViewFrame* pFrame,
::Window* pParentWindow,
const DrawViewShell& rShell)
: DrawViewShell (pFrame, pParentWindow, rShell)
{
Construct ();
}
GraphicViewShell::~GraphicViewShell (void)
{
}
void GraphicViewShell::Construct (void)
{
meShellType = ST_DRAW;
mpLayerTabBar.reset (new LayerTabBar(this,GetParentWindow()));
mpLayerTabBar->SetSplitHdl(LINK(this,GraphicViewShell,TabBarSplitHandler));
mpLayerTabBar->Show();
}
void GraphicViewShell::ChangeEditMode (
EditMode eMode,
bool bIsLayerModeActive)
{
// There is no page tab that could be shown instead of the layer tab.
// Therefore we have it allways visible regardless of what the caller
// said. (We have to change the callers behaviour, of course.)
DrawViewShell::ChangeEditMode (eMode, true);
}
void GraphicViewShell::ArrangeGUIElements (void)
{
if (mpLayerTabBar.get()!=NULL && mpLayerTabBar->IsVisible())
{
Size aSize = mpLayerTabBar->GetSizePixel();
const Size aFrameSize (
GetViewFrame()->GetWindow().GetOutputSizePixel());
if (aSize.Width() == 0)
{
if (pFrameView->GetTabCtrlPercent() == 0.0)
aSize.Width() = TABCONTROL_INITIAL_SIZE;
else
aSize.Width() = FRound(aFrameSize.Width()
* pFrameView->GetTabCtrlPercent());
}
aSize.Height() = GetParentWindow()->GetSettings().GetStyleSettings()
.GetScrollBarSize();
Point aPos (0, aViewSize.Height() - aSize.Height());
mpLayerTabBar->SetPosSizePixel (aPos, aSize);
if (aFrameSize.Width() > 0)
pFrameView->SetTabCtrlPercent (
(double) aTabControl.GetSizePixel().Width()
/ aFrameSize.Width());
else
pFrameView->SetTabCtrlPercent( 0.0 );
}
DrawViewShell::ArrangeGUIElements();
}
IMPL_LINK(GraphicViewShell, TabBarSplitHandler, TabBar*, pTabBar)
{
const long int nMax = aViewSize.Width()
- aScrBarWH.Width()
- pTabBar->GetPosPixel().X();
Size aTabSize = pTabBar->GetSizePixel();
aTabSize.Width() = Min(pTabBar->GetSplitSize(), (long)(nMax-1));
pTabBar->SetSizePixel (aTabSize);
Point aPos = pTabBar->GetPosPixel();
aPos.X() += aTabSize.Width();
Size aScrSize (nMax - aTabSize.Width(), aScrBarWH.Height());
mpHorizontalScrollBar->SetPosSizePixel(aPos, aScrSize);
return 0;
}
} // end of namespace sd
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: presvish.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: ka $ $Date: 2001-12-17 10:14: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: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFX_TOPFRM_HXX
#include <sfx2/topfrm.hxx>
#endif
#ifndef _SFX_DISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#include <svx/svxids.hrc>
#include <sfx2/app.hxx>
#include "sdresid.hxx"
#include "docshell.hxx"
#include "presvish.hxx"
#include "fuslshow.hxx"
#include "sdattr.hxx"
#include "sdpage.hxx"
#include "drawdoc.hxx"
#include "drawview.hxx"
#include "app.hrc"
#include "strings.hrc"
#include "glob.hrc"
#define SdPresViewShell
#include "sdslots.hxx"
// -------------------
// - SdPresViewShell -
// -------------------
SFX_IMPL_INTERFACE( SdPresViewShell, SdDrawViewShell, SdResId( STR_PRESVIEWSHELL ) )
{
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS | SFX_VISIBILITY_STANDARD |
SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER,
SdResId(RID_DRAW_TOOLBOX));
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OPTIONS | SFX_VISIBILITY_STANDARD |
SFX_VISIBILITY_SERVER,
SdResId(RID_DRAW_OPTIONS_TOOLBOX));
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_COMMONTASK | SFX_VISIBILITY_STANDARD |
SFX_VISIBILITY_SERVER,
SdResId(RID_DRAW_COMMONTASK_TOOLBOX));
}
// -----------------------------------------------------------------------------
SFX_IMPL_VIEWFACTORY( SdPresViewShell, SdResId( STR_DEFAULTVIEW ) )
{
SFX_VIEW_REGISTRATION( SdDrawDocShell );
}
// -----------------------------------------------------------------------------
TYPEINIT1( SdPresViewShell, SdDrawViewShell );
// -----------------------------------------------------------------------------
SdPresViewShell::SdPresViewShell( SfxViewFrame* pFrame, SfxViewShell *pOldShell ) :
SdDrawViewShell( pFrame, pOldShell ),
mbShowStarted( sal_False )
{
if( pDocSh && pDocSh->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
maOldVisArea = pDocSh->GetVisArea( ASPECT_CONTENT );
}
// -----------------------------------------------------------------------------
SdPresViewShell::SdPresViewShell( SfxViewFrame* pFrame, const SdDrawViewShell& rShell ) :
SdDrawViewShell( pFrame, rShell ),
mbShowStarted( sal_False )
{
if( pDocSh && pDocSh->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
maOldVisArea = pDocSh->GetVisArea( ASPECT_CONTENT );
}
// -----------------------------------------------------------------------------
SdPresViewShell::~SdPresViewShell()
{
if( pDocSh && pDocSh->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED && !maOldVisArea.IsEmpty() )
pDocSh->SetVisArea( maOldVisArea );
if( GetViewFrame() && GetViewFrame()->GetTopFrame() )
{
WorkWindow* pWorkWindow = (WorkWindow*) GetViewFrame()->GetTopFrame()->GetWindow().GetParent();
if( pWorkWindow )
pWorkWindow->StartPresentationMode( FALSE, pFuSlideShow ? pFuSlideShow->IsAlwaysOnTop() : 0 );
}
if( pFuSlideShow )
{
pFuSlideShow->Deactivate();
pFuSlideShow->Destroy();
pFuSlideShow = NULL;
}
}
// -----------------------------------------------------------------------------
void SdPresViewShell::Activate( BOOL bIsMDIActivate )
{
SfxViewShell::Activate( bIsMDIActivate );
if( bIsMDIActivate )
{
SdView* pView = GetView();
SfxBoolItem aItem( SID_NAVIGATOR_INIT, TRUE );
GetViewFrame()->GetDispatcher()->Execute( SID_NAVIGATOR_INIT, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aItem, 0L );
if( pFuSlideShow && !pFuSlideShow->IsTerminated() )
pFuSlideShow->Activate();
if( pFuActual )
pFuActual->Activate();
if( pView )
pView->ShowMarkHdl( NULL );
}
ReadFrameViewData( pFrameView );
pDocSh->Connect( this );
if( pFuSlideShow && !mbShowStarted )
{
pFuSlideShow->StartShow();
mbShowStarted = sal_True;
}
}
// -----------------------------------------------------------------------------
void SdPresViewShell::Paint( const Rectangle& rRect, SdWindow* pWin )
{
// allow paints only if show is already started
if( mbShowStarted )
SdDrawViewShell::Paint( rRect, pWin );
}
// -----------------------------------------------------------------------------
void SdPresViewShell::CreateFullScreenShow( SdViewShell* pOriginShell, SfxRequest& rReq )
{
SFX_REQUEST_ARG( rReq, pAlwaysOnTop, SfxBoolItem, ATTR_PRESENT_ALWAYS_ON_TOP, FALSE );
WorkWindow* pWorkWindow = new WorkWindow( NULL, WB_HIDE | WB_CLIPCHILDREN );
SdDrawDocument* pDoc = pOriginShell->GetDoc();
SdPage* pActualPage = pOriginShell->GetActualPage();
BOOL bAlwaysOnTop = ( ( SID_REHEARSE_TIMINGS != rReq.GetSlot() ) && pAlwaysOnTop ) ? pAlwaysOnTop->GetValue() : pDoc->GetPresAlwaysOnTop();
pWorkWindow->StartPresentationMode( TRUE, bAlwaysOnTop ? PRESENTATION_HIDEALLAPPS : 0 );
SfxTopFrame* pNewFrame = SfxTopFrame::Create( pDoc->GetDocSh(), pWorkWindow, 4, TRUE );
pNewFrame->SetPresentationMode( TRUE );
SdPresViewShell* pShell = (SdPresViewShell*) pNewFrame->GetCurrentViewFrame()->GetViewShell();
SfxUInt16Item aId( SID_CONFIGITEMID, SID_NAVIGATOR );
SfxBoolItem aShowItem( SID_SHOWPOPUPS, FALSE );
pShell->SwitchPage( ( pActualPage->GetPageNum() - 1 ) / 2 );
pShell->WriteFrameViewData();
pShell->GetViewFrame()->GetDispatcher()->Execute( SID_SHOWPOPUPS, SFX_CALLMODE_SYNCHRON, &aShowItem, &aId, 0L );
pShell->GetViewFrame()->Show();
pShell->pFuSlideShow = new FuSlideShow( pShell, pShell->pWindow, pShell->pDrView, pShell->pDoc, rReq );
pShell->GetActiveWindow()->GrabFocus();
}
<commit_msg>#92430# terminate fuslshow before destroy<commit_after>/*************************************************************************
*
* $RCSfile: presvish.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: cl $ $Date: 2002-02-05 10:10:49 $
*
* 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 _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFX_TOPFRM_HXX
#include <sfx2/topfrm.hxx>
#endif
#ifndef _SFX_DISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#include <svx/svxids.hrc>
#include <sfx2/app.hxx>
#include "sdresid.hxx"
#include "docshell.hxx"
#include "presvish.hxx"
#include "fuslshow.hxx"
#include "sdattr.hxx"
#include "sdpage.hxx"
#include "drawdoc.hxx"
#include "drawview.hxx"
#include "app.hrc"
#include "strings.hrc"
#include "glob.hrc"
#define SdPresViewShell
#include "sdslots.hxx"
// -------------------
// - SdPresViewShell -
// -------------------
SFX_IMPL_INTERFACE( SdPresViewShell, SdDrawViewShell, SdResId( STR_PRESVIEWSHELL ) )
{
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS | SFX_VISIBILITY_STANDARD |
SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER,
SdResId(RID_DRAW_TOOLBOX));
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OPTIONS | SFX_VISIBILITY_STANDARD |
SFX_VISIBILITY_SERVER,
SdResId(RID_DRAW_OPTIONS_TOOLBOX));
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_COMMONTASK | SFX_VISIBILITY_STANDARD |
SFX_VISIBILITY_SERVER,
SdResId(RID_DRAW_COMMONTASK_TOOLBOX));
}
// -----------------------------------------------------------------------------
SFX_IMPL_VIEWFACTORY( SdPresViewShell, SdResId( STR_DEFAULTVIEW ) )
{
SFX_VIEW_REGISTRATION( SdDrawDocShell );
}
// -----------------------------------------------------------------------------
TYPEINIT1( SdPresViewShell, SdDrawViewShell );
// -----------------------------------------------------------------------------
SdPresViewShell::SdPresViewShell( SfxViewFrame* pFrame, SfxViewShell *pOldShell ) :
SdDrawViewShell( pFrame, pOldShell ),
mbShowStarted( sal_False )
{
if( pDocSh && pDocSh->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
maOldVisArea = pDocSh->GetVisArea( ASPECT_CONTENT );
}
// -----------------------------------------------------------------------------
SdPresViewShell::SdPresViewShell( SfxViewFrame* pFrame, const SdDrawViewShell& rShell ) :
SdDrawViewShell( pFrame, rShell ),
mbShowStarted( sal_False )
{
if( pDocSh && pDocSh->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED )
maOldVisArea = pDocSh->GetVisArea( ASPECT_CONTENT );
}
// -----------------------------------------------------------------------------
SdPresViewShell::~SdPresViewShell()
{
if( pDocSh && pDocSh->GetCreateMode() == SFX_CREATE_MODE_EMBEDDED && !maOldVisArea.IsEmpty() )
pDocSh->SetVisArea( maOldVisArea );
if( GetViewFrame() && GetViewFrame()->GetTopFrame() )
{
WorkWindow* pWorkWindow = (WorkWindow*) GetViewFrame()->GetTopFrame()->GetWindow().GetParent();
if( pWorkWindow )
pWorkWindow->StartPresentationMode( FALSE, pFuSlideShow ? pFuSlideShow->IsAlwaysOnTop() : 0 );
}
if( pFuSlideShow )
{
pFuSlideShow->Deactivate();
pFuSlideShow->Terminate();
pFuSlideShow->Destroy();
pFuSlideShow = NULL;
}
}
// -----------------------------------------------------------------------------
void SdPresViewShell::Activate( BOOL bIsMDIActivate )
{
SfxViewShell::Activate( bIsMDIActivate );
if( bIsMDIActivate )
{
SdView* pView = GetView();
SfxBoolItem aItem( SID_NAVIGATOR_INIT, TRUE );
GetViewFrame()->GetDispatcher()->Execute( SID_NAVIGATOR_INIT, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aItem, 0L );
if( pFuSlideShow && !pFuSlideShow->IsTerminated() )
pFuSlideShow->Activate();
if( pFuActual )
pFuActual->Activate();
if( pView )
pView->ShowMarkHdl( NULL );
}
ReadFrameViewData( pFrameView );
pDocSh->Connect( this );
if( pFuSlideShow && !mbShowStarted )
{
pFuSlideShow->StartShow();
mbShowStarted = sal_True;
}
}
// -----------------------------------------------------------------------------
void SdPresViewShell::Paint( const Rectangle& rRect, SdWindow* pWin )
{
// allow paints only if show is already started
if( mbShowStarted )
SdDrawViewShell::Paint( rRect, pWin );
}
// -----------------------------------------------------------------------------
void SdPresViewShell::CreateFullScreenShow( SdViewShell* pOriginShell, SfxRequest& rReq )
{
SFX_REQUEST_ARG( rReq, pAlwaysOnTop, SfxBoolItem, ATTR_PRESENT_ALWAYS_ON_TOP, FALSE );
WorkWindow* pWorkWindow = new WorkWindow( NULL, WB_HIDE | WB_CLIPCHILDREN );
SdDrawDocument* pDoc = pOriginShell->GetDoc();
SdPage* pActualPage = pOriginShell->GetActualPage();
BOOL bAlwaysOnTop = ( ( SID_REHEARSE_TIMINGS != rReq.GetSlot() ) && pAlwaysOnTop ) ? pAlwaysOnTop->GetValue() : pDoc->GetPresAlwaysOnTop();
pWorkWindow->StartPresentationMode( TRUE, bAlwaysOnTop ? PRESENTATION_HIDEALLAPPS : 0 );
SfxTopFrame* pNewFrame = SfxTopFrame::Create( pDoc->GetDocSh(), pWorkWindow, 4, TRUE );
pNewFrame->SetPresentationMode( TRUE );
SdPresViewShell* pShell = (SdPresViewShell*) pNewFrame->GetCurrentViewFrame()->GetViewShell();
SfxUInt16Item aId( SID_CONFIGITEMID, SID_NAVIGATOR );
SfxBoolItem aShowItem( SID_SHOWPOPUPS, FALSE );
pShell->SwitchPage( ( pActualPage->GetPageNum() - 1 ) / 2 );
pShell->WriteFrameViewData();
pShell->GetViewFrame()->GetDispatcher()->Execute( SID_SHOWPOPUPS, SFX_CALLMODE_SYNCHRON, &aShowItem, &aId, 0L );
pShell->GetViewFrame()->Show();
pShell->pFuSlideShow = new FuSlideShow( pShell, pShell->pWindow, pShell->pDrView, pShell->pDoc, rReq );
pShell->GetActiveWindow()->GrabFocus();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include "cfactory.hpp"
#include "comreg.hpp"
#include "webmtypes.hpp"
#include <mfapi.h>
#include <cassert>
#include <comdef.h>
#include <uuids.h>
HMODULE g_hModule;
static ULONG s_cLock;
namespace WebmMfVorbisDecLib
{
HRESULT CreateDecoder(
IClassFactory*,
IUnknown*,
const IID&,
void**);
} //end namespace WebmMfVorbisDecLib
static CFactory s_handler_factory(&s_cLock, &WebmMfVorbisDecLib::CreateDecoder);
BOOL APIENTRY DllMain(
HINSTANCE hModule,
DWORD dwReason,
LPVOID)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
{
g_hModule = hModule;
break;
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
default:
break;
}
return TRUE;
}
STDAPI DllCanUnloadNow()
{
return s_cLock ? S_FALSE : S_OK;
}
STDAPI DllGetClassObject(
const CLSID& clsid,
const IID& iid,
void** ppv)
{
if (clsid == WebmTypes::CLSID_WebmMfVorbisDec)
return s_handler_factory.QueryInterface(iid, ppv);
return CLASS_E_CLASSNOTAVAILABLE;
}
STDAPI DllUnregisterServer()
{
HRESULT hr = MFTUnregister(WebmTypes::CLSID_WebmMfVorbisDec);
//assert(SUCCEEDED(hr)); //TODO: dump this it fails
hr = ComReg::UnRegisterCoclass(WebmTypes::CLSID_WebmMfVorbisDec);
return hr;
}
STDAPI DllRegisterServer()
{
HRESULT hr = DllUnregisterServer();
assert(SUCCEEDED(hr));
std::wstring filename_;
hr = ComReg::ComRegGetModuleFileName(g_hModule, filename_);
assert(SUCCEEDED(hr));
assert(!filename_.empty());
const wchar_t* const filename = filename_.c_str();
#if _DEBUG
const wchar_t friendly_name[] = L"WebM MF Vorbis Decoder Transform (Debug)";
#else
const wchar_t friendly_name[] = L"WebM MF Vorbis Decoder Transform";
#endif
hr = ComReg::RegisterCoclass(
WebmTypes::CLSID_WebmMfVorbisDec,
friendly_name,
filename,
L"Webm.MfVorbisDec",
L"Webm.MfVorbis.1",
false, //not insertable
false, //not a control
ComReg::kBoth, //DShow filters must support "both"
GUID_NULL, //typelib
0, //no version specified
0); //no toolbox bitmap
if (FAILED(hr))
return hr;
enum { cInputTypes = 1 };
MFT_REGISTER_TYPE_INFO pInputTypes[cInputTypes] =
{
{ MFMediaType_Video, WebmTypes::MEDIASUBTYPE_WEBM }
};
enum { cOutputTypes = 2 };
MFT_REGISTER_TYPE_INFO pOutputTypes[cOutputTypes] =
{
{ MFMediaType_Video, MFVideoFormat_YV12 },
{ MFMediaType_Video, MFVideoFormat_IYUV }
};
wchar_t* const friendly_name_ = const_cast<wchar_t*>(friendly_name);
hr = MFTRegister(
WebmTypes::CLSID_WebmMfVorbisDec,
MFT_CATEGORY_VIDEO_DECODER,
friendly_name_,
MFT_ENUM_FLAG_SYNCMFT, //TODO: for now, just support sync
cInputTypes,
pInputTypes,
cOutputTypes,
pOutputTypes,
0); //no attributes
return hr;
}
<commit_msg>Correct media types and prog-id.<commit_after>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include "cfactory.hpp"
#include "comreg.hpp"
#include "webmtypes.hpp"
#include "vorbistypes.hpp"
#include <mfapi.h>
#include <cassert>
#include <comdef.h>
#include <uuids.h>
HMODULE g_hModule;
static ULONG s_cLock;
namespace WebmMfVorbisDecLib
{
HRESULT CreateDecoder(
IClassFactory*,
IUnknown*,
const IID&,
void**);
} //end namespace WebmMfVorbisDecLib
static CFactory s_handler_factory(&s_cLock, &WebmMfVorbisDecLib::CreateDecoder);
BOOL APIENTRY DllMain(
HINSTANCE hModule,
DWORD dwReason,
LPVOID)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
{
g_hModule = hModule;
break;
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
default:
break;
}
return TRUE;
}
STDAPI DllCanUnloadNow()
{
return s_cLock ? S_FALSE : S_OK;
}
STDAPI DllGetClassObject(
const CLSID& clsid,
const IID& iid,
void** ppv)
{
if (clsid == WebmTypes::CLSID_WebmMfVorbisDec)
return s_handler_factory.QueryInterface(iid, ppv);
return CLASS_E_CLASSNOTAVAILABLE;
}
STDAPI DllUnregisterServer()
{
HRESULT hr = MFTUnregister(WebmTypes::CLSID_WebmMfVorbisDec);
//assert(SUCCEEDED(hr)); //TODO: dump this it fails
hr = ComReg::UnRegisterCoclass(WebmTypes::CLSID_WebmMfVorbisDec);
return hr;
}
STDAPI DllRegisterServer()
{
HRESULT hr = DllUnregisterServer();
assert(SUCCEEDED(hr));
std::wstring filename_;
hr = ComReg::ComRegGetModuleFileName(g_hModule, filename_);
assert(SUCCEEDED(hr));
assert(!filename_.empty());
const wchar_t* const filename = filename_.c_str();
#if _DEBUG
const wchar_t friendly_name[] = L"WebM MF Vorbis Decoder Transform (Debug)";
#else
const wchar_t friendly_name[] = L"WebM MF Vorbis Decoder Transform";
#endif
hr = ComReg::RegisterCoclass(
WebmTypes::CLSID_WebmMfVorbisDec,
friendly_name,
filename,
L"Webm.MfVorbisDec",
L"Webm.MfVorbisDec.1",
false, //not insertable
false, //not a control
ComReg::kBoth, //DShow filters must support "both"
GUID_NULL, //typelib
0, //no version specified
0); //no toolbox bitmap
if (FAILED(hr))
return hr;
enum { cInputTypes = 1 };
MFT_REGISTER_TYPE_INFO pInputTypes[cInputTypes] =
{
{ MFMediaType_Audio, VorbisTypes::MEDIASUBTYPE_Vorbis2 }
};
enum { cOutputTypes = 1 };
MFT_REGISTER_TYPE_INFO pOutputTypes[cOutputTypes] =
{
{ MFMediaType_Audio, MFAudioFormat_PCM}
};
wchar_t* const friendly_name_ = const_cast<wchar_t*>(friendly_name);
hr = MFTRegister(
WebmTypes::CLSID_WebmMfVorbisDec,
MFT_CATEGORY_AUDIO_DECODER,
friendly_name_,
MFT_ENUM_FLAG_SYNCMFT, //TODO: for now, just support sync
cInputTypes,
pInputTypes,
cOutputTypes,
pOutputTypes,
0); //no attributes
return hr;
}
<|endoftext|> |
<commit_before>#pragma once
#include <cmath>
#include <cassert>
namespace studd
{
// returns an iterator to the element which maximizes the function
template<class InputIt, class UnaryFunction,
class T = typename std::iterator_traits<InputIt>::value_type>
InputIt argmax(InputIt first, InputIt last, UnaryFunction f)
{
assert(std::distance(first, last) > 0);
T max;
InputIt max_it;
for (auto it = first; it != last; ++it)
{
auto res = f(*it);
if (it == first || res > max)
{
max = res;
max_it = it;
}
}
return max_it;
}
}
<commit_msg>argmax now returns a pair<iterator, maxvalue><commit_after>#pragma once
#include <cmath>
#include <cassert>
namespace studd
{
// returns an iterator to the element which maximizes the function
template<class InputIt, class UnaryFunction,
class T = typename std::iterator_traits<InputIt>::value_type>
auto argmax(InputIt first, InputIt last, UnaryFunction f)
-> std::pair<InputIt, decltype(f(*first))>
{
assert(std::distance(first, last) > 0);
decltype(f(*first)) max{};
InputIt max_it;
for (auto it = first; it != last; ++it)
{
auto res = f(*it);
if (it == first || res > max)
{
max = res;
max_it = it;
}
}
return std::make_pair(max_it, max);
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "core/sstring.hh"
namespace version {
inline const int native_protocol() {
return 3;
}
inline const sstring& release() {
static sstring v = "2.1.8";
return v;
}
}
<commit_msg>version: do not store current version as a string<commit_after>#pragma once
#include "core/sstring.hh"
#include "core/print.hh"
namespace version {
class version {
uint8_t maj;
uint8_t min;
uint16_t rev;
public:
version(uint8_t x, uint8_t y = 0, uint16_t z = 0): maj(x), min(y), rev(z) {}
sstring to_sstring() {
return sprint("%d.%d.%d", maj, min, rev);
}
static version current() {
static version v(2, 1, 8);
return v;
}
bool operator==(version v) const {
return (maj == v.maj) && (min == v.min) && (rev == v.rev);
}
bool operator!=(version v) const {
return !(v == *this);
}
bool operator<(version v) const {
if (maj < v.maj) {
return true;
} else if (maj > v.maj) {
return false;
}
if (min < v.min) {
return true;
} else if (min > v.min) {
return false;
}
return rev < v.rev;
}
bool operator<=(version v) {
return ((*this < v) || (*this == v));
}
bool operator>(version v) {
return !(*this <= v);
}
bool operator>=(version v) {
return ((*this == v) || !(*this < v));
}
};
inline const int native_protocol() {
return 3;
}
inline const sstring& release() {
static thread_local auto str_ver = version::current().to_sstring();
return str_ver;
}
}
<|endoftext|> |
<commit_before>/*
* sql_tests.cpp
*/
#include "SQLParser.h"
#include <stdio.h>
#include <string>
#include <cassert>
#include <thread>
#include <time.h>
#define STREQUALS(str1, str2) std::string(str1).compare(std::string(str2)) == 0
#define ASSERT(cond) if (!(cond)) { fprintf(stderr, "failed! Assertion (" #cond ")\n"); return; }
#define ASSERT_STR(STR1, STR2) ASSERT(STREQUALS(STR1, STR2));
void SelectTest1() {
printf("Test: SelectTest1... "); fflush(stdout);
const char* sql = "SELECT age, name, address from table WHERE age < 12.5;";
Statement* sqlStatement = SQLParser::parseSQLString(sql);
ASSERT(sqlStatement != NULL);
ASSERT(sqlStatement->type == eSelect);
SelectStatement* stmt = (SelectStatement*) sqlStatement;
ASSERT(stmt->select_list->size() == 3);
ASSERT_STR(stmt->select_list->at(0)->name, "age");
ASSERT_STR(stmt->select_list->at(1)->name, "name");
ASSERT_STR(stmt->select_list->at(2)->name, "address");
ASSERT(stmt->from_table != NULL);
ASSERT(stmt->from_table->type == eTableName);
ASSERT_STR(stmt->from_table->table_names->at(0), "table");
// WHERE
ASSERT(stmt->where_clause != NULL);
ASSERT(stmt->where_clause->expr->type == eExprColumnRef);
ASSERT_STR(stmt->where_clause->expr->name, "age");
ASSERT(stmt->where_clause->pred_type == SQL_LESS);
ASSERT(stmt->where_clause->expr2->type == eExprLiteralFloat);
ASSERT(stmt->where_clause->expr2->float_literal == 12.5);
printf("passed!\n");
}
void SelectTest2() {
printf("Test: SelectTest2... "); fflush(stdout);
const char* sql = "SELECT * FROM (SELECT age FROM table, table2);";
Statement* stmt = SQLParser::parseSQLString(sql);
ASSERT(stmt != NULL);
ASSERT(stmt->type == eSelect);
SelectStatement* select = (SelectStatement*) stmt;
ASSERT(select->select_list->size() == 1);
ASSERT(select->select_list->at(0)->type == eExprStar);
ASSERT(select->from_table != NULL);
ASSERT(select->from_table->type == eTableSelect);
ASSERT(select->from_table->stmt != NULL);
ASSERT(select->from_table->stmt->select_list->size() == 1);
ASSERT_STR(select->from_table->stmt->from_table->table_names->at(0), "table");
ASSERT_STR(select->from_table->stmt->from_table->table_names->at(1), "table2");
printf("passed!\n");
}
uint parse_count = 0;
uint conflicts = 0;
void SelectTest3(bool print) {
if (print) { printf("Test: SelectTest3... "); fflush(stdout); }
const char* sql = "SELECT name, AVG(age) FROM table GROUP BY name";
parse_count++;
Statement* stmt = SQLParser::parseSQLString(sql);
if (parse_count != 1) conflicts++;
parse_count--;
ASSERT(stmt != NULL);
ASSERT(stmt->type == eSelect);
SelectStatement* select = (SelectStatement*) stmt;
ASSERT(select->select_list->size() == 2);
ASSERT(select->select_list->at(0)->type == eExprColumnRef);
ASSERT(select->select_list->at(1)->type == eExprFunctionRef);
ASSERT_STR("name", select->select_list->at(0)->name);
ASSERT(select->group_by != NULL);
ASSERT(select->group_by->size() == 1);
ASSERT_STR("name", select->group_by->at(0)->name);
if (print) printf("passed!\n");
}
/** Multithread Test **/
void multithreadTest(int numberOfRuns, int id) {
for (int n = 0; n < numberOfRuns; ++n) {
SelectTest3(false);
}
}
void ThreadSafeTest(uint numThreads, uint runsPerThread) {
printf("Multithread-Test... ");
conflicts = 0;
std::thread* threads = new std::thread[numThreads];
for (int n = 0; n < numThreads; ++n) {
threads[n] = std::thread(multithreadTest, runsPerThread, n);
}
for (int n = 0; n < numThreads; ++n) {
threads[n].join();
}
printf("there were %u concurrent parses... ", conflicts);
printf("finished!\n");
}
/** Performance Test **/
void Benchmark1(uint numRuns) {
printf("Benchmarking... ");
clock_t start, end;
const char* sql = "SELECT SUM(age), name, address FROM (SELECT age FROM (SELECT age FROM (SELECT age FROM table, table2))) WHERE income > 10 GROUP BY age;";
start = clock();
for (uint n = 0; n < numRuns; ++n) {
Statement* stmt = SQLParser::parseSQLString(sql);
}
end = clock();
long diff = end-start;
printf("Total Time: %ld ticks (~%.4fms)\n", diff, 1000.0*diff/CLOCKS_PER_SEC);
printf("Time per exec: ~%.2f ticks (~%.4fms)\n", (double)diff/numRuns, (1000.0*diff/numRuns)/CLOCKS_PER_SEC);
printf("Benchmarking done!\n");
}
int main(int argc, char *argv[]) {
printf("\n######################################\n");
printf("## Running all tests...\n\n");
SelectTest1();
SelectTest2();
SelectTest3(true);
ThreadSafeTest(10, 1000);
Benchmark1(10000);
printf("\n## Finished running all tests...\n");
printf("######################################\n");
return 0;
}
<commit_msg>tests fix<commit_after>/*
* sql_tests.cpp
*/
#include "SQLParser.h"
#include <stdio.h>
#include <string>
#include <cassert>
#include <thread>
#include <time.h>
#define STREQUALS(str1, str2) std::string(str1).compare(std::string(str2)) == 0
#define ASSERT(cond) if (!(cond)) { fprintf(stderr, "failed! Assertion (" #cond ")\n"); return; }
#define ASSERT_STR(STR1, STR2) ASSERT(STREQUALS(STR1, STR2));
void SelectTest1() {
printf("Test: SelectTest1... "); fflush(stdout);
const char* sql = "SELECT age, name, address from table WHERE age < 12.5;";
Statement* sqlStatement = SQLParser::parseSQLString(sql);
ASSERT(sqlStatement != NULL);
ASSERT(sqlStatement->type == eSelect);
SelectStatement* stmt = (SelectStatement*) sqlStatement;
ASSERT(stmt->select_list->size() == 3);
ASSERT_STR(stmt->select_list->at(0)->name, "age");
ASSERT_STR(stmt->select_list->at(1)->name, "name");
ASSERT_STR(stmt->select_list->at(2)->name, "address");
ASSERT(stmt->from_table != NULL);
ASSERT(stmt->from_table->type == eTableName);
ASSERT_STR(stmt->from_table->name, "table");
// WHERE
ASSERT(stmt->where_clause != NULL);
ASSERT(stmt->where_clause->expr->type == eExprColumnRef);
ASSERT_STR(stmt->where_clause->expr->name, "age");
ASSERT(stmt->where_clause->pred_type == SQL_LESS);
ASSERT(stmt->where_clause->expr2->type == eExprLiteralFloat);
ASSERT(stmt->where_clause->expr2->float_literal == 12.5);
printf("passed!\n");
}
void SelectTest2() {
printf("Test: SelectTest2... "); fflush(stdout);
const char* sql = "SELECT * FROM (SELECT age FROM table, table2);";
Statement* stmt = SQLParser::parseSQLString(sql);
ASSERT(stmt != NULL);
ASSERT(stmt->type == eSelect);
SelectStatement* select = (SelectStatement*) stmt;
ASSERT(select->select_list->size() == 1);
ASSERT(select->select_list->at(0)->type == eExprStar);
ASSERT(select->from_table != NULL);
ASSERT(select->from_table->type == eTableSelect);
ASSERT(select->from_table->stmt != NULL);
ASSERT(select->from_table->stmt->select_list->size() == 1);
ASSERT(select->from_table->stmt->from_table->type == eTableCrossProduct);
// ASSERT_STR(select->from_table->stmt->from_table->table_names->at(0), "table");
// ASSERT_STR(select->from_table->stmt->from_table->table_names->at(1), "table2");
printf("passed!\n");
}
uint parse_count = 0;
uint conflicts = 0;
void SelectTest3(bool print) {
if (print) { printf("Test: SelectTest3... "); fflush(stdout); }
const char* sql = "SELECT name, AVG(age) FROM table GROUP BY name";
parse_count++;
Statement* stmt = SQLParser::parseSQLString(sql);
if (parse_count != 1) conflicts++;
parse_count--;
ASSERT(stmt != NULL);
ASSERT(stmt->type == eSelect);
SelectStatement* select = (SelectStatement*) stmt;
ASSERT(select->select_list->size() == 2);
ASSERT(select->select_list->at(0)->type == eExprColumnRef);
ASSERT(select->select_list->at(1)->type == eExprFunctionRef);
ASSERT_STR("name", select->select_list->at(0)->name);
ASSERT(select->group_by != NULL);
ASSERT(select->group_by->size() == 1);
ASSERT_STR("name", select->group_by->at(0)->name);
if (print) printf("passed!\n");
}
/** Multithread Test **/
void multithreadTest(int numberOfRuns, int id) {
for (int n = 0; n < numberOfRuns; ++n) {
SelectTest3(false);
}
}
void ThreadSafeTest(uint numThreads, uint runsPerThread) {
printf("Multithread-Test... ");
conflicts = 0;
std::thread* threads = new std::thread[numThreads];
for (int n = 0; n < numThreads; ++n) {
threads[n] = std::thread(multithreadTest, runsPerThread, n);
}
for (int n = 0; n < numThreads; ++n) {
threads[n].join();
}
printf("there were %u concurrent parses... ", conflicts);
printf("finished!\n");
}
/** Performance Test **/
void Benchmark1(uint numRuns) {
printf("Benchmarking... ");
clock_t start, end;
const char* sql = "SELECT SUM(age), name, address FROM (SELECT age FROM (SELECT age FROM (SELECT age FROM table, table2))) WHERE income > 10 GROUP BY age;";
start = clock();
for (uint n = 0; n < numRuns; ++n) {
Statement* stmt = SQLParser::parseSQLString(sql);
}
end = clock();
long diff = end-start;
printf("Total Time: %ld ticks (~%.4fms)\n", diff, 1000.0*diff/CLOCKS_PER_SEC);
printf("Time per exec: ~%.2f ticks (~%.4fms)\n", (double)diff/numRuns, (1000.0*diff/numRuns)/CLOCKS_PER_SEC);
printf("Benchmarking done!\n");
}
int main(int argc, char *argv[]) {
printf("\n######################################\n");
printf("## Running all tests...\n\n");
SelectTest1();
SelectTest2();
SelectTest3(true);
ThreadSafeTest(10, 1000);
Benchmark1(10000);
printf("\n## Finished running all tests...\n");
printf("######################################\n");
return 0;
}
<|endoftext|> |
<commit_before>#include "s3.h"
using namespace himan;
#ifdef HAVE_S3
#include "debug.h"
#include "timer.h"
#include "util.h"
#include <iostream>
#include <libs3.h>
#include <mutex>
#include <string.h> // memcpy
namespace
{
static std::once_flag oflag;
const char* access_key = 0;
const char* secret_key = 0;
const char* security_token = 0;
S3Protocol protocol = S3ProtocolHTTP;
thread_local S3Status statusG = S3StatusOK;
void CheckS3Error(S3Status errarg, const char* file, const int line);
#define S3_CHECK(errarg) CheckS3Error(errarg, __FILE__, __LINE__)
std::vector<std::string> GetBucketAndFileName(const std::string& fullFileName)
{
std::vector<std::string> ret;
auto fileName = fullFileName;
// strip protocol from string if it's there
const auto pos = fullFileName.find("s3://");
if (pos != std::string::npos)
{
fileName = fileName.erase(pos, 5);
}
// erase forward slash if exists (s3 buckets can't start with /)
if (fileName[0] == '/')
{
fileName = fileName.erase(0, 1);
}
auto tokens = util::Split(fileName, "/");
ret.push_back(tokens[0]);
tokens.erase(std::begin(tokens), std::begin(tokens) + 1);
std::string key;
for (const auto& piece : tokens)
{
if (!key.empty())
{
key += "/";
}
key += piece;
}
ret.push_back(key);
return ret;
}
inline void CheckS3Error(S3Status errarg, const char* file, const int line)
{
if (errarg)
{
std::cerr << "Error at " << file << "(" << line << "): " << S3_get_status_name(errarg) << std::endl;
himan::Abort();
}
}
S3Status responsePropertiesCallback(const S3ResponseProperties* properties, void* callbackData)
{
return S3StatusOK;
}
static void responseCompleteCallback(S3Status status, const S3ErrorDetails* error, void* callbackData)
{
statusG = status;
return;
}
thread_local S3ResponseHandler responseHandler = {&responsePropertiesCallback, &responseCompleteCallback};
static S3Status getObjectDataCallback(int bufferSize, const char* buffer, void* callbackData)
{
himan::buffer* ret = static_cast<himan::buffer*>(callbackData);
ret->data = static_cast<unsigned char*>(realloc(ret->data, ret->length + bufferSize));
memcpy(ret->data + ret->length, buffer, bufferSize);
ret->length += bufferSize;
return S3StatusOK;
}
void Initialize()
{
call_once(oflag, [&]() {
access_key = getenv("S3_ACCESS_KEY_ID");
secret_key = getenv("S3_SECRET_ACCESS_KEY");
security_token = getenv("S3_SESSION_TOKEN");
logger logr("s3");
if (!access_key)
{
logr.Info("Environment variable S3_ACCESS_KEY_ID not defined");
}
if (!secret_key)
{
logr.Info("Environment variable S3_SECRET_ACCESS_KEY not defined");
}
try
{
const auto envproto = himan::util::GetEnv("S3_PROTOCOL");
if (envproto == "https")
{
protocol = S3ProtocolHTTPS;
}
else if (envproto == "http")
{
protocol = S3ProtocolHTTP;
}
else
{
logr.Warning(fmt::format("Unrecognized value found from env variable S3_PROTOCOL: '{}'", envproto));
}
}
catch (const std::invalid_argument& e)
{
}
S3_CHECK(S3_initialize("s3", S3_INIT_ALL, NULL));
});
}
std::string ReadAWSRegionFromHostname(const std::string& hostname)
{
if (hostname.find("amazonaws.com") != std::string::npos)
{
// extract region name from host name, assuming aws hostname like
// s3.us-east-1.amazonaws.com
auto tokens = util::Split(hostname, ".");
logger logr("s3");
if (tokens.size() != 4)
{
logr.Fatal("Hostname does not follow pattern s3.<regionname>.amazonaws.com");
}
else
{
logr.Trace("s3 authentication hostname: " + tokens[1]);
return tokens[1];
}
}
return "";
}
struct write_data
{
himan::buffer buffer;
size_t write_ptr;
};
static int putObjectDataCallback(int bufferSize, char* buffer, void* callbackData)
{
write_data* data = static_cast<write_data*>(callbackData);
int bytesWritten = 0;
if (data->buffer.length)
{
bytesWritten =
static_cast<int>((static_cast<int>(data->buffer.length) > bufferSize) ? bufferSize : data->buffer.length);
memcpy(buffer, data->buffer.data + data->write_ptr, bytesWritten);
data->write_ptr += bytesWritten;
data->buffer.length -= bytesWritten;
}
return bytesWritten;
}
} // namespace
buffer s3::ReadFile(const file_information& fileInformation)
{
Initialize();
logger logr("s3");
S3GetObjectHandler getObjectHandler = {responseHandler, &getObjectDataCallback};
const auto bucketAndFileName = GetBucketAndFileName(fileInformation.file_location);
const auto bucket = bucketAndFileName[0];
const auto key = bucketAndFileName[1];
buffer ret;
#ifdef S3_DEFAULT_REGION
std::string region = ReadAWSRegionFromHostname(fileInformation.file_server);
// clang-format off
S3BucketContext bucketContext =
{
fileInformation.file_server.c_str(),
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token,
region.c_str()
};
#else
// clang-format off
S3BucketContext bucketContext =
{
fileInformation.file_server.c_str(),
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token
};
// clang-format on
#endif
int count = 0;
do
{
if (count > 0)
{
sleep(2 * count);
}
const unsigned long offset = fileInformation.offset.get();
const unsigned long length = fileInformation.length.get();
logr.Debug("Reading from host=" + fileInformation.file_server + " bucket=" + bucket + " key=" + key + " " +
std::to_string(offset) + ":" + std::to_string(length) + " (" + S3_get_status_name(statusG) + ")");
#ifdef S3_DEFAULT_REGION
S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, 0, &getObjectHandler, &ret);
#else
S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, &getObjectHandler, &ret);
#endif
count++;
} while (S3_status_is_retryable(statusG) && count < 3);
switch (statusG)
{
case S3StatusOK:
break;
case S3StatusInternalError:
logr.Error(std::string(S3_get_status_name(statusG)) + ": is there a proxy blocking the connection?");
throw himan::kFileDataNotFound;
case S3StatusFailedToConnect:
logr.Error(std::string(S3_get_status_name(statusG)) + ": is proxy required but not set?");
throw himan::kFileDataNotFound;
case S3StatusErrorInvalidAccessKeyId:
logr.Error(std::string(S3_get_status_name(statusG)) +
": are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?");
throw himan::kFileDataNotFound;
default:
logr.Error(S3_get_status_name(statusG));
throw himan::kFileDataNotFound;
}
if (ret.length == 0)
{
throw himan::kFileDataNotFound;
}
return ret;
}
void s3::WriteObject(const std::string& objectName, const buffer& buff)
{
Initialize();
const auto bucketAndFileName = GetBucketAndFileName(objectName);
const auto bucket = bucketAndFileName[0];
const auto key = bucketAndFileName[1];
const char* host = getenv("S3_HOSTNAME");
logger logr("s3");
if (!host)
{
logr.Fatal("Environment variable S3_HOSTNAME not defined");
himan::Abort();
}
#ifdef S3_DEFAULT_REGION
std::string region = ReadAWSRegionFromHostname(std::string(host));
// clang-format off
S3BucketContext bucketContext =
{
host,
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token,
region.c_str()
};
#else
// clang-format off
S3BucketContext bucketContext =
{
host,
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token
};
#endif
// clang-format on
S3PutObjectHandler putObjectHandler = {responseHandler, &putObjectDataCallback};
write_data data;
data.buffer.data = buff.data;
data.buffer.length = buff.length;
data.write_ptr = 0;
timer t(true);
int count = 0;
do
{
if (count > 0)
{
sleep(2 * count);
}
logr.Debug("Writing to host=" + std::string(host) + " bucket=" + bucket + " key=" + key + " (" +
S3_get_status_name(statusG) + ")");
#ifdef S3_DEFAULT_REGION
S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, 0, &putObjectHandler, &data);
#else
S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, &putObjectHandler, &data);
#endif
count++;
} while (S3_status_is_retryable(statusG) && count < 3);
// remove pointer to original buff so that double free doesn't occur
data.buffer.data = 0;
switch (statusG)
{
case S3StatusOK:
{
t.Stop();
const double time = static_cast<double>(t.GetTime());
const double size = util::round(static_cast<double>(buff.length) / 1024. / 1024., 1);
logr.Info("Wrote " + std::to_string(size) + "MB in " + std::to_string(time) + " ms (" +
std::to_string(size / time) + " MB/s)");
}
break;
case S3StatusInternalError:
logr.Error(std::string(S3_get_status_name(statusG)) + ": is there a proxy blocking the connection?");
throw himan::kFileDataNotFound;
case S3StatusFailedToConnect:
logr.Error(std::string(S3_get_status_name(statusG)) + ": is proxy required but not set?");
throw himan::kFileDataNotFound;
case S3StatusErrorInvalidAccessKeyId:
logr.Error(std::string(S3_get_status_name(statusG)) +
": are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?");
throw himan::kFileDataNotFound;
default:
logr.Error(S3_get_status_name(statusG));
throw himan::kFileDataNotFound;
}
}
#else
buffer s3::ReadFile(const file_information& fileInformation)
{
throw std::runtime_error("S3 support not compiled");
}
void s3::WriteObject(const std::string& objectName, const buffer& buff)
{
throw std::runtime_error("S3 support not compiled");
}
#endif
<commit_msg>Use fmt::format to create strings<commit_after>#include "s3.h"
using namespace himan;
#ifdef HAVE_S3
#include "debug.h"
#include "timer.h"
#include "util.h"
#include <iostream>
#include <libs3.h>
#include <mutex>
#include <string.h> // memcpy
namespace
{
static std::once_flag oflag;
const char* access_key = 0;
const char* secret_key = 0;
const char* security_token = 0;
S3Protocol protocol = S3ProtocolHTTP;
thread_local S3Status statusG = S3StatusOK;
void CheckS3Error(S3Status errarg, const char* file, const int line);
#define S3_CHECK(errarg) CheckS3Error(errarg, __FILE__, __LINE__)
void HandleS3Error(himan::logger& logr)
{
switch (statusG)
{
case S3StatusInternalError:
logr.Error(fmt::format("{}: is there a proxy blocking the connection?", S3_get_status_name(statusG)));
throw himan::kFileDataNotFound;
case S3StatusFailedToConnect:
logr.Error(fmt::format("{}: is proxy required but not set?", S3_get_status_name(statusG)));
throw himan::kFileDataNotFound;
case S3StatusErrorInvalidAccessKeyId:
logr.Error(fmt::format(
"{}: are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?",
S3_get_status_name(statusG)));
throw himan::kFileDataNotFound;
default:
logr.Error(S3_get_status_name(statusG));
throw himan::kFileDataNotFound;
}
}
std::vector<std::string> GetBucketAndFileName(const std::string& fullFileName)
{
std::vector<std::string> ret;
auto fileName = fullFileName;
// strip protocol from string if it's there
const auto pos = fullFileName.find("s3://");
if (pos != std::string::npos)
{
fileName = fileName.erase(pos, 5);
}
// erase forward slash if exists (s3 buckets can't start with /)
if (fileName[0] == '/')
{
fileName = fileName.erase(0, 1);
}
auto tokens = util::Split(fileName, "/");
ret.push_back(tokens[0]);
tokens.erase(std::begin(tokens), std::begin(tokens) + 1);
std::string key;
for (const auto& piece : tokens)
{
if (!key.empty())
{
key += "/";
}
key += piece;
}
ret.push_back(key);
return ret;
}
inline void CheckS3Error(S3Status errarg, const char* file, const int line)
{
if (errarg)
{
std::cerr << "Error at " << file << "(" << line << "): " << S3_get_status_name(errarg) << std::endl;
himan::Abort();
}
}
S3Status responsePropertiesCallback(const S3ResponseProperties* properties, void* callbackData)
{
return S3StatusOK;
}
static void responseCompleteCallback(S3Status status, const S3ErrorDetails* error, void* callbackData)
{
statusG = status;
return;
}
thread_local S3ResponseHandler responseHandler = {&responsePropertiesCallback, &responseCompleteCallback};
static S3Status getObjectDataCallback(int bufferSize, const char* buffer, void* callbackData)
{
himan::buffer* ret = static_cast<himan::buffer*>(callbackData);
ret->data = static_cast<unsigned char*>(realloc(ret->data, ret->length + bufferSize));
memcpy(ret->data + ret->length, buffer, bufferSize);
ret->length += bufferSize;
return S3StatusOK;
}
void Initialize()
{
call_once(oflag, [&]() {
access_key = getenv("S3_ACCESS_KEY_ID");
secret_key = getenv("S3_SECRET_ACCESS_KEY");
security_token = getenv("S3_SESSION_TOKEN");
logger logr("s3");
if (!access_key)
{
logr.Info("Environment variable S3_ACCESS_KEY_ID not defined");
}
if (!secret_key)
{
logr.Info("Environment variable S3_SECRET_ACCESS_KEY not defined");
}
try
{
const auto envproto = himan::util::GetEnv("S3_PROTOCOL");
if (envproto == "https")
{
protocol = S3ProtocolHTTPS;
}
else if (envproto == "http")
{
protocol = S3ProtocolHTTP;
}
else
{
logr.Warning(fmt::format("Unrecognized value found from env variable S3_PROTOCOL: '{}'", envproto));
}
}
catch (const std::invalid_argument& e)
{
}
S3_CHECK(S3_initialize("s3", S3_INIT_ALL, NULL));
});
}
std::string ReadAWSRegionFromHostname(const std::string& hostname)
{
if (hostname.find("amazonaws.com") != std::string::npos)
{
// extract region name from host name, assuming aws hostname like
// s3.us-east-1.amazonaws.com
auto tokens = util::Split(hostname, ".");
logger logr("s3");
if (tokens.size() != 4)
{
logr.Fatal("Hostname does not follow pattern s3.<regionname>.amazonaws.com");
}
else
{
logr.Trace(fmt::format("s3 authentication hostname: {}", tokens[1]));
return tokens[1];
}
}
return "";
}
struct write_data
{
himan::buffer buffer;
size_t write_ptr;
};
static int putObjectDataCallback(int bufferSize, char* buffer, void* callbackData)
{
write_data* data = static_cast<write_data*>(callbackData);
int bytesWritten = 0;
if (data->buffer.length)
{
bytesWritten =
static_cast<int>((static_cast<int>(data->buffer.length) > bufferSize) ? bufferSize : data->buffer.length);
memcpy(buffer, data->buffer.data + data->write_ptr, bytesWritten);
data->write_ptr += bytesWritten;
data->buffer.length -= bytesWritten;
}
return bytesWritten;
}
} // namespace
buffer s3::ReadFile(const file_information& fileInformation)
{
Initialize();
logger logr("s3");
S3GetObjectHandler getObjectHandler = {responseHandler, &getObjectDataCallback};
const auto bucketAndFileName = GetBucketAndFileName(fileInformation.file_location);
const auto bucket = bucketAndFileName[0];
const auto key = bucketAndFileName[1];
buffer ret;
#ifdef S3_DEFAULT_REGION
std::string region = ReadAWSRegionFromHostname(fileInformation.file_server);
// clang-format off
S3BucketContext bucketContext =
{
fileInformation.file_server.c_str(),
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token,
region.c_str()
};
#else
// clang-format off
S3BucketContext bucketContext =
{
fileInformation.file_server.c_str(),
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token
};
// clang-format on
#endif
int count = 0;
do
{
if (count > 0)
{
sleep(2 * count);
}
const unsigned long offset = fileInformation.offset.get();
const unsigned long length = fileInformation.length.get();
logr.Debug(fmt::format("Reading from host={} bucket={} key={} {}:{} ({})", fileInformation.file_server, bucket,
key, offset, length, S3_get_status_name(statusG)));
#ifdef S3_DEFAULT_REGION
S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, 0, &getObjectHandler, &ret);
#else
S3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, &getObjectHandler, &ret);
#endif
count++;
} while (S3_status_is_retryable(statusG) && count < 3);
switch (statusG)
{
case S3StatusOK:
break;
default:
HandleS3Error(logr);
break;
}
if (ret.length == 0)
{
throw himan::kFileDataNotFound;
}
return ret;
}
void s3::WriteObject(const std::string& objectName, const buffer& buff)
{
Initialize();
const auto bucketAndFileName = GetBucketAndFileName(objectName);
const auto bucket = bucketAndFileName[0];
const auto key = bucketAndFileName[1];
const char* host = getenv("S3_HOSTNAME");
logger logr("s3");
if (!host)
{
logr.Fatal("Environment variable S3_HOSTNAME not defined");
himan::Abort();
}
#ifdef S3_DEFAULT_REGION
std::string region = ReadAWSRegionFromHostname(std::string(host));
// clang-format off
S3BucketContext bucketContext =
{
host,
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token,
region.c_str()
};
#else
// clang-format off
S3BucketContext bucketContext =
{
host,
bucket.c_str(),
protocol,
S3UriStylePath,
access_key,
secret_key,
security_token
};
#endif
// clang-format on
S3PutObjectHandler putObjectHandler = {responseHandler, &putObjectDataCallback};
write_data data;
data.buffer.data = buff.data;
data.buffer.length = buff.length;
data.write_ptr = 0;
timer t(true);
int count = 0;
do
{
if (count > 0)
{
sleep(2 * count);
}
logr.Debug(
fmt::format("Writing to host={} bucket={} key={} ({})", host, bucket, key, S3_get_status_name(statusG)));
#ifdef S3_DEFAULT_REGION
S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, 0, &putObjectHandler, &data);
#else
S3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, &putObjectHandler, &data);
#endif
count++;
} while (S3_status_is_retryable(statusG) && count < 3);
// remove pointer to original buff so that double free doesn't occur
data.buffer.data = 0;
switch (statusG)
{
case S3StatusOK:
{
t.Stop();
const double time = static_cast<double>(t.GetTime());
const double size = util::round(static_cast<double>(buff.length) / 1024. / 1024., 1);
logr.Info("Wrote " + std::to_string(size) + "MB in " + std::to_string(time) + " ms (" +
std::to_string(size / time) + " MB/s)");
}
break;
default:
HandleS3Error(logr);
break;
}
}
#else
buffer s3::ReadFile(const file_information& fileInformation)
{
throw std::runtime_error("S3 support not compiled");
}
void s3::WriteObject(const std::string& objectName, const buffer& buff)
{
throw std::runtime_error("S3 support not compiled");
}
#endif
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <vector>
#include <cmath>
#include <string>
#include "common/input_output.h"
using std::cout;
using std::endl;
// all dimensions are in millimeters, milligrams
real container_width = 5; // width of area with particles
real container_length = 25; // length of area that roller will go over 1194mm maximum
real container_thickness = .25; // thickness of container walls
real container_height = 2; // height of the outer walls
real container_friction = 0;
real floor_friction = .2;
real spacer_width = 1;
real spacer_height = 1;
real roller_overlap = 1; // amount that roller goes over the container area
real roller_length = 2.5 - .25; // length of the roller
real roller_radius = 76.2 / 2.0; // radius of roller
real roller_omega = 0;
real roller_velocity = -127;
real roller_mass = 1;
real roller_friction = .1;
real roller_cohesion = 0;
real particle_radius = .058 / 2.0;
real particle_std_dev = .015 / 2.0;
real particle_mass = .05;
real particle_density = 0.93;
real particle_layer_thickness = particle_radius * 16;
real particle_friction = .52;
real rolling_friction = .1;
real spinning_friction = .1;
real gravity = -9810; // acceleration due to gravity
// step size which will not allow interpenetration more than 1/6 of smallest radius
real timestep = ((particle_radius - particle_std_dev) / 3.0) / roller_velocity;
// real timestep = .00005; // step size
real time_end = 1; // length of simulation
real current_time = 0;
int out_fps = 6000;
int out_steps = std::ceil((1.0 / timestep) / out_fps);
int num_steps = time_end / timestep;
int max_iteration = 15;
int tolerance = 1e-8;
std::string data_output_path = "data_sls";
std::shared_ptr<ChBody> ROLLER;
real ang = 0;
template <class T>
void RunTimeStep(T* mSys, const int frame) {
ChVector<> roller_pos = ROLLER->GetPos();
ROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness,
roller_pos.z + roller_velocity * timestep));
ROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity));
roller_omega = roller_velocity / roller_radius;
ang += roller_omega * timestep;
if (ang >= 2 * CH_C_PI) {
ang = 0;
}
Quaternion q1;
q1.Q_from_AngY(ang);
Quaternion q2;
q1 = Q_from_AngX(-ang);
ChQuaternion<> roller_quat;
roller_quat.Q_from_AngAxis(CH_C_PI / 2.0, ChVector<>(0, 0, 1));
ROLLER->SetRot(q1 % roller_quat);
ROLLER->SetWvel_loc(Vector(0, roller_omega, 0));
cout << "step " << frame << " " << ROLLER->GetPos().z << "\n";
}
int main(int argc, char* argv[]) {
real roller_start = container_length + roller_radius / 3.0;
time_end = (roller_start) / Abs(roller_velocity);
printf("Time to run: %f %f\n", roller_start, time_end);
num_steps = time_end / timestep;
ChSystemParallelDVI* system = new ChSystemParallelDVI;
system->Set_G_acc(ChVector<>(0, gravity, 0));
system->SetIntegrationType(ChSystem::INT_ANITESCU);
system->GetSettings()->min_threads = 8;
system->GetSettings()->solver.tolerance = tolerance;
system->GetSettings()->solver.solver_mode = SPINNING;
system->GetSettings()->solver.max_iteration_normal = max_iteration;
system->GetSettings()->solver.max_iteration_sliding = max_iteration;
system->GetSettings()->solver.max_iteration_spinning = max_iteration;
system->GetSettings()->solver.max_iteration_bilateral = 0; // make 1000, should be about 220
system->GetSettings()->solver.compute_N = false;
system->GetSettings()->solver.alpha = 0;
system->GetSettings()->solver.cache_step_length = true;
system->GetSettings()->solver.use_full_inertia_tensor = false;
system->GetSettings()->solver.contact_recovery_speed = 180;
system->GetSettings()->solver.bilateral_clamp_speed = 1e8;
system->ChangeSolverType(BB);
system->SetLoggingLevel(LOG_INFO);
system->SetLoggingLevel(LOG_TRACE);
system->GetSettings()->collision.collision_envelope = particle_radius * .05;
system->GetSettings()->collision.bins_per_axis = int3(40, 300, 400);
system->GetSettings()->collision.narrowphase_algorithm = NARROWPHASE_HYBRID_MPR;
system->GetSettings()->collision.use_two_level = false;
system->GetSettings()->collision.fixed_bins = true;
auto material_plate = std::make_shared<ChMaterialSurface>();
material_plate->SetFriction(0);
std::shared_ptr<ChBody> PLATE = std::make_shared<ChBody>(new ChCollisionModelParallel);
utils::InitializeObject(PLATE, 100000, material_plate, ChVector<>(0, 0, 0), QUNIT, true, true, 2, 6);
utils::AddBoxGeometry(PLATE.get(), Vector(container_thickness, container_height, container_length),
Vector(-container_width + container_thickness, container_height, 0));
utils::AddBoxGeometry(PLATE.get(), Vector(container_thickness, container_height, container_length),
Vector(container_width - container_thickness, container_height, 0));
utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_height, container_thickness),
Vector(0, container_height, -container_length + container_thickness));
utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_height, container_thickness),
Vector(0, container_height, container_length - container_thickness));
utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_thickness, container_length),
Vector(0, container_height * 2, 0));
FinalizeObject(PLATE, (ChSystemParallel*)system);
auto material_bottom = std::make_shared<ChMaterialSurface>();
material_bottom->SetFriction(floor_friction);
std::shared_ptr<ChBody> BOTTOM = std::make_shared<ChBody>(new ChCollisionModelParallel);
utils::InitializeObject(BOTTOM, 100000, material_bottom, ChVector<>(0, 0, 0), QUNIT, true, true, 2, 6);
utils::AddBoxGeometry(BOTTOM.get(), ChVector<>(container_width, container_thickness, container_length));
FinalizeObject(BOTTOM, (ChSystemParallel*)system);
ROLLER = std::make_shared<ChBody>(new ChCollisionModelParallel);
ChQuaternion<> roller_quat;
roller_quat.Q_from_AngAxis(CH_C_PI / 2.0, ChVector<>(0, 0, 1));
auto material_roller = std::make_shared<ChMaterialSurface>();
material_roller->SetFriction(roller_friction);
utils::InitializeObject(ROLLER, 100000, material_roller,
ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_start),
roller_quat, true, false, 6, 6);
utils::AddCylinderGeometry(ROLLER.get(), roller_radius, roller_length * 2);
FinalizeObject(ROLLER, (ChSystemParallel*)system);
auto material_granular = std::make_shared<ChMaterialSurface>();
material_granular->SetFriction(particle_friction);
material_granular->SetRollingFriction(rolling_friction);
material_granular->SetSpinningFriction(spinning_friction);
utils::Generator* gen = new utils::Generator(system);
std::shared_ptr<MixtureIngredient>& m1 = gen->AddMixtureIngredient(utils::SPHERE, 1);
m1->setDefaultSize(particle_radius);
m1->setDefaultDensity(particle_density);
m1->setDistributionSize(particle_radius, particle_std_dev, particle_radius - particle_std_dev,
particle_radius + particle_std_dev);
m1->setDefaultMaterialDVI(material_granular);
gen->createObjectsBox(utils::HCP_PACK, (particle_radius + particle_std_dev) * 2, ChVector<>(0, 1.0, 0),
ChVector<>(container_width * .9, particle_layer_thickness, container_length * .9));
#if 0
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
gl_window.Initialize(1280, 720, "Bucky", system);
gl_window.SetCamera(ChVector<>(0, 0, -10), ChVector<>(0, 0, 0), ChVector<>(0, 1, 0), 0.1);
gl_window.Pause();
int frame = 0;
while (frame < num_steps) {
if (gl_window.Active()) {
if (gl_window.DoStepDynamics(timestep)) {
// TimingOutput(system);
RunTimeStep(system, frame);
frame++;
}
gl_window.Render();
} else {
exit(0);
}
}
#else
double time = 0, exec_time = 0;
int sim_frame = 0, out_frame = 0, next_out_frame = 0;
while (time < time_end) {
system->DoStepDynamics(timestep);
if (sim_frame == next_out_frame) {
std::cout << "write: " << out_frame << std::endl;
DumpAllObjectsWithGeometryPovray(system, data_output_path + "data_" + std::to_string(out_frame) + ".dat",
true);
out_frame++;
next_out_frame += out_steps;
}
RunTimeStep(system, sim_frame);
// Update counters.
time += timestep;
sim_frame++;
exec_time += system->GetTimerStep();
}
cout << "==================================" << endl;
cout << "Simulation time: " << exec_time << endl;
#endif
}
<commit_msg>Make sure tilmestep doesn't become negative if velocity is negative<commit_after>#include <stdio.h>
#include <vector>
#include <cmath>
#include <string>
#include "common/input_output.h"
using std::cout;
using std::endl;
// all dimensions are in millimeters, milligrams
real container_width = 5; // width of area with particles
real container_length = 25; // length of area that roller will go over 1194mm maximum
real container_thickness = .25; // thickness of container walls
real container_height = 2; // height of the outer walls
real container_friction = 0;
real floor_friction = .2;
real spacer_width = 1;
real spacer_height = 1;
real roller_overlap = 1; // amount that roller goes over the container area
real roller_length = 2.5 - .25; // length of the roller
real roller_radius = 76.2 / 2.0; // radius of roller
real roller_omega = 0;
real roller_velocity = -127;
real roller_mass = 1;
real roller_friction = .1;
real roller_cohesion = 0;
real particle_radius = .058 / 2.0;
real particle_std_dev = .015 / 2.0;
real particle_mass = .05;
real particle_density = 0.93;
real particle_layer_thickness = particle_radius * 16;
real particle_friction = .52;
real rolling_friction = .1;
real spinning_friction = .1;
real gravity = -9810; // acceleration due to gravity
// step size which will not allow interpenetration more than 1/6 of smallest radius
real timestep = Abs(((particle_radius - particle_std_dev) / 3.0) / roller_velocity);
// real timestep = .00005; // step size
real time_end = 1; // length of simulation
real current_time = 0;
int out_fps = 6000;
int out_steps = std::ceil((1.0 / timestep) / out_fps);
int num_steps = time_end / timestep;
int max_iteration = 15;
int tolerance = 1e-8;
std::string data_output_path = "data_sls";
std::shared_ptr<ChBody> ROLLER;
real ang = 0;
template <class T>
void RunTimeStep(T* mSys, const int frame) {
ChVector<> roller_pos = ROLLER->GetPos();
ROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness,
roller_pos.z + roller_velocity * timestep));
ROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity));
roller_omega = roller_velocity / roller_radius;
ang += roller_omega * timestep;
if (ang >= 2 * CH_C_PI) {
ang = 0;
}
Quaternion q1;
q1.Q_from_AngY(ang);
Quaternion q2;
q1 = Q_from_AngX(-ang);
ChQuaternion<> roller_quat;
roller_quat.Q_from_AngAxis(CH_C_PI / 2.0, ChVector<>(0, 0, 1));
ROLLER->SetRot(q1 % roller_quat);
ROLLER->SetWvel_loc(Vector(0, roller_omega, 0));
cout << "step " << frame << " " << ROLLER->GetPos().z << "\n";
}
int main(int argc, char* argv[]) {
real roller_start = container_length + roller_radius / 3.0;
time_end = (roller_start) / Abs(roller_velocity);
printf("Time to run: %f %f\n", roller_start, time_end);
num_steps = time_end / timestep;
ChSystemParallelDVI* system = new ChSystemParallelDVI;
system->Set_G_acc(ChVector<>(0, gravity, 0));
system->SetIntegrationType(ChSystem::INT_ANITESCU);
system->GetSettings()->min_threads = 8;
system->GetSettings()->solver.tolerance = tolerance;
system->GetSettings()->solver.solver_mode = SPINNING;
system->GetSettings()->solver.max_iteration_normal = max_iteration;
system->GetSettings()->solver.max_iteration_sliding = max_iteration;
system->GetSettings()->solver.max_iteration_spinning = max_iteration;
system->GetSettings()->solver.max_iteration_bilateral = 0; // make 1000, should be about 220
system->GetSettings()->solver.compute_N = false;
system->GetSettings()->solver.alpha = 0;
system->GetSettings()->solver.cache_step_length = true;
system->GetSettings()->solver.use_full_inertia_tensor = false;
system->GetSettings()->solver.contact_recovery_speed = 180;
system->GetSettings()->solver.bilateral_clamp_speed = 1e8;
system->ChangeSolverType(BB);
system->SetLoggingLevel(LOG_INFO);
system->SetLoggingLevel(LOG_TRACE);
system->GetSettings()->collision.collision_envelope = particle_radius * .05;
system->GetSettings()->collision.bins_per_axis = int3(40, 300, 400);
system->GetSettings()->collision.narrowphase_algorithm = NARROWPHASE_HYBRID_MPR;
system->GetSettings()->collision.use_two_level = false;
system->GetSettings()->collision.fixed_bins = true;
auto material_plate = std::make_shared<ChMaterialSurface>();
material_plate->SetFriction(0);
std::shared_ptr<ChBody> PLATE = std::make_shared<ChBody>(new ChCollisionModelParallel);
utils::InitializeObject(PLATE, 100000, material_plate, ChVector<>(0, 0, 0), QUNIT, true, true, 2, 6);
utils::AddBoxGeometry(PLATE.get(), Vector(container_thickness, container_height, container_length),
Vector(-container_width + container_thickness, container_height, 0));
utils::AddBoxGeometry(PLATE.get(), Vector(container_thickness, container_height, container_length),
Vector(container_width - container_thickness, container_height, 0));
utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_height, container_thickness),
Vector(0, container_height, -container_length + container_thickness));
utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_height, container_thickness),
Vector(0, container_height, container_length - container_thickness));
utils::AddBoxGeometry(PLATE.get(), Vector(container_width, container_thickness, container_length),
Vector(0, container_height * 2, 0));
FinalizeObject(PLATE, (ChSystemParallel*)system);
auto material_bottom = std::make_shared<ChMaterialSurface>();
material_bottom->SetFriction(floor_friction);
std::shared_ptr<ChBody> BOTTOM = std::make_shared<ChBody>(new ChCollisionModelParallel);
utils::InitializeObject(BOTTOM, 100000, material_bottom, ChVector<>(0, 0, 0), QUNIT, true, true, 2, 6);
utils::AddBoxGeometry(BOTTOM.get(), ChVector<>(container_width, container_thickness, container_length));
FinalizeObject(BOTTOM, (ChSystemParallel*)system);
ROLLER = std::make_shared<ChBody>(new ChCollisionModelParallel);
ChQuaternion<> roller_quat;
roller_quat.Q_from_AngAxis(CH_C_PI / 2.0, ChVector<>(0, 0, 1));
auto material_roller = std::make_shared<ChMaterialSurface>();
material_roller->SetFriction(roller_friction);
utils::InitializeObject(ROLLER, 100000, material_roller,
ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_start),
roller_quat, true, false, 6, 6);
utils::AddCylinderGeometry(ROLLER.get(), roller_radius, roller_length * 2);
FinalizeObject(ROLLER, (ChSystemParallel*)system);
auto material_granular = std::make_shared<ChMaterialSurface>();
material_granular->SetFriction(particle_friction);
material_granular->SetRollingFriction(rolling_friction);
material_granular->SetSpinningFriction(spinning_friction);
utils::Generator* gen = new utils::Generator(system);
std::shared_ptr<MixtureIngredient>& m1 = gen->AddMixtureIngredient(utils::SPHERE, 1);
m1->setDefaultSize(particle_radius);
m1->setDefaultDensity(particle_density);
m1->setDistributionSize(particle_radius, particle_std_dev, particle_radius - particle_std_dev,
particle_radius + particle_std_dev);
m1->setDefaultMaterialDVI(material_granular);
gen->createObjectsBox(utils::HCP_PACK, (particle_radius + particle_std_dev) * 2, ChVector<>(0, 1.0, 0),
ChVector<>(container_width * .9, particle_layer_thickness, container_length * .9));
#if 0
opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance();
gl_window.Initialize(1280, 720, "Bucky", system);
gl_window.SetCamera(ChVector<>(0, 0, -10), ChVector<>(0, 0, 0), ChVector<>(0, 1, 0), 0.1);
gl_window.Pause();
int frame = 0;
while (frame < num_steps) {
if (gl_window.Active()) {
if (gl_window.DoStepDynamics(timestep)) {
// TimingOutput(system);
RunTimeStep(system, frame);
frame++;
}
gl_window.Render();
} else {
exit(0);
}
}
#else
double time = 0, exec_time = 0;
int sim_frame = 0, out_frame = 0, next_out_frame = 0;
while (time < time_end) {
system->DoStepDynamics(timestep);
if (sim_frame == next_out_frame) {
std::cout << "write: " << out_frame << std::endl;
DumpAllObjectsWithGeometryPovray(system, data_output_path + "data_" + std::to_string(out_frame) + ".dat",
true);
out_frame++;
next_out_frame += out_steps;
}
RunTimeStep(system, sim_frame);
// Update counters.
time += timestep;
sim_frame++;
exec_time += system->GetTimerStep();
}
cout << "==================================" << endl;
cout << "Simulation time: " << exec_time << endl;
#endif
}
<|endoftext|> |
<commit_before>#include "waypoint_serializer.h"
#include "swganh_core/object/waypoint/waypoint.h"
#include "swganh/crc.h"
using namespace swganh::object;
void PlayerWaypointSerializer::SerializeBaseline(swganh::ByteBuffer& data, const PlayerWaypointSerializer& t)
{
data.write<uint64_t>(t.waypoint->GetObjectId());
data.write<uint32_t>(0);
auto coordinates_ = t.waypoint->GetCoordinates();
data.write<float>(coordinates_.x);
data.write<float>(coordinates_.y);
data.write<float>(coordinates_.z);
data.write<uint64_t>(0);
data.write<uint32_t>(swganh::memcrc(t.waypoint->GetPlanet()));
data.write<std::wstring>(t.waypoint->GetName());
data.write<uint64_t>(t.waypoint->GetObjectId());
data.write<uint8_t>(t.waypoint->GetColor());
data.write<uint8_t>(t.waypoint->Active() ? 1 : 0);
}
void PlayerWaypointSerializer::SerializeDelta(swganh::ByteBuffer& data, const PlayerWaypointSerializer& t)
{
data.write<uint32_t>(0);
auto coordinates_ = t.waypoint->GetCoordinates();
data.write<float>(coordinates_.x);
data.write<float>(coordinates_.y);
data.write<float>(coordinates_.z);
data.write<uint64_t>(0);
data.write<uint32_t>(swganh::memcrc(t.waypoint->GetPlanet()));
data.write<std::wstring>(t.waypoint->GetName());
data.write<uint64_t>(t.waypoint->GetObjectId());
data.write<uint8_t>(t.waypoint->GetColor());
data.write<uint8_t>(t.waypoint->Active() ? 1 : 0);
}
bool PlayerWaypointSerializer::operator==(const PlayerWaypointSerializer& other)
{
return waypoint->GetObjectId() == other.waypoint->GetObjectId();
}<commit_msg>fixed serialization for player waypoints.<commit_after>#include "waypoint_serializer.h"
#include "swganh_core/object/waypoint/waypoint.h"
#include "swganh/crc.h"
using namespace swganh::object;
void PlayerWaypointSerializer::SerializeBaseline(swganh::ByteBuffer& data, const PlayerWaypointSerializer& t)
{
data.write<uint8_t>(0);
data.write<uint64_t>(t.waypoint->GetObjectId());
data.write<uint32_t>(0);
auto coordinates_ = t.waypoint->GetCoordinates();
data.write<float>(coordinates_.x);
data.write<float>(coordinates_.y);
data.write<float>(coordinates_.z);
data.write<uint64_t>(0);
data.write<uint32_t>(swganh::memcrc(t.waypoint->GetPlanet()));
data.write<std::wstring>(t.waypoint->GetName());
data.write<uint64_t>(t.waypoint->GetObjectId());
data.write<uint8_t>(t.waypoint->GetColor());
data.write<uint8_t>(t.waypoint->Active() ? 1 : 0);
}
void PlayerWaypointSerializer::SerializeDelta(swganh::ByteBuffer& data, const PlayerWaypointSerializer& t)
{
data.write<uint64_t>(t.waypoint->GetObjectId());
data.write<uint32_t>(0);
auto coordinates_ = t.waypoint->GetCoordinates();
data.write<float>(coordinates_.x);
data.write<float>(coordinates_.y);
data.write<float>(coordinates_.z);
data.write<uint64_t>(0);
data.write<uint32_t>(swganh::memcrc(t.waypoint->GetPlanet()));
data.write<std::wstring>(t.waypoint->GetName());
data.write<uint64_t>(t.waypoint->GetObjectId());
data.write<uint8_t>(t.waypoint->GetColor());
data.write<uint8_t>(t.waypoint->Active() ? 1 : 0);
}
bool PlayerWaypointSerializer::operator==(const PlayerWaypointSerializer& other)
{
return waypoint->GetObjectId() == other.waypoint->GetObjectId();
}<|endoftext|> |
<commit_before>/* Copyright 2018 Google Inc. 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 <cstdint>
#include <memory>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "re2/re2.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow_serving/model_servers/http_rest_api_handler.h"
#include "tensorflow_serving/model_servers/http_server.h"
#include "tensorflow_serving/model_servers/server_core.h"
#include "tensorflow_serving/util/net_http/server/public/httpserver.h"
#include "tensorflow_serving/util/net_http/server/public/response_code_enum.h"
#include "tensorflow_serving/util/net_http/server/public/server_request_interface.h"
#include "tensorflow_serving/util/prometheus_exporter.h"
#include "tensorflow_serving/util/threadpool_executor.h"
namespace tensorflow {
namespace serving {
namespace {
net_http::HTTPStatusCode ToHTTPStatusCode(const Status& status) {
using error::Code;
using net_http::HTTPStatusCode;
switch (status.code()) {
case Code::OK:
return HTTPStatusCode::OK;
case Code::CANCELLED:
return HTTPStatusCode::CLIENT_CLOSED_REQUEST;
case Code::UNKNOWN:
return HTTPStatusCode::ERROR;
case Code::INVALID_ARGUMENT:
return HTTPStatusCode::BAD_REQUEST;
case Code::DEADLINE_EXCEEDED:
return HTTPStatusCode::GATEWAY_TO;
case Code::NOT_FOUND:
return HTTPStatusCode::NOT_FOUND;
case Code::ALREADY_EXISTS:
return HTTPStatusCode::CONFLICT;
case Code::PERMISSION_DENIED:
return HTTPStatusCode::FORBIDDEN;
case Code::RESOURCE_EXHAUSTED:
return HTTPStatusCode::TOO_MANY_REQUESTS;
case Code::FAILED_PRECONDITION:
return HTTPStatusCode::BAD_REQUEST;
case Code::ABORTED:
return HTTPStatusCode::CONFLICT;
case Code::OUT_OF_RANGE:
return HTTPStatusCode::BAD_REQUEST;
case Code::UNIMPLEMENTED:
return HTTPStatusCode::NOT_IMP;
case Code::INTERNAL:
return HTTPStatusCode::ERROR;
case Code::UNAVAILABLE:
return HTTPStatusCode::SERVICE_UNAV;
case Code::DATA_LOSS:
return HTTPStatusCode::ERROR;
case Code::UNAUTHENTICATED:
return HTTPStatusCode::UNAUTHORIZED;
case Code::
DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_USE_DEFAULT_IN_SWITCH_INSTEAD_:
case error::Code_INT_MIN_SENTINEL_DO_NOT_USE_:
case error::Code_INT_MAX_SENTINEL_DO_NOT_USE_:
return HTTPStatusCode::ERROR;
}
}
void ProcessPrometheusRequest(PrometheusExporter* exporter,
const PrometheusConfig& prometheus_config,
net_http::ServerRequestInterface* req) {
std::vector<std::pair<string, string>> headers;
headers.push_back({"Content-Type", "text/plain"});
string output;
Status status;
// Check if url matches the path.
if (req->uri_path() != prometheus_config.path()) {
output = absl::StrFormat("Unexpected path: %s. Should be %s",
req->uri_path(), prometheus_config.path());
status = Status(error::Code::INVALID_ARGUMENT, output);
} else {
status = exporter->GeneratePage(&output);
}
const net_http::HTTPStatusCode http_status = ToHTTPStatusCode(status);
// Note: we add headers+output for non successful status too, in case the
// output contains details about the error (e.g. error messages).
for (const auto& kv : headers) {
req->OverwriteResponseHeader(kv.first, kv.second);
}
req->WriteResponseString(output);
if (http_status != net_http::HTTPStatusCode::OK) {
VLOG(1) << "Error Processing prometheus metrics request. Error: "
<< status.ToString();
}
req->ReplyWithStatus(http_status);
}
class RequestExecutor final : public net_http::EventExecutor {
public:
explicit RequestExecutor(int num_threads)
: executor_(Env::Default(), "httprestserver", num_threads) {}
void Schedule(std::function<void()> fn) override { executor_.Schedule(fn); }
private:
ThreadPoolExecutor executor_;
};
class RestApiRequestDispatcher {
public:
RestApiRequestDispatcher(int timeout_in_ms, ServerCore* core)
: regex_(HttpRestApiHandler::kPathRegex) {
RunOptions run_options = RunOptions();
run_options.set_timeout_in_ms(timeout_in_ms);
handler_.reset(new HttpRestApiHandler(run_options, core));
}
net_http::RequestHandler Dispatch(net_http::ServerRequestInterface* req) {
if (RE2::FullMatch(string(req->uri_path()), regex_)) {
return [this](net_http::ServerRequestInterface* req) {
this->ProcessRequest(req);
};
}
VLOG(1) << "Ignoring HTTP request: " << req->http_method() << " "
<< req->uri_path();
return nullptr;
}
private:
void ProcessRequest(net_http::ServerRequestInterface* req) {
string body;
int64_t num_bytes = 0;
auto request_chunk = req->ReadRequestBytes(&num_bytes);
while (request_chunk != nullptr) {
absl::StrAppend(&body, absl::string_view(request_chunk.get(), num_bytes));
request_chunk = req->ReadRequestBytes(&num_bytes);
}
std::vector<std::pair<string, string>> headers;
string output;
VLOG(1) << "Processing HTTP request: " << req->http_method() << " "
<< req->uri_path() << " body: " << body.size() << " bytes.";
const auto status = handler_->ProcessRequest(
req->http_method(), req->uri_path(), body, &headers, &output);
const auto http_status = ToHTTPStatusCode(status);
// Note: we add headers+output for non successful status too, in case the
// output contains details about the error (e.g. error messages).
for (const auto& kv : headers) {
req->OverwriteResponseHeader(kv.first, kv.second);
}
req->WriteResponseString(output);
if (http_status != net_http::HTTPStatusCode::OK) {
VLOG(1) << "Error Processing HTTP/REST request: " << req->http_method()
<< " " << req->uri_path() << " Error: " << status.ToString();
}
req->ReplyWithStatus(http_status);
}
const RE2 regex_;
std::unique_ptr<HttpRestApiHandler> handler_;
};
} // namespace
std::unique_ptr<net_http::HTTPServerInterface> CreateAndStartHttpServer(
int port, int num_threads, int timeout_in_ms,
const MonitoringConfig& monitoring_config, ServerCore* core) {
auto options = absl::make_unique<net_http::ServerOptions>();
options->AddPort(static_cast<uint32_t>(port));
options->SetExecutor(absl::make_unique<RequestExecutor>(num_threads));
auto server = net_http::CreateEvHTTPServer(std::move(options));
if (server == nullptr) {
return nullptr;
}
// Register handler for prometheus metric endpoint.
if (monitoring_config.prometheus_config().enable()) {
std::shared_ptr<PrometheusExporter> exporter =
std::make_shared<PrometheusExporter>();
net_http::RequestHandlerOptions prometheus_request_options;
PrometheusConfig prometheus_config = monitoring_config.prometheus_config();
server->RegisterRequestHandler(
monitoring_config.prometheus_config().path(),
[exporter, prometheus_config](net_http::ServerRequestInterface* req) {
ProcessPrometheusRequest(exporter.get(), prometheus_config, req);
},
prometheus_request_options);
}
std::shared_ptr<RestApiRequestDispatcher> dispatcher =
std::make_shared<RestApiRequestDispatcher>(timeout_in_ms, core);
net_http::RequestHandlerOptions handler_options;
server->RegisterRequestDispatcher(
[dispatcher](net_http::ServerRequestInterface* req) {
return dispatcher->Dispatch(req);
},
handler_options);
if (server->StartAcceptingRequests()) {
return server;
}
return nullptr;
}
} // namespace serving
} // namespace tensorflow
<commit_msg>Fix default path of metrics endpoint<commit_after>/* Copyright 2018 Google Inc. 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 <cstdint>
#include <memory>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "re2/re2.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow_serving/model_servers/http_rest_api_handler.h"
#include "tensorflow_serving/model_servers/http_server.h"
#include "tensorflow_serving/model_servers/server_core.h"
#include "tensorflow_serving/util/net_http/server/public/httpserver.h"
#include "tensorflow_serving/util/net_http/server/public/response_code_enum.h"
#include "tensorflow_serving/util/net_http/server/public/server_request_interface.h"
#include "tensorflow_serving/util/prometheus_exporter.h"
#include "tensorflow_serving/util/threadpool_executor.h"
namespace tensorflow {
namespace serving {
namespace {
net_http::HTTPStatusCode ToHTTPStatusCode(const Status& status) {
using error::Code;
using net_http::HTTPStatusCode;
switch (status.code()) {
case Code::OK:
return HTTPStatusCode::OK;
case Code::CANCELLED:
return HTTPStatusCode::CLIENT_CLOSED_REQUEST;
case Code::UNKNOWN:
return HTTPStatusCode::ERROR;
case Code::INVALID_ARGUMENT:
return HTTPStatusCode::BAD_REQUEST;
case Code::DEADLINE_EXCEEDED:
return HTTPStatusCode::GATEWAY_TO;
case Code::NOT_FOUND:
return HTTPStatusCode::NOT_FOUND;
case Code::ALREADY_EXISTS:
return HTTPStatusCode::CONFLICT;
case Code::PERMISSION_DENIED:
return HTTPStatusCode::FORBIDDEN;
case Code::RESOURCE_EXHAUSTED:
return HTTPStatusCode::TOO_MANY_REQUESTS;
case Code::FAILED_PRECONDITION:
return HTTPStatusCode::BAD_REQUEST;
case Code::ABORTED:
return HTTPStatusCode::CONFLICT;
case Code::OUT_OF_RANGE:
return HTTPStatusCode::BAD_REQUEST;
case Code::UNIMPLEMENTED:
return HTTPStatusCode::NOT_IMP;
case Code::INTERNAL:
return HTTPStatusCode::ERROR;
case Code::UNAVAILABLE:
return HTTPStatusCode::SERVICE_UNAV;
case Code::DATA_LOSS:
return HTTPStatusCode::ERROR;
case Code::UNAUTHENTICATED:
return HTTPStatusCode::UNAUTHORIZED;
case Code::
DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_USE_DEFAULT_IN_SWITCH_INSTEAD_:
case error::Code_INT_MIN_SENTINEL_DO_NOT_USE_:
case error::Code_INT_MAX_SENTINEL_DO_NOT_USE_:
return HTTPStatusCode::ERROR;
}
}
void ProcessPrometheusRequest(PrometheusExporter* exporter,
const string& path,
net_http::ServerRequestInterface* req) {
std::vector<std::pair<string, string>> headers;
headers.push_back({"Content-Type", "text/plain"});
string output;
Status status;
// Check if url matches the path.
if (req->uri_path() != path) {
output = absl::StrFormat("Unexpected path: %s. Should be %s",
req->uri_path(), path);
status = Status(error::Code::INVALID_ARGUMENT, output);
} else {
status = exporter->GeneratePage(&output);
}
const net_http::HTTPStatusCode http_status = ToHTTPStatusCode(status);
// Note: we add headers+output for non successful status too, in case the
// output contains details about the error (e.g. error messages).
for (const auto& kv : headers) {
req->OverwriteResponseHeader(kv.first, kv.second);
}
req->WriteResponseString(output);
if (http_status != net_http::HTTPStatusCode::OK) {
VLOG(1) << "Error Processing prometheus metrics request. Error: "
<< status.ToString();
}
req->ReplyWithStatus(http_status);
}
class RequestExecutor final : public net_http::EventExecutor {
public:
explicit RequestExecutor(int num_threads)
: executor_(Env::Default(), "httprestserver", num_threads) {}
void Schedule(std::function<void()> fn) override { executor_.Schedule(fn); }
private:
ThreadPoolExecutor executor_;
};
class RestApiRequestDispatcher {
public:
RestApiRequestDispatcher(int timeout_in_ms, ServerCore* core)
: regex_(HttpRestApiHandler::kPathRegex) {
RunOptions run_options = RunOptions();
run_options.set_timeout_in_ms(timeout_in_ms);
handler_.reset(new HttpRestApiHandler(run_options, core));
}
net_http::RequestHandler Dispatch(net_http::ServerRequestInterface* req) {
if (RE2::FullMatch(string(req->uri_path()), regex_)) {
return [this](net_http::ServerRequestInterface* req) {
this->ProcessRequest(req);
};
}
VLOG(1) << "Ignoring HTTP request: " << req->http_method() << " "
<< req->uri_path();
return nullptr;
}
private:
void ProcessRequest(net_http::ServerRequestInterface* req) {
string body;
int64_t num_bytes = 0;
auto request_chunk = req->ReadRequestBytes(&num_bytes);
while (request_chunk != nullptr) {
absl::StrAppend(&body, absl::string_view(request_chunk.get(), num_bytes));
request_chunk = req->ReadRequestBytes(&num_bytes);
}
std::vector<std::pair<string, string>> headers;
string output;
VLOG(1) << "Processing HTTP request: " << req->http_method() << " "
<< req->uri_path() << " body: " << body.size() << " bytes.";
const auto status = handler_->ProcessRequest(
req->http_method(), req->uri_path(), body, &headers, &output);
const auto http_status = ToHTTPStatusCode(status);
// Note: we add headers+output for non successful status too, in case the
// output contains details about the error (e.g. error messages).
for (const auto& kv : headers) {
req->OverwriteResponseHeader(kv.first, kv.second);
}
req->WriteResponseString(output);
if (http_status != net_http::HTTPStatusCode::OK) {
VLOG(1) << "Error Processing HTTP/REST request: " << req->http_method()
<< " " << req->uri_path() << " Error: " << status.ToString();
}
req->ReplyWithStatus(http_status);
}
const RE2 regex_;
std::unique_ptr<HttpRestApiHandler> handler_;
};
} // namespace
std::unique_ptr<net_http::HTTPServerInterface> CreateAndStartHttpServer(
int port, int num_threads, int timeout_in_ms,
const MonitoringConfig& monitoring_config, ServerCore* core) {
auto options = absl::make_unique<net_http::ServerOptions>();
options->AddPort(static_cast<uint32_t>(port));
options->SetExecutor(absl::make_unique<RequestExecutor>(num_threads));
auto server = net_http::CreateEvHTTPServer(std::move(options));
if (server == nullptr) {
return nullptr;
}
// Register handler for prometheus metric endpoint.
if (monitoring_config.prometheus_config().enable()) {
std::shared_ptr<PrometheusExporter> exporter =
std::make_shared<PrometheusExporter>();
net_http::RequestHandlerOptions prometheus_request_options;
PrometheusConfig prometheus_config = monitoring_config.prometheus_config();
auto path = prometheus_config.path().empty() ? PrometheusExporter::kPrometheusPath : prometheus_config.path();
server->RegisterRequestHandler(
path,
[exporter, path](net_http::ServerRequestInterface* req) {
ProcessPrometheusRequest(exporter.get(), path, req);
},
prometheus_request_options);
}
std::shared_ptr<RestApiRequestDispatcher> dispatcher =
std::make_shared<RestApiRequestDispatcher>(timeout_in_ms, core);
net_http::RequestHandlerOptions handler_options;
server->RegisterRequestDispatcher(
[dispatcher](net_http::ServerRequestInterface* req) {
return dispatcher->Dispatch(req);
},
handler_options);
if (server->StartAcceptingRequests()) {
return server;
}
return nullptr;
}
} // namespace serving
} // namespace tensorflow
<|endoftext|> |
<commit_before>/////////////////////////////////////////
//
// OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////
// Client class - Sending routines
// Created 22/7/02
// Jason Boettcher
#include "LieroX.h"
#include "CClientNetEngine.h"
#include "StringUtils.h"
#include "CClient.h"
#include "Protocol.h"
#include "game/CWorm.h"
#include "MathLib.h"
#include "ChatCommand.h"
#include "OLXCommand.h"
#include "EndianSwap.h"
#include "CServer.h"
#include "AuxLib.h"
#include "CChannel.h"
#include "DeprecatedGUI/Menu.h"
#include "IRC.h"
#include "OLXConsole.h"
#include "game/Game.h"
#include "gusanos/network.h"
#include "CGameScript.h"
#include "game/GameState.h"
// declare them only locally here as nobody really should use them explicitly
std::string OldLxCompatibleString(const std::string &Utf8String);
///////////////////
// Send the worm details
void CClientNetEngine::SendWormDetails()
{
if(game.isServer()) return;
// Don't flood packets so often
// we are checking in w->checkPacketNeeded() if we need to send an update
// we are checking with bandwidth if we should add an update
/*if ((tLX->currentTime - fLastUpdateSent) <= tLXOptions->fUpdatePeriod)
if (getGameLobby()->iGameType != GME_LOCAL)
return; */
// TODO: Have we always used the limitcheck from GameServer here?
// We should perhaps move it out from GameServer. Looks a bit strange here to use something from GameServer.
if( game.isClient() // we are a client in a netgame
&& !GameServer::checkUploadBandwidth(client->getChannel()->getOutgoingRate()) )
return;
if(!game.gameScript()->gusEngineUsed() && client->getServerVersion() < OLXBetaVersion(0,59,10)) {
// Check if we need to write the state update
bool update = false;
for_each_iterator(CWorm*, w, game.localWorms())
if (w->get()->getAlive() && w->get()->checkPacketNeeded()) {
update = true;
break;
}
if(update) {
// Write the update
CBytestream bs;
bs.writeByte(C2S_UPDATE);
for_each_iterator(CWorm*, w, game.localWorms())
w->get()->writePacket(&bs, false, NULL);
client->bsUnreliable.Append(&bs);
client->fLastUpdateSent = tLX->currentTime;
}
}
// handle Gusanos updates
// only for join-mode because otherwise, we would handle it in CServer
if(game.isClient() && network.getNetControl()) {
const size_t maxBytes = size_t(-1); // TODO ?
if(maxBytes > 0 && network.getNetControl()->olxSendNodeUpdates(NetConnID_server(), maxBytes))
client->fLastUpdateSent = tLX->currentTime;
}
}
void CClientNetEngine::SendGameReady()
{
if(client->getServerVersion() >= OLXBetaVersion(0,59,10)) return;
CBytestream bs;
bs.writeByte(C2S_IMREADY);
if(game.bServerChoosesWeapons) {
bs.writeByte(0);
} else {
// Send my worm's weapon details
bs.writeByte(game.localWorms()->size());
for_each_iterator(CWorm*, w, game.localWorms())
w->get()->writeWeapons( &bs );
}
client->cNetChan->AddReliablePacketToSend(bs);
}
///////////////////
// Send a death
void CClientNetEngine::SendDeath(int victim, int killer)
{
CBytestream bs;
bs.writeByte(C2S_DEATH);
bs.writeInt(victim,1);
bs.writeInt(killer,1);
client->cNetChan->AddReliablePacketToSend(bs);
}
void CClientNetEngineBeta9::SendDeath(int victim, int killer)
{
// If we have some damage reports in buffer send them first so clients won't sum up updated damage score and reported damage packet sent later
SendReportDamage(true);
CClientNetEngine::SendDeath(victim, killer);
}
///////////////////
// Send a string of text
void CClientNetEngine::SendText(const std::string& sText, std::string sWormName)
{
if(HandleDebugCommand(sText)) return;
bool chat_command = sText.size() >= 2 && sText[0] == '/' && sText[1] != '/';
if (sText.find("/irc ") == 0 || sText.find("/chat ") == 0) { // Send text to IRC
bool res = false;
if (GetGlobalIRC())
res = GetGlobalIRC()->sendChat(sText.substr(sText.find(' ') + 1));
if (!res)
client->cChatbox.AddText("Could not send the IRC message", tLX->clNetworkText, TXT_NETWORK, tLX->currentTime);
return;
}
// We can safely send long messages to servers >= beta8
if (client->getServerVersion() >= OLXBetaVersion(8)) {
// HTML support since beta 8
SendTextInternal(OldLxCompatibleString(sText), sWormName);
// <=beta7 server
} else {
if (chat_command &&
client->getServerVersion() < OLXBetaVersion(3) && // <beta3 clients don't have chat command support
sText.find("/me ") != 0) // Ignores "/me" special command
{
// Try if we can execute the same command in console (mainly for "/suicide" command to work on all servers)
if( !subStrCaseEqual( sText.substr(1), "suicide", 7 ) )
Con_Execute(sText.substr(1));
else
client->cChatbox.AddText("HINT: server cannot execute commands, only OLX beta3+ can", tLX->clNotice, TXT_NOTICE, tLX->currentTime);
return;
} else if (chat_command &&
client->getServerVersion() >= OLXBetaVersion(3)) {
// we don't have to split chat commands
// "/me ..." is also save, because server uses SendGlobalText for sending and it splits the text there
SendTextInternal(OldLxCompatibleString(sText), sWormName);
} else { // we can savely split the message (and we have to)
// If the text is too long, split it in smaller pieces and then send (backward comaptibility)
int name_w = tLX->cFont.GetWidth(sWormName + ": ");
std::vector<std::string> split = splitstring(StripHtmlTags(sText), 63,
client->iNetStatus == NET_CONNECTED ? 600 - name_w : 300 - name_w, tLX->cFont);
// Check
if (split.size() == 0) { // More than weird...
SendTextInternal(OldLxCompatibleString(StripHtmlTags(sText)), sWormName);
return;
}
// Send the first chunk
SendTextInternal(OldLxCompatibleString(split[0]), sWormName);
// Send the text
for (std::vector<std::string>::const_iterator it = split.begin() + 1; it != split.end(); it++)
SendTextInternal(OldLxCompatibleString(*it), "");
}
}
}
void CClientNetEngineBeta7::SendChatCommandCompletionRequest(const std::string& startStr) {
CBytestream bs;
bs.writeByte(C2S_CHATCMDCOMPLREQ);
bs.writeString(startStr);
client->cNetChan->AddReliablePacketToSend(bs);
}
void CClientNetEngineBeta7::SendAFK(int wormid, AFK_TYPE afkType, const std::string & message ) {
if( client->getServerVersion() < OLXBetaVersion(7) )
return;
std::string msg = message;
if( msg == "" )
{
switch(afkType) {
case AFK_BACK_ONLINE: break;
case AFK_TYPING_CHAT: msg = "(typing)"; break;
case AFK_AWAY: msg = "(away)"; break;
case AFK_SELECTING_WPNS: msg = "(selecting weapons)"; break;
case AFK_CONSOLE: msg = "(console)"; break;
case AFK_MENU: msg = "(menu)"; break;
}
}
{
CWorm* w = game.wormById(wormid, false);
if(w) w->setAFK(afkType, msg);
}
CBytestream bs;
bs.writeByte(C2S_AFK);
bs.writeByte(wormid);
bs.writeByte(afkType);
if(msg.size() > 127)
msg = msg.substr(0, 127);
bs.writeString(msg);
client->cNetChan->AddReliablePacketToSend(bs);
}
/////////////////////
// Internal function for text sending, does not do any checks or parsing
void CClientNetEngine::SendTextInternal(const std::string& sText, const std::string& sWormName)
{
if(!client) {
errors << "CClientNetEngine::SendTextInternal(" << sWormName << ": " << sText << "): my client is unset" << endl;
return;
}
if(!client->cNetChan) {
errors << "CClientNetEngine::SendTextInternal(" << sWormName << ": " << sText << "): cNetChan of my client (" << client->debugName() << ") is unset" << endl;
return;
}
CBytestream bs;
bs.writeByte(C2S_CHATTEXT);
if (sWormName.size() == 0)
bs.writeString(sText);
else if( sText.find("/me ") == 0 && client->getServerVersion() < OLXBetaVersion(0,58,1) ) // "/me " chat command
bs.writeString( "* " + sWormName + " " + sText.substr(4)); // Add star so clients with empty name won't fake others
else // "/me " command is server-sided on Beta9
bs.writeString(sWormName + ": " + sText);
client->cNetChan->AddReliablePacketToSend(bs);
}
#ifdef FUZZY_ERROR_TESTING
//////////////////
// Send a random packet to server (used for debugging)
void CClientNetEngine::SendRandomPacket()
{
// don't send random packets from the local client to our own server
if( getGameLobby()->iGameType != GME_JOIN ) return;
CBytestream bs;
int random_length = GetRandomInt(50);
for (int i=0; i < random_length; i++)
bs.writeByte((uchar)GetRandomInt(255));
client->cNetChan->AddReliablePacketToSend(bs);
bs.Clear();
// Test connectionless packets
if (GetRandomInt(100) >= 75) {
bs.writeInt(-1, 4);
static const std::string commands[] = { "lx::getchallenge", "lx::connect", "lx::ping", "lx::query",
"lx::getinfo", "lx::wantsjoin", "lx::traverse", "lx::registered"};
bs.writeString(commands[GetRandomInt(500) % (sizeof(commands)/sizeof(std::string))]);
for (int i=0; i < random_length; i++)
bs.writeByte((uchar)GetRandomInt(255));
SetRemoteNetAddr(client->tSocket, client->cNetChan->getAddress());
bs.Send(client->tSocket);
}
}
#endif
void CClientNetEngine::SendGrabBonus(int id, int wormid)
{
CBytestream bs;
bs.writeByte(C2S_GRABBONUS);
bs.writeByte(id);
bs.writeByte(wormid);
bs.writeByte(game.wormById(wormid)->getCurrentWeapon());
client->cNetChan->AddReliablePacketToSend(bs);
}
void CClientNetEngine::SendUpdateLobby(bool ready)
{
CBytestream bs;
bs.writeByte(C2S_UPDATELOBBY);
bs.writeByte(ready);
client->getChannel()->AddReliablePacketToSend(bs);
}
void CClientNetEngine::SendDisconnect()
{
CBytestream bs;
bs.writeByte(C2S_DISCONNECT);
// Send the pack a few times to make sure the server gets the packet
if( client->cNetChan != NULL)
for(int i=0;i<3;i++)
client->cNetChan->Transmit(&bs);
}
void CClientNetEngine::SendFileData()
{
CBytestream bs;
bs.writeByte(C2S_SENDFILE);
client->getUdpFileDownloader()->send(&bs);
client->getChannel()->AddReliablePacketToSend(bs);
}
void CClientNetEngineBeta9::QueueReportDamage(int victim, float damage, int offender)
{
// Buffer up all damage and send it once per 0.1 second for LAN nettype, or once per 0.3 seconds for modem
std::pair< int, int > dmgPair = std::make_pair( victim, offender );
if( cDamageReport.count( dmgPair ) == 0 )
cDamageReport[ dmgPair ] = 0;
cDamageReport[ dmgPair ] += damage;
SendReportDamage();
}
void CClientNetEngineBeta9::SendReportDamage(bool flush)
{
if( ! flush && tLX->currentTime - fLastDamageReportSent < 0.1f * ( NST_LOCAL - client->getNetSpeed() ) )
return;
CBytestream bs;
for( std::map< std::pair< int, int >, float > :: iterator it = cDamageReport.begin();
it != cDamageReport.end(); it++ )
{
int victim = it->first.first;
int offender = it->first.second;
float damage = it->second;
bs.writeByte(C2S_REPORTDAMAGE);
bs.writeByte(victim);
bs.writeFloat(damage);
bs.writeByte(offender);
}
client->cNetChan->AddReliablePacketToSend(bs);
cDamageReport.clear();
fLastDamageReportSent = tLX->currentTime;
}
void CClientNetEngineBeta9NewNet::SendNewNetChecksum()
{
CBytestream bs;
bs.writeByte(C2S_NEWNET_CHECKSUM);
AbsTime time;
unsigned checksum = NewNet::GetChecksum( &time );
bs.writeInt(checksum, 4);
bs.writeInt((unsigned)time.milliseconds(), 4);
client->cNetChan->AddReliablePacketToSend(bs);
}
void CClient::SendGameStateUpdates() {
if(getStatus() != NET_CONNECTING)
return;
if(getServerVersion() < OLXBetaVersion(0,59,10))
return;
GameState& state = *serverGameState;
GameStateUpdates updates;
updates.diffFromStateToCurrent(state);
if(!updates) return;
{
CBytestream bs;
bs.writeByte(C2S_GAMEATTRUPDATE);
updates.writeToBs(&bs, state);
cNetChan->AddReliablePacketToSend(bs);
}
state.updateToCurrent();
}
<commit_msg>whoops<commit_after>/////////////////////////////////////////
//
// OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////
// Client class - Sending routines
// Created 22/7/02
// Jason Boettcher
#include "LieroX.h"
#include "CClientNetEngine.h"
#include "StringUtils.h"
#include "CClient.h"
#include "Protocol.h"
#include "game/CWorm.h"
#include "MathLib.h"
#include "ChatCommand.h"
#include "OLXCommand.h"
#include "EndianSwap.h"
#include "CServer.h"
#include "AuxLib.h"
#include "CChannel.h"
#include "DeprecatedGUI/Menu.h"
#include "IRC.h"
#include "OLXConsole.h"
#include "game/Game.h"
#include "gusanos/network.h"
#include "CGameScript.h"
#include "game/GameState.h"
// declare them only locally here as nobody really should use them explicitly
std::string OldLxCompatibleString(const std::string &Utf8String);
///////////////////
// Send the worm details
void CClientNetEngine::SendWormDetails()
{
if(game.isServer()) return;
// Don't flood packets so often
// we are checking in w->checkPacketNeeded() if we need to send an update
// we are checking with bandwidth if we should add an update
/*if ((tLX->currentTime - fLastUpdateSent) <= tLXOptions->fUpdatePeriod)
if (getGameLobby()->iGameType != GME_LOCAL)
return; */
// TODO: Have we always used the limitcheck from GameServer here?
// We should perhaps move it out from GameServer. Looks a bit strange here to use something from GameServer.
if( game.isClient() // we are a client in a netgame
&& !GameServer::checkUploadBandwidth(client->getChannel()->getOutgoingRate()) )
return;
if(!game.gameScript()->gusEngineUsed() && client->getServerVersion() < OLXBetaVersion(0,59,10)) {
// Check if we need to write the state update
bool update = false;
for_each_iterator(CWorm*, w, game.localWorms())
if (w->get()->getAlive() && w->get()->checkPacketNeeded()) {
update = true;
break;
}
if(update) {
// Write the update
CBytestream bs;
bs.writeByte(C2S_UPDATE);
for_each_iterator(CWorm*, w, game.localWorms())
w->get()->writePacket(&bs, false, NULL);
client->bsUnreliable.Append(&bs);
client->fLastUpdateSent = tLX->currentTime;
}
}
// handle Gusanos updates
// only for join-mode because otherwise, we would handle it in CServer
if(game.isClient() && network.getNetControl()) {
const size_t maxBytes = size_t(-1); // TODO ?
if(maxBytes > 0 && network.getNetControl()->olxSendNodeUpdates(NetConnID_server(), maxBytes))
client->fLastUpdateSent = tLX->currentTime;
}
}
void CClientNetEngine::SendGameReady()
{
if(client->getServerVersion() >= OLXBetaVersion(0,59,10)) return;
CBytestream bs;
bs.writeByte(C2S_IMREADY);
if(game.bServerChoosesWeapons) {
bs.writeByte(0);
} else {
// Send my worm's weapon details
bs.writeByte(game.localWorms()->size());
for_each_iterator(CWorm*, w, game.localWorms())
w->get()->writeWeapons( &bs );
}
client->cNetChan->AddReliablePacketToSend(bs);
}
///////////////////
// Send a death
void CClientNetEngine::SendDeath(int victim, int killer)
{
CBytestream bs;
bs.writeByte(C2S_DEATH);
bs.writeInt(victim,1);
bs.writeInt(killer,1);
client->cNetChan->AddReliablePacketToSend(bs);
}
void CClientNetEngineBeta9::SendDeath(int victim, int killer)
{
// If we have some damage reports in buffer send them first so clients won't sum up updated damage score and reported damage packet sent later
SendReportDamage(true);
CClientNetEngine::SendDeath(victim, killer);
}
///////////////////
// Send a string of text
void CClientNetEngine::SendText(const std::string& sText, std::string sWormName)
{
if(HandleDebugCommand(sText)) return;
bool chat_command = sText.size() >= 2 && sText[0] == '/' && sText[1] != '/';
if (sText.find("/irc ") == 0 || sText.find("/chat ") == 0) { // Send text to IRC
bool res = false;
if (GetGlobalIRC())
res = GetGlobalIRC()->sendChat(sText.substr(sText.find(' ') + 1));
if (!res)
client->cChatbox.AddText("Could not send the IRC message", tLX->clNetworkText, TXT_NETWORK, tLX->currentTime);
return;
}
// We can safely send long messages to servers >= beta8
if (client->getServerVersion() >= OLXBetaVersion(8)) {
// HTML support since beta 8
SendTextInternal(OldLxCompatibleString(sText), sWormName);
// <=beta7 server
} else {
if (chat_command &&
client->getServerVersion() < OLXBetaVersion(3) && // <beta3 clients don't have chat command support
sText.find("/me ") != 0) // Ignores "/me" special command
{
// Try if we can execute the same command in console (mainly for "/suicide" command to work on all servers)
if( !subStrCaseEqual( sText.substr(1), "suicide", 7 ) )
Con_Execute(sText.substr(1));
else
client->cChatbox.AddText("HINT: server cannot execute commands, only OLX beta3+ can", tLX->clNotice, TXT_NOTICE, tLX->currentTime);
return;
} else if (chat_command &&
client->getServerVersion() >= OLXBetaVersion(3)) {
// we don't have to split chat commands
// "/me ..." is also save, because server uses SendGlobalText for sending and it splits the text there
SendTextInternal(OldLxCompatibleString(sText), sWormName);
} else { // we can savely split the message (and we have to)
// If the text is too long, split it in smaller pieces and then send (backward comaptibility)
int name_w = tLX->cFont.GetWidth(sWormName + ": ");
std::vector<std::string> split = splitstring(StripHtmlTags(sText), 63,
client->iNetStatus == NET_CONNECTED ? 600 - name_w : 300 - name_w, tLX->cFont);
// Check
if (split.size() == 0) { // More than weird...
SendTextInternal(OldLxCompatibleString(StripHtmlTags(sText)), sWormName);
return;
}
// Send the first chunk
SendTextInternal(OldLxCompatibleString(split[0]), sWormName);
// Send the text
for (std::vector<std::string>::const_iterator it = split.begin() + 1; it != split.end(); it++)
SendTextInternal(OldLxCompatibleString(*it), "");
}
}
}
void CClientNetEngineBeta7::SendChatCommandCompletionRequest(const std::string& startStr) {
CBytestream bs;
bs.writeByte(C2S_CHATCMDCOMPLREQ);
bs.writeString(startStr);
client->cNetChan->AddReliablePacketToSend(bs);
}
void CClientNetEngineBeta7::SendAFK(int wormid, AFK_TYPE afkType, const std::string & message ) {
if( client->getServerVersion() < OLXBetaVersion(7) )
return;
std::string msg = message;
if( msg == "" )
{
switch(afkType) {
case AFK_BACK_ONLINE: break;
case AFK_TYPING_CHAT: msg = "(typing)"; break;
case AFK_AWAY: msg = "(away)"; break;
case AFK_SELECTING_WPNS: msg = "(selecting weapons)"; break;
case AFK_CONSOLE: msg = "(console)"; break;
case AFK_MENU: msg = "(menu)"; break;
}
}
{
CWorm* w = game.wormById(wormid, false);
if(w) w->setAFK(afkType, msg);
}
CBytestream bs;
bs.writeByte(C2S_AFK);
bs.writeByte(wormid);
bs.writeByte(afkType);
if(msg.size() > 127)
msg = msg.substr(0, 127);
bs.writeString(msg);
client->cNetChan->AddReliablePacketToSend(bs);
}
/////////////////////
// Internal function for text sending, does not do any checks or parsing
void CClientNetEngine::SendTextInternal(const std::string& sText, const std::string& sWormName)
{
if(!client) {
errors << "CClientNetEngine::SendTextInternal(" << sWormName << ": " << sText << "): my client is unset" << endl;
return;
}
if(!client->cNetChan) {
errors << "CClientNetEngine::SendTextInternal(" << sWormName << ": " << sText << "): cNetChan of my client (" << client->debugName() << ") is unset" << endl;
return;
}
CBytestream bs;
bs.writeByte(C2S_CHATTEXT);
if (sWormName.size() == 0)
bs.writeString(sText);
else if( sText.find("/me ") == 0 && client->getServerVersion() < OLXBetaVersion(0,58,1) ) // "/me " chat command
bs.writeString( "* " + sWormName + " " + sText.substr(4)); // Add star so clients with empty name won't fake others
else // "/me " command is server-sided on Beta9
bs.writeString(sWormName + ": " + sText);
client->cNetChan->AddReliablePacketToSend(bs);
}
#ifdef FUZZY_ERROR_TESTING
//////////////////
// Send a random packet to server (used for debugging)
void CClientNetEngine::SendRandomPacket()
{
// don't send random packets from the local client to our own server
if( getGameLobby()->iGameType != GME_JOIN ) return;
CBytestream bs;
int random_length = GetRandomInt(50);
for (int i=0; i < random_length; i++)
bs.writeByte((uchar)GetRandomInt(255));
client->cNetChan->AddReliablePacketToSend(bs);
bs.Clear();
// Test connectionless packets
if (GetRandomInt(100) >= 75) {
bs.writeInt(-1, 4);
static const std::string commands[] = { "lx::getchallenge", "lx::connect", "lx::ping", "lx::query",
"lx::getinfo", "lx::wantsjoin", "lx::traverse", "lx::registered"};
bs.writeString(commands[GetRandomInt(500) % (sizeof(commands)/sizeof(std::string))]);
for (int i=0; i < random_length; i++)
bs.writeByte((uchar)GetRandomInt(255));
SetRemoteNetAddr(client->tSocket, client->cNetChan->getAddress());
bs.Send(client->tSocket);
}
}
#endif
void CClientNetEngine::SendGrabBonus(int id, int wormid)
{
CBytestream bs;
bs.writeByte(C2S_GRABBONUS);
bs.writeByte(id);
bs.writeByte(wormid);
bs.writeByte(game.wormById(wormid)->getCurrentWeapon());
client->cNetChan->AddReliablePacketToSend(bs);
}
void CClientNetEngine::SendUpdateLobby(bool ready)
{
CBytestream bs;
bs.writeByte(C2S_UPDATELOBBY);
bs.writeByte(ready);
client->getChannel()->AddReliablePacketToSend(bs);
}
void CClientNetEngine::SendDisconnect()
{
CBytestream bs;
bs.writeByte(C2S_DISCONNECT);
// Send the pack a few times to make sure the server gets the packet
if( client->cNetChan != NULL)
for(int i=0;i<3;i++)
client->cNetChan->Transmit(&bs);
}
void CClientNetEngine::SendFileData()
{
CBytestream bs;
bs.writeByte(C2S_SENDFILE);
client->getUdpFileDownloader()->send(&bs);
client->getChannel()->AddReliablePacketToSend(bs);
}
void CClientNetEngineBeta9::QueueReportDamage(int victim, float damage, int offender)
{
// Buffer up all damage and send it once per 0.1 second for LAN nettype, or once per 0.3 seconds for modem
std::pair< int, int > dmgPair = std::make_pair( victim, offender );
if( cDamageReport.count( dmgPair ) == 0 )
cDamageReport[ dmgPair ] = 0;
cDamageReport[ dmgPair ] += damage;
SendReportDamage();
}
void CClientNetEngineBeta9::SendReportDamage(bool flush)
{
if( ! flush && tLX->currentTime - fLastDamageReportSent < 0.1f * ( NST_LOCAL - client->getNetSpeed() ) )
return;
CBytestream bs;
for( std::map< std::pair< int, int >, float > :: iterator it = cDamageReport.begin();
it != cDamageReport.end(); it++ )
{
int victim = it->first.first;
int offender = it->first.second;
float damage = it->second;
bs.writeByte(C2S_REPORTDAMAGE);
bs.writeByte(victim);
bs.writeFloat(damage);
bs.writeByte(offender);
}
client->cNetChan->AddReliablePacketToSend(bs);
cDamageReport.clear();
fLastDamageReportSent = tLX->currentTime;
}
void CClientNetEngineBeta9NewNet::SendNewNetChecksum()
{
CBytestream bs;
bs.writeByte(C2S_NEWNET_CHECKSUM);
AbsTime time;
unsigned checksum = NewNet::GetChecksum( &time );
bs.writeInt(checksum, 4);
bs.writeInt((unsigned)time.milliseconds(), 4);
client->cNetChan->AddReliablePacketToSend(bs);
}
void CClient::SendGameStateUpdates() {
if(getStatus() != NET_CONNECTED)
return;
if(getServerVersion() < OLXBetaVersion(0,59,10))
return;
GameState& state = *serverGameState;
GameStateUpdates updates;
updates.diffFromStateToCurrent(state);
if(!updates) return;
{
CBytestream bs;
bs.writeByte(C2S_GAMEATTRUPDATE);
updates.writeToBs(&bs, state);
cNetChan->AddReliablePacketToSend(bs);
}
state.updateToCurrent();
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2017 Inviwo Foundation
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include "pythonscript.h"
#include <inviwo/core/util/assertion.h>
#include <inviwo/core/util/stringconversion.h>
#include <inviwo/core/util/filesystem.h>
#include <modules/python3/pythonexecutionoutputobservable.h>
#include <modules/python3/pythoninterpreter.h>
#include <modules/python3/pybindutils.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <modules/python3/python3module.h>
#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>
#include <traceback.h>
#include <frameobject.h>
#define BYTE_CODE static_cast<PyObject*>(byteCode_)
namespace inviwo {
PythonScript::PythonScript() : source_(""), byteCode_(nullptr), isCompileNeeded_(false) {}
PythonScript::~PythonScript() {
Py_XDECREF(BYTE_CODE);
}
bool PythonScript::compile() {
Py_XDECREF(BYTE_CODE);
byteCode_ = Py_CompileString(source_.c_str(), filename_.c_str(), Py_file_input);
isCompileNeeded_ = !checkCompileError();
if (isCompileNeeded_) {
Py_XDECREF(BYTE_CODE);
byteCode_ = nullptr;
}
return !isCompileNeeded_;
}
bool PythonScript::run(const VariableMap& extraLocalVariables,
std::function<void(pybind11::dict)> callback) {
if (isCompileNeeded_ && !compile()) {
LogError("Failed to run script, script could not be compiled");
return false;
}
ivwAssert(byteCode_ != nullptr, "No byte code");
auto m = PyImport_AddModule("__main__");
if (m == NULL) return false;
PyObject* copy = PyDict_Copy(PyModule_GetDict(m));
for (auto ea : extraLocalVariables) {
PyDict_SetItemString(copy, ea.first.c_str(), ea.second.ptr());
}
InviwoApplication::getPtr()->getInteractionStateManager().beginInteraction();
PyObject* ret = PyEval_EvalCode(BYTE_CODE, copy, copy);
InviwoApplication::getPtr()->getInteractionStateManager().endInteraction();
bool success = checkRuntimeError();
if (success) {
callback(pyutil::toPyBindObjectBorrow<pybind11::dict>(copy));
}
Py_XDECREF(ret);
Py_XDECREF(copy);
return success;
}
void PythonScript::setFilename(std::string filename) {
filename_ = filename;
}
std::string PythonScript::getSource() const {
return source_;
}
void PythonScript::setSource(const std::string& source) {
source_ = source;
isCompileNeeded_ = true;
Py_XDECREF(BYTE_CODE);
byteCode_ = nullptr;
}
bool PythonScript::checkCompileError() {
if (!PyErr_Occurred())
return true;
PyObject* errtype, *errvalue, *traceback;
PyErr_Fetch(&errtype, &errvalue, &traceback);
std::string log = "";
char* msg = nullptr;
PyObject* obj = nullptr;
if (PyArg_ParseTuple(errvalue, "sO", &msg, &obj)) {
int line, col;
char* code = nullptr;
char* mod = nullptr;
if (PyArg_ParseTuple(obj, "siis", &mod, &line, &col, &code)) {
log = "[" + toString(line) + ":" + toString(col) + "] " + toString(msg) + ": " + toString(code);
}
}
// convert error to string, if it could not be parsed
if (log.empty()) {
LogWarn("Failed to parse exception, printing as string:");
auto s = pyutil::toPyBindObjectSteal<pybind11::str>(PyObject_Str(errvalue));
if (s.check()) {
log = s;
}
}
Py_XDECREF(errtype);
Py_XDECREF(errvalue);
Py_XDECREF(traceback);
LogError(log);
return false;
}
bool PythonScript::checkRuntimeError() {
if (!PyErr_Occurred())
return true;
std::string pyException = "";
PyObject* pyError_type = nullptr;
PyObject* pyError_value = nullptr;
PyObject* pyError_traceback = nullptr;
PyObject* pyError_string = nullptr;
PyErr_Fetch(&pyError_type, &pyError_value, &pyError_traceback);
int errorLine = -1;
std::string stacktraceStr;
if (pyError_traceback) {
PyTracebackObject* traceback = (PyTracebackObject*)pyError_traceback;
while (traceback) {
PyFrameObject* frame = traceback->tb_frame;
std::string stacktraceLine;
if (frame && frame->f_code) {
PyCodeObject* codeObject = frame->f_code;
auto co_filename = pyutil::toPyBindObjectBorrow<pybind11::str>(codeObject->co_filename);
if (co_filename)
stacktraceLine.append(std::string(" File \"") + std::string(co_filename) + std::string("\", "));
errorLine = PyCode_Addr2Line(codeObject, frame->f_lasti);
stacktraceLine.append(std::string("line ") + toString(errorLine));
auto co_name = pyutil::toPyBindObjectBorrow<pybind11::str>(codeObject->co_name);
if (co_name)
stacktraceLine.append(std::string(", in ") + std::string(co_name));
}
stacktraceLine.append("\n");
stacktraceStr = stacktraceLine + stacktraceStr;
traceback = traceback->tb_next;
}
}
std::stringstream s;
s << errorLine;
pyException.append(std::string("[") + s.str() + std::string("] "));
if (pyError_value){
auto pyError_string = pyutil::toPyBindObjectSteal<pybind11::str>(PyObject_Str(pyError_value));
if(pyError_string){
pyException.append(pyError_string);
}
}
else {
pyException.append("<No data available>");
}
pyException.append("\n");
// finally append stacktrace string
if (!stacktraceStr.empty()) {
pyException.append("Stacktrace (most recent call first):\n");
pyException.append(stacktraceStr);
} else {
pyException.append("<No stacktrace available>");
LogWarn("Failed to parse traceback");
}
Py_XDECREF(pyError_type);
Py_XDECREF(pyError_value);
Py_XDECREF(pyError_traceback);
LogError(pyException);
InviwoApplication::getPtr()
->getModuleByType<Python3Module>()
->getPythonInterpreter()
->pythonExecutionOutputEvent(pyException, sysstderr);
return false;
}
PythonScriptDisk::PythonScriptDisk(std::string filename)
: PythonScript(), SingleFileObserver(filename) {
setFilename(filename);
onChange([this]() { readFileAndSetSource(); });
readFileAndSetSource();
}
void PythonScriptDisk::readFileAndSetSource() {
std::ifstream inFile(getFilename());
std::string src((std::istreambuf_iterator<char>(inFile)), std::istreambuf_iterator<char>());
setSource(src);
}
} // namespace
<commit_msg>Python: Warning fixes<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2017 Inviwo Foundation
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include "pythonscript.h"
#include <inviwo/core/util/assertion.h>
#include <inviwo/core/util/stringconversion.h>
#include <inviwo/core/util/filesystem.h>
#include <modules/python3/pythonexecutionoutputobservable.h>
#include <modules/python3/pythoninterpreter.h>
#include <modules/python3/pybindutils.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <modules/python3/python3module.h>
#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>
#include <traceback.h>
#include <frameobject.h>
#define BYTE_CODE static_cast<PyObject*>(byteCode_)
namespace inviwo {
PythonScript::PythonScript() : source_(""), byteCode_(nullptr), isCompileNeeded_(false) {}
PythonScript::~PythonScript() {
Py_XDECREF(BYTE_CODE);
}
bool PythonScript::compile() {
Py_XDECREF(BYTE_CODE);
byteCode_ = Py_CompileString(source_.c_str(), filename_.c_str(), Py_file_input);
isCompileNeeded_ = !checkCompileError();
if (isCompileNeeded_) {
Py_XDECREF(BYTE_CODE);
byteCode_ = nullptr;
}
return !isCompileNeeded_;
}
bool PythonScript::run(const VariableMap& extraLocalVariables,
std::function<void(pybind11::dict)> callback) {
if (isCompileNeeded_ && !compile()) {
LogError("Failed to run script, script could not be compiled");
return false;
}
ivwAssert(byteCode_ != nullptr, "No byte code");
auto m = PyImport_AddModule("__main__");
if (m == NULL) return false;
PyObject* copy = PyDict_Copy(PyModule_GetDict(m));
for (auto ea : extraLocalVariables) {
PyDict_SetItemString(copy, ea.first.c_str(), ea.second.ptr());
}
InviwoApplication::getPtr()->getInteractionStateManager().beginInteraction();
PyObject* ret = PyEval_EvalCode(BYTE_CODE, copy, copy);
InviwoApplication::getPtr()->getInteractionStateManager().endInteraction();
bool success = checkRuntimeError();
if (success) {
callback(pyutil::toPyBindObjectBorrow<pybind11::dict>(copy));
}
Py_XDECREF(ret);
Py_XDECREF(copy);
return success;
}
void PythonScript::setFilename(std::string filename) {
filename_ = filename;
}
std::string PythonScript::getSource() const {
return source_;
}
void PythonScript::setSource(const std::string& source) {
source_ = source;
isCompileNeeded_ = true;
Py_XDECREF(BYTE_CODE);
byteCode_ = nullptr;
}
bool PythonScript::checkCompileError() {
if (!PyErr_Occurred())
return true;
PyObject* errtype, *errvalue, *traceback;
PyErr_Fetch(&errtype, &errvalue, &traceback);
std::string log = "";
char* msg = nullptr;
PyObject* obj = nullptr;
if (PyArg_ParseTuple(errvalue, "sO", &msg, &obj)) {
int line, col;
char* code = nullptr;
char* mod = nullptr;
if (PyArg_ParseTuple(obj, "siis", &mod, &line, &col, &code)) {
log = "[" + toString(line) + ":" + toString(col) + "] " + toString(msg) + ": " + toString(code);
}
}
// convert error to string, if it could not be parsed
if (log.empty()) {
LogWarn("Failed to parse exception, printing as string:");
auto s = pyutil::toPyBindObjectSteal<pybind11::str>(PyObject_Str(errvalue));
if (s.check()) {
log = s;
}
}
Py_XDECREF(errtype);
Py_XDECREF(errvalue);
Py_XDECREF(traceback);
LogError(log);
return false;
}
bool PythonScript::checkRuntimeError() {
if (!PyErr_Occurred())
return true;
std::string pyException = "";
PyObject* pyError_type = nullptr;
PyObject* pyError_value = nullptr;
PyObject* pyError_traceback = nullptr;
PyErr_Fetch(&pyError_type, &pyError_value, &pyError_traceback);
int errorLine = -1;
std::string stacktraceStr;
if (pyError_traceback) {
PyTracebackObject* traceback = (PyTracebackObject*)pyError_traceback;
while (traceback) {
PyFrameObject* frame = traceback->tb_frame;
std::string stacktraceLine;
if (frame && frame->f_code) {
PyCodeObject* codeObject = frame->f_code;
auto co_filename = pyutil::toPyBindObjectBorrow<pybind11::str>(codeObject->co_filename);
if (co_filename)
stacktraceLine.append(std::string(" File \"") + std::string(co_filename) + std::string("\", "));
errorLine = PyCode_Addr2Line(codeObject, frame->f_lasti);
stacktraceLine.append(std::string("line ") + toString(errorLine));
auto co_name = pyutil::toPyBindObjectBorrow<pybind11::str>(codeObject->co_name);
if (co_name)
stacktraceLine.append(std::string(", in ") + std::string(co_name));
}
stacktraceLine.append("\n");
stacktraceStr = stacktraceLine + stacktraceStr;
traceback = traceback->tb_next;
}
}
std::stringstream s;
s << errorLine;
pyException.append(std::string("[") + s.str() + std::string("] "));
if (pyError_value){
auto pyError_string = pyutil::toPyBindObjectSteal<pybind11::str>(PyObject_Str(pyError_value));
if(pyError_string){
pyException.append(pyError_string);
}
}
else {
pyException.append("<No data available>");
}
pyException.append("\n");
// finally append stacktrace string
if (!stacktraceStr.empty()) {
pyException.append("Stacktrace (most recent call first):\n");
pyException.append(stacktraceStr);
} else {
pyException.append("<No stacktrace available>");
LogWarn("Failed to parse traceback");
}
Py_XDECREF(pyError_type);
Py_XDECREF(pyError_value);
Py_XDECREF(pyError_traceback);
LogError(pyException);
InviwoApplication::getPtr()
->getModuleByType<Python3Module>()
->getPythonInterpreter()
->pythonExecutionOutputEvent(pyException, sysstderr);
return false;
}
PythonScriptDisk::PythonScriptDisk(std::string filename)
: PythonScript(), SingleFileObserver(filename) {
setFilename(filename);
onChange([this]() { readFileAndSetSource(); });
readFileAndSetSource();
}
void PythonScriptDisk::readFileAndSetSource() {
std::ifstream inFile(getFilename());
std::string src((std::istreambuf_iterator<char>(inFile)), std::istreambuf_iterator<char>());
setSource(src);
}
} // namespace
<|endoftext|> |
<commit_before>#include "config.h"
#include "common.hpp"
#include "fetch/http.hpp"
#include "logging/logger.hpp"
#include "http_server/server.hpp"
#include "vector_tile.pb.h"
#include <mapnik/datasource_cache.hpp>
#include <iostream>
namespace {
server_options default_options(const std::string &map_file) {
server_options options;
options.path_multiplier = 16;
options.buffer_size = 0;
options.scale_factor = 1.0;
options.offset_x = 0;
options.offset_y = 0;
options.tolerance = 1;
options.image_format = "jpeg";
options.scaling_method = mapnik::SCALING_NEAR;
options.scale_denominator = 0.0;
options.thread_hint = 1;
options.map_file = map_file;
options.port = "";
return options;
}
void test_fetch_empty() {
server_options options = default_options("test/empty_map_file.xml");
http::server3::server server("localhost", options);
std::string port = server.port();
server.run(false);
avecado::fetch::http fetch((boost::format("http://localhost:%1%") % port).str(), "pbf");
avecado::fetch_response response(fetch(0, 0, 0));
server.stop();
test::assert_equal<bool>(response.is_left(), true, "should fetch tile OK");
test::assert_equal<int>(response.left()->mapnik_tile().layers_size(), 0, "should have no layers");
}
void test_fetch_single_line() {
server_options options = default_options("test/single_line.xml");
http::server3::server server("localhost", options);
std::string port = server.port();
server.run(false);
avecado::fetch::http fetch((boost::format("http://localhost:%1%") % port).str(), "pbf");
avecado::fetch_response response(fetch(0, 0, 0));
server.stop();
test::assert_equal<bool>(response.is_left(), true, "should fetch tile OK");
test::assert_equal<int>(response.left()->mapnik_tile().layers_size(), 1, "should have one layer");
}
} // anonymous namespace
int main() {
int tests_failed = 0;
std::cout << "== Testing HTTP fetching ==" << std::endl << std::endl;
// need datasource cache set up so that input plugins are available
// when we parse map XML.
mapnik::datasource_cache::instance().register_datasources(MAPNIK_DEFAULT_INPUT_PLUGIN_DIR);
#define RUN_TEST(x) { tests_failed += test::run(#x, &(x)); }
RUN_TEST(test_fetch_empty);
RUN_TEST(test_fetch_single_line);
std::cout << " >> Tests failed: " << tests_failed << std::endl << std::endl;
return (tests_failed > 0) ? 1 : 0;
}
<commit_msg>Added a new test for HTTP status codes and factored out common patterns in existing tests.<commit_after>#include "config.h"
#include "common.hpp"
#include "fetcher_io.hpp"
#include "fetch/http.hpp"
#include "logging/logger.hpp"
#include "http_server/server.hpp"
#include "vector_tile.pb.h"
#include <mapnik/datasource_cache.hpp>
#include <iostream>
namespace {
server_options default_options(const std::string &map_file) {
server_options options;
options.path_multiplier = 16;
options.buffer_size = 0;
options.scale_factor = 1.0;
options.offset_x = 0;
options.offset_y = 0;
options.tolerance = 1;
options.image_format = "jpeg";
options.scaling_method = mapnik::SCALING_NEAR;
options.scale_denominator = 0.0;
options.thread_hint = 1;
options.map_file = map_file;
options.port = "";
return options;
}
struct server_guard {
server_options options;
http::server3::server server;
std::string port;
server_guard(const std::string &map_xml)
: options(default_options(map_xml))
, server("localhost", options)
, port(server.port()) {
server.run(false);
}
~server_guard() {
server.stop();
}
std::string base_url() {
return (boost::format("http://localhost:%1%") % port).str();
}
};
void test_fetch_empty() {
server_guard guard("test/empty_map_file.xml");
avecado::fetch::http fetch(guard.base_url(), "pbf");
avecado::fetch_response response(fetch(0, 0, 0));
test::assert_equal<bool>(response.is_left(), true, "should fetch tile OK");
test::assert_equal<int>(response.left()->mapnik_tile().layers_size(), 0, "should have no layers");
}
void test_fetch_single_line() {
server_guard guard("test/single_line.xml");
avecado::fetch::http fetch(guard.base_url(), "pbf");
avecado::fetch_response response(fetch(0, 0, 0));
test::assert_equal<bool>(response.is_left(), true, "should fetch tile OK");
test::assert_equal<int>(response.left()->mapnik_tile().layers_size(), 1, "should have one layer");
}
void assert_is_error(avecado::fetch::http &fetch, int z, int x, int y, avecado::fetch_status status) {
avecado::fetch_response response(fetch(z, x, y));
test::assert_equal<bool>(response.is_right(), true, (boost::format("(%1%, %2%, %3%): response should be failure") % z % x % y).str());
test::assert_equal<avecado::fetch_status>(response.right().status, status,
(boost::format("(%1%, %2%, %3%): response status is not what was expected") % z % x % y).str());
}
void test_fetch_errors() {
using avecado::fetch_status;
server_guard guard("test/empty_map_file.xml");
avecado::fetch::http fetch(guard.base_url(), "pbf");
assert_is_error(fetch, 0, 0, 1, fetch_status::bad_request);
}
} // anonymous namespace
int main() {
int tests_failed = 0;
std::cout << "== Testing HTTP fetching ==" << std::endl << std::endl;
// need datasource cache set up so that input plugins are available
// when we parse map XML.
mapnik::datasource_cache::instance().register_datasources(MAPNIK_DEFAULT_INPUT_PLUGIN_DIR);
#define RUN_TEST(x) { tests_failed += test::run(#x, &(x)); }
RUN_TEST(test_fetch_empty);
RUN_TEST(test_fetch_single_line);
RUN_TEST(test_fetch_errors);
std::cout << " >> Tests failed: " << tests_failed << std::endl << std::endl;
return (tests_failed > 0) ? 1 : 0;
}
<|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_PLAYGROUND_PRODUCTS_BASE_HH
#define DUNE_GDT_PLAYGROUND_PRODUCTS_BASE_HH
#include <type_traits>
#include <dune/grid/common/gridview.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/common/tmp-storage.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/walker.hh>
#include <dune/stuff/la/container/pattern.hh>
#include <dune/gdt/assembler/system.hh>
#include <dune/gdt/localoperator/codim1.hh>
#include <dune/gdt/playground/localevaluation/swipdg.hh>
#include <dune/gdt/products/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>
namespace Dune {
namespace GDT {
namespace Products {
// forward, needed for the traits
template< class GridViewImp,
class DiffusionFactorImp,
class RangeImp,
class SourceImp,
class FieldImp,
class DiffusionTensorImp >
class EllipticSWIPDGPenaltyLocalizable;
namespace internal {
template< class GridViewImp,
class DiffusionFactorImp,
class RangeImp,
class SourceImp,
class FieldImp,
class DiffusionTensorImp >
class EllipticSWIPDGPenaltyLocalizableTraits
{
public:
typedef EllipticSWIPDGPenaltyLocalizable
< GridViewImp, DiffusionFactorImp, RangeImp, SourceImp, FieldImp, DiffusionTensorImp > derived_type;
typedef GridViewImp GridViewType;
typedef RangeImp RangeType;
typedef SourceImp SourceType;
typedef FieldImp FieldType;
}; // class EllipticSWIPDGPenaltyLocalizableTraits
} // namespace internal
template< class GridViewImp,
class DiffusionFactorImp,
class RangeImp,
class SourceImp = RangeImp,
class FieldImp = double,
class DiffusionTensorImp = void >
class EllipticSWIPDGPenaltyLocalizable
: public LocalizableProductInterface< internal::EllipticSWIPDGPenaltyLocalizableTraits< GridViewImp, DiffusionFactorImp, RangeImp, SourceImp, FieldImp, DiffusionTensorImp > >
, public Stuff::Grid::Functor::Codim1< GridViewImp >
{
typedef LocalizableProductInterface< internal::EllipticSWIPDGPenaltyLocalizableTraits
< GridViewImp, DiffusionFactorImp, RangeImp, SourceImp, FieldImp, DiffusionTensorImp > > ProductBaseType;
typedef Stuff::Grid::Functor::Codim1< GridViewImp > FunctorBaseType;
public:
typedef internal::EllipticSWIPDGPenaltyLocalizableTraits
< GridViewImp, DiffusionFactorImp, RangeImp, SourceImp, FieldImp, DiffusionTensorImp > Traits;
typedef typename FunctorBaseType::GridViewType GridViewType;
typedef typename ProductBaseType::RangeType RangeType;
typedef typename ProductBaseType::SourceType SourceType;
typedef typename ProductBaseType::FieldType FieldType;
typedef typename FunctorBaseType::EntityType EntityType;
typedef typename FunctorBaseType::IntersectionType IntersectionType;
typedef DiffusionFactorImp DiffusionFactorType;
typedef DiffusionTensorImp DiffusionTensorType;
typedef LocalOperator::Codim1CouplingIntegral
< LocalEvaluation::SWIPDG::InnerPenalty< DiffusionFactorType, DiffusionTensorType > > CouplingOperatorType;
typedef LocalOperator::Codim1BoundaryIntegral
< LocalEvaluation::SWIPDG::BoundaryLHSPenalty< DiffusionFactorType, DiffusionTensorType > > BoundaryOperatorType;
private:
typedef DSC::TmpMatricesStorage< FieldType > TmpMatricesProviderType;
public:
EllipticSWIPDGPenaltyLocalizable(const GridViewType& grd_vw,
const RangeType& rng,
const SourceType& src,
const DiffusionFactorType& diffusion_factor,
const DiffusionTensorType& diffusion_tensor,
const size_t over_integrate = 0)
: grid_view_(grd_vw)
, range_(rng)
, source_(src)
, diffusion_factor_(diffusion_factor)
, diffusion_tensor_(diffusion_tensor)
, coupling_operator_(over_integrate, diffusion_factor_, diffusion_tensor_)
, boundary_operator_(over_integrate, diffusion_factor_, diffusion_tensor_)
, inner_intersections_()
, boundary_intersections_()
, tmp_storage_(nullptr)
, prepared_(false)
, finalized_(false)
, result_(0)
, finalized_result_(0)
{}
virtual ~EllipticSWIPDGPenaltyLocalizable() {}
const GridViewType& grid_view() const
{
return grid_view_;
}
const RangeType& range() const
{
return range_;
}
const SourceType& source() const
{
return source_;
}
virtual void prepare() DS_OVERRIDE
{
if (!prepared_) {
tmp_storage_ = std::unique_ptr< TmpMatricesProviderType >(new TmpMatricesProviderType({4,
std::max(coupling_operator_.numTmpObjectsRequired(),
boundary_operator_.numTmpObjectsRequired())},
1, 1));
result_ = FieldType(0.0);
prepared_ = true;
}
} // ... prepare()
FieldType compute_locally(const IntersectionType& intersection,
const EntityType& inside_entity,
const EntityType& outside_entity) const
{
assert(prepared_);
assert(tmp_storage_);
auto& tmp_storage = tmp_storage_->matrices();
assert(tmp_storage.size() >= 2);
assert(tmp_storage[0].size() >= 4);
auto& local_operator_result_en_en = tmp_storage[0][0];
auto& local_operator_result_ne_ne = tmp_storage[0][1];
auto& local_operator_result_en_ne = tmp_storage[0][2];
auto& local_operator_result_ne_en = tmp_storage[0][3];
auto& tmp_matrices = tmp_storage[1];
// get the local functions
const auto local_source_ptr_en = this->source().local_function(inside_entity);
const auto local_source_ptr_ne = this->source().local_function(outside_entity);
const auto local_range_ptr_en = this->range().local_function(inside_entity);
const auto local_range_ptr_ne = this->range().local_function(outside_entity);
// apply local operator
FieldType ret = 0;
if (inner_intersections_.apply_on(grid_view_, intersection)) {
coupling_operator_.apply(*local_range_ptr_en,
*local_source_ptr_en,
*local_source_ptr_ne,
*local_range_ptr_ne,
intersection,
local_operator_result_en_en,
local_operator_result_ne_ne,
local_operator_result_en_ne,
local_operator_result_ne_en,
tmp_matrices);
assert(local_operator_result_en_en.rows() == 1);
assert(local_operator_result_en_en.cols() == 1);
assert(local_operator_result_ne_ne.rows() == 1);
assert(local_operator_result_ne_ne.cols() == 1);
assert(local_operator_result_en_ne.rows() == 1);
assert(local_operator_result_en_ne.cols() == 1);
assert(local_operator_result_ne_en.rows() == 1);
assert(local_operator_result_ne_en.cols() == 1);
ret += local_operator_result_en_en[0][0]
+ local_operator_result_ne_ne[0][0]
+ local_operator_result_en_ne[0][0]
+ local_operator_result_ne_en[0][0];
}
if (boundary_intersections_.apply_on(grid_view_, intersection)) {
boundary_operator_.apply(*local_range_ptr_en,
*local_source_ptr_en,
intersection,
local_operator_result_en_en,
tmp_matrices);
assert(local_operator_result_en_en.rows() == 1);
assert(local_operator_result_en_en.cols() == 1);
ret += local_operator_result_en_en[0][0];
}
return ret;
} // ... compute_locally(...)
virtual void apply_local(const IntersectionType& intersection,
const EntityType& inside_entity,
const EntityType& outside_entity) DS_OVERRIDE
{
*result_ += compute_locally(intersection, inside_entity, outside_entity);
}
virtual void finalize() DS_OVERRIDE
{
if (!finalized_) {
finalized_result_ = result_.sum();
finalized_result_ = grid_view_.comm().sum(finalized_result_);
finalized_ = true;
}
} // ... finalize(...)
FieldType apply2()
{
if (!finalized_) {
Stuff::Grid::Walker< GridViewType > grid_walker(grid_view_);
grid_walker.add(*this);
grid_walker.walk();
}
return finalized_result_;
} // ... apply2(...)
private:
const GridViewType& grid_view_;
const RangeType& range_;
const SourceType& source_;
const DiffusionFactorType& diffusion_factor_;
const DiffusionTensorType& diffusion_tensor_;
const CouplingOperatorType coupling_operator_;
const BoundaryOperatorType boundary_operator_;
const DSG::ApplyOn::InnerIntersectionsPrimally< GridViewType > inner_intersections_;
const DSG::ApplyOn::BoundaryIntersections< GridViewType > boundary_intersections_;
std::unique_ptr< TmpMatricesProviderType > tmp_storage_;
bool prepared_;
bool finalized_;
DS::PerThreadValue< FieldType > result_;
FieldType finalized_result_;
}; // class EllipticSWIPDGPenaltyLocalizable
} // namespace Products
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_PLAYGROUND_PRODUCTS_BASE_HH
<commit_msg>[products.elliptic-swipdg] added first draft of assemblable product<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_PLAYGROUND_PRODUCTS_BASE_HH
#define DUNE_GDT_PLAYGROUND_PRODUCTS_BASE_HH
#include <type_traits>
#include <dune/grid/common/gridview.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/common/tmp-storage.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/walker.hh>
#include <dune/stuff/la/container/pattern.hh>
#include <dune/gdt/assembler/system.hh>
#include <dune/gdt/assembler/local/codim1.hh>
#include <dune/gdt/localoperator/codim1.hh>
#include <dune/gdt/playground/localevaluation/swipdg.hh>
#include <dune/gdt/products/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>
namespace Dune {
namespace GDT {
namespace Products {
// forward, needed for the traits
template< class GridViewImp,
class DiffusionFactorImp,
class RangeImp,
class SourceImp,
class FieldImp,
class DiffusionTensorImp >
class EllipticSWIPDGPenaltyLocalizable;
template< class DiffusionFactorImp,
class MatrixImp,
class RangeSpaceImp,
class GridViewImp,
class SourceSpaceImp,
class DiffusionTensorImp >
class EllipticSWIPDGPenaltyAssemblable;
namespace internal {
template< class GridViewImp,
class DiffusionFactorImp,
class RangeImp,
class SourceImp,
class FieldImp,
class DiffusionTensorImp >
class EllipticSWIPDGPenaltyLocalizableTraits
{
public:
typedef EllipticSWIPDGPenaltyLocalizable
< GridViewImp, DiffusionFactorImp, RangeImp, SourceImp, FieldImp, DiffusionTensorImp > derived_type;
typedef GridViewImp GridViewType;
typedef RangeImp RangeType;
typedef SourceImp SourceType;
typedef FieldImp FieldType;
}; // class EllipticSWIPDGPenaltyLocalizableTraits
template< class DiffusionFactorImp,
class MatrixImp,
class RangeSpaceImp,
class GridViewImp,
class SourceSpaceImp,
class DiffusionTensorImp >
class EllipticSWIPDGPenaltyAssemblableTraits
{
public:
typedef EllipticSWIPDGPenaltyAssemblable
< DiffusionFactorImp, MatrixImp, RangeSpaceImp, GridViewImp, SourceSpaceImp, DiffusionTensorImp > derived_type;
typedef GridViewImp GridViewType;
typedef RangeSpaceImp RangeSpaceType;
typedef SourceSpaceImp SourceSpaceType;
typedef MatrixImp MatrixType;
}; // class EllipticSWIPDGPenaltyAssemblableTraits
} // namespace internal
template< class GridViewImp,
class DiffusionFactorImp,
class RangeImp,
class SourceImp = RangeImp,
class FieldImp = double,
class DiffusionTensorImp = void >
class EllipticSWIPDGPenaltyLocalizable
: public LocalizableProductInterface< internal::EllipticSWIPDGPenaltyLocalizableTraits< GridViewImp, DiffusionFactorImp, RangeImp, SourceImp, FieldImp, DiffusionTensorImp > >
, public Stuff::Grid::Functor::Codim1< GridViewImp >
{
typedef LocalizableProductInterface< internal::EllipticSWIPDGPenaltyLocalizableTraits
< GridViewImp, DiffusionFactorImp, RangeImp, SourceImp, FieldImp, DiffusionTensorImp > > ProductBaseType;
typedef Stuff::Grid::Functor::Codim1< GridViewImp > FunctorBaseType;
public:
typedef internal::EllipticSWIPDGPenaltyLocalizableTraits
< GridViewImp, DiffusionFactorImp, RangeImp, SourceImp, FieldImp, DiffusionTensorImp > Traits;
typedef typename FunctorBaseType::GridViewType GridViewType;
typedef typename ProductBaseType::RangeType RangeType;
typedef typename ProductBaseType::SourceType SourceType;
typedef typename ProductBaseType::FieldType FieldType;
typedef typename FunctorBaseType::EntityType EntityType;
typedef typename FunctorBaseType::IntersectionType IntersectionType;
typedef DiffusionFactorImp DiffusionFactorType;
typedef DiffusionTensorImp DiffusionTensorType;
typedef LocalOperator::Codim1CouplingIntegral
< LocalEvaluation::SWIPDG::InnerPenalty< DiffusionFactorType, DiffusionTensorType > > CouplingOperatorType;
typedef LocalOperator::Codim1BoundaryIntegral
< LocalEvaluation::SWIPDG::BoundaryLHSPenalty< DiffusionFactorType, DiffusionTensorType > > BoundaryOperatorType;
private:
typedef DSC::TmpMatricesStorage< FieldType > TmpMatricesProviderType;
public:
EllipticSWIPDGPenaltyLocalizable(const GridViewType& grd_vw,
const RangeType& rng,
const SourceType& src,
const DiffusionFactorType& diffusion_factor,
const DiffusionTensorType& diffusion_tensor,
const size_t over_integrate = 0)
: grid_view_(grd_vw)
, range_(rng)
, source_(src)
, diffusion_factor_(diffusion_factor)
, diffusion_tensor_(diffusion_tensor)
, coupling_operator_(over_integrate, diffusion_factor_, diffusion_tensor_)
, boundary_operator_(over_integrate, diffusion_factor_, diffusion_tensor_)
, inner_intersections_()
, boundary_intersections_()
, tmp_storage_(nullptr)
, prepared_(false)
, finalized_(false)
, result_(0)
, finalized_result_(0)
{}
virtual ~EllipticSWIPDGPenaltyLocalizable() {}
const GridViewType& grid_view() const
{
return grid_view_;
}
const RangeType& range() const
{
return range_;
}
const SourceType& source() const
{
return source_;
}
virtual void prepare() DS_OVERRIDE
{
if (!prepared_) {
tmp_storage_ = std::unique_ptr< TmpMatricesProviderType >(new TmpMatricesProviderType({4,
std::max(coupling_operator_.numTmpObjectsRequired(),
boundary_operator_.numTmpObjectsRequired())},
1, 1));
result_ = FieldType(0.0);
prepared_ = true;
}
} // ... prepare()
FieldType compute_locally(const IntersectionType& intersection,
const EntityType& inside_entity,
const EntityType& outside_entity) const
{
assert(prepared_);
assert(tmp_storage_);
auto& tmp_storage = tmp_storage_->matrices();
assert(tmp_storage.size() >= 2);
assert(tmp_storage[0].size() >= 4);
auto& local_operator_result_en_en = tmp_storage[0][0];
auto& local_operator_result_ne_ne = tmp_storage[0][1];
auto& local_operator_result_en_ne = tmp_storage[0][2];
auto& local_operator_result_ne_en = tmp_storage[0][3];
auto& tmp_matrices = tmp_storage[1];
// get the local functions
const auto local_source_ptr_en = this->source().local_function(inside_entity);
const auto local_source_ptr_ne = this->source().local_function(outside_entity);
const auto local_range_ptr_en = this->range().local_function(inside_entity);
const auto local_range_ptr_ne = this->range().local_function(outside_entity);
// apply local operator
FieldType ret = 0;
if (inner_intersections_.apply_on(grid_view_, intersection)) {
coupling_operator_.apply(*local_range_ptr_en,
*local_source_ptr_en,
*local_source_ptr_ne,
*local_range_ptr_ne,
intersection,
local_operator_result_en_en,
local_operator_result_ne_ne,
local_operator_result_en_ne,
local_operator_result_ne_en,
tmp_matrices);
assert(local_operator_result_en_en.rows() == 1);
assert(local_operator_result_en_en.cols() == 1);
assert(local_operator_result_ne_ne.rows() == 1);
assert(local_operator_result_ne_ne.cols() == 1);
assert(local_operator_result_en_ne.rows() == 1);
assert(local_operator_result_en_ne.cols() == 1);
assert(local_operator_result_ne_en.rows() == 1);
assert(local_operator_result_ne_en.cols() == 1);
ret += local_operator_result_en_en[0][0]
+ local_operator_result_ne_ne[0][0]
+ local_operator_result_en_ne[0][0]
+ local_operator_result_ne_en[0][0];
}
if (boundary_intersections_.apply_on(grid_view_, intersection)) {
boundary_operator_.apply(*local_range_ptr_en,
*local_source_ptr_en,
intersection,
local_operator_result_en_en,
tmp_matrices);
assert(local_operator_result_en_en.rows() == 1);
assert(local_operator_result_en_en.cols() == 1);
ret += local_operator_result_en_en[0][0];
}
return ret;
} // ... compute_locally(...)
virtual void apply_local(const IntersectionType& intersection,
const EntityType& inside_entity,
const EntityType& outside_entity) DS_OVERRIDE
{
*result_ += compute_locally(intersection, inside_entity, outside_entity);
}
virtual void finalize() DS_OVERRIDE
{
if (!finalized_) {
finalized_result_ = result_.sum();
finalized_result_ = grid_view_.comm().sum(finalized_result_);
finalized_ = true;
}
} // ... finalize(...)
FieldType apply2()
{
if (!finalized_) {
Stuff::Grid::Walker< GridViewType > grid_walker(grid_view_);
grid_walker.add(*this);
grid_walker.walk();
}
return finalized_result_;
} // ... apply2(...)
private:
const GridViewType& grid_view_;
const RangeType& range_;
const SourceType& source_;
const DiffusionFactorType& diffusion_factor_;
const DiffusionTensorType& diffusion_tensor_;
const CouplingOperatorType coupling_operator_;
const BoundaryOperatorType boundary_operator_;
const DSG::ApplyOn::InnerIntersectionsPrimally< GridViewType > inner_intersections_;
const DSG::ApplyOn::BoundaryIntersections< GridViewType > boundary_intersections_;
std::unique_ptr< TmpMatricesProviderType > tmp_storage_;
bool prepared_;
bool finalized_;
DS::PerThreadValue< FieldType > result_;
FieldType finalized_result_;
}; // class EllipticSWIPDGPenaltyLocalizable
template< class DiffusionFactorImp,
class MatrixImp,
class RangeSpaceImp,
class GridViewImp = typename RangeSpaceImp::GridViewType,
class SourceSpaceImp = RangeSpaceImp,
class DiffusionTensorImp = void >
class EllipticSWIPDGPenaltyAssemblable
: DSC::StorageProvider< MatrixImp >
, public AssemblableProductInterface< internal::EllipticSWIPDGPenaltyAssemblableTraits
< DiffusionFactorImp, MatrixImp, RangeSpaceImp, GridViewImp, SourceSpaceImp, DiffusionTensorImp > >
, public SystemAssembler< RangeSpaceImp, GridViewImp, SourceSpaceImp >
{
typedef DSC::StorageProvider< MatrixImp > StorageBaseType;
typedef AssemblableProductInterface< internal::EllipticSWIPDGPenaltyAssemblableTraits
< DiffusionFactorImp, MatrixImp, RangeSpaceImp, GridViewImp, SourceSpaceImp, DiffusionTensorImp > >
ProductBaseType;
typedef SystemAssembler < RangeSpaceImp, GridViewImp, SourceSpaceImp > AssemblerBaseType;
public:
typedef internal::EllipticSWIPDGPenaltyAssemblableTraits
< DiffusionFactorImp, MatrixImp, RangeSpaceImp, GridViewImp, SourceSpaceImp, DiffusionTensorImp > Traits;
typedef typename AssemblerBaseType::GridViewType GridViewType;
typedef typename ProductBaseType::RangeSpaceType RangeSpaceType;
typedef typename ProductBaseType::SourceSpaceType SourceSpaceType;
typedef typename ProductBaseType::FieldType FieldType;
typedef typename ProductBaseType::MatrixType MatrixType;
typedef typename AssemblerBaseType::EntityType EntityType;
typedef typename AssemblerBaseType::IntersectionType IntersectionType;
typedef DiffusionFactorImp DiffusionFactorType;
typedef DiffusionTensorImp DiffusionTensorType;
typedef LocalOperator::Codim1CouplingIntegral
< LocalEvaluation::SWIPDG::InnerPenalty< DiffusionFactorType, DiffusionTensorType > > CouplingOperatorType;
typedef LocalOperator::Codim1BoundaryIntegral
< LocalEvaluation::SWIPDG::BoundaryLHSPenalty< DiffusionFactorType, DiffusionTensorType > > BoundaryOperatorType;
typedef LocalAssembler::Codim1CouplingMatrix< CouplingOperatorType > CouplingAssemblerType;
typedef LocalAssembler::Codim1BoundaryMatrix< BoundaryOperatorType > BoundaryAssemblerType;
using ProductBaseType::pattern;
static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,
const SourceSpaceType& source_space,
const GridViewType& grid_view)
{
return range_space.compute_face_and_volume_pattern(grid_view, source_space);
}
EllipticSWIPDGPenaltyAssemblable(const RangeSpaceType& rng_spc,
const GridViewType& grd_vw,
const SourceSpaceType& src_spc,
const DiffusionFactorImp& diffusion_factor,
const DiffusionTensorImp& diffusion_tensor,
const size_t over_integrate = 0)
: StorageBaseType(new MatrixType(rng_spc.mapper().size(), src_spc.mapper().size(), pattern(rng_spc, src_spc, grd_vw)))
, AssemblerBaseType(rng_spc, src_spc, grd_vw)
, diffusion_factor_(diffusion_factor)
, diffusion_tensor_(diffusion_tensor)
, coupling_operator_(over_integrate, diffusion_factor_, diffusion_tensor_)
, boundary_operator_(over_integrate, diffusion_factor_, diffusion_tensor_)
, coupling_assembler_(coupling_operator_)
, boundary_assembler_(boundary_operator_)
, assembled_(false)
{
setup();
}
const GridViewType& grid_view() const
{
return AssemblerBaseType::grid_view();
}
const RangeSpaceType& range_space() const
{
return AssemblerBaseType::test_space();
}
const SourceSpaceType& source_space() const
{
return AssemblerBaseType::ansatz_space();
}
MatrixType& matrix()
{
return StorageBaseType::storage_access();
}
const MatrixType& matrix() const
{
return StorageBaseType::storage_access();
}
void assemble()
{
if (!assembled_) {
AssemblerBaseType::assemble();
assembled_ = true;
}
} // ... assemble()
private:
void setup()
{
this->add(coupling_assembler_, matrix(), new DSG::ApplyOn::InnerIntersectionsPrimally< GridViewType >());
this->add(boundary_assembler_, matrix(), new DSG::ApplyOn::BoundaryIntersections< GridViewType >());
}
const DiffusionFactorType& diffusion_factor_;
const DiffusionTensorType& diffusion_tensor_;
const CouplingOperatorType coupling_operator_;
const BoundaryOperatorType boundary_operator_;
const CouplingAssemblerType coupling_assembler_;
const BoundaryAssemblerType boundary_assembler_;
bool assembled_;
}; // class EllipticSWIPDGPenaltyAssemblable
} // namespace Products
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_PLAYGROUND_PRODUCTS_BASE_HH
<|endoftext|> |
<commit_before>// graph.cpp: Santiago Arias
// Description: Graph algo
#include <iostream>
#include <vector>
using namespace std;
//using std::vector;
class Edgenode{//node
public:
Edgenode(): value(-1){ }
Edgenode(int v):value(v){}
int value;
};
class Graph{
public:
Graph():
nvertices(0), nedges(0), edges(0, vector<Edgenode*>(0)){}
Graph(int number_nodes);
int V(); // returns the number of vertices in the graph
int E(); // returns the number of edges in the graph
bool adjacent(int x, int y); // tests whether there is an edge from node x to node y.
vector<Edgenode*> neighbors(int x, int y); // lists all nodes y such that there is an edge from x to y.
void add(int x, int y); // adds to G the edge from x to y, if it is not there.
void remove(int x, int y); // removes the edge from x to y, if it is there.
int get_node_value(Edgenode x); // returns the value associated with the node x.
void set_node_value(Edgenode x, Edgenode a); // sets the value associated with the node x to a.
int get_edge_value(int x, int y); // returns the value associated to the edge (x,y).
void set_edge_value(int x, int y, Edgenode *v); // sets the value associated to the edge (x,y) to v.
void print();
private:
int nvertices; // number of vertices
int nedges; // number of edges
vector< vector<Edgenode*> > edges; // adjacency information
};
Graph::Graph(int nnodes):
edges(nnodes, vector<Edgenode*>(nnodes))
{
for(int i = 0; i < nnodes; ++i)
for(int j = i; j < nnodes; ++j){
if(i == j){
edges[i][j] = 0; // null pointer no loops
}
else{
edges[i][j] = new Edgenode(1);
edges[j][i] = edges[i][j];
nedges++;
nvertices += 2;
}
}
}
// returns the number of vertices in the graph
int Graph::V(){
return nvertices;
}
// returns the number of edges in the graph
int Graph::E(){
return nedges;
}
// tests whether there is an edge from node x to node y.
bool Graph::adjacent(int x, int y){
if(x < edges.size() && y < edges[x].size()){
if(edges[x][y] != 0)
return true;
}
return false;
}
// lists all nodes y such that there is an edge from x to y.
vector<Edgenode*> Graph::neighbors(int x, int y){
if(y < edges.size()){
return edges[y];
}
return vector<Edgenode*>();
}
// adds to G the edge from x to y, if it is not there.
void Graph::add(int x, int y){
if(x < edges.size() && y < edges[x].size()){
if(edges[x][y] == 0){
edges[x][y] = new Edgenode(1);
edges[y][x] = edges[x][y];
}
}
}
// removes the edge from x to y, if it is there.
void Graph::remove(int x, int y){
if(x < edges.size() && y < edges[x].size()){
edges[x][y] = 0;
edges[y][x] = 0;
}
}
// returns the value associated with the node x.
int Graph::get_node_value(Edgenode x){
return x.value;
}
// sets the value associated with the node x to a.
void Graph::set_node_value(Edgenode x, Edgenode a){
a.value = x.value;
}
// returns the value associated to the edge (x,y).
int Graph::get_edge_value(int x, int y){
if(x < edges.size() && y < edges[x].size()){
if(edges[x][y])
return edges[x][y]->value;
}
return 0;
}
// sets the value associated to the edge (x,y)
void Graph::set_edge_value(int x, int y, Edgenode *e){
if(x < edges.size() && y < edges[x].size()){
if(edges[x][y] && e){
e->value = edges[x][y]->value;
}
}
}
void Graph::print(){
for(int i = 0; i < edges.size(); ++i){
for(int j = 0; j < edges.size(); ++j){
if(edges[i][j])
cout << edges[i][j]->value << " ";
else
cout << "x" << " ";
}
cout << endl;
}
}
int main(){
Graph g(4);
g.print();
return 0;
}
<commit_msg>testing graph<commit_after>// graph.cpp: Santiago Arias
// Description: Graph algo
#include <iostream>
#include <vector>
using namespace std;
//using std::vector;
class Edgenode{//node
public:
Edgenode(): value(-1){ }
Edgenode(int v):value(v){}
int value;
};
class Graph{
public:
Graph():
nvertices(0), nedges(0), edges(0, vector<Edgenode*>(0)){}
Graph(int number_nodes);
int V(); // returns the number of vertices in the graph
int E(); // returns the number of edges in the graph
bool adjacent(int x, int y); // tests whether there is an edge from node x to node y.
vector<Edgenode*> neighbors(int y); // lists all nodes y such that there is an edge from x to y.
void add(int x, int y); // adds to G the edge from x to y, if it is not there.
void remove(int x, int y); // removes the edge from x to y, if it is there.
int get_node_value(Edgenode x); // returns the value associated with the node x.
void set_node_value(Edgenode x, Edgenode a); // sets the value associated with the node x to a.
int get_edge_value(int x, int y); // returns the value associated to the edge (x,y).
void set_edge_value(int x, int y, Edgenode *v); // sets the value associated to the edge (x,y) to v.
void print();
private:
int nvertices; // number of vertices
int nedges; // number of edges
vector< vector<Edgenode*> > edges; // adjacency information
};
Graph::Graph(int nnodes):
nedges(0), nvertices(0), edges(nnodes, vector<Edgenode*>(nnodes))
{
for(int i = 0; i < nnodes; ++i){
nvertices++;
for(int j = i; j < nnodes; ++j){
if(i == j){
edges[i][j] = 0; // null pointer no loops
} else {
edges[i][j] = new Edgenode(1);
edges[j][i] = edges[i][j];
nedges++;
}
}
}
}
// returns the number of vertices in the graph
int Graph::V(){
return nvertices;
}
// returns the number of edges in the graph
int Graph::E(){
return nedges;
}
// tests whether there is an edge from node x to node y.
bool Graph::adjacent(int x, int y){
if(x < edges.size() && y < edges[x].size()){
if(edges[x][y] != 0)
return true;
}
return false;
}
// lists all nodes y such that there is an edge from x to y.
vector<Edgenode*> Graph::neighbors(int y){
if(y < edges.size()){
return edges[y];
}
return vector<Edgenode*>();
}
// adds to G the edge from x to y, if it is not there.
void Graph::add(int x, int y){
if(x < edges.size() && y < edges[x].size()){
if(edges[x][y] == 0){
edges[x][y] = new Edgenode(1);
edges[y][x] = edges[x][y];
}
}
}
// removes the edge from x to y, if it is there.
void Graph::remove(int x, int y){
if(x < edges.size() && y < edges[x].size()){
edges[x][y] = 0;
edges[y][x] = 0;
}
}
// returns the value associated with the node x.
int Graph::get_node_value(Edgenode x){
return x.value;
}
// sets the value associated with the node x to a.
void Graph::set_node_value(Edgenode x, Edgenode a){
a.value = x.value;
}
// returns the value associated to the edge (x,y).
int Graph::get_edge_value(int x, int y){
if(x < edges.size() && y < edges[x].size()){
if(edges[x][y])
return edges[x][y]->value;
}
return 0;
}
// sets the value associated to the edge (x,y)
void Graph::set_edge_value(int x, int y, Edgenode *e){
if(x < edges.size() && y < edges[x].size()){
if(edges[x][y] && e){
e->value = edges[x][y]->value;
}
}
}
void Graph::print(){
for(int i = 0; i < edges.size(); ++i){
for(int j = 0; j < edges.size(); ++j){
if(edges[i][j])
cout << edges[i][j]->value << " ";
else
cout << "x" << " ";
}
cout << endl;
}
}
void test_graph(){
cout << "test default constructor" << endl;
Graph g1;
g1.print();
cout << endl;
cout << "test size constructor" << endl;
Graph g2(4);
g2.print();
cout << endl;
cout << "test number of vertices in graph" << endl;
cout << boolalpha << (g1.V() == 0) << " " << (g2.V() == 4) << endl;
cout << endl;
cout << "test number of edges in graph" << endl;
cout << boolalpha << (g1.E() == 0) << " " << (g2.E() == 6) << endl;
cout << endl;
cout << "test adjacent method" << endl;
bool result;
bool expected;
for(int i = 0; i < g2.V(); ++i){
for(int j = i; j < g2.V(); ++j){
result = g2.adjacent(i,j);
expected = (i == j)? false:true;
cout << boolalpha << (result == expected) << " ";
}
cout << endl;
}
cout << endl;
cout << "test neighbors method" << endl;
vector<Edgenode*> neighbors1 = g2.neighbors(0);
for(int i = 0; i < neighbors1.size(); ++i){
if(neighbors1[i])
cout << "0 - " << i << endl;
}
cout << "test 2" << endl;
vector<Edgenode*> neighbors2 = g2.neighbors(2);
for(int i = 0; i < neighbors2.size(); ++i){
if(neighbors2[i])
cout << "2 - " << i << endl;
}
cout << endl;
// vector<Edgenode*> neighbors(int x, int y); // lists all nodes y such that there is an edge from x to y.
// void add(int x, int y); // adds to G the edge from x to y, if it is not there.
// void remove(int x, int y); // removes the edge from x to y, if it is there.
// int get_node_value(Edgenode x); // returns the value associated with the node x.
// void set_node_value(Edgenode x, Edgenode a); // sets the value associated with the node x to a.
// int get_edge_value(int x, int y); // returns the value associated to the edge (x,y).
// void set_edge_value(int x, int y, Edgenode *v); // sets the value associated to the edge (x,y) to v.
// void print();
// private:
// int nvertices; // number of vertices
// int nedges; // number of edges
// vector< vector<Edgenode*> > edges; // adjacency information
}
int main(){
test_graph();
return 0;
}
<|endoftext|> |
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#pragma once
#include <deque>
#include <pficommon/concurrent/rwmutex.h>
#include <pficommon/data/serialization.h>
#include <pficommon/data/serialization/unordered_map.h>
#include <pficommon/data/unordered_map.h>
#include <cstdlib>
#include <stdint.h>
#include "../common/exception.hpp"
namespace jubatus {
namespace stat {
class stat_error : public jubatus::exception::jubaexception<stat_error> {
public:
stat_error(const std::string &msg)
: msg_(msg) {}
~stat_error() throw() {}
const char *what() throw() {
return msg_.c_str();
}
private:
std::string msg_;
};
class stat {
public:
stat(size_t window_size);
virtual ~stat();
void push(const std::string &key, double val);
double sum(const std::string &key) const;
double stddev(const std::string &key) const;
double max(const std::string &key) const;
double min(const std::string &key) const;
double entropy() const;
double moment(const std::string &key, int n, double c) const;
bool save(std::ostream&);
bool load(std::istream&);
std::string type() const;
private:
friend class pfi::data::serialization::access;
template <class Archive>
void serialize(Archive &ar) {
ar & window_size_ & window_;
}
size_t window_size_;
struct stat_val {
stat_val()
: n_(0)
, sum_(0)
, max_(0)
, min_(0) {
}
void add(double d) {
n_ += 1;
sum_ += d;
sum2_ += d * d;
if (n_ > 1)
max_ = std::max(max_, d);
else
max_ = d;
if (n_ > 1)
min_ = std::min(min_, d);
else
min_ = d;
}
void rem(double d, const std::string &key, stat &st) {
n_ -= 1;
sum_ -= d;
sum2_ -= d * d;
if (max_ == d) {
if (n_ > 0) {
bool first = true;
for (size_t i = 0; i < st.window_.size(); ++i) {
if (st.window_[i].second.first != key) continue;
double d = st.window_[i].second.second;
if (first) {
max_ = d;
first = false;
}
else {
max_ = std::max(max_, d);
}
}
}
else {
max_ = 0;
}
}
if (min_ == d) {
if (n_ > 0) {
bool first = true;
for (size_t i = 0; i < st.window_.size(); ++i) {
if (st.window_[i].second.first != key) continue;
double d = st.window_[i].second.second;
if (first) {
min_ = d;
first = false;
}
else {
min_ = std::min(min_, d);
}
}
}
else {
min_ = 0;
}
}
}
size_t n_;
double sum_, sum2_;
double max_;
double min_;
};
protected:
std::deque<std::pair<uint64_t, std::pair<std::string, double> > > window_;
pfi::data::unordered_map<std::string, stat_val> stats_;
};
}
} // namespace jubatus
<commit_msg>initialize sum2_<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#pragma once
#include <deque>
#include <pficommon/concurrent/rwmutex.h>
#include <pficommon/data/serialization.h>
#include <pficommon/data/serialization/unordered_map.h>
#include <pficommon/data/unordered_map.h>
#include <cstdlib>
#include <stdint.h>
#include "../common/exception.hpp"
namespace jubatus {
namespace stat {
class stat_error : public jubatus::exception::jubaexception<stat_error> {
public:
stat_error(const std::string &msg)
: msg_(msg) {}
~stat_error() throw() {}
const char *what() throw() {
return msg_.c_str();
}
private:
std::string msg_;
};
class stat {
public:
stat(size_t window_size);
virtual ~stat();
void push(const std::string &key, double val);
double sum(const std::string &key) const;
double stddev(const std::string &key) const;
double max(const std::string &key) const;
double min(const std::string &key) const;
double entropy() const;
double moment(const std::string &key, int n, double c) const;
bool save(std::ostream&);
bool load(std::istream&);
std::string type() const;
private:
friend class pfi::data::serialization::access;
template <class Archive>
void serialize(Archive &ar) {
ar & window_size_ & window_;
}
size_t window_size_;
struct stat_val {
stat_val()
: n_(0)
, sum_(0)
, sum2_(0)
, max_(0)
, min_(0) {
}
void add(double d) {
n_ += 1;
sum_ += d;
sum2_ += d * d;
if (n_ > 1)
max_ = std::max(max_, d);
else
max_ = d;
if (n_ > 1)
min_ = std::min(min_, d);
else
min_ = d;
}
void rem(double d, const std::string &key, stat &st) {
n_ -= 1;
sum_ -= d;
sum2_ -= d * d;
if (max_ == d) {
if (n_ > 0) {
bool first = true;
for (size_t i = 0; i < st.window_.size(); ++i) {
if (st.window_[i].second.first != key) continue;
double d = st.window_[i].second.second;
if (first) {
max_ = d;
first = false;
}
else {
max_ = std::max(max_, d);
}
}
}
else {
max_ = 0;
}
}
if (min_ == d) {
if (n_ > 0) {
bool first = true;
for (size_t i = 0; i < st.window_.size(); ++i) {
if (st.window_[i].second.first != key) continue;
double d = st.window_[i].second.second;
if (first) {
min_ = d;
first = false;
}
else {
min_ = std::min(min_, d);
}
}
}
else {
min_ = 0;
}
}
}
size_t n_;
double sum_, sum2_;
double max_;
double min_;
};
protected:
std::deque<std::pair<uint64_t, std::pair<std::string, double> > > window_;
pfi::data::unordered_map<std::string, stat_val> stats_;
};
}
} // namespace jubatus
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "hash.h"
#include "uint256.h"
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
// Skip leading spaces.
while (*psz && isspace(*psz))
psz++;
// Skip and count leading '1's.
int zeroes = 0;
while (*psz == '1') {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
// Process the characters.
while (*psz && !isspace(*psz)) {
// Decode base58 character
const char* ch = strchr(pszBase58, *psz);
if (ch == NULL)
return false;
// Apply "b256 = b256 * 58 + ch".
int carry = ch - pszBase58;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
psz++;
}
// Skip trailing spaces.
while (isspace(*psz))
psz++;
if (*psz != 0)
return false;
// Skip leading zeroes in b256.
std::vector<unsigned char>::iterator it = b256.begin();
while (it != b256.end() && *it == 0)
it++;
// Copy result into output vector.
vch.reserve(zeroes + (b256.end() - it));
vch.assign(zeroes, 0x00);
while (it != b256.end())
vch.push_back(*(it++));
return true;
}
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
// Skip & count leading zeroes.
int zeroes = 0;
int length = 0;
while (pbegin != pend && *pbegin == 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
int size = (pend - pbegin) * 138 / 100 + 1; // log(256) / log(58), rounded up.
std::vector<unsigned char> b58(size);
// Process the bytes.
while (pbegin != pend) {
int carry = *pbegin;
int i = 0;
// Apply "b58 = b58 * 256 + ch".
for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) {
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(carry == 0);
length = i;
pbegin++;
}
// Skip leading zeroes in base58 result.
std::vector<unsigned char>::iterator it = b58.begin() + (size - length);
while (it != b58.end() && *it == 0)
it++;
// Translate the result into a string.
std::string str;
str.reserve(zeroes + (b58.end() - it));
str.assign(zeroes, '1');
while (it != b58.end())
str += pszBase58[*(it++)];
return str;
}
std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet) ||
(vchRet.size() < 4)) {
vchRet.clear();
return false;
}
// re-calculate the checksum, insure it matches the included 4-byte checksum
uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size() - 4);
return true;
}
bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
CBase58Data::CBase58Data()
{
vchVersion.clear();
vchData.clear();
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
vchVersion = vchVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}
bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
std::vector<unsigned char> vchTemp;
bool rc58 = DecodeBase58Check(psz, vchTemp);
if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
vchData.clear();
vchVersion.clear();
return false;
}
vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
vchData.resize(vchTemp.size() - nVersionBytes);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
memory_cleanse(&vchTemp[0], vchData.size());
return true;
}
bool CBase58Data::SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string CBase58Data::ToString() const
{
std::vector<unsigned char> vch = vchVersion;
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CBase58Data::CompareTo(const CBase58Data& b58) const
{
if (vchVersion < b58.vchVersion)
return -1;
if (vchVersion > b58.vchVersion)
return 1;
if (vchData < b58.vchData)
return -1;
if (vchData > b58.vchData)
return 1;
return 0;
}
namespace
{
class CBitcoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CBitcoinAddress* addr;
public:
CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
bool operator()(const CNoDestination& no) const { return false; }
};
} // anon namespace
bool CBitcoinAddress::Set(const CKeyID& id)
{
SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CScriptID& id)
{
SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CTxDestination& dest)
{
return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
}
bool CBitcoinAddress::IsValid() const
{
return IsValid(Params());
}
bool CBitcoinAddress::IsValid(const CChainParams& params) const
{
bool fCorrectSize = vchData.size() == 20;
bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
return fCorrectSize && fKnownVersion;
}
CTxDestination CBitcoinAddress::Get() const
{
if (!IsValid())
return CNoDestination();
uint160 id;
memcpy(&id, &vchData[0], 20);
if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return CKeyID(id);
else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
return CScriptID(id);
else
return CNoDestination();
}
bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const
{
if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return false;
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
bool CBitcoinAddress::IsScript() const
{
return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}
void CBitcoinSecret::SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey CBitcoinSecret::GetKey()
{
CKey ret;
assert(vchData.size() >= 32);
ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool CBitcoinSecret::IsValid() const
{
bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
return fExpectedFormat && fCorrectVersion;
}
bool CBitcoinSecret::SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool CBitcoinSecret::SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
<commit_msg>CBase58Data::SetString: cleanse the full vector<commit_after>// Copyright (c) 2014-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "hash.h"
#include "uint256.h"
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
// Skip leading spaces.
while (*psz && isspace(*psz))
psz++;
// Skip and count leading '1's.
int zeroes = 0;
while (*psz == '1') {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
// Process the characters.
while (*psz && !isspace(*psz)) {
// Decode base58 character
const char* ch = strchr(pszBase58, *psz);
if (ch == NULL)
return false;
// Apply "b256 = b256 * 58 + ch".
int carry = ch - pszBase58;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
psz++;
}
// Skip trailing spaces.
while (isspace(*psz))
psz++;
if (*psz != 0)
return false;
// Skip leading zeroes in b256.
std::vector<unsigned char>::iterator it = b256.begin();
while (it != b256.end() && *it == 0)
it++;
// Copy result into output vector.
vch.reserve(zeroes + (b256.end() - it));
vch.assign(zeroes, 0x00);
while (it != b256.end())
vch.push_back(*(it++));
return true;
}
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
// Skip & count leading zeroes.
int zeroes = 0;
int length = 0;
while (pbegin != pend && *pbegin == 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
int size = (pend - pbegin) * 138 / 100 + 1; // log(256) / log(58), rounded up.
std::vector<unsigned char> b58(size);
// Process the bytes.
while (pbegin != pend) {
int carry = *pbegin;
int i = 0;
// Apply "b58 = b58 * 256 + ch".
for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) {
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(carry == 0);
length = i;
pbegin++;
}
// Skip leading zeroes in base58 result.
std::vector<unsigned char>::iterator it = b58.begin() + (size - length);
while (it != b58.end() && *it == 0)
it++;
// Translate the result into a string.
std::string str;
str.reserve(zeroes + (b58.end() - it));
str.assign(zeroes, '1');
while (it != b58.end())
str += pszBase58[*(it++)];
return str;
}
std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet) ||
(vchRet.size() < 4)) {
vchRet.clear();
return false;
}
// re-calculate the checksum, insure it matches the included 4-byte checksum
uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size() - 4);
return true;
}
bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
CBase58Data::CBase58Data()
{
vchVersion.clear();
vchData.clear();
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
vchVersion = vchVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}
bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
std::vector<unsigned char> vchTemp;
bool rc58 = DecodeBase58Check(psz, vchTemp);
if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
vchData.clear();
vchVersion.clear();
return false;
}
vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
vchData.resize(vchTemp.size() - nVersionBytes);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
memory_cleanse(&vchTemp[0], vchTemp.size());
return true;
}
bool CBase58Data::SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string CBase58Data::ToString() const
{
std::vector<unsigned char> vch = vchVersion;
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CBase58Data::CompareTo(const CBase58Data& b58) const
{
if (vchVersion < b58.vchVersion)
return -1;
if (vchVersion > b58.vchVersion)
return 1;
if (vchData < b58.vchData)
return -1;
if (vchData > b58.vchData)
return 1;
return 0;
}
namespace
{
class CBitcoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CBitcoinAddress* addr;
public:
CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
bool operator()(const CNoDestination& no) const { return false; }
};
} // anon namespace
bool CBitcoinAddress::Set(const CKeyID& id)
{
SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CScriptID& id)
{
SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CTxDestination& dest)
{
return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
}
bool CBitcoinAddress::IsValid() const
{
return IsValid(Params());
}
bool CBitcoinAddress::IsValid(const CChainParams& params) const
{
bool fCorrectSize = vchData.size() == 20;
bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
return fCorrectSize && fKnownVersion;
}
CTxDestination CBitcoinAddress::Get() const
{
if (!IsValid())
return CNoDestination();
uint160 id;
memcpy(&id, &vchData[0], 20);
if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return CKeyID(id);
else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
return CScriptID(id);
else
return CNoDestination();
}
bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const
{
if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return false;
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
bool CBitcoinAddress::IsScript() const
{
return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}
void CBitcoinSecret::SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey CBitcoinSecret::GetKey()
{
CKey ret;
assert(vchData.size() >= 32);
ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool CBitcoinSecret::IsValid() const
{
bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
return fExpectedFormat && fCorrectVersion;
}
bool CBitcoinSecret::SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool CBitcoinSecret::SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
<|endoftext|> |
<commit_before>/*
OpenDECK library v1.3
File: Buttons.cpp
Last revision date: 2014-12-25
Author: Igor Petrovic
*/
#include "OpenDeck.h"
const uint8_t buttonDebounceCompare = 0b11111000;
void OpenDeck::setButtonPressed(uint8_t buttonNumber, bool state) {
uint8_t arrayIndex = buttonNumber/8;
uint8_t buttonIndex = buttonNumber - 8*arrayIndex;
bitWrite(buttonPressed[arrayIndex], buttonIndex, state);
}
buttonType OpenDeck::getButtonType(uint8_t buttonNumber) {
uint8_t arrayIndex = buttonNumber/8;
uint8_t buttonIndex = buttonNumber - 8*arrayIndex;
if (bitRead(_buttonType[arrayIndex], buttonIndex))
return buttonLatching;
return buttonMomentary;
}
bool OpenDeck::getButtonPCenabled(uint8_t buttonNumber) {
uint8_t arrayIndex = buttonNumber/8;
uint8_t buttonIndex = buttonNumber - 8*arrayIndex;
return bitRead(buttonPCenabled[arrayIndex], buttonIndex);
}
uint8_t OpenDeck::getButtonNote(uint8_t buttonNumber) {
return noteNumber[buttonNumber];
}
bool OpenDeck::getButtonPressed(uint8_t buttonNumber) {
uint8_t arrayIndex = buttonNumber/8;
uint8_t buttonIndex = buttonNumber - 8*arrayIndex;
return bitRead(buttonPressed[arrayIndex], buttonIndex);
}
void OpenDeck::processMomentaryButton(uint8_t buttonNumber, bool buttonState) {
if (buttonState) {
//send note on only once
if (!getButtonPressed(buttonNumber)) {
setButtonPressed(buttonNumber, true);
if (getButtonPCenabled(buttonNumber)) {
sendProgramChange(_programChangeChannel, noteNumber[buttonNumber]);
return;
}
sendMIDInote(noteNumber[buttonNumber], true, _noteChannel);
}
} else { //button is released
if (getButtonPressed(buttonNumber)) {
if (!getButtonPCenabled(buttonNumber))
sendMIDInote(noteNumber[buttonNumber], false, _noteChannel);
setButtonPressed(buttonNumber, false);
}
}
}
void OpenDeck::processLatchingButton(uint8_t buttonNumber, bool buttonState) {
if (buttonState != getPreviousButtonState(buttonNumber)) {
if (buttonState) {
//button is pressed
//if a button has been already pressed
if (getButtonPressed(buttonNumber)) {
sendMIDInote(noteNumber[buttonNumber], false, _noteChannel);
//reset pressed state
setButtonPressed(buttonNumber, false);
} else {
//send note on
sendMIDInote(noteNumber[buttonNumber], true, _noteChannel);
//toggle buttonPressed flag to true
setButtonPressed(buttonNumber, true);
}
}
}
}
void OpenDeck::readButtons() {
#ifdef BOARD
uint8_t availableButtonData = boardObject.buttonDataAvailable();
if (!availableButtonData) return;
for (int i=0; i<availableButtonData; i++) {
uint8_t buttonNumber = boardObject.getButtonNumber(i);
uint8_t buttonState = boardObject.getButtonState(i);
if (buttonDebounced(buttonNumber, buttonState)) {
switch (getButtonType(buttonNumber)) {
case buttonLatching:
processLatchingButton(buttonNumber, buttonState);
break;
case buttonMomentary:
processMomentaryButton(buttonNumber, buttonState);
break;
default:
break;
}
updateButtonState(buttonNumber, buttonState);
}
}
#endif
}
void OpenDeck::updateButtonState(uint8_t buttonNumber, uint8_t buttonState) {
uint8_t arrayIndex = buttonNumber/8;
uint8_t buttonIndex = buttonNumber - 8*arrayIndex;
//update state if it's different than last one
if (bitRead(previousButtonState[arrayIndex], buttonIndex) != buttonState)
bitWrite(previousButtonState[arrayIndex], buttonIndex, buttonState);
}
bool OpenDeck::getPreviousButtonState(uint8_t buttonNumber) {
uint8_t arrayIndex = buttonNumber/8;
uint8_t buttonIndex = buttonNumber - 8*arrayIndex;
return bitRead(previousButtonState[arrayIndex], buttonIndex);
}
bool OpenDeck::buttonDebounced(uint8_t buttonNumber, bool buttonState) {
//shift new button reading into previousButtonState
buttonDebounceCounter[buttonNumber] = (buttonDebounceCounter[buttonNumber] << 1) | buttonState | buttonDebounceCompare;
//if button is debounced, return true
return ((buttonDebounceCounter[buttonNumber] == buttonDebounceCompare) || (buttonDebounceCounter[buttonNumber] == 0xFF));
}
void OpenDeck::sendMIDInote(uint8_t buttonNote, bool buttonState, uint8_t channel) {
switch (buttonState) {
case false:
//button released
if (standardNoteOffEnabled()) {
#ifdef USBMIDI
usbMIDI.sendNoteOff(buttonNote, velocityOff, channel);
#endif
#ifdef HW_MIDI
MIDI.sendNoteOff(buttonNote, velocityOff, channel);
#endif
} else {
#ifdef HW_MIDI
MIDI.sendNoteOn(buttonNote, velocityOff, channel);
#endif
#ifdef USBMIDI
usbMIDI.sendNoteOn(buttonNote, velocityOff, channel);
#endif
}
break;
case true:
//button pressed
#ifdef HW_MIDI
MIDI.sendNoteOn(buttonNote, velocityOn, channel);
#endif
#ifdef USBMIDI
usbMIDI.sendNoteOn(buttonNote, velocityOn, channel);
#endif
break;
}
}
void OpenDeck::sendProgramChange(uint8_t channel, uint8_t program) {
#ifdef USBMIDI
usbMIDI.sendProgramChange(program, channel);
#endif
#ifdef HW_MIDI
MIDI.sendProgramChange(program, channel);
#endif
}<commit_msg>reduce button debounce time<commit_after>/*
OpenDECK library v1.3
File: Buttons.cpp
Last revision date: 2014-12-25
Author: Igor Petrovic
*/
#include "OpenDeck.h"
const uint8_t buttonDebounceCompare = 0b11111100;
void OpenDeck::setButtonPressed(uint8_t buttonNumber, bool state) {
uint8_t arrayIndex = buttonNumber/8;
uint8_t buttonIndex = buttonNumber - 8*arrayIndex;
bitWrite(buttonPressed[arrayIndex], buttonIndex, state);
}
buttonType OpenDeck::getButtonType(uint8_t buttonNumber) {
uint8_t arrayIndex = buttonNumber/8;
uint8_t buttonIndex = buttonNumber - 8*arrayIndex;
if (bitRead(_buttonType[arrayIndex], buttonIndex))
return buttonLatching;
return buttonMomentary;
}
bool OpenDeck::getButtonPCenabled(uint8_t buttonNumber) {
uint8_t arrayIndex = buttonNumber/8;
uint8_t buttonIndex = buttonNumber - 8*arrayIndex;
return bitRead(buttonPCenabled[arrayIndex], buttonIndex);
}
uint8_t OpenDeck::getButtonNote(uint8_t buttonNumber) {
return noteNumber[buttonNumber];
}
bool OpenDeck::getButtonPressed(uint8_t buttonNumber) {
uint8_t arrayIndex = buttonNumber/8;
uint8_t buttonIndex = buttonNumber - 8*arrayIndex;
return bitRead(buttonPressed[arrayIndex], buttonIndex);
}
void OpenDeck::processMomentaryButton(uint8_t buttonNumber, bool buttonState) {
if (buttonState) {
//send note on only once
if (!getButtonPressed(buttonNumber)) {
setButtonPressed(buttonNumber, true);
if (getButtonPCenabled(buttonNumber)) {
sendProgramChange(_programChangeChannel, noteNumber[buttonNumber]);
return;
}
sendMIDInote(noteNumber[buttonNumber], true, _noteChannel);
}
} else { //button is released
if (getButtonPressed(buttonNumber)) {
if (!getButtonPCenabled(buttonNumber))
sendMIDInote(noteNumber[buttonNumber], false, _noteChannel);
setButtonPressed(buttonNumber, false);
}
}
}
void OpenDeck::processLatchingButton(uint8_t buttonNumber, bool buttonState) {
if (buttonState != getPreviousButtonState(buttonNumber)) {
if (buttonState) {
//button is pressed
//if a button has been already pressed
if (getButtonPressed(buttonNumber)) {
sendMIDInote(noteNumber[buttonNumber], false, _noteChannel);
//reset pressed state
setButtonPressed(buttonNumber, false);
} else {
//send note on
sendMIDInote(noteNumber[buttonNumber], true, _noteChannel);
//toggle buttonPressed flag to true
setButtonPressed(buttonNumber, true);
}
}
}
}
void OpenDeck::readButtons() {
#ifdef BOARD
uint8_t availableButtonData = boardObject.buttonDataAvailable();
if (!availableButtonData) return;
for (int i=0; i<availableButtonData; i++) {
uint8_t buttonNumber = boardObject.getButtonNumber(i);
uint8_t buttonState = boardObject.getButtonState(i);
if (buttonDebounced(buttonNumber, buttonState)) {
switch (getButtonType(buttonNumber)) {
case buttonLatching:
processLatchingButton(buttonNumber, buttonState);
break;
case buttonMomentary:
processMomentaryButton(buttonNumber, buttonState);
break;
default:
break;
}
updateButtonState(buttonNumber, buttonState);
}
}
#endif
}
void OpenDeck::updateButtonState(uint8_t buttonNumber, uint8_t buttonState) {
uint8_t arrayIndex = buttonNumber/8;
uint8_t buttonIndex = buttonNumber - 8*arrayIndex;
//update state if it's different than last one
if (bitRead(previousButtonState[arrayIndex], buttonIndex) != buttonState)
bitWrite(previousButtonState[arrayIndex], buttonIndex, buttonState);
}
bool OpenDeck::getPreviousButtonState(uint8_t buttonNumber) {
uint8_t arrayIndex = buttonNumber/8;
uint8_t buttonIndex = buttonNumber - 8*arrayIndex;
return bitRead(previousButtonState[arrayIndex], buttonIndex);
}
bool OpenDeck::buttonDebounced(uint8_t buttonNumber, bool buttonState) {
//shift new button reading into previousButtonState
buttonDebounceCounter[buttonNumber] = (buttonDebounceCounter[buttonNumber] << 1) | buttonState | buttonDebounceCompare;
//if button is debounced, return true
return ((buttonDebounceCounter[buttonNumber] == buttonDebounceCompare) || (buttonDebounceCounter[buttonNumber] == 0xFF));
}
void OpenDeck::sendMIDInote(uint8_t buttonNote, bool buttonState, uint8_t channel) {
switch (buttonState) {
case false:
//button released
if (standardNoteOffEnabled()) {
#ifdef USBMIDI
usbMIDI.sendNoteOff(buttonNote, velocityOff, channel);
#endif
#ifdef HW_MIDI
MIDI.sendNoteOff(buttonNote, velocityOff, channel);
#endif
} else {
#ifdef HW_MIDI
MIDI.sendNoteOn(buttonNote, velocityOff, channel);
#endif
#ifdef USBMIDI
usbMIDI.sendNoteOn(buttonNote, velocityOff, channel);
#endif
}
break;
case true:
//button pressed
#ifdef HW_MIDI
MIDI.sendNoteOn(buttonNote, velocityOn, channel);
#endif
#ifdef USBMIDI
usbMIDI.sendNoteOn(buttonNote, velocityOn, channel);
#endif
break;
}
}
void OpenDeck::sendProgramChange(uint8_t channel, uint8_t program) {
#ifdef USBMIDI
usbMIDI.sendProgramChange(program, channel);
#endif
#ifdef HW_MIDI
MIDI.sendProgramChange(program, channel);
#endif
}<|endoftext|> |
<commit_before>// Copyright (c) 2015, Galaxy 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 "sdk/galaxy.h"
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <errno.h>
#include <string.h>
#include <gflags/gflags.h>
#include <tprinter.h>
#include <string_util.h>
DECLARE_string(master_host);
DECLARE_string(master_port);
DECLARE_string(flagfile);
const std::string kGalaxyUsage = "\n./galaxy_client submit <job_name> <job_package> <replica> <cpu> <mem> <start_cmd> <batch> <deploy_step> <label>\n"
"./galaxy_client list\n"
"./galaxy_client listagent\n"
"./galaxy_client kill <jobid>\n"
"./galaxy_client update <jobid> <replica>\n"
"./galaxy_client label <label_name> <agent_endpoints_file>";
bool LoadAgentEndpointsFromFile(
const std::string& file_name,
std::vector<std::string>* agents) {
const int LINE_BUF_SIZE = 1024;
char line_buf[LINE_BUF_SIZE];
std::ifstream fin(file_name.c_str(), std::ifstream::in);
if (!fin.is_open()) {
fprintf(stderr, "open %s failed\n", file_name.c_str());
return false;
}
bool ret = true;
while (fin.good()) {
fin.getline(line_buf, LINE_BUF_SIZE);
if (fin.gcount() == LINE_BUF_SIZE) {
fprintf(stderr, "line buffer size overflow\n");
ret = false;
break;
} else if (fin.gcount() == 0) {
continue;
}
fprintf(stdout, "label %s\n", line_buf);
// NOTE string size should == strlen
std::string agent_endpoint(line_buf, strlen(line_buf));
agents->push_back(agent_endpoint);
}
if (!ret) {
fin.close();
return false;
}
if (fin.fail()) {
fin.close();
return false;
}
fin.close();
return true;
}
int LabelAgent(int argc, char* argv[]) {
if (argc < 1) {
return -1;
}
std::string label(argv[0]);
std::vector<std::string> agent_endpoints;
if (argc == 2 && LoadAgentEndpointsFromFile(argv[1], &agent_endpoints)) {
return -1;
}
baidu::galaxy::Galaxy* galaxy = baidu::galaxy::Galaxy::ConnectGalaxy(FLAGS_master_host + ":" + FLAGS_master_port);
if (!galaxy->LabelAgents(label, agent_endpoints)) {
return -1;
}
return 0;
}
void ReadBinary(const std::string& file, std::string* binary) {
FILE* fp = fopen(file.c_str(), "rb");
if (fp == NULL) {
fprintf(stderr, "Read binary fail\n");
return;
}
char buf[1024];
int len = 0;
while ((len = fread(buf, 1, sizeof(buf), fp)) > 0) {
binary->append(buf, len);
}
fclose(fp);
}
int AddJob(int argc, char* argv[]) {
if (argc < 6) {
return 1;
}
baidu::galaxy::Galaxy* galaxy = baidu::galaxy::Galaxy::ConnectGalaxy(FLAGS_master_host + ":" + FLAGS_master_port);
baidu::galaxy::JobDescription job;
job.job_name = argv[0];
std::string binary(argv[1]);
if (binary.find("ftp") == 0) {
job.binary = binary;
}else {
ReadBinary(argv[1], &job.binary);
}
printf("binary size %lu\n", job.binary.size());
job.replica = atoi(argv[2]);
job.cpu_required = atoi(argv[3]);
job.mem_required = atoi(argv[4]);
job.deploy_step = 0;
job.cmd_line = argv[5];
job.is_batch = (argc > 6 && 0 == strcmp(argv[6], "batch"));
job.deploy_step = job.replica;
if (argc > 7) {
job.deploy_step = atoi(argv[7]);
}
if (argc > 8) {
job.label = argv[8];
}
std::string jobid = galaxy->SubmitJob(job);
if (jobid.empty()) {
fprintf(stderr, "Submit job fail\n");
return 1;
}
printf("Submit job %s\n", jobid.c_str());
return 0;
}
int UpdateJob(int argc, char* argv[]) {
if (argc < 2) {
return 1;
}
baidu::galaxy::Galaxy* galaxy = baidu::galaxy::Galaxy::ConnectGalaxy(FLAGS_master_host + ":" + FLAGS_master_port);
baidu::galaxy::JobDescription desc;
std::string jobid;
jobid.assign(argv[0]);
desc.replica = atoi(argv[1]);
bool ok = galaxy->UpdateJob(jobid, desc);
if (ok) {
printf("Update job %s ok\n", jobid.c_str());
return 0;
}else {
printf("Fail to update job %s\n", jobid.c_str());
return 1;
}
}
int ListAgent(int /*argc*/, char*[] /*argv*/) {
baidu::galaxy::Galaxy* galaxy = baidu::galaxy::Galaxy::ConnectGalaxy(FLAGS_master_host + ":" + FLAGS_master_port);
std::vector<baidu::galaxy::NodeDescription> agents;
baidu::common::TPrinter tp(11);
tp.AddRow(11, "", "addr","state", "pods", "cpu_used", "cpu_assigned", "cpu_total", "mem_used", "mem_assigned", "mem_total", "labels");
if (galaxy->ListAgents(&agents)) {
for (uint32_t i = 0; i < agents.size(); i++) {
std::vector<std::string> vs;
vs.push_back(baidu::common::NumToString(i + 1));
vs.push_back(agents[i].addr);
vs.push_back(agents[i].state);
vs.push_back(baidu::common::NumToString(agents[i].task_num));
vs.push_back(baidu::common::NumToString(agents[i].cpu_used));
vs.push_back(baidu::common::NumToString(agents[i].cpu_assigned));
vs.push_back(baidu::common::NumToString(agents[i].cpu_share));
vs.push_back(baidu::common::NumToString(agents[i].mem_used));
vs.push_back(baidu::common::NumToString(agents[i].mem_assigned));
vs.push_back(baidu::common::NumToString(agents[i].mem_share));
vs.push_back(agents[i].labels);
tp.AddRow(vs);
}
printf("%s\n", tp.ToString().c_str());
return 0;
}
printf("Listagent fail\n");
return 1;
}
int ListJob(int /*argc*/, char*[] /*argv*/) {
baidu::galaxy::Galaxy* galaxy = baidu::galaxy::Galaxy::ConnectGalaxy(FLAGS_master_host + ":" + FLAGS_master_port);
std::vector<baidu::galaxy::JobInformation> infos;
baidu::common::TPrinter tp(8);
tp.AddRow(8, "", "id", "name", "stat(r/p/d)", "replica", "batch", "cpu", "memory");
if (galaxy->ListJobs(&infos)) {
for (uint32_t i = 0; i < infos.size(); i++) {
std::vector<std::string> vs;
vs.push_back(baidu::common::NumToString(i + 1));
vs.push_back(infos[i].job_id);
vs.push_back(infos[i].job_name);
vs.push_back(baidu::common::NumToString(infos[i].running_num) + "/" +
baidu::common::NumToString(infos[i].pending_num) + "/" +
baidu::common::NumToString(infos[i].deploying_num));
vs.push_back(baidu::common::NumToString(infos[i].replica));
vs.push_back(infos[i].is_batch ? "batch" : "");
vs.push_back(baidu::common::NumToString(infos[i].cpu_used));
vs.push_back(baidu::common::NumToString(infos[i].mem_used));
tp.AddRow(vs);
}
printf("%s\n", tp.ToString().c_str());
return 0;
}
fprintf(stderr, "List fail\n");
return 1;
}
int main(int argc, char* argv[]) {
FLAGS_flagfile = "./galaxy.flag";
::google::SetUsageMessage(kGalaxyUsage);
::google::ParseCommandLineFlags(&argc, &argv, true);
if(argc < 2){
fprintf(stderr,"Usage:%s\n", kGalaxyUsage.c_str());
return -1;
}
if (strcmp(argv[1], "submit") == 0) {
return AddJob(argc - 2, argv + 2);
} else if (strcmp(argv[1], "list") == 0) {
return ListJob(argc - 2, argv + 2);
} else if (strcmp(argv[1], "listagent") == 0) {
return ListAgent(argc - 2, argv + 2);
} else if (strcmp(argv[1], "label") == 0) {
return LabelAgent(argc - 2, argv + 2);
} else if (strcmp(argv[1], "update") == 0) {
return UpdateJob(argc - 2, argv + 2);
} else {
fprintf(stderr,"Usage:%s\n", kGalaxyUsage.c_str());
return -1;
}
return 0;
}
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
<commit_msg>fix review comment<commit_after>// Copyright (c) 2015, Galaxy 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 "sdk/galaxy.h"
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <errno.h>
#include <string.h>
#include <gflags/gflags.h>
#include <tprinter.h>
#include <string_util.h>
DECLARE_string(master_host);
DECLARE_string(master_port);
DECLARE_string(flagfile);
const std::string kGalaxyUsage = "\n./galaxy_client submit <job_name> <job_package> <replica> <cpu> <mem> <start_cmd> <batch> <deploy_step> <label>\n"
"./galaxy_client list\n"
"./galaxy_client listagent\n"
"./galaxy_client kill <jobid>\n"
"./galaxy_client update <jobid> <replica>\n"
"./galaxy_client label <label_name> <agent_endpoints_file>";
bool LoadAgentEndpointsFromFile(
const std::string& file_name,
std::vector<std::string>* agents) {
const int LINE_BUF_SIZE = 1024;
char line_buf[LINE_BUF_SIZE];
std::ifstream fin(file_name.c_str(), std::ifstream::in);
if (!fin.is_open()) {
fprintf(stderr, "open %s failed\n", file_name.c_str());
return false;
}
bool ret = true;
while (fin.good()) {
fin.getline(line_buf, LINE_BUF_SIZE);
if (fin.gcount() == LINE_BUF_SIZE) {
fprintf(stderr, "line buffer size overflow\n");
ret = false;
break;
} else if (fin.gcount() == 0) {
continue;
}
fprintf(stdout, "label %s\n", line_buf);
// NOTE string size should == strlen
std::string agent_endpoint(line_buf, strlen(line_buf));
agents->push_back(agent_endpoint);
}
if (!ret) {
fin.close();
return false;
}
if (fin.fail()) {
fin.close();
return false;
}
fin.close();
return true;
}
int LabelAgent(int argc, char* argv[]) {
if (argc < 1) {
return -1;
}
std::string label(argv[0]);
std::vector<std::string> agent_endpoints;
if (argc == 2 && LoadAgentEndpointsFromFile(argv[1], &agent_endpoints)) {
return -1;
}
baidu::galaxy::Galaxy* galaxy = baidu::galaxy::Galaxy::ConnectGalaxy(FLAGS_master_host + ":" + FLAGS_master_port);
if (!galaxy->LabelAgents(label, agent_endpoints)) {
return -1;
}
return 0;
}
void ReadBinary(const std::string& file, std::string* binary) {
FILE* fp = fopen(file.c_str(), "rb");
if (fp == NULL) {
fprintf(stderr, "Read binary fail\n");
return;
}
char buf[1024];
int len = 0;
while ((len = fread(buf, 1, sizeof(buf), fp)) > 0) {
binary->append(buf, len);
}
fclose(fp);
}
int AddJob(int argc, char* argv[]) {
if (argc < 6) {
return 1;
}
baidu::galaxy::Galaxy* galaxy = baidu::galaxy::Galaxy::ConnectGalaxy(FLAGS_master_host + ":" + FLAGS_master_port);
baidu::galaxy::JobDescription job;
job.job_name = argv[0];
std::string binary(argv[1]);
if (binary.substr(0,6) == "ftp://") {
job.binary = binary;
}else {
ReadBinary(argv[1], &job.binary);
}
printf("binary size %lu\n", job.binary.size());
job.replica = atoi(argv[2]);
job.cpu_required = atoi(argv[3]);
job.mem_required = atoi(argv[4]);
job.deploy_step = 0;
job.cmd_line = argv[5];
job.is_batch = (argc > 6 && 0 == strcmp(argv[6], "batch"));
job.deploy_step = job.replica;
if (argc > 7) {
job.deploy_step = atoi(argv[7]);
}
if (argc > 8) {
job.label = argv[8];
}
std::string jobid = galaxy->SubmitJob(job);
if (jobid.empty()) {
fprintf(stderr, "Submit job fail\n");
return 1;
}
printf("Submit job %s\n", jobid.c_str());
return 0;
}
int UpdateJob(int argc, char* argv[]) {
if (argc < 2) {
return 1;
}
baidu::galaxy::Galaxy* galaxy = baidu::galaxy::Galaxy::ConnectGalaxy(FLAGS_master_host + ":" + FLAGS_master_port);
baidu::galaxy::JobDescription desc;
std::string jobid;
jobid.assign(argv[0]);
desc.replica = atoi(argv[1]);
bool ok = galaxy->UpdateJob(jobid, desc);
if (ok) {
printf("Update job %s ok\n", jobid.c_str());
return 0;
}else {
printf("Fail to update job %s\n", jobid.c_str());
return 1;
}
}
int ListAgent(int /*argc*/, char*[] /*argv*/) {
baidu::galaxy::Galaxy* galaxy = baidu::galaxy::Galaxy::ConnectGalaxy(FLAGS_master_host + ":" + FLAGS_master_port);
std::vector<baidu::galaxy::NodeDescription> agents;
baidu::common::TPrinter tp(11);
tp.AddRow(11, "", "addr","state", "pods", "cpu_used", "cpu_assigned", "cpu_total", "mem_used", "mem_assigned", "mem_total", "labels");
if (galaxy->ListAgents(&agents)) {
for (uint32_t i = 0; i < agents.size(); i++) {
std::vector<std::string> vs;
vs.push_back(baidu::common::NumToString(i + 1));
vs.push_back(agents[i].addr);
vs.push_back(agents[i].state);
vs.push_back(baidu::common::NumToString(agents[i].task_num));
vs.push_back(baidu::common::NumToString(agents[i].cpu_used));
vs.push_back(baidu::common::NumToString(agents[i].cpu_assigned));
vs.push_back(baidu::common::NumToString(agents[i].cpu_share));
vs.push_back(baidu::common::NumToString(agents[i].mem_used));
vs.push_back(baidu::common::NumToString(agents[i].mem_assigned));
vs.push_back(baidu::common::NumToString(agents[i].mem_share));
vs.push_back(agents[i].labels);
tp.AddRow(vs);
}
printf("%s\n", tp.ToString().c_str());
return 0;
}
printf("Listagent fail\n");
return 1;
}
int ListJob(int /*argc*/, char*[] /*argv*/) {
baidu::galaxy::Galaxy* galaxy = baidu::galaxy::Galaxy::ConnectGalaxy(FLAGS_master_host + ":" + FLAGS_master_port);
std::vector<baidu::galaxy::JobInformation> infos;
baidu::common::TPrinter tp(8);
tp.AddRow(8, "", "id", "name", "stat(r/p/d)", "replica", "batch", "cpu", "memory");
if (galaxy->ListJobs(&infos)) {
for (uint32_t i = 0; i < infos.size(); i++) {
std::vector<std::string> vs;
vs.push_back(baidu::common::NumToString(i + 1));
vs.push_back(infos[i].job_id);
vs.push_back(infos[i].job_name);
vs.push_back(baidu::common::NumToString(infos[i].running_num) + "/" +
baidu::common::NumToString(infos[i].pending_num) + "/" +
baidu::common::NumToString(infos[i].deploying_num));
vs.push_back(baidu::common::NumToString(infos[i].replica));
vs.push_back(infos[i].is_batch ? "batch" : "");
vs.push_back(baidu::common::NumToString(infos[i].cpu_used));
vs.push_back(baidu::common::NumToString(infos[i].mem_used));
tp.AddRow(vs);
}
printf("%s\n", tp.ToString().c_str());
return 0;
}
fprintf(stderr, "List fail\n");
return 1;
}
int main(int argc, char* argv[]) {
FLAGS_flagfile = "./galaxy.flag";
::google::SetUsageMessage(kGalaxyUsage);
::google::ParseCommandLineFlags(&argc, &argv, true);
if(argc < 2){
fprintf(stderr,"Usage:%s\n", kGalaxyUsage.c_str());
return -1;
}
if (strcmp(argv[1], "submit") == 0) {
return AddJob(argc - 2, argv + 2);
} else if (strcmp(argv[1], "list") == 0) {
return ListJob(argc - 2, argv + 2);
} else if (strcmp(argv[1], "listagent") == 0) {
return ListAgent(argc - 2, argv + 2);
} else if (strcmp(argv[1], "label") == 0) {
return LabelAgent(argc - 2, argv + 2);
} else if (strcmp(argv[1], "update") == 0) {
return UpdateJob(argc - 2, argv + 2);
} else {
fprintf(stderr,"Usage:%s\n", kGalaxyUsage.c_str());
return -1;
}
return 0;
}
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
<|endoftext|> |
<commit_before><commit_msg>Added "structure disambiguation maps" to conceptual inheritance prototype. The purpose of this is to provide the ability to request different conceptual structures of the same conceptual type -- e.g. the additive group or the multiplicative group of a field.<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 "SkColorPriv.h"
#include "SkDebugCanvas.h"
#include "SkDrawCommand.h"
#include "SkDrawFilter.h"
#include "SkDevice.h"
#include "SkXfermode.h"
#ifdef SK_BUILD_FOR_WIN
// iostream includes xlocale which generates warning 4530 because we're compiling without
// exceptions
#pragma warning(push)
#pragma warning(disable : 4530)
#endif
#include <iostream>
#ifdef SK_BUILD_FOR_WIN
#pragma warning(pop)
#endif
static SkBitmap make_noconfig_bm(int width, int height) {
SkBitmap bm;
bm.setConfig(SkBitmap::kNo_Config, width, height);
return bm;
}
SkDebugCanvas::SkDebugCanvas(int width, int height)
: INHERITED(make_noconfig_bm(width, height))
, fOverdrawViz(false)
, fOverdrawFilter(NULL)
, fOutstandingSaveCount(0) {
// TODO(chudy): Free up memory from all draw commands in destructor.
fWidth = width;
fHeight = height;
// do we need fBm anywhere?
fBm.setConfig(SkBitmap::kNo_Config, fWidth, fHeight);
fFilter = false;
fIndex = 0;
fUserMatrix.reset();
}
SkDebugCanvas::~SkDebugCanvas() {
fCommandVector.deleteAll();
SkSafeUnref(fOverdrawFilter);
}
void SkDebugCanvas::addDrawCommand(SkDrawCommand* command) {
fCommandVector.push(command);
}
void SkDebugCanvas::draw(SkCanvas* canvas) {
if(!fCommandVector.isEmpty()) {
for (int i = 0; i < fCommandVector.count(); i++) {
if (fCommandVector[i]->isVisible()) {
fCommandVector[i]->execute(canvas);
}
}
}
fIndex = fCommandVector.count() - 1;
}
void SkDebugCanvas::applyUserTransform(SkCanvas* canvas) {
canvas->concat(fUserMatrix);
}
int SkDebugCanvas::getCommandAtPoint(int x, int y, int index) {
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config, 1, 1);
bitmap.allocPixels();
SkCanvas canvas(bitmap);
canvas.translate(SkIntToScalar(-x), SkIntToScalar(-y));
applyUserTransform(&canvas);
int layer = 0;
SkColor prev = bitmap.getColor(0,0);
for (int i = 0; i < index; i++) {
if (fCommandVector[i]->isVisible()) {
fCommandVector[i]->execute(&canvas);
}
if (prev != bitmap.getColor(0,0)) {
layer = i;
}
prev = bitmap.getColor(0,0);
}
return layer;
}
static SkPMColor OverdrawXferModeProc(SkPMColor src, SkPMColor dst) {
// This table encodes the color progression of the overdraw visualization
static const SkPMColor gTable[] = {
SkPackARGB32(0x00, 0x00, 0x00, 0x00),
SkPackARGB32(0xFF, 128, 158, 255),
SkPackARGB32(0xFF, 170, 185, 212),
SkPackARGB32(0xFF, 213, 195, 170),
SkPackARGB32(0xFF, 255, 192, 127),
SkPackARGB32(0xFF, 255, 185, 85),
SkPackARGB32(0xFF, 255, 165, 42),
SkPackARGB32(0xFF, 255, 135, 0),
SkPackARGB32(0xFF, 255, 95, 0),
SkPackARGB32(0xFF, 255, 50, 0),
SkPackARGB32(0xFF, 255, 0, 0)
};
for (size_t i = 0; i < SK_ARRAY_COUNT(gTable)-1; ++i) {
if (gTable[i] == dst) {
return gTable[i+1];
}
}
return gTable[SK_ARRAY_COUNT(gTable)-1];
}
// The OverdrawFilter modifies every paint to use an SkProcXfermode which
// in turn invokes OverdrawXferModeProc
class OverdrawFilter : public SkDrawFilter {
public:
OverdrawFilter() {
fXferMode = new SkProcXfermode(OverdrawXferModeProc);
}
virtual ~OverdrawFilter() {
delete fXferMode;
}
virtual bool filter(SkPaint* p, Type) SK_OVERRIDE {
p->setXfermode(fXferMode);
return true;
}
protected:
SkXfermode* fXferMode;
private:
typedef SkDrawFilter INHERITED;
};
void SkDebugCanvas::drawTo(SkCanvas* canvas, int index) {
SkASSERT(!fCommandVector.isEmpty());
SkASSERT(index < fCommandVector.count());
int i;
// This only works assuming the canvas and device are the same ones that
// were previously drawn into because they need to preserve all saves
// and restores.
if (fIndex < index) {
i = fIndex + 1;
} else {
for (int j = 0; j < fOutstandingSaveCount; j++) {
canvas->restore();
}
i = 0;
canvas->clear(SK_ColorTRANSPARENT);
canvas->resetMatrix();
SkRect rect = SkRect::MakeWH(SkIntToScalar(fWidth),
SkIntToScalar(fHeight));
canvas->clipRect(rect, SkRegion::kReplace_Op );
applyUserTransform(canvas);
fOutstandingSaveCount = 0;
// The setting of the draw filter has to go here (rather than in
// SkRasterWidget) due to the canvas restores this class performs.
// Since the draw filter is stored in the layer stack if we
// call setDrawFilter on anything but the root layer odd things happen
if (fOverdrawViz) {
if (NULL == fOverdrawFilter) {
fOverdrawFilter = new OverdrawFilter;
}
if (fOverdrawFilter != canvas->getDrawFilter()) {
canvas->setDrawFilter(fOverdrawFilter);
}
} else {
canvas->setDrawFilter(NULL);
}
}
for (; i <= index; i++) {
if (i == index && fFilter) {
SkPaint p;
p.setColor(0xAAFFFFFF);
canvas->save();
canvas->resetMatrix();
SkRect mask;
mask.set(SkIntToScalar(0), SkIntToScalar(0),
SkIntToScalar(fWidth), SkIntToScalar(fHeight));
canvas->clipRect(mask, SkRegion::kReplace_Op, false);
canvas->drawRectCoords(SkIntToScalar(0), SkIntToScalar(0),
SkIntToScalar(fWidth), SkIntToScalar(fHeight), p);
canvas->restore();
}
if (fCommandVector[i]->isVisible()) {
fCommandVector[i]->execute(canvas);
fCommandVector[i]->trackSaveState(&fOutstandingSaveCount);
}
}
fMatrix = canvas->getTotalMatrix();
fClip = canvas->getTotalClip().getBounds();
fIndex = index;
}
void SkDebugCanvas::deleteDrawCommandAt(int index) {
SkASSERT(index < fCommandVector.count());
delete fCommandVector[index];
fCommandVector.remove(index);
}
SkDrawCommand* SkDebugCanvas::getDrawCommandAt(int index) {
SkASSERT(index < fCommandVector.count());
return fCommandVector[index];
}
void SkDebugCanvas::setDrawCommandAt(int index, SkDrawCommand* command) {
SkASSERT(index < fCommandVector.count());
delete fCommandVector[index];
fCommandVector[index] = command;
}
SkTDArray<SkString*>* SkDebugCanvas::getCommandInfo(int index) {
SkASSERT(index < fCommandVector.count());
return fCommandVector[index]->Info();
}
bool SkDebugCanvas::getDrawCommandVisibilityAt(int index) {
SkASSERT(index < fCommandVector.count());
return fCommandVector[index]->isVisible();
}
const SkTDArray <SkDrawCommand*>& SkDebugCanvas::getDrawCommands() const {
return fCommandVector;
}
SkTDArray <SkDrawCommand*>& SkDebugCanvas::getDrawCommands() {
return fCommandVector;
}
// TODO(chudy): Free command string memory.
SkTArray<SkString>* SkDebugCanvas::getDrawCommandsAsStrings() const {
SkTArray<SkString>* commandString = new SkTArray<SkString>(fCommandVector.count());
if (!fCommandVector.isEmpty()) {
for (int i = 0; i < fCommandVector.count(); i ++) {
commandString->push_back() = fCommandVector[i]->toString();
}
}
return commandString;
}
void SkDebugCanvas::toggleFilter(bool toggle) {
fFilter = toggle;
}
void SkDebugCanvas::clear(SkColor color) {
addDrawCommand(new SkClearCommand(color));
}
bool SkDebugCanvas::clipPath(const SkPath& path, SkRegion::Op op, bool doAA) {
addDrawCommand(new SkClipPathCommand(path, op, doAA));
return true;
}
bool SkDebugCanvas::clipRect(const SkRect& rect, SkRegion::Op op, bool doAA) {
addDrawCommand(new SkClipRectCommand(rect, op, doAA));
return true;
}
bool SkDebugCanvas::clipRRect(const SkRRect& rrect, SkRegion::Op op, bool doAA) {
addDrawCommand(new SkClipRRectCommand(rrect, op, doAA));
return true;
}
bool SkDebugCanvas::clipRegion(const SkRegion& region, SkRegion::Op op) {
addDrawCommand(new SkClipRegionCommand(region, op));
return true;
}
bool SkDebugCanvas::concat(const SkMatrix& matrix) {
addDrawCommand(new SkConcatCommand(matrix));
return true;
}
void SkDebugCanvas::drawBitmap(const SkBitmap& bitmap, SkScalar left,
SkScalar top, const SkPaint* paint = NULL) {
addDrawCommand(new SkDrawBitmapCommand(bitmap, left, top, paint));
}
void SkDebugCanvas::drawBitmapRectToRect(const SkBitmap& bitmap,
const SkRect* src, const SkRect& dst, const SkPaint* paint) {
addDrawCommand(new SkDrawBitmapRectCommand(bitmap, src, dst, paint));
}
void SkDebugCanvas::drawBitmapMatrix(const SkBitmap& bitmap,
const SkMatrix& matrix, const SkPaint* paint) {
addDrawCommand(new SkDrawBitmapMatrixCommand(bitmap, matrix, paint));
}
void SkDebugCanvas::drawBitmapNine(const SkBitmap& bitmap,
const SkIRect& center, const SkRect& dst, const SkPaint* paint) {
addDrawCommand(new SkDrawBitmapNineCommand(bitmap, center, dst, paint));
}
void SkDebugCanvas::drawData(const void* data, size_t length) {
addDrawCommand(new SkDrawDataCommand(data, length));
}
void SkDebugCanvas::beginCommentGroup(const char* description) {
addDrawCommand(new SkBeginCommentGroupCommand(description));
}
void SkDebugCanvas::addComment(const char* kywd, const char* value) {
addDrawCommand(new SkCommentCommand(kywd, value));
}
void SkDebugCanvas::endCommentGroup() {
addDrawCommand(new SkEndCommentGroupCommand());
}
void SkDebugCanvas::drawOval(const SkRect& oval, const SkPaint& paint) {
addDrawCommand(new SkDrawOvalCommand(oval, paint));
}
void SkDebugCanvas::drawPaint(const SkPaint& paint) {
addDrawCommand(new SkDrawPaintCommand(paint));
}
void SkDebugCanvas::drawPath(const SkPath& path, const SkPaint& paint) {
addDrawCommand(new SkDrawPathCommand(path, paint));
}
void SkDebugCanvas::drawPicture(SkPicture& picture) {
addDrawCommand(new SkDrawPictureCommand(picture));
}
void SkDebugCanvas::drawPoints(PointMode mode, size_t count,
const SkPoint pts[], const SkPaint& paint) {
addDrawCommand(new SkDrawPointsCommand(mode, count, pts, paint));
}
void SkDebugCanvas::drawPosText(const void* text, size_t byteLength,
const SkPoint pos[], const SkPaint& paint) {
addDrawCommand(new SkDrawPosTextCommand(text, byteLength, pos, paint));
}
void SkDebugCanvas::drawPosTextH(const void* text, size_t byteLength,
const SkScalar xpos[], SkScalar constY, const SkPaint& paint) {
addDrawCommand(
new SkDrawPosTextHCommand(text, byteLength, xpos, constY, paint));
}
void SkDebugCanvas::drawRect(const SkRect& rect, const SkPaint& paint) {
// NOTE(chudy): Messing up when renamed to DrawRect... Why?
addDrawCommand(new SkDrawRectCommand(rect, paint));
}
void SkDebugCanvas::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
addDrawCommand(new SkDrawRRectCommand(rrect, paint));
}
void SkDebugCanvas::drawSprite(const SkBitmap& bitmap, int left, int top,
const SkPaint* paint = NULL) {
addDrawCommand(new SkDrawSpriteCommand(bitmap, left, top, paint));
}
void SkDebugCanvas::drawText(const void* text, size_t byteLength, SkScalar x,
SkScalar y, const SkPaint& paint) {
addDrawCommand(new SkDrawTextCommand(text, byteLength, x, y, paint));
}
void SkDebugCanvas::drawTextOnPath(const void* text, size_t byteLength,
const SkPath& path, const SkMatrix* matrix, const SkPaint& paint) {
addDrawCommand(
new SkDrawTextOnPathCommand(text, byteLength, path, matrix, paint));
}
void SkDebugCanvas::drawVertices(VertexMode vmode, int vertexCount,
const SkPoint vertices[], const SkPoint texs[], const SkColor colors[],
SkXfermode*, const uint16_t indices[], int indexCount,
const SkPaint& paint) {
addDrawCommand(new SkDrawVerticesCommand(vmode, vertexCount, vertices,
texs, colors, NULL, indices, indexCount, paint));
}
void SkDebugCanvas::restore() {
addDrawCommand(new SkRestoreCommand());
}
bool SkDebugCanvas::rotate(SkScalar degrees) {
addDrawCommand(new SkRotateCommand(degrees));
return true;
}
int SkDebugCanvas::save(SaveFlags flags) {
addDrawCommand(new SkSaveCommand(flags));
return true;
}
int SkDebugCanvas::saveLayer(const SkRect* bounds, const SkPaint* paint,
SaveFlags flags) {
addDrawCommand(new SkSaveLayerCommand(bounds, paint, flags));
return true;
}
bool SkDebugCanvas::scale(SkScalar sx, SkScalar sy) {
addDrawCommand(new SkScaleCommand(sx, sy));
return true;
}
void SkDebugCanvas::setMatrix(const SkMatrix& matrix) {
addDrawCommand(new SkSetMatrixCommand(matrix));
}
bool SkDebugCanvas::skew(SkScalar sx, SkScalar sy) {
addDrawCommand(new SkSkewCommand(sx, sy));
return true;
}
bool SkDebugCanvas::translate(SkScalar dx, SkScalar dy) {
addDrawCommand(new SkTranslateCommand(dx, dy));
return true;
}
void SkDebugCanvas::toggleCommand(int index, bool toggle) {
SkASSERT(index < fCommandVector.count());
fCommandVector[index]->setVisible(toggle);
}
<commit_msg>SkDebugCanvas: remove unused <iostream> include.<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 "SkColorPriv.h"
#include "SkDebugCanvas.h"
#include "SkDrawCommand.h"
#include "SkDrawFilter.h"
#include "SkDevice.h"
#include "SkXfermode.h"
static SkBitmap make_noconfig_bm(int width, int height) {
SkBitmap bm;
bm.setConfig(SkBitmap::kNo_Config, width, height);
return bm;
}
SkDebugCanvas::SkDebugCanvas(int width, int height)
: INHERITED(make_noconfig_bm(width, height))
, fOverdrawViz(false)
, fOverdrawFilter(NULL)
, fOutstandingSaveCount(0) {
// TODO(chudy): Free up memory from all draw commands in destructor.
fWidth = width;
fHeight = height;
// do we need fBm anywhere?
fBm.setConfig(SkBitmap::kNo_Config, fWidth, fHeight);
fFilter = false;
fIndex = 0;
fUserMatrix.reset();
}
SkDebugCanvas::~SkDebugCanvas() {
fCommandVector.deleteAll();
SkSafeUnref(fOverdrawFilter);
}
void SkDebugCanvas::addDrawCommand(SkDrawCommand* command) {
fCommandVector.push(command);
}
void SkDebugCanvas::draw(SkCanvas* canvas) {
if(!fCommandVector.isEmpty()) {
for (int i = 0; i < fCommandVector.count(); i++) {
if (fCommandVector[i]->isVisible()) {
fCommandVector[i]->execute(canvas);
}
}
}
fIndex = fCommandVector.count() - 1;
}
void SkDebugCanvas::applyUserTransform(SkCanvas* canvas) {
canvas->concat(fUserMatrix);
}
int SkDebugCanvas::getCommandAtPoint(int x, int y, int index) {
SkBitmap bitmap;
bitmap.setConfig(SkBitmap::kARGB_8888_Config, 1, 1);
bitmap.allocPixels();
SkCanvas canvas(bitmap);
canvas.translate(SkIntToScalar(-x), SkIntToScalar(-y));
applyUserTransform(&canvas);
int layer = 0;
SkColor prev = bitmap.getColor(0,0);
for (int i = 0; i < index; i++) {
if (fCommandVector[i]->isVisible()) {
fCommandVector[i]->execute(&canvas);
}
if (prev != bitmap.getColor(0,0)) {
layer = i;
}
prev = bitmap.getColor(0,0);
}
return layer;
}
static SkPMColor OverdrawXferModeProc(SkPMColor src, SkPMColor dst) {
// This table encodes the color progression of the overdraw visualization
static const SkPMColor gTable[] = {
SkPackARGB32(0x00, 0x00, 0x00, 0x00),
SkPackARGB32(0xFF, 128, 158, 255),
SkPackARGB32(0xFF, 170, 185, 212),
SkPackARGB32(0xFF, 213, 195, 170),
SkPackARGB32(0xFF, 255, 192, 127),
SkPackARGB32(0xFF, 255, 185, 85),
SkPackARGB32(0xFF, 255, 165, 42),
SkPackARGB32(0xFF, 255, 135, 0),
SkPackARGB32(0xFF, 255, 95, 0),
SkPackARGB32(0xFF, 255, 50, 0),
SkPackARGB32(0xFF, 255, 0, 0)
};
for (size_t i = 0; i < SK_ARRAY_COUNT(gTable)-1; ++i) {
if (gTable[i] == dst) {
return gTable[i+1];
}
}
return gTable[SK_ARRAY_COUNT(gTable)-1];
}
// The OverdrawFilter modifies every paint to use an SkProcXfermode which
// in turn invokes OverdrawXferModeProc
class OverdrawFilter : public SkDrawFilter {
public:
OverdrawFilter() {
fXferMode = new SkProcXfermode(OverdrawXferModeProc);
}
virtual ~OverdrawFilter() {
delete fXferMode;
}
virtual bool filter(SkPaint* p, Type) SK_OVERRIDE {
p->setXfermode(fXferMode);
return true;
}
protected:
SkXfermode* fXferMode;
private:
typedef SkDrawFilter INHERITED;
};
void SkDebugCanvas::drawTo(SkCanvas* canvas, int index) {
SkASSERT(!fCommandVector.isEmpty());
SkASSERT(index < fCommandVector.count());
int i;
// This only works assuming the canvas and device are the same ones that
// were previously drawn into because they need to preserve all saves
// and restores.
if (fIndex < index) {
i = fIndex + 1;
} else {
for (int j = 0; j < fOutstandingSaveCount; j++) {
canvas->restore();
}
i = 0;
canvas->clear(SK_ColorTRANSPARENT);
canvas->resetMatrix();
SkRect rect = SkRect::MakeWH(SkIntToScalar(fWidth),
SkIntToScalar(fHeight));
canvas->clipRect(rect, SkRegion::kReplace_Op );
applyUserTransform(canvas);
fOutstandingSaveCount = 0;
// The setting of the draw filter has to go here (rather than in
// SkRasterWidget) due to the canvas restores this class performs.
// Since the draw filter is stored in the layer stack if we
// call setDrawFilter on anything but the root layer odd things happen
if (fOverdrawViz) {
if (NULL == fOverdrawFilter) {
fOverdrawFilter = new OverdrawFilter;
}
if (fOverdrawFilter != canvas->getDrawFilter()) {
canvas->setDrawFilter(fOverdrawFilter);
}
} else {
canvas->setDrawFilter(NULL);
}
}
for (; i <= index; i++) {
if (i == index && fFilter) {
SkPaint p;
p.setColor(0xAAFFFFFF);
canvas->save();
canvas->resetMatrix();
SkRect mask;
mask.set(SkIntToScalar(0), SkIntToScalar(0),
SkIntToScalar(fWidth), SkIntToScalar(fHeight));
canvas->clipRect(mask, SkRegion::kReplace_Op, false);
canvas->drawRectCoords(SkIntToScalar(0), SkIntToScalar(0),
SkIntToScalar(fWidth), SkIntToScalar(fHeight), p);
canvas->restore();
}
if (fCommandVector[i]->isVisible()) {
fCommandVector[i]->execute(canvas);
fCommandVector[i]->trackSaveState(&fOutstandingSaveCount);
}
}
fMatrix = canvas->getTotalMatrix();
fClip = canvas->getTotalClip().getBounds();
fIndex = index;
}
void SkDebugCanvas::deleteDrawCommandAt(int index) {
SkASSERT(index < fCommandVector.count());
delete fCommandVector[index];
fCommandVector.remove(index);
}
SkDrawCommand* SkDebugCanvas::getDrawCommandAt(int index) {
SkASSERT(index < fCommandVector.count());
return fCommandVector[index];
}
void SkDebugCanvas::setDrawCommandAt(int index, SkDrawCommand* command) {
SkASSERT(index < fCommandVector.count());
delete fCommandVector[index];
fCommandVector[index] = command;
}
SkTDArray<SkString*>* SkDebugCanvas::getCommandInfo(int index) {
SkASSERT(index < fCommandVector.count());
return fCommandVector[index]->Info();
}
bool SkDebugCanvas::getDrawCommandVisibilityAt(int index) {
SkASSERT(index < fCommandVector.count());
return fCommandVector[index]->isVisible();
}
const SkTDArray <SkDrawCommand*>& SkDebugCanvas::getDrawCommands() const {
return fCommandVector;
}
SkTDArray <SkDrawCommand*>& SkDebugCanvas::getDrawCommands() {
return fCommandVector;
}
// TODO(chudy): Free command string memory.
SkTArray<SkString>* SkDebugCanvas::getDrawCommandsAsStrings() const {
SkTArray<SkString>* commandString = new SkTArray<SkString>(fCommandVector.count());
if (!fCommandVector.isEmpty()) {
for (int i = 0; i < fCommandVector.count(); i ++) {
commandString->push_back() = fCommandVector[i]->toString();
}
}
return commandString;
}
void SkDebugCanvas::toggleFilter(bool toggle) {
fFilter = toggle;
}
void SkDebugCanvas::clear(SkColor color) {
addDrawCommand(new SkClearCommand(color));
}
bool SkDebugCanvas::clipPath(const SkPath& path, SkRegion::Op op, bool doAA) {
addDrawCommand(new SkClipPathCommand(path, op, doAA));
return true;
}
bool SkDebugCanvas::clipRect(const SkRect& rect, SkRegion::Op op, bool doAA) {
addDrawCommand(new SkClipRectCommand(rect, op, doAA));
return true;
}
bool SkDebugCanvas::clipRRect(const SkRRect& rrect, SkRegion::Op op, bool doAA) {
addDrawCommand(new SkClipRRectCommand(rrect, op, doAA));
return true;
}
bool SkDebugCanvas::clipRegion(const SkRegion& region, SkRegion::Op op) {
addDrawCommand(new SkClipRegionCommand(region, op));
return true;
}
bool SkDebugCanvas::concat(const SkMatrix& matrix) {
addDrawCommand(new SkConcatCommand(matrix));
return true;
}
void SkDebugCanvas::drawBitmap(const SkBitmap& bitmap, SkScalar left,
SkScalar top, const SkPaint* paint = NULL) {
addDrawCommand(new SkDrawBitmapCommand(bitmap, left, top, paint));
}
void SkDebugCanvas::drawBitmapRectToRect(const SkBitmap& bitmap,
const SkRect* src, const SkRect& dst, const SkPaint* paint) {
addDrawCommand(new SkDrawBitmapRectCommand(bitmap, src, dst, paint));
}
void SkDebugCanvas::drawBitmapMatrix(const SkBitmap& bitmap,
const SkMatrix& matrix, const SkPaint* paint) {
addDrawCommand(new SkDrawBitmapMatrixCommand(bitmap, matrix, paint));
}
void SkDebugCanvas::drawBitmapNine(const SkBitmap& bitmap,
const SkIRect& center, const SkRect& dst, const SkPaint* paint) {
addDrawCommand(new SkDrawBitmapNineCommand(bitmap, center, dst, paint));
}
void SkDebugCanvas::drawData(const void* data, size_t length) {
addDrawCommand(new SkDrawDataCommand(data, length));
}
void SkDebugCanvas::beginCommentGroup(const char* description) {
addDrawCommand(new SkBeginCommentGroupCommand(description));
}
void SkDebugCanvas::addComment(const char* kywd, const char* value) {
addDrawCommand(new SkCommentCommand(kywd, value));
}
void SkDebugCanvas::endCommentGroup() {
addDrawCommand(new SkEndCommentGroupCommand());
}
void SkDebugCanvas::drawOval(const SkRect& oval, const SkPaint& paint) {
addDrawCommand(new SkDrawOvalCommand(oval, paint));
}
void SkDebugCanvas::drawPaint(const SkPaint& paint) {
addDrawCommand(new SkDrawPaintCommand(paint));
}
void SkDebugCanvas::drawPath(const SkPath& path, const SkPaint& paint) {
addDrawCommand(new SkDrawPathCommand(path, paint));
}
void SkDebugCanvas::drawPicture(SkPicture& picture) {
addDrawCommand(new SkDrawPictureCommand(picture));
}
void SkDebugCanvas::drawPoints(PointMode mode, size_t count,
const SkPoint pts[], const SkPaint& paint) {
addDrawCommand(new SkDrawPointsCommand(mode, count, pts, paint));
}
void SkDebugCanvas::drawPosText(const void* text, size_t byteLength,
const SkPoint pos[], const SkPaint& paint) {
addDrawCommand(new SkDrawPosTextCommand(text, byteLength, pos, paint));
}
void SkDebugCanvas::drawPosTextH(const void* text, size_t byteLength,
const SkScalar xpos[], SkScalar constY, const SkPaint& paint) {
addDrawCommand(
new SkDrawPosTextHCommand(text, byteLength, xpos, constY, paint));
}
void SkDebugCanvas::drawRect(const SkRect& rect, const SkPaint& paint) {
// NOTE(chudy): Messing up when renamed to DrawRect... Why?
addDrawCommand(new SkDrawRectCommand(rect, paint));
}
void SkDebugCanvas::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
addDrawCommand(new SkDrawRRectCommand(rrect, paint));
}
void SkDebugCanvas::drawSprite(const SkBitmap& bitmap, int left, int top,
const SkPaint* paint = NULL) {
addDrawCommand(new SkDrawSpriteCommand(bitmap, left, top, paint));
}
void SkDebugCanvas::drawText(const void* text, size_t byteLength, SkScalar x,
SkScalar y, const SkPaint& paint) {
addDrawCommand(new SkDrawTextCommand(text, byteLength, x, y, paint));
}
void SkDebugCanvas::drawTextOnPath(const void* text, size_t byteLength,
const SkPath& path, const SkMatrix* matrix, const SkPaint& paint) {
addDrawCommand(
new SkDrawTextOnPathCommand(text, byteLength, path, matrix, paint));
}
void SkDebugCanvas::drawVertices(VertexMode vmode, int vertexCount,
const SkPoint vertices[], const SkPoint texs[], const SkColor colors[],
SkXfermode*, const uint16_t indices[], int indexCount,
const SkPaint& paint) {
addDrawCommand(new SkDrawVerticesCommand(vmode, vertexCount, vertices,
texs, colors, NULL, indices, indexCount, paint));
}
void SkDebugCanvas::restore() {
addDrawCommand(new SkRestoreCommand());
}
bool SkDebugCanvas::rotate(SkScalar degrees) {
addDrawCommand(new SkRotateCommand(degrees));
return true;
}
int SkDebugCanvas::save(SaveFlags flags) {
addDrawCommand(new SkSaveCommand(flags));
return true;
}
int SkDebugCanvas::saveLayer(const SkRect* bounds, const SkPaint* paint,
SaveFlags flags) {
addDrawCommand(new SkSaveLayerCommand(bounds, paint, flags));
return true;
}
bool SkDebugCanvas::scale(SkScalar sx, SkScalar sy) {
addDrawCommand(new SkScaleCommand(sx, sy));
return true;
}
void SkDebugCanvas::setMatrix(const SkMatrix& matrix) {
addDrawCommand(new SkSetMatrixCommand(matrix));
}
bool SkDebugCanvas::skew(SkScalar sx, SkScalar sy) {
addDrawCommand(new SkSkewCommand(sx, sy));
return true;
}
bool SkDebugCanvas::translate(SkScalar dx, SkScalar dy) {
addDrawCommand(new SkTranslateCommand(dx, dy));
return true;
}
void SkDebugCanvas::toggleCommand(int index, bool toggle) {
SkASSERT(index < fCommandVector.count());
fCommandVector[index]->setVisible(toggle);
}
<|endoftext|> |
<commit_before>/*
* ALURE OpenAL utility library
* Copyright (c) 2009-2010 by Chris Robinson.
*
* 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 "config.h"
#include "main.h"
#include <string.h>
#include <assert.h>
#include <algorithm>
#include <vector>
#include <memory>
#include <string>
#include <istream>
#include <fstream>
#include <iostream>
#include <sstream>
const Decoder::ListType& Decoder::GetList()
{ return AddList(); }
Decoder::ListType& Decoder::AddList(Decoder::FactoryType func, ALint prio)
{
static ListType FuncList;
if(func)
{
assert(SearchSecond(FuncList.begin(), FuncList.end(), func) == FuncList.end());
FuncList.insert(std::make_pair(prio, func));
}
return FuncList;
}
struct nullStream : public alureStream {
virtual bool IsValid() { return false; }
virtual bool GetFormat(ALenum*,ALuint*,ALuint*) { return false; }
virtual ALuint GetData(ALubyte*,ALuint) { return 0; }
virtual bool Rewind() { return false; }
nullStream():alureStream(NULL) {}
};
struct customStream : public alureStream {
void *usrFile;
ALenum format;
ALuint samplerate;
ALuint blockAlign;
MemDataInfo memInfo;
UserCallbacks cb;
virtual bool IsValid()
{ return usrFile != NULL; }
virtual bool GetFormat(ALenum *fmt, ALuint *frequency, ALuint *blockalign)
{
if(format == AL_NONE)
{
if(!cb.get_fmt || !cb.get_fmt(usrFile, &format, &samplerate, &blockAlign))
return false;
}
if(DetectBlockAlignment(format) != blockAlign)
blockAlign = 0;
*fmt = format;
*frequency = samplerate;
*blockalign = blockAlign;
return true;
}
virtual ALuint GetData(ALubyte *data, ALuint bytes)
{ return cb.decode(usrFile, data, bytes); }
virtual bool Rewind()
{
if(cb.rewind && cb.rewind(usrFile))
return true;
SetError("Rewind failed");
return false;
}
customStream(const char *fname, const UserCallbacks &callbacks)
: alureStream(NULL), usrFile(NULL), format(0), samplerate(0),
blockAlign(0), cb(callbacks)
{ if(cb.open_file) usrFile = cb.open_file(fname); }
customStream(const MemDataInfo &memData, const UserCallbacks &callbacks)
: alureStream(NULL), usrFile(NULL), format(0), samplerate(0),
blockAlign(0), memInfo(memData), cb(callbacks)
{ if(cb.open_mem) usrFile = cb.open_mem(memInfo.Data, memInfo.Length); }
customStream(void *userdata, ALenum fmt, ALuint srate, const UserCallbacks &callbacks)
: alureStream(NULL), usrFile(userdata), format(fmt), samplerate(srate),
blockAlign(DetectBlockAlignment(format)), cb(callbacks)
{ }
virtual ~customStream()
{
if(cb.close && usrFile)
cb.close(usrFile);
usrFile = NULL;
}
};
template <typename T>
static alureStream *get_stream_decoder(const T &fdata)
{
std::map<ALint,UserCallbacks>::iterator i = InstalledCallbacks.begin();
while(i != InstalledCallbacks.end() && i->first < 0)
{
std::auto_ptr<alureStream> stream(new customStream(fdata, i->second));
if(stream->IsValid()) return stream.release();
i++;
}
std::istream *file = new InStream(fdata);
if(!file->fail())
{
const Decoder::ListType Factories = Decoder::GetList();
Decoder::ListType::const_reverse_iterator factory = Factories.rbegin();
Decoder::ListType::const_reverse_iterator end = Factories.rend();
while(factory != end)
{
file->clear();
file->seekg(0, std::ios_base::beg);
std::auto_ptr<alureStream> stream(factory->second(file));
if(stream.get() != NULL) return stream.release();
factory++;
}
SetError("Unsupported type");
delete file;
}
else
{
SetError("Failed to open file");
delete file;
}
while(i != InstalledCallbacks.end())
{
std::auto_ptr<alureStream> stream(new customStream(fdata, i->second));
if(stream->IsValid()) return stream.release();
i++;
}
return NULL;
}
alureStream *create_stream(const char *fname)
{ return get_stream_decoder(fname); }
alureStream *create_stream(const MemDataInfo &memData)
{ return get_stream_decoder(memData); }
alureStream *create_stream(ALvoid *userdata, ALenum format, ALuint rate, const UserCallbacks &cb)
{ return new customStream(userdata, format, rate, cb); }
<commit_msg>Remove unused nullStream<commit_after>/*
* ALURE OpenAL utility library
* Copyright (c) 2009-2010 by Chris Robinson.
*
* 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 "config.h"
#include "main.h"
#include <string.h>
#include <assert.h>
#include <algorithm>
#include <vector>
#include <memory>
#include <string>
#include <istream>
#include <fstream>
#include <iostream>
#include <sstream>
const Decoder::ListType& Decoder::GetList()
{ return AddList(); }
Decoder::ListType& Decoder::AddList(Decoder::FactoryType func, ALint prio)
{
static ListType FuncList;
if(func)
{
assert(SearchSecond(FuncList.begin(), FuncList.end(), func) == FuncList.end());
FuncList.insert(std::make_pair(prio, func));
}
return FuncList;
}
struct customStream : public alureStream {
void *usrFile;
ALenum format;
ALuint samplerate;
ALuint blockAlign;
MemDataInfo memInfo;
UserCallbacks cb;
virtual bool IsValid()
{ return usrFile != NULL; }
virtual bool GetFormat(ALenum *fmt, ALuint *frequency, ALuint *blockalign)
{
if(format == AL_NONE)
{
if(!cb.get_fmt || !cb.get_fmt(usrFile, &format, &samplerate, &blockAlign))
return false;
}
if(DetectBlockAlignment(format) != blockAlign)
blockAlign = 0;
*fmt = format;
*frequency = samplerate;
*blockalign = blockAlign;
return true;
}
virtual ALuint GetData(ALubyte *data, ALuint bytes)
{ return cb.decode(usrFile, data, bytes); }
virtual bool Rewind()
{
if(cb.rewind && cb.rewind(usrFile))
return true;
SetError("Rewind failed");
return false;
}
customStream(const char *fname, const UserCallbacks &callbacks)
: alureStream(NULL), usrFile(NULL), format(0), samplerate(0),
blockAlign(0), cb(callbacks)
{ if(cb.open_file) usrFile = cb.open_file(fname); }
customStream(const MemDataInfo &memData, const UserCallbacks &callbacks)
: alureStream(NULL), usrFile(NULL), format(0), samplerate(0),
blockAlign(0), memInfo(memData), cb(callbacks)
{ if(cb.open_mem) usrFile = cb.open_mem(memInfo.Data, memInfo.Length); }
customStream(void *userdata, ALenum fmt, ALuint srate, const UserCallbacks &callbacks)
: alureStream(NULL), usrFile(userdata), format(fmt), samplerate(srate),
blockAlign(DetectBlockAlignment(format)), cb(callbacks)
{ }
virtual ~customStream()
{
if(cb.close && usrFile)
cb.close(usrFile);
usrFile = NULL;
}
};
template <typename T>
static alureStream *get_stream_decoder(const T &fdata)
{
std::map<ALint,UserCallbacks>::iterator i = InstalledCallbacks.begin();
while(i != InstalledCallbacks.end() && i->first < 0)
{
std::auto_ptr<alureStream> stream(new customStream(fdata, i->second));
if(stream->IsValid()) return stream.release();
i++;
}
std::istream *file = new InStream(fdata);
if(!file->fail())
{
const Decoder::ListType Factories = Decoder::GetList();
Decoder::ListType::const_reverse_iterator factory = Factories.rbegin();
Decoder::ListType::const_reverse_iterator end = Factories.rend();
while(factory != end)
{
file->clear();
file->seekg(0, std::ios_base::beg);
std::auto_ptr<alureStream> stream(factory->second(file));
if(stream.get() != NULL) return stream.release();
factory++;
}
SetError("Unsupported type");
delete file;
}
else
{
SetError("Failed to open file");
delete file;
}
while(i != InstalledCallbacks.end())
{
std::auto_ptr<alureStream> stream(new customStream(fdata, i->second));
if(stream->IsValid()) return stream.release();
i++;
}
return NULL;
}
alureStream *create_stream(const char *fname)
{ return get_stream_decoder(fname); }
alureStream *create_stream(const MemDataInfo &memData)
{ return get_stream_decoder(memData); }
alureStream *create_stream(ALvoid *userdata, ALenum format, ALuint rate, const UserCallbacks &cb)
{ return new customStream(userdata, format, rate, cb); }
<|endoftext|> |
<commit_before>#include "selfdrive/ui/qt/setup/setup.h"
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <QApplication>
#include <QLabel>
#include <QVBoxLayout>
#include <curl/curl.h>
#include "selfdrive/hardware/hw.h"
#include "selfdrive/ui/qt/api.h"
#include "selfdrive/ui/qt/qt_window.h"
#include "selfdrive/ui/qt/offroad/networking.h"
#include "selfdrive/ui/qt/widgets/input.h"
const char* USER_AGENT = "AGNOSSetup-0.1";
const QString DASHCAM_URL = "https://dashcam.comma.ai";
void Setup::download(QString url) {
CURL *curl = curl_easy_init();
if (!curl) {
emit finished(false);
return;
}
char tmpfile[] = "/tmp/installer_XXXXXX";
FILE *fp = fdopen(mkstemp(tmpfile), "w");
curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
int ret = curl_easy_perform(curl);
if (ret != CURLE_OK) {
emit finished(false);
return;
}
curl_easy_cleanup(curl);
fclose(fp);
rename(tmpfile, "/tmp/installer");
emit finished(true);
}
QWidget * Setup::low_voltage() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 0, 55, 55);
main_layout->setSpacing(0);
// inner text layout: warning icon, title, and body
QVBoxLayout *inner_layout = new QVBoxLayout();
inner_layout->setContentsMargins(110, 144, 365, 0);
main_layout->addLayout(inner_layout);
QLabel *triangle = new QLabel();
triangle->setPixmap(QPixmap(ASSET_PATH + "offroad/icon_warning.png"));
inner_layout->addWidget(triangle, 0, Qt::AlignTop | Qt::AlignLeft);
inner_layout->addSpacing(80);
QLabel *title = new QLabel("WARNING: Low Voltage");
title->setStyleSheet("font-size: 90px; font-weight: 500; color: #FF594F;");
inner_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft);
inner_layout->addSpacing(25);
QLabel *body = new QLabel("Power your device in a car with a harness or proceed at your own risk.");
body->setWordWrap(true);
body->setAlignment(Qt::AlignTop | Qt::AlignLeft);
body->setStyleSheet("font-size: 80px; font-weight: 300;");
inner_layout->addWidget(body);
inner_layout->addStretch();
// power off + continue buttons
QHBoxLayout *blayout = new QHBoxLayout();
blayout->setSpacing(50);
main_layout->addLayout(blayout, 0);
QPushButton *poweroff = new QPushButton("Power off");
poweroff->setObjectName("navBtn");
blayout->addWidget(poweroff);
QObject::connect(poweroff, &QPushButton::clicked, this, [=]() {
Hardware::poweroff();
});
QPushButton *cont = new QPushButton("Continue");
cont->setObjectName("navBtn");
blayout->addWidget(cont);
QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage);
return widget;
}
QWidget * Setup::getting_started() {
QWidget *widget = new QWidget();
QHBoxLayout *main_layout = new QHBoxLayout(widget);
main_layout->setMargin(0);
QVBoxLayout *vlayout = new QVBoxLayout();
vlayout->setContentsMargins(165, 280, 100, 0);
main_layout->addLayout(vlayout);
QLabel *title = new QLabel("Getting Started");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
vlayout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft);
vlayout->addSpacing(90);
QLabel *desc = new QLabel("Before we get on the road, let’s finish installation and cover some details.");
desc->setWordWrap(true);
desc->setStyleSheet("font-size: 80px; font-weight: 300;");
vlayout->addWidget(desc, 0, Qt::AlignTop | Qt::AlignLeft);
vlayout->addStretch();
QPushButton *btn = new QPushButton();
btn->setIcon(QIcon(":/img_continue_triangle.svg"));
btn->setIconSize(QSize(54, 106));
btn->setFixedSize(310, 1080);
btn->setProperty("primary", true);
btn->setStyleSheet("border: none;");
main_layout->addWidget(btn, 0, Qt::AlignRight);
QObject::connect(btn, &QPushButton::clicked, this, &Setup::nextPage);
return widget;
}
QWidget * Setup::network_setup() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 50, 55, 50);
// title
QLabel *title = new QLabel("Connect to Wi-Fi");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop);
main_layout->addSpacing(25);
// wifi widget
Networking *networking = new Networking(this, false);
networking->setStyleSheet("Networking {background-color: #292929; border-radius: 13px;}");
main_layout->addWidget(networking, 1);
main_layout->addSpacing(35);
// back + continue buttons
QHBoxLayout *blayout = new QHBoxLayout;
main_layout->addLayout(blayout);
blayout->setSpacing(50);
QPushButton *back = new QPushButton("Back");
back->setObjectName("navBtn");
QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage);
blayout->addWidget(back);
QPushButton *cont = new QPushButton();
cont->setObjectName("navBtn");
cont->setProperty("primary", true);
QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage);
blayout->addWidget(cont);
// setup timer for testing internet connection
HttpRequest *request = new HttpRequest(this, false, 2500);
QObject::connect(request, &HttpRequest::requestDone, [=](const QString &, bool success) {
cont->setEnabled(success);
if (success) {
const bool cell = networking->wifi->currentNetworkType() == NetworkType::CELL;
cont->setText(cell ? "Continue without Wi-Fi" : "Continue");
} else {
cont->setText("Waiting for internet");
}
repaint();
});
request->sendRequest(DASHCAM_URL);
QTimer *timer = new QTimer(this);
QObject::connect(timer, &QTimer::timeout, [=]() {
if (!request->active() && cont->isVisible()) {
request->sendRequest(DASHCAM_URL);
}
});
timer->start(1000);
return widget;
}
QWidget * radio_button(QString title, QButtonGroup *group) {
QPushButton *btn = new QPushButton(title);
btn->setCheckable(true);
group->addButton(btn);
btn->setStyleSheet(R"(
QPushButton {
height: 230;
padding-left: 100px;
padding-right: 100px;
text-align: left;
font-size: 80px;
font-weight: 400;
border-radius: 10px;
background-color: #4F4F4F;
}
QPushButton:checked {
background-color: #465BEA;
}
)");
// checkmark icon
QPixmap pix(":/img_circled_check.svg");
btn->setIcon(pix);
btn->setIconSize(QSize(0, 0));
btn->setLayoutDirection(Qt::RightToLeft);
QObject::connect(btn, &QPushButton::toggled, [=](bool checked) {
btn->setIconSize(checked ? QSize(104, 104) : QSize(0, 0));
});
return btn;
}
QWidget * Setup::software_selection() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 50, 55, 50);
main_layout->setSpacing(0);
// title
QLabel *title = new QLabel("Choose Software to Install");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop);
main_layout->addSpacing(50);
// dashcam + custom radio buttons
QButtonGroup *group = new QButtonGroup(widget);
group->setExclusive(true);
QWidget *dashcam = radio_button("Dashcam", group);
main_layout->addWidget(dashcam);
main_layout->addSpacing(30);
QWidget *custom = radio_button("Custom Software", group);
main_layout->addWidget(custom);
main_layout->addStretch();
// back + continue buttons
QHBoxLayout *blayout = new QHBoxLayout;
main_layout->addLayout(blayout);
blayout->setSpacing(50);
QPushButton *back = new QPushButton("Back");
back->setObjectName("navBtn");
QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage);
blayout->addWidget(back);
QPushButton *cont = new QPushButton("Continue");
cont->setObjectName("navBtn");
cont->setEnabled(false);
cont->setProperty("primary", true);
blayout->addWidget(cont);
QObject::connect(cont, &QPushButton::clicked, [=]() {
auto w = currentWidget();
QTimer::singleShot(0, [=]() {
setCurrentWidget(downloading_widget);
});
QString url = DASHCAM_URL;
if (group->checkedButton() != dashcam) {
url = InputDialog::getText("Enter URL", this, "for Custom Software");
}
if (!url.isEmpty()) {
QTimer::singleShot(1000, this, [=]() {
download(url);
});
} else {
setCurrentWidget(w);
}
});
connect(group, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), [=](QAbstractButton *btn) {
btn->setChecked(true);
cont->setEnabled(true);
});
return widget;
}
QWidget * Setup::downloading() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
QLabel *txt = new QLabel("Downloading...");
txt->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(txt, 0, Qt::AlignCenter);
return widget;
}
QWidget * Setup::download_failed() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 225, 55, 55);
main_layout->setSpacing(0);
QLabel *title = new QLabel("Download Failed");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft);
main_layout->addSpacing(67);
QLabel *body = new QLabel("Ensure the entered URL is valid, and the device’s internet connection is good.");
body->setWordWrap(true);
body->setAlignment(Qt::AlignTop | Qt::AlignLeft);
body->setStyleSheet("font-size: 80px; font-weight: 300; margin-right: 100px;");
main_layout->addWidget(body);
main_layout->addStretch();
// reboot + start over buttons
QHBoxLayout *blayout = new QHBoxLayout();
blayout->setSpacing(50);
main_layout->addLayout(blayout, 0);
QPushButton *reboot = new QPushButton("Reboot device");
reboot->setObjectName("navBtn");
blayout->addWidget(reboot);
QObject::connect(reboot, &QPushButton::clicked, this, [=]() {
Hardware::reboot();
});
QPushButton *restart = new QPushButton("Start over");
restart->setObjectName("navBtn");
restart->setProperty("primary", true);
blayout->addWidget(restart);
QObject::connect(restart, &QPushButton::clicked, this, [=]() {
setCurrentIndex(2);
});
widget->setStyleSheet(R"(
QLabel {
margin-left: 117;
}
)");
return widget;
}
void Setup::prevPage() {
setCurrentIndex(currentIndex() - 1);
}
void Setup::nextPage() {
setCurrentIndex(currentIndex() + 1);
}
Setup::Setup(QWidget *parent) : QStackedWidget(parent) {
std::stringstream buffer;
buffer << std::ifstream("/sys/class/hwmon/hwmon1/in1_input").rdbuf();
float voltage = (float)std::atoi(buffer.str().c_str()) / 1000.;
if (voltage < 7) {
addWidget(low_voltage());
}
addWidget(getting_started());
addWidget(network_setup());
addWidget(software_selection());
downloading_widget = downloading();
addWidget(downloading_widget);
failed_widget = download_failed();
addWidget(failed_widget);
QObject::connect(this, &Setup::finished, [=](bool success) {
// hide setup on success
qDebug() << "finished" << success;
if (success) {
QTimer::singleShot(3000, this, &QWidget::hide);
} else {
setCurrentWidget(failed_widget);
}
});
// TODO: revisit pressed bg color
setStyleSheet(R"(
* {
color: white;
font-family: Inter;
}
Setup {
background-color: black;
}
QPushButton#navBtn {
height: 160;
font-size: 55px;
font-weight: 400;
border-radius: 10px;
background-color: #333333;
}
QPushButton#navBtn:disabled, QPushButton[primary='true']:disabled {
color: #808080;
background-color: #333333;
}
QPushButton#navBtn:pressed {
background-color: #444444;
}
QPushButton[primary='true'], #navBtn[primary='true'] {
background-color: #465BEA;
}
QPushButton[primary='true']:pressed, #navBtn:pressed[primary='true'] {
background-color: #3049F4;
}
)");
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Setup setup;
setMainWindow(&setup);
return a.exec();
}
<commit_msg>ui/setup: check http status code (#23597)<commit_after>#include "selfdrive/ui/qt/setup/setup.h"
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <QApplication>
#include <QLabel>
#include <QVBoxLayout>
#include <curl/curl.h>
#include "selfdrive/hardware/hw.h"
#include "selfdrive/ui/qt/api.h"
#include "selfdrive/ui/qt/qt_window.h"
#include "selfdrive/ui/qt/offroad/networking.h"
#include "selfdrive/ui/qt/widgets/input.h"
const char* USER_AGENT = "AGNOSSetup-0.1";
const QString DASHCAM_URL = "https://dashcam.comma.ai";
void Setup::download(QString url) {
CURL *curl = curl_easy_init();
if (!curl) {
emit finished(false);
return;
}
char tmpfile[] = "/tmp/installer_XXXXXX";
FILE *fp = fdopen(mkstemp(tmpfile), "w");
curl_easy_setopt(curl, CURLOPT_URL, url.toStdString().c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
int ret = curl_easy_perform(curl);
long res_status = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &res_status);
if (ret == CURLE_OK && res_status == 200) {
rename(tmpfile, "/tmp/installer");
emit finished(true);
} else {
emit finished(false);
}
curl_easy_cleanup(curl);
fclose(fp);
}
QWidget * Setup::low_voltage() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 0, 55, 55);
main_layout->setSpacing(0);
// inner text layout: warning icon, title, and body
QVBoxLayout *inner_layout = new QVBoxLayout();
inner_layout->setContentsMargins(110, 144, 365, 0);
main_layout->addLayout(inner_layout);
QLabel *triangle = new QLabel();
triangle->setPixmap(QPixmap(ASSET_PATH + "offroad/icon_warning.png"));
inner_layout->addWidget(triangle, 0, Qt::AlignTop | Qt::AlignLeft);
inner_layout->addSpacing(80);
QLabel *title = new QLabel("WARNING: Low Voltage");
title->setStyleSheet("font-size: 90px; font-weight: 500; color: #FF594F;");
inner_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft);
inner_layout->addSpacing(25);
QLabel *body = new QLabel("Power your device in a car with a harness or proceed at your own risk.");
body->setWordWrap(true);
body->setAlignment(Qt::AlignTop | Qt::AlignLeft);
body->setStyleSheet("font-size: 80px; font-weight: 300;");
inner_layout->addWidget(body);
inner_layout->addStretch();
// power off + continue buttons
QHBoxLayout *blayout = new QHBoxLayout();
blayout->setSpacing(50);
main_layout->addLayout(blayout, 0);
QPushButton *poweroff = new QPushButton("Power off");
poweroff->setObjectName("navBtn");
blayout->addWidget(poweroff);
QObject::connect(poweroff, &QPushButton::clicked, this, [=]() {
Hardware::poweroff();
});
QPushButton *cont = new QPushButton("Continue");
cont->setObjectName("navBtn");
blayout->addWidget(cont);
QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage);
return widget;
}
QWidget * Setup::getting_started() {
QWidget *widget = new QWidget();
QHBoxLayout *main_layout = new QHBoxLayout(widget);
main_layout->setMargin(0);
QVBoxLayout *vlayout = new QVBoxLayout();
vlayout->setContentsMargins(165, 280, 100, 0);
main_layout->addLayout(vlayout);
QLabel *title = new QLabel("Getting Started");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
vlayout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft);
vlayout->addSpacing(90);
QLabel *desc = new QLabel("Before we get on the road, let’s finish installation and cover some details.");
desc->setWordWrap(true);
desc->setStyleSheet("font-size: 80px; font-weight: 300;");
vlayout->addWidget(desc, 0, Qt::AlignTop | Qt::AlignLeft);
vlayout->addStretch();
QPushButton *btn = new QPushButton();
btn->setIcon(QIcon(":/img_continue_triangle.svg"));
btn->setIconSize(QSize(54, 106));
btn->setFixedSize(310, 1080);
btn->setProperty("primary", true);
btn->setStyleSheet("border: none;");
main_layout->addWidget(btn, 0, Qt::AlignRight);
QObject::connect(btn, &QPushButton::clicked, this, &Setup::nextPage);
return widget;
}
QWidget * Setup::network_setup() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 50, 55, 50);
// title
QLabel *title = new QLabel("Connect to Wi-Fi");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop);
main_layout->addSpacing(25);
// wifi widget
Networking *networking = new Networking(this, false);
networking->setStyleSheet("Networking {background-color: #292929; border-radius: 13px;}");
main_layout->addWidget(networking, 1);
main_layout->addSpacing(35);
// back + continue buttons
QHBoxLayout *blayout = new QHBoxLayout;
main_layout->addLayout(blayout);
blayout->setSpacing(50);
QPushButton *back = new QPushButton("Back");
back->setObjectName("navBtn");
QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage);
blayout->addWidget(back);
QPushButton *cont = new QPushButton();
cont->setObjectName("navBtn");
cont->setProperty("primary", true);
QObject::connect(cont, &QPushButton::clicked, this, &Setup::nextPage);
blayout->addWidget(cont);
// setup timer for testing internet connection
HttpRequest *request = new HttpRequest(this, false, 2500);
QObject::connect(request, &HttpRequest::requestDone, [=](const QString &, bool success) {
cont->setEnabled(success);
if (success) {
const bool cell = networking->wifi->currentNetworkType() == NetworkType::CELL;
cont->setText(cell ? "Continue without Wi-Fi" : "Continue");
} else {
cont->setText("Waiting for internet");
}
repaint();
});
request->sendRequest(DASHCAM_URL);
QTimer *timer = new QTimer(this);
QObject::connect(timer, &QTimer::timeout, [=]() {
if (!request->active() && cont->isVisible()) {
request->sendRequest(DASHCAM_URL);
}
});
timer->start(1000);
return widget;
}
QWidget * radio_button(QString title, QButtonGroup *group) {
QPushButton *btn = new QPushButton(title);
btn->setCheckable(true);
group->addButton(btn);
btn->setStyleSheet(R"(
QPushButton {
height: 230;
padding-left: 100px;
padding-right: 100px;
text-align: left;
font-size: 80px;
font-weight: 400;
border-radius: 10px;
background-color: #4F4F4F;
}
QPushButton:checked {
background-color: #465BEA;
}
)");
// checkmark icon
QPixmap pix(":/img_circled_check.svg");
btn->setIcon(pix);
btn->setIconSize(QSize(0, 0));
btn->setLayoutDirection(Qt::RightToLeft);
QObject::connect(btn, &QPushButton::toggled, [=](bool checked) {
btn->setIconSize(checked ? QSize(104, 104) : QSize(0, 0));
});
return btn;
}
QWidget * Setup::software_selection() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 50, 55, 50);
main_layout->setSpacing(0);
// title
QLabel *title = new QLabel("Choose Software to Install");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop);
main_layout->addSpacing(50);
// dashcam + custom radio buttons
QButtonGroup *group = new QButtonGroup(widget);
group->setExclusive(true);
QWidget *dashcam = radio_button("Dashcam", group);
main_layout->addWidget(dashcam);
main_layout->addSpacing(30);
QWidget *custom = radio_button("Custom Software", group);
main_layout->addWidget(custom);
main_layout->addStretch();
// back + continue buttons
QHBoxLayout *blayout = new QHBoxLayout;
main_layout->addLayout(blayout);
blayout->setSpacing(50);
QPushButton *back = new QPushButton("Back");
back->setObjectName("navBtn");
QObject::connect(back, &QPushButton::clicked, this, &Setup::prevPage);
blayout->addWidget(back);
QPushButton *cont = new QPushButton("Continue");
cont->setObjectName("navBtn");
cont->setEnabled(false);
cont->setProperty("primary", true);
blayout->addWidget(cont);
QObject::connect(cont, &QPushButton::clicked, [=]() {
auto w = currentWidget();
QTimer::singleShot(0, [=]() {
setCurrentWidget(downloading_widget);
});
QString url = DASHCAM_URL;
if (group->checkedButton() != dashcam) {
url = InputDialog::getText("Enter URL", this, "for Custom Software");
}
if (!url.isEmpty()) {
QTimer::singleShot(1000, this, [=]() {
download(url);
});
} else {
setCurrentWidget(w);
}
});
connect(group, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), [=](QAbstractButton *btn) {
btn->setChecked(true);
cont->setEnabled(true);
});
return widget;
}
QWidget * Setup::downloading() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
QLabel *txt = new QLabel("Downloading...");
txt->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(txt, 0, Qt::AlignCenter);
return widget;
}
QWidget * Setup::download_failed() {
QWidget *widget = new QWidget();
QVBoxLayout *main_layout = new QVBoxLayout(widget);
main_layout->setContentsMargins(55, 225, 55, 55);
main_layout->setSpacing(0);
QLabel *title = new QLabel("Download Failed");
title->setStyleSheet("font-size: 90px; font-weight: 500;");
main_layout->addWidget(title, 0, Qt::AlignTop | Qt::AlignLeft);
main_layout->addSpacing(67);
QLabel *body = new QLabel("Ensure the entered URL is valid, and the device’s internet connection is good.");
body->setWordWrap(true);
body->setAlignment(Qt::AlignTop | Qt::AlignLeft);
body->setStyleSheet("font-size: 80px; font-weight: 300; margin-right: 100px;");
main_layout->addWidget(body);
main_layout->addStretch();
// reboot + start over buttons
QHBoxLayout *blayout = new QHBoxLayout();
blayout->setSpacing(50);
main_layout->addLayout(blayout, 0);
QPushButton *reboot = new QPushButton("Reboot device");
reboot->setObjectName("navBtn");
blayout->addWidget(reboot);
QObject::connect(reboot, &QPushButton::clicked, this, [=]() {
Hardware::reboot();
});
QPushButton *restart = new QPushButton("Start over");
restart->setObjectName("navBtn");
restart->setProperty("primary", true);
blayout->addWidget(restart);
QObject::connect(restart, &QPushButton::clicked, this, [=]() {
setCurrentIndex(2);
});
widget->setStyleSheet(R"(
QLabel {
margin-left: 117;
}
)");
return widget;
}
void Setup::prevPage() {
setCurrentIndex(currentIndex() - 1);
}
void Setup::nextPage() {
setCurrentIndex(currentIndex() + 1);
}
Setup::Setup(QWidget *parent) : QStackedWidget(parent) {
std::stringstream buffer;
buffer << std::ifstream("/sys/class/hwmon/hwmon1/in1_input").rdbuf();
float voltage = (float)std::atoi(buffer.str().c_str()) / 1000.;
if (voltage < 7) {
addWidget(low_voltage());
}
addWidget(getting_started());
addWidget(network_setup());
addWidget(software_selection());
downloading_widget = downloading();
addWidget(downloading_widget);
failed_widget = download_failed();
addWidget(failed_widget);
QObject::connect(this, &Setup::finished, [=](bool success) {
// hide setup on success
qDebug() << "finished" << success;
if (success) {
QTimer::singleShot(3000, this, &QWidget::hide);
} else {
setCurrentWidget(failed_widget);
}
});
// TODO: revisit pressed bg color
setStyleSheet(R"(
* {
color: white;
font-family: Inter;
}
Setup {
background-color: black;
}
QPushButton#navBtn {
height: 160;
font-size: 55px;
font-weight: 400;
border-radius: 10px;
background-color: #333333;
}
QPushButton#navBtn:disabled, QPushButton[primary='true']:disabled {
color: #808080;
background-color: #333333;
}
QPushButton#navBtn:pressed {
background-color: #444444;
}
QPushButton[primary='true'], #navBtn[primary='true'] {
background-color: #465BEA;
}
QPushButton[primary='true']:pressed, #navBtn:pressed[primary='true'] {
background-color: #3049F4;
}
)");
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Setup setup;
setMainWindow(&setup);
return a.exec();
}
<|endoftext|> |
<commit_before>#include "vg_set.hpp"
namespace vg {
// sets of VGs on disk
void VGset::transform(std::function<void(VG*)> lambda) {
for (auto& name : filenames) {
// load
VG* g = NULL;
if (name == "-") {
g = new VG(std::cin, show_progress);
} else {
ifstream in(name.c_str());
g = new VG(in, show_progress);
in.close();
}
g->name = name;
// apply
lambda(g);
// write to the same file
ofstream out(name.c_str());
g->serialize_to_ostream(out);
out.close();
delete g;
}
}
void VGset::for_each(std::function<void(VG*)> lambda) {
for (auto& name : filenames) {
// load
VG* g = NULL;
if (name == "-") {
g = new VG(std::cin, show_progress);
} else {
ifstream in(name.c_str());
g = new VG(in, show_progress);
in.close();
}
g->name = name;
// apply
lambda(g);
delete g;
}
}
int64_t VGset::merge_id_space(void) {
int64_t max_id = 0;
auto lambda = [&max_id](VG* g) {
if (max_id > 0) g->increment_node_ids(max_id);
max_id = g->max_node_id();
};
transform(lambda);
return max_id;
}
void VGset::store_in_index(Index& index) {
index.close();
index.prepare_for_bulk_load();
index.open();
for_each([&index, this](VG* g) {
g->show_progress = show_progress;
index.load_graph(*g);
});
// clean up after bulk load
index.flush();
index.close();
index.reset_options();
index.open();
index.compact();
}
// stores kmers of size kmer_size with stride over paths in graphs in the index
void VGset::index_kmers(Index& index, int kmer_size, int stride) {
index.close();
index.prepare_for_bulk_load();
index.open();
for_each([&index, kmer_size, stride, this](VG* g) {
// set up an index per process
// we merge them at the end of this graph
vector<Index*> indexes;
vector<int64_t> counts;
int thread_count = 1;
#pragma omp parallel
{
#pragma omp master
{
thread_count = omp_get_num_threads();
for (int i = 0; i < thread_count; ++i) {
stringstream s;
s << index.name << "." << i;
string n = s.str();
Index* idx = new Index;
idx->open(n);
//idx->prepare_for_bulk_load();
indexes.push_back(idx);
counts.push_back(0);
}
}
}
auto keep_kmer = [&indexes, &counts, this](string& kmer, Node* n, int p) {
if (allATGC(kmer)) {
counts[omp_get_thread_num()]++;
indexes[omp_get_thread_num()]->put_kmer(kmer, n->id(), p);
}
};
g->create_progress("indexing kmers of " + g->name, g->size());
g->for_each_kmer_parallel(kmer_size, keep_kmer, stride);
g->destroy_progress();
int64_t total_kmers = 0;
for (auto i : counts) total_kmers += i;
int64_t count = 0;
// merge results
index.remember_kmer_size(kmer_size);
g->create_progress("merging kmers of " + g->name, total_kmers);
//#pragma omp parallel for schedule(static, 1)
for (int i = 0; i < thread_count; ++i) {
//for (auto* idx : indexes) {
auto* idx = indexes[i];
//idx->flush();
idx->for_all([g, &index, &count](string& k, string& v) {
#pragma omp atomic
++count;
if (count % 10000) g->update_progress(count);
index.db->Put(index.write_options, k, v);
});
string dbname = idx->name;
//cerr << dbname << endl;
delete idx;
int r = system((string("rm -r ") + dbname).c_str());
}
g->destroy_progress();
});
// clean up after bulk load
index.flush();
index.close();
index.reset_options();
index.open();
index.compact();
}
void VGset::for_each_kmer_parallel(function<void(string&, Node*, int)>& lambda,
int kmer_size, int stride) {
for_each([&lambda, kmer_size, stride, this](VG* g) {
g->show_progress = show_progress;
g->progress_message = "processing kmers of " + g->name;
g->for_each_kmer_parallel(kmer_size, lambda, stride);
});
}
}
<commit_msg>prep for bulk load on index shards<commit_after>#include "vg_set.hpp"
namespace vg {
// sets of VGs on disk
void VGset::transform(std::function<void(VG*)> lambda) {
for (auto& name : filenames) {
// load
VG* g = NULL;
if (name == "-") {
g = new VG(std::cin, show_progress);
} else {
ifstream in(name.c_str());
g = new VG(in, show_progress);
in.close();
}
g->name = name;
// apply
lambda(g);
// write to the same file
ofstream out(name.c_str());
g->serialize_to_ostream(out);
out.close();
delete g;
}
}
void VGset::for_each(std::function<void(VG*)> lambda) {
for (auto& name : filenames) {
// load
VG* g = NULL;
if (name == "-") {
g = new VG(std::cin, show_progress);
} else {
ifstream in(name.c_str());
g = new VG(in, show_progress);
in.close();
}
g->name = name;
// apply
lambda(g);
delete g;
}
}
int64_t VGset::merge_id_space(void) {
int64_t max_id = 0;
auto lambda = [&max_id](VG* g) {
if (max_id > 0) g->increment_node_ids(max_id);
max_id = g->max_node_id();
};
transform(lambda);
return max_id;
}
void VGset::store_in_index(Index& index) {
index.close();
index.prepare_for_bulk_load();
index.open();
for_each([&index, this](VG* g) {
g->show_progress = show_progress;
index.load_graph(*g);
});
// clean up after bulk load
index.flush();
index.close();
index.reset_options();
index.open();
index.compact();
}
// stores kmers of size kmer_size with stride over paths in graphs in the index
void VGset::index_kmers(Index& index, int kmer_size, int stride) {
index.close();
index.prepare_for_bulk_load();
index.open();
for_each([&index, kmer_size, stride, this](VG* g) {
// set up an index per process
// we merge them at the end of this graph
vector<Index*> indexes;
vector<int64_t> counts;
int thread_count = 1;
#pragma omp parallel
{
#pragma omp master
{
thread_count = omp_get_num_threads();
for (int i = 0; i < thread_count; ++i) {
stringstream s;
s << index.name << "." << i;
string n = s.str();
Index* idx = new Index;
idx->open(n);
idx->prepare_for_bulk_load();
indexes.push_back(idx);
counts.push_back(0);
}
}
}
auto keep_kmer = [&indexes, &counts, this](string& kmer, Node* n, int p) {
if (allATGC(kmer)) {
counts[omp_get_thread_num()]++;
indexes[omp_get_thread_num()]->put_kmer(kmer, n->id(), p);
}
};
g->create_progress("indexing kmers of " + g->name, g->size());
g->for_each_kmer_parallel(kmer_size, keep_kmer, stride);
g->destroy_progress();
int64_t total_kmers = 0;
for (auto i : counts) total_kmers += i;
int64_t count = 0;
// merge results
index.remember_kmer_size(kmer_size);
g->create_progress("merging kmers of " + g->name, total_kmers);
//#pragma omp parallel for schedule(static, 1)
for (int i = 0; i < thread_count; ++i) {
//for (auto* idx : indexes) {
auto* idx = indexes[i];
//idx->flush();
idx->for_all([g, &index, &count](string& k, string& v) {
#pragma omp atomic
++count;
if (count % 10000) g->update_progress(count);
index.db->Put(index.write_options, k, v);
});
string dbname = idx->name;
//cerr << dbname << endl;
delete idx;
int r = system((string("rm -r ") + dbname).c_str());
}
g->destroy_progress();
});
// clean up after bulk load
index.flush();
index.close();
index.reset_options();
index.open();
index.compact();
}
void VGset::for_each_kmer_parallel(function<void(string&, Node*, int)>& lambda,
int kmer_size, int stride) {
for_each([&lambda, kmer_size, stride, this](VG* g) {
g->show_progress = show_progress;
g->progress_message = "processing kmers of " + g->name;
g->for_each_kmer_parallel(kmer_size, lambda, stride);
});
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/Language.h"
#include "fnord-base/random.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "fnord-logtable/ArtifactIndex.h"
#include <fnord-fts/fts.h>
#include <fnord-fts/fts_common.h>
#include "fnord-logtable/TableReader.h"
#include "common.h"
#include "schemas.h"
#include "CustomerNamespace.h"
#include "CTRCounter.h"
#include "analytics/ReportBuilder.h"
#include "analytics/AnalyticsTableScanSource.h"
#include "analytics/CTRBySearchTermCrossCategoryMapper.h"
#include "analytics/CTRCounterMergeReducer.h"
#include "analytics/CTRCounterTableSink.h"
#include "analytics/CTRCounterTableSource.h"
#include "analytics/RelatedTermsMapper.h"
#include "analytics/TopCategoriesByTermMapper.h"
#include "analytics/TermInfoMergeReducer.h"
using namespace fnord;
using namespace cm;
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
//flags.defineFlag(
// "conf",
// cli::FlagParser::T_STRING,
// false,
// NULL,
// "./conf",
// "conf directory",
// "<path>");
//flags.defineFlag(
// "index",
// cli::FlagParser::T_STRING,
// false,
// NULL,
// NULL,
// "index directory",
// "<path>");
flags.defineFlag(
"replica",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"replica id",
"<id>");
flags.defineFlag(
"datadir",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"artifact directory",
"<path>");
flags.defineFlag(
"tempdir",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"artifact directory",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
auto tempdir = flags.getString("tempdir");
auto datadir = flags.getString("datadir");
thread::ThreadPool tpool;
cm::ReportBuilder report_builder(&tpool);
auto buildid = "golden";
//Random rnd;
//auto buildid = rnd.hex128();
//auto table = logtable::TableReader::open(
// "joined_sessions-dawanda",
// flags.getString("replica"),
// flags.getString("datadir"),
// joinedSessionsSchema());
//auto snap = table->getSnapshot();
//Set<String> searchterm_x_e1_tables;
//Set<String> related_terms_tables;
//for (const auto& c : snap->head->chunks) {
// auto input_table = StringUtil::format(
// "$0/$1.$2.$3.cst",
// datadir,
// "joined_sessions-dawanda",
// c.replica_id,
// c.chunk_id);
// /* map related terms */
// auto related_terms_table = StringUtil::format(
// "$0/dawanda_related_terms.$1.$2.sst",
// tempdir,
// c.replica_id,
// c.chunk_id);
// related_terms_tables.emplace(related_terms_table);
// report_builder.addReport(
// new RelatedTermsMapper(
// new AnalyticsTableScanSource(input_table),
// new TermInfoTableSink(related_terms_table)));
// /* map serchterm x e1 */
// auto searchterm_x_e1_table = StringUtil::format(
// "$0/dawanda_ctr_by_searchterm_cross_e1.$1.$2.sst",
// tempdir,
// c.replica_id,
// c.chunk_id);
// searchterm_x_e1_tables.emplace(searchterm_x_e1_table);
// report_builder.addReport(
// new CTRBySearchTermCrossCategoryMapper(
// new AnalyticsTableScanSource(input_table),
// new CTRCounterTableSink(0, 0, searchterm_x_e1_table),
// "category1"));
//}
//report_builder.addReport(
// new TermInfoMergeReducer(
// new TermInfoTableSource(related_terms_tables),
// new TermInfoTableSink(
// StringUtil::format(
// "$0/dawanda_related_terms.$1.sst",
// tempdir,
// buildid))));
//report_builder.addReport(
// new TopCategoriesByTermMapper(
// new CTRCounterTableSource(searchterm_x_e1_tables),
// new TermInfoTableSink(
// StringUtil::format(
// "$0/dawanda_top_cats_by_searchterm_e1.$1.sst",
// tempdir,
// buildid)),
// "e1-"));
//report_builder.addReport(
// new TermInfoMergeReducer(
// new TermInfoTableSource(Set<String> {
// StringUtil::format(
// "$0/dawanda_related_terms.$1.sst",
// tempdir,
// buildid),
// StringUtil::format(
// "$0/dawanda_top_cats_by_searchterm_e1.$1.sst",
// tempdir,
// buildid)
// }),
// new TermInfoTableSink(
// StringUtil::format(
// "$0/dawanda_termstats.$1.sst",
// tempdir,
// buildid))));
//report_builder.buildAll();
fnord::logInfo(
"cm.reportbuild",
"Build completed: dawanda_termstats.$0.sst",
buildid);
logtable::ArtifactIndex artifacts(datadir, "termstats", false);
auto outfile = StringUtil::format("termstats-dawanda.$0.sst", buildid);
auto tempfile_path = FileUtil::joinPaths(tempdir, outfile);
auto outfile_path = FileUtil::joinPaths(datadir, outfile);
FileUtil::mv(tempfile_path, outfile_path);
logtable::ArtifactRef afx;
afx.name = StringUtil::format("termstats-dawanda.$0", buildid);
afx.status = logtable::ArtifactStatus::PRESENT;
afx.attributes.emplace_back(
"built_at",
StringUtil::toString(WallClock::unixMicros() / kMicrosPerSecond));
afx.files.emplace_back(logtable::ArtifactFileRef {
.filename = outfile,
.size = FileUtil::size(outfile_path),
.checksum = FileUtil::checksum(outfile_path)
});
artifacts.addArtifact(afx);
return 0;
}
<commit_msg>bring back autocompletebuild<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/Language.h"
#include "fnord-base/random.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-base/thread/threadpool.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "fnord-logtable/ArtifactIndex.h"
#include <fnord-fts/fts.h>
#include <fnord-fts/fts_common.h>
#include "fnord-logtable/TableReader.h"
#include "common.h"
#include "schemas.h"
#include "CustomerNamespace.h"
#include "CTRCounter.h"
#include "analytics/ReportBuilder.h"
#include "analytics/AnalyticsTableScanSource.h"
#include "analytics/CTRBySearchTermCrossCategoryMapper.h"
#include "analytics/CTRCounterMergeReducer.h"
#include "analytics/CTRCounterTableSink.h"
#include "analytics/CTRCounterTableSource.h"
#include "analytics/RelatedTermsMapper.h"
#include "analytics/TopCategoriesByTermMapper.h"
#include "analytics/TermInfoMergeReducer.h"
using namespace fnord;
using namespace cm;
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
//flags.defineFlag(
// "conf",
// cli::FlagParser::T_STRING,
// false,
// NULL,
// "./conf",
// "conf directory",
// "<path>");
//flags.defineFlag(
// "index",
// cli::FlagParser::T_STRING,
// false,
// NULL,
// NULL,
// "index directory",
// "<path>");
flags.defineFlag(
"replica",
cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"replica id",
"<id>");
flags.defineFlag(
"datadir",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"artifact directory",
"<path>");
flags.defineFlag(
"tempdir",
cli::FlagParser::T_STRING,
false,
NULL,
NULL,
"artifact directory",
"<path>");
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
auto tempdir = flags.getString("tempdir");
auto datadir = flags.getString("datadir");
thread::ThreadPool tpool;
cm::ReportBuilder report_builder(&tpool);
Random rnd;
auto buildid = rnd.hex128();
auto table = logtable::TableReader::open(
"joined_sessions-dawanda",
flags.getString("replica"),
flags.getString("datadir"),
joinedSessionsSchema());
auto snap = table->getSnapshot();
Set<String> searchterm_x_e1_tables;
Set<String> related_terms_tables;
for (const auto& c : snap->head->chunks) {
auto input_table = StringUtil::format(
"$0/$1.$2.$3.cst",
datadir,
"joined_sessions-dawanda",
c.replica_id,
c.chunk_id);
/* map related terms */
auto related_terms_table = StringUtil::format(
"$0/dawanda_related_terms.$1.$2.sst",
tempdir,
c.replica_id,
c.chunk_id);
related_terms_tables.emplace(related_terms_table);
report_builder.addReport(
new RelatedTermsMapper(
new AnalyticsTableScanSource(input_table),
new TermInfoTableSink(related_terms_table)));
/* map serchterm x e1 */
auto searchterm_x_e1_table = StringUtil::format(
"$0/dawanda_ctr_by_searchterm_cross_e1.$1.$2.sst",
tempdir,
c.replica_id,
c.chunk_id);
searchterm_x_e1_tables.emplace(searchterm_x_e1_table);
report_builder.addReport(
new CTRBySearchTermCrossCategoryMapper(
new AnalyticsTableScanSource(input_table),
new CTRCounterTableSink(0, 0, searchterm_x_e1_table),
"category1"));
}
report_builder.addReport(
new TermInfoMergeReducer(
new TermInfoTableSource(related_terms_tables),
new TermInfoTableSink(
StringUtil::format(
"$0/dawanda_related_terms.$1.sst",
tempdir,
buildid))));
report_builder.addReport(
new TopCategoriesByTermMapper(
new CTRCounterTableSource(searchterm_x_e1_tables),
new TermInfoTableSink(
StringUtil::format(
"$0/dawanda_top_cats_by_searchterm_e1.$1.sst",
tempdir,
buildid)),
"e1-"));
report_builder.addReport(
new TermInfoMergeReducer(
new TermInfoTableSource(Set<String> {
StringUtil::format(
"$0/dawanda_related_terms.$1.sst",
tempdir,
buildid),
StringUtil::format(
"$0/dawanda_top_cats_by_searchterm_e1.$1.sst",
tempdir,
buildid)
}),
new TermInfoTableSink(
StringUtil::format(
"$0/dawanda_termstats.$1.sst",
tempdir,
buildid))));
report_builder.buildAll();
fnord::logInfo(
"cm.reportbuild",
"Build completed: dawanda_termstats.$0.sst",
buildid);
logtable::ArtifactIndex artifacts(datadir, "termstats", false);
auto outfile = StringUtil::format("termstats-dawanda.$0.sst", buildid);
auto tempfile_path = FileUtil::joinPaths(tempdir, outfile);
auto outfile_path = FileUtil::joinPaths(datadir, outfile);
FileUtil::mv(tempfile_path, outfile_path);
logtable::ArtifactRef afx;
afx.name = StringUtil::format("termstats-dawanda.$0", buildid);
afx.status = logtable::ArtifactStatus::PRESENT;
afx.attributes.emplace_back(
"built_at",
StringUtil::toString(WallClock::unixMicros() / kMicrosPerSecond));
afx.files.emplace_back(logtable::ArtifactFileRef {
.filename = outfile,
.size = FileUtil::size(outfile_path),
.checksum = FileUtil::checksum(outfile_path)
});
artifacts.addArtifact(afx);
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2014-2016 the project authors as listed in the AUTHORS file.
// All rights reserved. Use of this source code is governed by the
// license that can be found in the LICENSE file.
#include "Device.h"
#include "MqttDevice.h"
#include <Arduino.h>
#include <stdio.h>
#include <string.h>
#define MAX_TOPIC_LENGTH 1024
#define MAX_MESSAGE_LENGTH 256
MqttDevice::MqttDevice(PubSubClient* client, char* topic) {
_client = client;
_topic = topic;
}
void MqttDevice::handleNextMessage(Message* message) {
char topicBuffer[MAX_TOPIC_LENGTH];
char messageBuffer[MAX_MESSAGE_LENGTH];
Device* messageDevice = ((Device*) message->device);
for (int i=0;i<messageDevice->numMessages();i++) {
topicBuffer[0] = 0;
messageBuffer[0] = 0;
strncpy(topicBuffer, _topic, MAX_TOPIC_LENGTH);
((MqttDevice*) message->device)->publishTopic(i, message, topicBuffer, MAX_TOPIC_LENGTH);
messageDevice->getMessageText(i, message, messageBuffer, MAX_MESSAGE_LENGTH);
if (strlen(topicBuffer) != 0) {
_client->publish(topicBuffer, messageBuffer);
}
}
}
void MqttDevice::publishTopic(Message* message, char* buffer, int maxLength) {
}
void MqttDevice::publishTopic(int messageNum, Message* message, char* buffer, int maxLength) {
publishTopic(message, buffer, maxLength);
}
<commit_msg>fix problem with overidden publishTopic<commit_after>// Copyright 2014-2016 the project authors as listed in the AUTHORS file.
// All rights reserved. Use of this source code is governed by the
// license that can be found in the LICENSE file.
#include "Device.h"
#include "MqttDevice.h"
#include <Arduino.h>
#include <stdio.h>
#include <string.h>
#define MAX_TOPIC_LENGTH 1024
#define MAX_MESSAGE_LENGTH 256
MqttDevice::MqttDevice(PubSubClient* client, char* topic) {
_client = client;
_topic = topic;
}
void MqttDevice::handleNextMessage(Message* message) {
char topicBuffer[MAX_TOPIC_LENGTH];
char messageBuffer[MAX_MESSAGE_LENGTH];
Device* messageDevice = ((Device*) message->device);
for (int i=0;i<messageDevice->numMessages();i++) {
topicBuffer[0] = 0;
messageBuffer[0] = 0;
strncpy(topicBuffer, _topic, MAX_TOPIC_LENGTH);
publishTopic(i, message, topicBuffer, MAX_TOPIC_LENGTH);
messageDevice->getMessageText(i, message, messageBuffer, MAX_MESSAGE_LENGTH);
if (strlen(topicBuffer) != 0) {
_client->publish(topicBuffer, messageBuffer);
}
}
}
void MqttDevice::publishTopic(Message* message, char* buffer, int maxLength) {
}
void MqttDevice::publishTopic(int messageNum, Message* message, char* buffer, int maxLength) {
publishTopic(message, buffer, maxLength);
}
<|endoftext|> |
<commit_before>// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#include "sw/device/silicon_creator/lib/otbn_util.h"
#include "gtest/gtest.h"
namespace otbn_util_unittest {
namespace {
TEST(OtbnTest, OtbnInit) {
otbn_t otbn;
otbn_init(&otbn);
EXPECT_EQ(otbn.app_is_loaded, kHardenedBoolFalse);
EXPECT_EQ(otbn.error_bits, kOtbnErrBitsNoError);
}
} // namespace
} // namespace otbn_util_unittest
<commit_msg>[sw/silicon_creator] Add unit test for otbn_load_app<commit_after>// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#include "sw/device/silicon_creator/lib/otbn_util.h"
#include <array>
#include "gtest/gtest.h"
#include "sw/device/lib/base/mock_abs_mmio.h"
#include "sw/device/silicon_creator/lib/base/mock_sec_mmio.h"
#include "sw/device/silicon_creator/lib/drivers/mock_rnd.h"
#include "sw/device/silicon_creator/testing/rom_test.h"
#include "hw/top_earlgrey/sw/autogen/top_earlgrey.h"
#include "otbn_regs.h" // Generated.
namespace otbn_util_unittest {
namespace {
using ::testing::Return;
TEST(OtbnTest, OtbnInit) {
otbn_t otbn;
otbn_init(&otbn);
EXPECT_EQ(otbn.app_is_loaded, kHardenedBoolFalse);
EXPECT_EQ(otbn.error_bits, kOtbnErrBitsNoError);
}
class OtbnTest : public rom_test::RomTest {
protected:
/**
* Sets expectations for running an OTBN command.
*
* @param cmd Command expected to be run.
* @param err_bits Error bits to be returned.
* @param status Status of OTBN to be returned after the command is done.
*/
void ExpectCmdRun(otbn_cmd_t cmd, otbn_err_bits_t err_bits,
otbn_status_t status) {
EXPECT_ABS_WRITE32(base_ + OTBN_INTR_STATE_REG_OFFSET,
{
{OTBN_INTR_COMMON_DONE_BIT, 1},
});
EXPECT_ABS_WRITE32(base_ + OTBN_CMD_REG_OFFSET, cmd);
EXPECT_ABS_READ32(base_ + OTBN_INTR_STATE_REG_OFFSET, 0);
EXPECT_ABS_READ32(base_ + OTBN_INTR_STATE_REG_OFFSET,
{
{OTBN_INTR_COMMON_DONE_BIT, 1},
});
EXPECT_ABS_WRITE32(base_ + OTBN_INTR_STATE_REG_OFFSET,
{
{OTBN_INTR_COMMON_DONE_BIT, 1},
});
EXPECT_ABS_READ32(base_ + OTBN_ERR_BITS_REG_OFFSET, err_bits);
EXPECT_ABS_READ32(base_ + OTBN_STATUS_REG_OFFSET, status);
if (err_bits == kOtbnErrBitsNoError && status == kOtbnStatusIdle) {
EXPECT_ABS_READ32(base_ + OTBN_STATUS_REG_OFFSET, status);
}
}
uint32_t base_ = TOP_EARLGREY_OTBN_BASE_ADDR;
rom_test::MockAbsMmio abs_mmio_;
rom_test::MockRnd rnd_;
rom_test::MockSecMmio sec_mmio_;
};
class OtbnAppTest : public OtbnTest {};
TEST_F(OtbnAppTest, OtbnLoadAppSuccess) {
std::array<uint32_t, 2> imem_data = {0x01234567, 0x89abcdef};
std::array<uint32_t, 2> dmem_data = {0x456789ab, 0xcdef0123};
otbn_app_t app = {
.imem_start = imem_data.data(),
.imem_end = imem_data.data() + imem_data.size(),
.dmem_data_start = dmem_data.data(),
.dmem_data_end = dmem_data.data() + imem_data.size(),
};
// Test assumption.
static_assert(OTBN_DMEM_SIZE_BYTES >= sizeof(uint32_t) * dmem_data.size(),
"OTBN DMEM size too small");
static_assert(OTBN_IMEM_SIZE_BYTES >= sizeof(uint32_t) * imem_data.size(),
"OTBN IMEM size too small");
// `otbn_busy_wait_for_done` - begin with busy to ensure we wait until idle.
EXPECT_ABS_READ32(base_ + OTBN_STATUS_REG_OFFSET, kOtbnStatusBusyExecute);
EXPECT_ABS_READ32(base_ + OTBN_STATUS_REG_OFFSET, kOtbnStatusBusySecWipeDmem);
// Read twice for hardening.
EXPECT_ABS_READ32(base_ + OTBN_STATUS_REG_OFFSET, kOtbnStatusIdle);
EXPECT_ABS_READ32(base_ + OTBN_STATUS_REG_OFFSET, kOtbnStatusIdle);
// `otbn_imem_sec_wipe`
ExpectCmdRun(kOtbnCmdSecWipeImem, kOtbnErrBitsNoError, kOtbnStatusIdle);
// `otbn_imem_write`
EXPECT_CALL(rnd_, Uint32()).WillOnce(Return(0));
EXPECT_ABS_WRITE32(base_ + OTBN_IMEM_REG_OFFSET, imem_data[0]);
EXPECT_ABS_WRITE32(base_ + OTBN_IMEM_REG_OFFSET + sizeof(uint32_t),
imem_data[1]);
// `otbn_dmem_sec_wipe`
ExpectCmdRun(kOtbnCmdSecWipeDmem, kOtbnErrBitsNoError, kOtbnStatusIdle);
// `otbn_dmem_write`
EXPECT_CALL(rnd_, Uint32()).WillOnce(Return(0));
EXPECT_ABS_WRITE32(base_ + OTBN_DMEM_REG_OFFSET, dmem_data[0]);
EXPECT_ABS_WRITE32(base_ + OTBN_DMEM_REG_OFFSET + sizeof(uint32_t),
dmem_data[1]);
otbn_t otbn;
otbn_init(&otbn);
EXPECT_EQ(otbn_load_app(&otbn, app), kErrorOk);
}
TEST_F(OtbnAppTest, OtbnLoadInvalidApp) {
// Create an invalid app with an empty IMEM range.
std::array<uint32_t, 0> imem_data = {};
std::array<uint32_t, 2> dmem_data = {0x456789ab, 0xcdef0123};
otbn_app_t app = {
.imem_start = imem_data.data(),
.imem_end = imem_data.data() + imem_data.size(),
.dmem_data_start = dmem_data.data(),
.dmem_data_end = dmem_data.data() + dmem_data.size(),
};
// Test assumption.
static_assert(OTBN_DMEM_SIZE_BYTES >= sizeof(uint32_t) * dmem_data.size(),
"OTBN DMEM size too small");
static_assert(OTBN_IMEM_SIZE_BYTES >= sizeof(uint32_t) * imem_data.size(),
"OTBN IMEM size too small");
otbn_t otbn;
otbn_init(&otbn);
EXPECT_EQ(otbn_load_app(&otbn, app), kErrorOtbnInvalidArgument);
}
} // namespace
} // namespace otbn_util_unittest
<|endoftext|> |
<commit_before>#include "pch.h"
#include "ang/core/async.hpp"
using namespace ang;
using namespace ang::core;
using namespace ang::core::async;
ANG_IMPLEMENT_INTERFACE(ang::core::async, ioperation<void>);
ANG_IMPLEMENT_BASIC_INTERFACE(ang::core::async::itask, ioperation<void>);
//ANG_IMPLEMENT_BASIC_INTERFACE(ang::core::async::iasync<void>, itask)
ANG_IMPLEMENT_FLAGS(async, async_action_status, uint);
extern "C" ulong64 ang_get_performance_time();
////////////////////////////////////////////////////////////////
mutex::mutex()
: _handle(NULL)
{
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
_handle = memory::default_allocator<pthread_mutex_t>::alloc(1);
pthread_mutex_init((pthread_mutex_t*)_handle, &attr);
pthread_mutexattr_destroy(&attr);
#elif defined WINDOWS_PLATFORM
_handle = memory::default_allocator<CRITICAL_SECTION>::alloc(1);
InitializeCriticalSection((LPCRITICAL_SECTION)_handle);
//this->_handle = CreateMutexExW(NULL, NULL, 0, SYNCHRONIZE);
#endif
}
mutex::mutex(bool _lock)
: _handle(NULL)
{
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
_handle = memory::default_allocator<pthread_mutex_t>::alloc(1);
pthread_mutex_init((pthread_mutex_t*)_handle, &attr);
pthread_mutexattr_destroy(&attr);
if (_lock)pthread_mutex_lock((pthread_mutex_t*)_handle);
#elif defined WINDOWS_PLATFORM
//this->_handle = CreateMutexExW(NULL, NULL, 0, SYNCHRONIZE);
_handle = memory::default_allocator<CRITICAL_SECTION>::alloc(1);
InitializeCriticalSection((LPCRITICAL_SECTION)_handle);
if (_lock)WaitForSingleObjectEx(this->_handle, INFINITE, FALSE);
#endif
}
mutex::~mutex()
{
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
pthread_mutex_destroy((pthread_mutex_t*)_handle);
memory::default_allocator<pthread_mutex_t>::free((pthread_mutex_t*)_handle);
#elif defined WINDOWS_PLATFORM
//::CloseHandle(this->_handle);
DeleteCriticalSection((LPCRITICAL_SECTION)_handle);
memory::default_allocator<CRITICAL_SECTION>::free((LPCRITICAL_SECTION)_handle);
#endif
}
bool mutex::lock()const
{
if (_handle != NULL)
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
return pthread_mutex_lock((pthread_mutex_t*)_handle) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
//return WaitForSingleObjectEx(this->_handle, INFINITE, FALSE) == WAIT_OBJECT_0 ? true : false;
EnterCriticalSection(LPCRITICAL_SECTION(_handle));
return true;
#endif
return false;
}
bool mutex::trylock()const
{
if (_handle != NULL)
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
return pthread_mutex_trylock((pthread_mutex_t*)_handle) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
//return WaitForSingleObjectEx(this->_handle, 0, FALSE) == WAIT_OBJECT_0 ? true : false;
return TryEnterCriticalSection(LPCRITICAL_SECTION(_handle)) ? true : false;
#endif
return false;
}
bool mutex::unlock()const
{
if (_handle != NULL)
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
return pthread_mutex_unlock((pthread_mutex_t*)_handle) == 0 ? ang_true : ang_false;
#elif defined WINDOWS_PLATFORM
LeaveCriticalSection(LPCRITICAL_SECTION(_handle));
return true;
//return ReleaseMutex(this->_handle) ? true : false;
#endif
return false;
}
////////////////////////////////////////////////////////////////////////////////
cond::cond()
{
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
_handle = memory::default_allocator<pthread_cond_t>::alloc(1);
pthread_cond_init((pthread_cond_t*)_handle, NULL);
#elif defined WINDOWS_PLATFORM
this->_handle = CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);
#endif
}
cond::~cond()
{
if (_handle != NULL)
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
{
pthread_cond_destroy((pthread_cond_t*)_handle);
memory::default_allocator<pthread_cond_t>::free((pthread_cond_t*)_handle);
}
#elif defined WINDOWS_PLATFORM
CloseHandle(this->_handle);
#endif
_handle = NULL;
}
bool cond::wait(mutex& mutex)const
{
if (_handle == NULL)
return false;
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
return pthread_cond_wait((pthread_cond_t*)_handle, (pthread_mutex_t*)mutex._handle) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
mutex.unlock();
auto res = WaitForSingleObjectEx(this->_handle, INFINITE, FALSE) == WAIT_OBJECT_0 ? true : false;
mutex.lock();
return res;
#endif
}
bool cond::wait(mutex_ptr_t mutex)const
{
if (_handle == NULL)
return false;
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
if (mutex.is_empty())
return false;
return pthread_cond_wait((pthread_cond_t*)_handle, (pthread_mutex_t*)mutex->_handle) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
if(!mutex.is_empty())mutex->unlock();
auto res = WaitForSingleObjectEx(this->_handle, INFINITE, FALSE) == WAIT_OBJECT_0 ? true : false;
if (!mutex.is_empty())mutex->lock();
return res;
#endif
}
bool cond::wait(mutex& mutex, dword ms)const
{
if (_handle == NULL)
return false;
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
timespec time;
time.tv_sec = (long)ms / 1000;
time.tv_nsec = ((long)ms - time.tv_sec * 1000) * 1000;
return pthread_cond_timedwait((pthread_cond_t*)_handle, (pthread_mutex_t*)mutex._handle, &time) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
mutex.unlock();
auto res = WaitForSingleObjectEx(this->_handle, ms, FALSE) == WAIT_OBJECT_0 ? true : false;
mutex.lock();
return res;
#endif
}
bool cond::wait(mutex_ptr_t mutex, dword ms)const
{
if (_handle == NULL)
return false;
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
if (mutex.is_empty())
return false;
timespec time;
time.tv_sec = (long)ms / 1000;
time.tv_nsec = ((long)ms - time.tv_sec * 1000) * 1000;
return pthread_cond_timedwait((pthread_cond_t*)_handle, (pthread_mutex_t*)mutex->_handle, &time) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
if (!mutex.is_empty())mutex->unlock();
auto res = WaitForSingleObjectEx(this->_handle, ms, FALSE) == WAIT_OBJECT_0 ? true : false;
if (!mutex.is_empty())mutex->lock();
return res;
#endif
}
bool cond::signal()const
{
if (_handle != null)
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
return pthread_cond_broadcast((pthread_cond_t*)_handle) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
{
bool _res = SetEvent(_handle) ? true : false;
ResetEvent(_handle);
return _res;
}
#endif
return false;
}
<commit_msg>* fix for mutex<commit_after>#include "pch.h"
#include "ang/core/async.hpp"
using namespace ang;
using namespace ang::core;
using namespace ang::core::async;
ANG_IMPLEMENT_INTERFACE(ang::core::async, ioperation<void>);
ANG_IMPLEMENT_BASIC_INTERFACE(ang::core::async::itask, ioperation<void>);
//ANG_IMPLEMENT_BASIC_INTERFACE(ang::core::async::iasync<void>, itask)
ANG_IMPLEMENT_FLAGS(async, async_action_status, uint);
extern "C" ulong64 ang_get_performance_time();
////////////////////////////////////////////////////////////////
mutex::mutex()
: _handle(NULL)
{
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
_handle = memory::default_allocator<pthread_mutex_t>::alloc(1);
pthread_mutex_init((pthread_mutex_t*)_handle, &attr);
pthread_mutexattr_destroy(&attr);
#elif defined WINDOWS_PLATFORM
_handle = memory::default_allocator<CRITICAL_SECTION>::alloc(1);
InitializeCriticalSection((LPCRITICAL_SECTION)_handle);
//this->_handle = CreateMutexExW(NULL, NULL, 0, SYNCHRONIZE);
#endif
}
mutex::mutex(bool _lock)
: _handle(NULL)
{
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
_handle = memory::default_allocator<pthread_mutex_t>::alloc(1);
pthread_mutex_init((pthread_mutex_t*)_handle, &attr);
pthread_mutexattr_destroy(&attr);
if (_lock)pthread_mutex_lock((pthread_mutex_t*)_handle);
#elif defined WINDOWS_PLATFORM
//this->_handle = CreateMutexExW(NULL, NULL, 0, SYNCHRONIZE);
_handle = memory::default_allocator<CRITICAL_SECTION>::alloc(1);
InitializeCriticalSection((LPCRITICAL_SECTION)_handle);
if (_lock)EnterCriticalSection(LPCRITICAL_SECTION(_handle));
#endif
}
mutex::~mutex()
{
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
pthread_mutex_destroy((pthread_mutex_t*)_handle);
memory::default_allocator<pthread_mutex_t>::free((pthread_mutex_t*)_handle);
#elif defined WINDOWS_PLATFORM
//::CloseHandle(this->_handle);
DeleteCriticalSection((LPCRITICAL_SECTION)_handle);
memory::default_allocator<CRITICAL_SECTION>::free((LPCRITICAL_SECTION)_handle);
#endif
}
bool mutex::lock()const
{
if (_handle != NULL)
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
return pthread_mutex_lock((pthread_mutex_t*)_handle) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
//return WaitForSingleObjectEx(this->_handle, INFINITE, FALSE) == WAIT_OBJECT_0 ? true : false;
EnterCriticalSection(LPCRITICAL_SECTION(_handle));
return true;
#endif
return false;
}
bool mutex::trylock()const
{
if (_handle != NULL)
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
return pthread_mutex_trylock((pthread_mutex_t*)_handle) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
//return WaitForSingleObjectEx(this->_handle, 0, FALSE) == WAIT_OBJECT_0 ? true : false;
return TryEnterCriticalSection(LPCRITICAL_SECTION(_handle)) ? true : false;
#endif
return false;
}
bool mutex::unlock()const
{
if (_handle != NULL)
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
return pthread_mutex_unlock((pthread_mutex_t*)_handle) == 0 ? ang_true : ang_false;
#elif defined WINDOWS_PLATFORM
LeaveCriticalSection(LPCRITICAL_SECTION(_handle));
return true;
//return ReleaseMutex(this->_handle) ? true : false;
#endif
return false;
}
////////////////////////////////////////////////////////////////////////////////
cond::cond()
{
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
_handle = memory::default_allocator<pthread_cond_t>::alloc(1);
pthread_cond_init((pthread_cond_t*)_handle, NULL);
#elif defined WINDOWS_PLATFORM
this->_handle = CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);
#endif
}
cond::~cond()
{
if (_handle != NULL)
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
{
pthread_cond_destroy((pthread_cond_t*)_handle);
memory::default_allocator<pthread_cond_t>::free((pthread_cond_t*)_handle);
}
#elif defined WINDOWS_PLATFORM
CloseHandle(this->_handle);
#endif
_handle = NULL;
}
bool cond::wait(mutex& mutex)const
{
if (_handle == NULL)
return false;
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
return pthread_cond_wait((pthread_cond_t*)_handle, (pthread_mutex_t*)mutex._handle) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
mutex.unlock();
auto res = WaitForSingleObjectEx(this->_handle, INFINITE, FALSE) == WAIT_OBJECT_0 ? true : false;
mutex.lock();
return res;
#endif
}
bool cond::wait(mutex_ptr_t mutex)const
{
if (_handle == NULL)
return false;
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
if (mutex.is_empty())
return false;
return pthread_cond_wait((pthread_cond_t*)_handle, (pthread_mutex_t*)mutex->_handle) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
if(!mutex.is_empty())mutex->unlock();
auto res = WaitForSingleObjectEx(this->_handle, INFINITE, FALSE) == WAIT_OBJECT_0 ? true : false;
if (!mutex.is_empty())mutex->lock();
return res;
#endif
}
bool cond::wait(mutex& mutex, dword ms)const
{
if (_handle == NULL)
return false;
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
timespec time;
time.tv_sec = (long)ms / 1000;
time.tv_nsec = ((long)ms - time.tv_sec * 1000) * 1000;
return pthread_cond_timedwait((pthread_cond_t*)_handle, (pthread_mutex_t*)mutex._handle, &time) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
mutex.unlock();
auto res = WaitForSingleObjectEx(this->_handle, ms, FALSE) == WAIT_OBJECT_0 ? true : false;
mutex.lock();
return res;
#endif
}
bool cond::wait(mutex_ptr_t mutex, dword ms)const
{
if (_handle == NULL)
return false;
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
if (mutex.is_empty())
return false;
timespec time;
time.tv_sec = (long)ms / 1000;
time.tv_nsec = ((long)ms - time.tv_sec * 1000) * 1000;
return pthread_cond_timedwait((pthread_cond_t*)_handle, (pthread_mutex_t*)mutex->_handle, &time) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
if (!mutex.is_empty())mutex->unlock();
auto res = WaitForSingleObjectEx(this->_handle, ms, FALSE) == WAIT_OBJECT_0 ? true : false;
if (!mutex.is_empty())mutex->lock();
return res;
#endif
}
bool cond::signal()const
{
if (_handle != null)
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
return pthread_cond_broadcast((pthread_cond_t*)_handle) == 0 ? true : false;
#elif defined WINDOWS_PLATFORM
{
bool _res = SetEvent(_handle) ? true : false;
ResetEvent(_handle);
return _res;
}
#endif
return false;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2006-2009 by Marc Boris Duerner, Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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 "tcpsocketimpl.h"
#include "cxxtools/net/tcpsocket.h"
#include "cxxtools/log.h"
#include "cxxtools/systemerror.h"
#include "cxxtools/ioerror.h"
#include "cxxtools/sslcertificate.h"
#include <stdexcept>
#include <errno.h>
#include "config.h"
log_define("cxxtools.net.tcpsocket")
namespace cxxtools {
namespace net {
TcpSocket::TcpSocket()
: _impl(new TcpSocketImpl(*this))
{
}
TcpSocket::TcpSocket(const TcpServer& server, unsigned flags)
: _impl(new TcpSocketImpl(*this))
{
try
{
accept(server, flags);
}
catch (...)
{
delete _impl;
throw;
}
}
TcpSocket::TcpSocket(const std::string& ipaddr, unsigned short int port)
: _impl(new TcpSocketImpl(*this))
{
try
{
connect(ipaddr, port);
}
catch (...)
{
delete _impl;
throw;
}
}
TcpSocket::TcpSocket(const AddrInfo& addrinfo)
: _impl(new TcpSocketImpl(*this))
{
try
{
connect(addrinfo);
}
catch (...)
{
delete _impl;
throw;
}
}
TcpSocket::~TcpSocket()
{
try
{
close();
}
catch(const std::exception& e)
{
log_error("TcpSocket::close failed: " << e.what());
}
delete _impl;
}
std::string TcpSocket::getSockAddr() const
{
return _impl->getSockAddr();
}
std::string TcpSocket::getPeerAddr() const
{
return _impl->getPeerAddr();
}
void TcpSocket::setTimeout(Milliseconds timeout)
{
_impl->setTimeout(timeout);
}
Milliseconds TcpSocket::timeout() const
{
return _impl->timeout();
}
void TcpSocket::connect(const AddrInfo& addrinfo)
{
close();
_impl->beginConnect(addrinfo);
_impl->endConnect();
setEnabled(true);
setAsync(true);
setEof(false);
}
bool TcpSocket::beginConnect(const AddrInfo& addrinfo)
{
close();
bool ret = _impl->beginConnect(addrinfo);
setEnabled(true);
setAsync(true);
setEof(false);
if (ret)
connected(*this);
return ret;
}
void TcpSocket::endConnect()
{
try
{
_impl->endConnect();
}
catch (...)
{
close();
throw;
}
}
bool TcpSocket::isConnected() const
{
return _impl->isConnected();
}
int TcpSocket::getFd() const
{
return _impl->fd();
}
void TcpSocket::loadSslCertificateFile(const std::string& certFile, const std::string& privateKeyFile)
{
#ifdef WITH_SSL
_impl->loadSslCertificateFile(certFile, privateKeyFile);
#else
log_warn("can't load certificate file since ssl is disabled");
#endif
}
void TcpSocket::setSslVerify(int level, const std::string& ca)
{
#ifdef WITH_SSL
_impl->setSslVerify(level, ca);
#else
log_warn("can't set ssl verify level since ssl is disabled");
#endif
}
bool TcpSocket::hasSslPeerCertificate() const
{
#ifdef WITH_SSL
return getSslPeerCertificate();
#else
return false;
#endif
}
const SslCertificate& TcpSocket::getSslPeerCertificate() const
{
#ifdef WITH_SSL
return _impl->getSslPeerCertificate();
#else
log_warn("can't get ssl peer certificate since ssl is disabled");
static SslCertificate cert;
return cert;
#endif
}
void TcpSocket::beginSslConnect()
{
#ifdef WITH_SSL
if (_impl->beginSslConnect())
sslConnected(*this);
#else
log_warn("can't connect ssl since ssl is disabled");
sslConnected(*this);
#endif
}
void TcpSocket::endSslConnect()
{
#ifdef WITH_SSL
_impl->endSslConnect();
#endif
}
void TcpSocket::sslConnect()
{
#ifdef WITH_SSL
_impl->beginSslConnect();
_impl->endSslConnect();
#else
log_warn("can't connect ssl since ssl is disabled");
sslConnected(*this);
#endif
}
void TcpSocket::beginSslAccept()
{
#ifdef WITH_SSL
if (_impl->beginSslAccept())
sslAccepted(*this);
#else
log_warn("can't accept ssl connection since ssl is disabled");
sslAccepted(*this);
#endif
}
void TcpSocket::endSslAccept()
{
#ifdef WITH_SSL
_impl->endSslAccept();
#endif
}
void TcpSocket::sslAccept()
{
#ifdef WITH_SSL
_impl->beginSslAccept();
_impl->endSslAccept();
#else
log_warn("can't accept ssl connection since ssl is disabled");
#endif
}
void TcpSocket::beginSslShutdown()
{
#ifdef WITH_SSL
if (_impl->beginSslShutdown())
sslClosed(*this);
#else
log_warn("can't shutdown ssl connection since ssl is disabled");
sslClosed(*this);
#endif
}
void TcpSocket::endSslShutdown()
{
#ifdef WITH_SSL
_impl->endSslShutdown();
#endif
}
void TcpSocket::sslShutdown()
{
#ifdef WITH_SSL
_impl->beginSslShutdown();
_impl->endSslShutdown();
#else
log_warn("can't shutdown ssl connection since ssl is disabled");
#endif
}
void TcpSocket::accept(const TcpServer& server, unsigned flags)
{
close();
_impl->accept(server, flags);
setEnabled(true);
setAsync(true);
setEof(false);
}
SelectableImpl& TcpSocket::simpl()
{
return *_impl;
}
size_t TcpSocket::onBeginRead(char* buffer, size_t n, bool& eof)
{
if (!_impl->isConnected())
throw IOError("socket not connected when trying to read");
return _impl->beginRead(buffer, n, eof);
}
size_t TcpSocket::onBeginWrite(const char* buffer, size_t n)
{
if (!_impl->isConnected())
throw IOError("socket not connected when trying to read");
return _impl->beginWrite(buffer, n);
}
IODeviceImpl& TcpSocket::ioimpl()
{
return *_impl;
}
short TcpSocket::poll(short events) const
{
struct pollfd fds;
fds.fd = _impl->fd();
fds.events = events;
int timeout = getTimeout().ceil();
log_debug("poll timeout " << timeout);
int p = ::poll(&fds, 1, timeout);
log_debug("poll returns " << p << " revents " << fds.revents);
if (p < 0)
{
log_error("error in poll; errno=" << errno);
throw SystemError("poll");
}
else if (p == 0)
{
log_debug("poll timeout (" << timeout << ')');
throw IOTimeout();
}
return fds.revents;
}
} // namespace net
} // namespace cxxtools
<commit_msg>minor fix in error message<commit_after>/*
* Copyright (C) 2006-2009 by Marc Boris Duerner, Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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 "tcpsocketimpl.h"
#include "cxxtools/net/tcpsocket.h"
#include "cxxtools/log.h"
#include "cxxtools/systemerror.h"
#include "cxxtools/ioerror.h"
#include "cxxtools/sslcertificate.h"
#include <stdexcept>
#include <errno.h>
#include "config.h"
log_define("cxxtools.net.tcpsocket")
namespace cxxtools {
namespace net {
TcpSocket::TcpSocket()
: _impl(new TcpSocketImpl(*this))
{
}
TcpSocket::TcpSocket(const TcpServer& server, unsigned flags)
: _impl(new TcpSocketImpl(*this))
{
try
{
accept(server, flags);
}
catch (...)
{
delete _impl;
throw;
}
}
TcpSocket::TcpSocket(const std::string& ipaddr, unsigned short int port)
: _impl(new TcpSocketImpl(*this))
{
try
{
connect(ipaddr, port);
}
catch (...)
{
delete _impl;
throw;
}
}
TcpSocket::TcpSocket(const AddrInfo& addrinfo)
: _impl(new TcpSocketImpl(*this))
{
try
{
connect(addrinfo);
}
catch (...)
{
delete _impl;
throw;
}
}
TcpSocket::~TcpSocket()
{
try
{
close();
}
catch(const std::exception& e)
{
log_error("TcpSocket::close failed: " << e.what());
}
delete _impl;
}
std::string TcpSocket::getSockAddr() const
{
return _impl->getSockAddr();
}
std::string TcpSocket::getPeerAddr() const
{
return _impl->getPeerAddr();
}
void TcpSocket::setTimeout(Milliseconds timeout)
{
_impl->setTimeout(timeout);
}
Milliseconds TcpSocket::timeout() const
{
return _impl->timeout();
}
void TcpSocket::connect(const AddrInfo& addrinfo)
{
close();
_impl->beginConnect(addrinfo);
_impl->endConnect();
setEnabled(true);
setAsync(true);
setEof(false);
}
bool TcpSocket::beginConnect(const AddrInfo& addrinfo)
{
close();
bool ret = _impl->beginConnect(addrinfo);
setEnabled(true);
setAsync(true);
setEof(false);
if (ret)
connected(*this);
return ret;
}
void TcpSocket::endConnect()
{
try
{
_impl->endConnect();
}
catch (...)
{
close();
throw;
}
}
bool TcpSocket::isConnected() const
{
return _impl->isConnected();
}
int TcpSocket::getFd() const
{
return _impl->fd();
}
void TcpSocket::loadSslCertificateFile(const std::string& certFile, const std::string& privateKeyFile)
{
#ifdef WITH_SSL
_impl->loadSslCertificateFile(certFile, privateKeyFile);
#else
log_warn("can't load certificate file since ssl is disabled");
#endif
}
void TcpSocket::setSslVerify(int level, const std::string& ca)
{
#ifdef WITH_SSL
_impl->setSslVerify(level, ca);
#else
log_warn("can't set ssl verify level since ssl is disabled");
#endif
}
bool TcpSocket::hasSslPeerCertificate() const
{
#ifdef WITH_SSL
return getSslPeerCertificate();
#else
return false;
#endif
}
const SslCertificate& TcpSocket::getSslPeerCertificate() const
{
#ifdef WITH_SSL
return _impl->getSslPeerCertificate();
#else
log_warn("can't get ssl peer certificate since ssl is disabled");
static SslCertificate cert;
return cert;
#endif
}
void TcpSocket::beginSslConnect()
{
#ifdef WITH_SSL
if (_impl->beginSslConnect())
sslConnected(*this);
#else
log_warn("can't connect ssl since ssl is disabled");
sslConnected(*this);
#endif
}
void TcpSocket::endSslConnect()
{
#ifdef WITH_SSL
_impl->endSslConnect();
#endif
}
void TcpSocket::sslConnect()
{
#ifdef WITH_SSL
_impl->beginSslConnect();
_impl->endSslConnect();
#else
log_warn("can't connect ssl since ssl is disabled");
sslConnected(*this);
#endif
}
void TcpSocket::beginSslAccept()
{
#ifdef WITH_SSL
if (_impl->beginSslAccept())
sslAccepted(*this);
#else
log_warn("can't accept ssl connection since ssl is disabled");
sslAccepted(*this);
#endif
}
void TcpSocket::endSslAccept()
{
#ifdef WITH_SSL
_impl->endSslAccept();
#endif
}
void TcpSocket::sslAccept()
{
#ifdef WITH_SSL
_impl->beginSslAccept();
_impl->endSslAccept();
#else
log_warn("can't accept ssl connection since ssl is disabled");
#endif
}
void TcpSocket::beginSslShutdown()
{
#ifdef WITH_SSL
if (_impl->beginSslShutdown())
sslClosed(*this);
#else
log_warn("can't shutdown ssl connection since ssl is disabled");
sslClosed(*this);
#endif
}
void TcpSocket::endSslShutdown()
{
#ifdef WITH_SSL
_impl->endSslShutdown();
#endif
}
void TcpSocket::sslShutdown()
{
#ifdef WITH_SSL
_impl->beginSslShutdown();
_impl->endSslShutdown();
#else
log_warn("can't shutdown ssl connection since ssl is disabled");
#endif
}
void TcpSocket::accept(const TcpServer& server, unsigned flags)
{
close();
_impl->accept(server, flags);
setEnabled(true);
setAsync(true);
setEof(false);
}
SelectableImpl& TcpSocket::simpl()
{
return *_impl;
}
size_t TcpSocket::onBeginRead(char* buffer, size_t n, bool& eof)
{
if (!_impl->isConnected())
throw IOError("socket not connected when trying to read");
return _impl->beginRead(buffer, n, eof);
}
size_t TcpSocket::onBeginWrite(const char* buffer, size_t n)
{
if (!_impl->isConnected())
throw IOError("socket not connected when trying to write");
return _impl->beginWrite(buffer, n);
}
IODeviceImpl& TcpSocket::ioimpl()
{
return *_impl;
}
short TcpSocket::poll(short events) const
{
struct pollfd fds;
fds.fd = _impl->fd();
fds.events = events;
int timeout = getTimeout().ceil();
log_debug("poll timeout " << timeout);
int p = ::poll(&fds, 1, timeout);
log_debug("poll returns " << p << " revents " << fds.revents);
if (p < 0)
{
log_error("error in poll; errno=" << errno);
throw SystemError("poll");
}
else if (p == 0)
{
log_debug("poll timeout (" << timeout << ')');
throw IOTimeout();
}
return fds.revents;
}
} // namespace net
} // namespace cxxtools
<|endoftext|> |
<commit_before>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#if V8_TARGET_ARCH_X87
#include "src/interface-descriptors.h"
namespace v8 {
namespace internal {
const Register CallInterfaceDescriptor::ContextRegister() { return esi; }
const Register LoadDescriptor::ReceiverRegister() { return edx; }
const Register LoadDescriptor::NameRegister() { return ecx; }
const Register LoadDescriptor::SlotRegister() { return eax; }
const Register LoadWithVectorDescriptor::VectorRegister() { return ebx; }
const Register StoreDescriptor::ReceiverRegister() { return edx; }
const Register StoreDescriptor::NameRegister() { return ecx; }
const Register StoreDescriptor::ValueRegister() { return eax; }
const Register VectorStoreICTrampolineDescriptor::SlotRegister() { return edi; }
const Register VectorStoreICDescriptor::VectorRegister() { return ebx; }
const Register StoreTransitionDescriptor::MapRegister() { return ebx; }
const Register ElementTransitionAndStoreDescriptor::MapRegister() {
return ebx;
}
const Register InstanceofDescriptor::left() { return eax; }
const Register InstanceofDescriptor::right() { return edx; }
const Register ArgumentsAccessReadDescriptor::index() { return edx; }
const Register ArgumentsAccessReadDescriptor::parameter_count() { return eax; }
const Register ApiGetterDescriptor::function_address() { return edx; }
const Register MathPowTaggedDescriptor::exponent() { return eax; }
const Register MathPowIntegerDescriptor::exponent() {
return MathPowTaggedDescriptor::exponent();
}
const Register GrowArrayElementsDescriptor::ObjectRegister() { return eax; }
const Register GrowArrayElementsDescriptor::KeyRegister() { return ebx; }
void FastNewClosureDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ebx};
data->Initialize(arraysize(registers), registers, NULL);
}
void FastNewContextDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edi};
data->Initialize(arraysize(registers), registers, NULL);
}
void ToNumberDescriptor::Initialize(CallInterfaceDescriptorData* data) {
// ToNumberStub invokes a function, and therefore needs a context.
Register registers[] = {esi, eax};
data->Initialize(arraysize(registers), registers, NULL);
}
void NumberToStringDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {esi, eax};
data->Initialize(arraysize(registers), registers, NULL);
}
void TypeofDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ebx};
data->Initialize(arraysize(registers), registers, NULL);
}
void FastCloneShallowArrayDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, eax, ebx, ecx};
Representation representations[] = {
Representation::Tagged(), Representation::Tagged(), Representation::Smi(),
Representation::Tagged()};
data->Initialize(arraysize(registers), registers, representations);
}
void FastCloneShallowObjectDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, eax, ebx, ecx, edx};
data->Initialize(arraysize(registers), registers, NULL);
}
void CreateAllocationSiteDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ebx, edx};
Representation representations[] = {Representation::Tagged(),
Representation::Tagged(),
Representation::Smi()};
data->Initialize(arraysize(registers), registers, representations);
}
void CreateWeakCellDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ebx, edx, edi};
Representation representations[] = {
Representation::Tagged(), Representation::Tagged(), Representation::Smi(),
Representation::Tagged()};
data->Initialize(arraysize(registers), registers, representations);
}
void StoreArrayLiteralElementDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ecx, eax};
data->Initialize(arraysize(registers), registers, NULL);
}
void CallFunctionDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edi};
data->Initialize(arraysize(registers), registers, NULL);
}
void CallFunctionWithFeedbackDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edi, edx};
Representation representations[] = {Representation::Tagged(),
Representation::Tagged(),
Representation::Smi()};
data->Initialize(arraysize(registers), registers, representations);
}
void CallFunctionWithFeedbackAndVectorDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edi, edx, ebx};
Representation representations[] = {
Representation::Tagged(), Representation::Tagged(), Representation::Smi(),
Representation::Tagged()};
data->Initialize(arraysize(registers), registers, representations);
}
void CallConstructDescriptor::Initialize(CallInterfaceDescriptorData* data) {
// eax : number of arguments
// ebx : feedback vector
// edx : (only if ebx is not the megamorphic symbol) slot in feedback
// vector (Smi)
// edi : constructor function
// TODO(turbofan): So far we don't gather type feedback and hence skip the
// slot parameter, but ArrayConstructStub needs the vector to be undefined.
Register registers[] = {esi, eax, edi, ebx};
data->Initialize(arraysize(registers), registers, NULL);
}
void RegExpConstructResultDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ecx, ebx, eax};
data->Initialize(arraysize(registers), registers, NULL);
}
void TransitionElementsKindDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, eax, ebx};
data->Initialize(arraysize(registers), registers, NULL);
}
void AllocateHeapNumberDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
// register state
// esi -- context
Register registers[] = {esi};
data->Initialize(arraysize(registers), registers, nullptr);
}
void ArrayConstructorConstantArgCountDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
// register state
// eax -- number of arguments
// edi -- function
// ebx -- allocation site with elements kind
Register registers[] = {esi, edi, ebx};
data->Initialize(arraysize(registers), registers, NULL);
}
void ArrayConstructorDescriptor::Initialize(CallInterfaceDescriptorData* data) {
// stack param count needs (constructor pointer, and single argument)
Register registers[] = {esi, edi, ebx, eax};
Representation representations[] = {
Representation::Tagged(), Representation::Tagged(),
Representation::Tagged(), Representation::Integer32()};
data->Initialize(arraysize(registers), registers, representations);
}
void InternalArrayConstructorConstantArgCountDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
// register state
// eax -- number of arguments
// edi -- function
Register registers[] = {esi, edi};
data->Initialize(arraysize(registers), registers, NULL);
}
void InternalArrayConstructorDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
// stack param count needs (constructor pointer, and single argument)
Register registers[] = {esi, edi, eax};
Representation representations[] = {Representation::Tagged(),
Representation::Tagged(),
Representation::Integer32()};
data->Initialize(arraysize(registers), registers, representations);
}
void CompareDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edx, eax};
data->Initialize(arraysize(registers), registers, NULL);
}
void CompareNilDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {esi, eax};
data->Initialize(arraysize(registers), registers, NULL);
}
void ToBooleanDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {esi, eax};
data->Initialize(arraysize(registers), registers, NULL);
}
void BinaryOpDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edx, eax};
data->Initialize(arraysize(registers), registers, NULL);
}
void BinaryOpWithAllocationSiteDescriptor::Initialize(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ecx, edx, eax};
data->Initialize(arraysize(registers), registers, NULL);
}
void StringAddDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edx, eax};
data->Initialize(arraysize(registers), registers, NULL);
}
void KeyedDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
ecx, // key
};
Representation representations[] = {
Representation::Tagged(), // context
Representation::Tagged(), // key
};
data->Initialize(arraysize(registers), registers, representations);
}
void NamedDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
ecx, // name
};
Representation representations[] = {
Representation::Tagged(), // context
Representation::Tagged(), // name
};
data->Initialize(arraysize(registers), registers, representations);
}
void CallHandlerDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
edx, // name
};
Representation representations[] = {
Representation::Tagged(), // context
Representation::Tagged(), // receiver
};
data->Initialize(arraysize(registers), registers, representations);
}
void ArgumentAdaptorDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
edi, // JSFunction
eax, // actual number of arguments
ebx, // expected number of arguments
};
Representation representations[] = {
Representation::Tagged(), // context
Representation::Tagged(), // JSFunction
Representation::Integer32(), // actual number of arguments
Representation::Integer32(), // expected number of arguments
};
data->Initialize(arraysize(registers), registers, representations);
}
void ApiFunctionDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
edi, // callee
ebx, // call_data
ecx, // holder
edx, // api_function_address
eax, // actual number of arguments
};
Representation representations[] = {
Representation::Tagged(), // context
Representation::Tagged(), // callee
Representation::Tagged(), // call_data
Representation::Tagged(), // holder
Representation::External(), // api_function_address
Representation::Integer32(), // actual number of arguments
};
data->Initialize(arraysize(registers), registers, representations);
}
void ApiAccessorDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
edi, // callee
ebx, // call_data
ecx, // holder
edx, // api_function_address
};
Representation representations[] = {
Representation::Tagged(), // context
Representation::Tagged(), // callee
Representation::Tagged(), // call_data
Representation::Tagged(), // holder
Representation::External(), // api_function_address
};
data->Initialize(arraysize(registers), registers, representations);
}
void MathRoundVariantDescriptor::Initialize(CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
edi, // math rounding function
edx, // vector slot id
};
Representation representations[] = {
Representation::Tagged(), //
Representation::Tagged(), //
Representation::Tagged(), //
};
data->Initialize(arraysize(registers), registers, representations);
}
} // namespace internal
} // namespace v8
#endif // V8_TARGET_ARCH_X87
<commit_msg>X87: Use big-boy Types to annotate interface descriptor parameters.<commit_after>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#if V8_TARGET_ARCH_X87
#include "src/interface-descriptors.h"
namespace v8 {
namespace internal {
const Register CallInterfaceDescriptor::ContextRegister() { return esi; }
const Register LoadDescriptor::ReceiverRegister() { return edx; }
const Register LoadDescriptor::NameRegister() { return ecx; }
const Register LoadDescriptor::SlotRegister() { return eax; }
const Register LoadWithVectorDescriptor::VectorRegister() { return ebx; }
const Register StoreDescriptor::ReceiverRegister() { return edx; }
const Register StoreDescriptor::NameRegister() { return ecx; }
const Register StoreDescriptor::ValueRegister() { return eax; }
const Register VectorStoreICTrampolineDescriptor::SlotRegister() { return edi; }
const Register VectorStoreICDescriptor::VectorRegister() { return ebx; }
const Register StoreTransitionDescriptor::MapRegister() { return ebx; }
const Register ElementTransitionAndStoreDescriptor::MapRegister() {
return ebx;
}
const Register InstanceofDescriptor::left() { return eax; }
const Register InstanceofDescriptor::right() { return edx; }
const Register ArgumentsAccessReadDescriptor::index() { return edx; }
const Register ArgumentsAccessReadDescriptor::parameter_count() { return eax; }
const Register ApiGetterDescriptor::function_address() { return edx; }
const Register MathPowTaggedDescriptor::exponent() { return eax; }
const Register MathPowIntegerDescriptor::exponent() {
return MathPowTaggedDescriptor::exponent();
}
const Register GrowArrayElementsDescriptor::ObjectRegister() { return eax; }
const Register GrowArrayElementsDescriptor::KeyRegister() { return ebx; }
void FastNewClosureDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ebx};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void FastNewContextDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edi};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void ToNumberDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
// ToNumberStub invokes a function, and therefore needs a context.
Register registers[] = {esi, eax};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void NumberToStringDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, eax};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void TypeofDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ebx};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void FastCloneShallowArrayDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, eax, ebx, ecx};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void FastCloneShallowObjectDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, eax, ebx, ecx, edx};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void CreateAllocationSiteDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ebx, edx};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void CreateWeakCellDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ebx, edx, edi};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void StoreArrayLiteralElementDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ecx, eax};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void CallFunctionDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edi};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void CallFunctionWithFeedbackDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edi, edx};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void CallFunctionWithFeedbackAndVectorDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edi, edx, ebx};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void CallConstructDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
// eax : number of arguments
// ebx : feedback vector
// edx : (only if ebx is not the megamorphic symbol) slot in feedback
// vector (Smi)
// edi : constructor function
// TODO(turbofan): So far we don't gather type feedback and hence skip the
// slot parameter, but ArrayConstructStub needs the vector to be undefined.
Register registers[] = {esi, eax, edi, ebx};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void RegExpConstructResultDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ecx, ebx, eax};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void TransitionElementsKindDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, eax, ebx};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void AllocateHeapNumberDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
// register state
// esi -- context
Register registers[] = {esi};
data->InitializePlatformSpecific(arraysize(registers), registers, nullptr);
}
void ArrayConstructorConstantArgCountDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
// register state
// eax -- number of arguments
// edi -- function
// ebx -- allocation site with elements kind
Register registers[] = {esi, edi, ebx};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void ArrayConstructorDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
// stack param count needs (constructor pointer, and single argument)
Register registers[] = {esi, edi, ebx, eax};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void InternalArrayConstructorConstantArgCountDescriptor::
InitializePlatformSpecific(CallInterfaceDescriptorData* data) {
// register state
// eax -- number of arguments
// edi -- function
Register registers[] = {esi, edi};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void InternalArrayConstructorDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
// stack param count needs (constructor pointer, and single argument)
Register registers[] = {esi, edi, eax};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void CompareDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edx, eax};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void CompareNilDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, eax};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void ToBooleanDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, eax};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void BinaryOpDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edx, eax};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void BinaryOpWithAllocationSiteDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, ecx, edx, eax};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void StringAddDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {esi, edx, eax};
data->InitializePlatformSpecific(arraysize(registers), registers, NULL);
}
void KeyedDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
ecx, // key
};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void NamedDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
ecx, // name
};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void CallHandlerDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
edx, // name
};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void ArgumentAdaptorDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
edi, // JSFunction
eax, // actual number of arguments
ebx, // expected number of arguments
};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void ApiFunctionDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
edi, // callee
ebx, // call_data
ecx, // holder
edx, // api_function_address
eax, // actual number of arguments
};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void ApiAccessorDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
edi, // callee
ebx, // call_data
ecx, // holder
edx, // api_function_address
};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
void MathRoundVariantDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
Register registers[] = {
esi, // context
edi, // math rounding function
edx, // vector slot id
};
data->InitializePlatformSpecific(arraysize(registers), registers);
}
} // namespace internal
} // namespace v8
#endif // V8_TARGET_ARCH_X87
<|endoftext|> |
<commit_before>#include "photon_blocks.h"
#include "photon_opengl.h"
#include "photon_level.h"
#include "photon_laser.h"
#include "photon_texture.h"
#include "glm/ext.hpp"
GLuint texture_plain_block, texture_mirror;
namespace photon{
namespace blocks{
void DrawBox(glm::uvec2 location){
// TODO - maybe add optional rotation? perhaps via UV coordinates?
glBegin(GL_QUADS);{
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 1.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + 0.5, location.y + 0.5);
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 1.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - 0.5, location.y + 0.5);
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 0.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - 0.5, location.y - 0.5);
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 0.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + 0.5, location.y - 0.5);
}glEnd();
}
void DrawMirror(glm::uvec2 location, float angle){
glm::vec2 point1(0.4f, 0.05f);
glm::vec2 point2(0.05f, 0.4f);
point1 = glm::rotate(point1, angle);
point2 = glm::rotate(point2, angle + 90.0f);
glBegin(GL_QUADS);{
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 1.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + point1.x, location.y + point1.y);
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 1.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - point2.x, location.y - point2.y);
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 0.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - point1.x, location.y - point1.y);
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 0.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + point2.x, location.y + point2.y);
}glEnd();
}
void Draw(photon_block block, glm::uvec2 location){
switch(block.type){
case PHOTON_BLOCKS_AIR:
break;
case PHOTON_BLOCKS_PLAIN:
glBindTexture(GL_TEXTURE_2D, texture_plain_block);
DrawBox(location);
break;
case PHOTON_BLOCKS_INDESTRUCTIBLE:
// TODO - make different texture.
glBindTexture(GL_TEXTURE_2D, texture_plain_block);
DrawBox(location);
break;
case PHOTON_BLOCKS_MIRROR:
case PHOTON_BLOCKS_MIRROR_LOCKED:
glBindTexture(GL_TEXTURE_2D, texture_mirror);
DrawMirror(location, block.data);
break;
}
}
photon_lasersegment *OnLightInteract(photon_lasersegment *segment, glm::uvec2 location, photon_level &level){
photon_block &block = level.grid[location.x][location.y];
switch(block.type){
case PHOTON_BLOCKS_AIR:
default:
break;
case PHOTON_BLOCKS_RECIEVER:
// TODO - make trigger
case PHOTON_BLOCKS_PLAIN:
case PHOTON_BLOCKS_INDESTRUCTIBLE:
// stops tracing the laser.
return nullptr;
break;
case PHOTON_BLOCKS_MIRROR:
case PHOTON_BLOCKS_MIRROR_LOCKED:
segment = tracer::CreateChildBeam(segment);
float angle = segment->angle - block.data;
angle = fmod(angle + 180.0f, 360.0f) - 180.0f;
segment->angle = block.data - angle;
break;
}
return segment;
}
void LoadTextures(){
texture_plain_block = texture::Load("/textures/block.png");
texture_mirror = texture::Load("/textures/mirror.png");
}
void OnPhotonInteract(glm::uvec2 location, photon_level &level){
photon_block &block = level.grid[location.x][location.y];
switch(block.type){
case PHOTON_BLOCKS_AIR:
// TODO - place currently selected item in inventory.
block.type = PHOTON_BLOCKS_MIRROR;
break;
default:
break;
case PHOTON_BLOCKS_MIRROR:
// TODO - store mirror in inventory.
block.type = PHOTON_BLOCKS_AIR;
break;
}
}
void OnRotate(glm::uvec2 location, photon_level &level, bool counter_clockwise){
photon_block &block = level.grid[location.x][location.y];
switch(block.type){
default:
break;
case PHOTON_BLOCKS_MIRROR:
if(counter_clockwise){
block.data += 22.5f;
}else{
block.data -= 22.5f;
}
break;
}
}
}
}
<commit_msg>temporary fix of error when a mirror is parallel to the beam that hits it.<commit_after>#include "photon_blocks.h"
#include "photon_opengl.h"
#include "photon_level.h"
#include "photon_laser.h"
#include "photon_texture.h"
#include "glm/ext.hpp"
GLuint texture_plain_block, texture_mirror;
namespace photon{
namespace blocks{
void DrawBox(glm::uvec2 location){
// TODO - maybe add optional rotation? perhaps via UV coordinates?
glBegin(GL_QUADS);{
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 1.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + 0.5, location.y + 0.5);
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 1.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - 0.5, location.y + 0.5);
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 0.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - 0.5, location.y - 0.5);
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 0.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + 0.5, location.y - 0.5);
}glEnd();
}
void DrawMirror(glm::uvec2 location, float angle){
glm::vec2 point1(0.4f, 0.05f);
glm::vec2 point2(0.05f, 0.4f);
point1 = glm::rotate(point1, angle);
point2 = glm::rotate(point2, angle + 90.0f);
glBegin(GL_QUADS);{
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 1.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + point1.x, location.y + point1.y);
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 1.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - point2.x, location.y - point2.y);
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 0.0f, 0.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x - point1.x, location.y - point1.y);
glVertexAttrib2f(PHOTON_VERTEX_UV_ATTRIBUTE, 1.0f, 0.0f);
glVertexAttrib2f(PHOTON_VERTEX_LOCATION_ATTRIBUTE,location.x + point2.x, location.y + point2.y);
}glEnd();
}
void Draw(photon_block block, glm::uvec2 location){
switch(block.type){
case PHOTON_BLOCKS_AIR:
break;
case PHOTON_BLOCKS_PLAIN:
glBindTexture(GL_TEXTURE_2D, texture_plain_block);
DrawBox(location);
break;
case PHOTON_BLOCKS_INDESTRUCTIBLE:
// TODO - make different texture.
glBindTexture(GL_TEXTURE_2D, texture_plain_block);
DrawBox(location);
break;
case PHOTON_BLOCKS_MIRROR:
case PHOTON_BLOCKS_MIRROR_LOCKED:
glBindTexture(GL_TEXTURE_2D, texture_mirror);
DrawMirror(location, block.data);
break;
}
}
photon_lasersegment *OnLightInteract(photon_lasersegment *segment, glm::uvec2 location, photon_level &level){
photon_block &block = level.grid[location.x][location.y];
switch(block.type){
case PHOTON_BLOCKS_AIR:
default:
break;
case PHOTON_BLOCKS_RECIEVER:
// TODO - make trigger
case PHOTON_BLOCKS_PLAIN:
case PHOTON_BLOCKS_INDESTRUCTIBLE:
// stops tracing the laser.
return nullptr;
break;
case PHOTON_BLOCKS_MIRROR:
case PHOTON_BLOCKS_MIRROR_LOCKED:
float angle = segment->angle - block.data;
if(fmod(angle, 180.0f) == 0.0f){
return nullptr;
}
angle = fmod(angle + 180.0f, 360.0f) - 180.0f;
segment = tracer::CreateChildBeam(segment);
segment->angle = block.data - angle;
break;
}
return segment;
}
void LoadTextures(){
texture_plain_block = texture::Load("/textures/block.png");
texture_mirror = texture::Load("/textures/mirror.png");
}
void OnPhotonInteract(glm::uvec2 location, photon_level &level){
photon_block &block = level.grid[location.x][location.y];
switch(block.type){
case PHOTON_BLOCKS_AIR:
// TODO - place currently selected item in inventory.
block.type = PHOTON_BLOCKS_MIRROR;
break;
default:
break;
case PHOTON_BLOCKS_MIRROR:
// TODO - store mirror in inventory.
block.type = PHOTON_BLOCKS_AIR;
break;
}
}
void OnRotate(glm::uvec2 location, photon_level &level, bool counter_clockwise){
photon_block &block = level.grid[location.x][location.y];
switch(block.type){
default:
break;
case PHOTON_BLOCKS_MIRROR:
if(counter_clockwise){
block.data += 22.5f;
}else{
block.data -= 22.5f;
}
break;
}
}
}
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* $ Id: $
*/
#if !defined(XALAN_XSLTRESULTTARGET_HEADER_GUARD)
#define XALAN_XSLTRESULTTARGET_HEADER_GUARD
// Base include file. Must be first.
#include "XSLTDefinitions.hpp"
#include <cstdio>
#if defined(XALAN_CLASSIC_IOSTREAMS)
class ostream;
#else
#include <iosfwd>
#endif
#include <xalanc/XalanDOM/XalanDOMString.hpp>
XALAN_CPP_NAMESPACE_BEGIN
class FormatterListener;
class Writer;
class XALAN_XSLT_EXPORT XSLTResultTarget
{
public:
#if defined(XALAN_NO_STD_NAMESPACE)
typedef ostream StreamType;
#else
typedef std::ostream StreamType;
#endif
explicit
XSLTResultTarget();
/**
* Create a new output target with a file name.
*
* @param fileName valid system file name
*/
XSLTResultTarget(const XalanDOMString& fileName);
/**
* Create a new output target with a file name.
*
* @param fileName valid system file name
*/
XSLTResultTarget(const XalanDOMChar* fileName);
/**
* Create a new output target with a file name.
*
* @param fileName valid system file name
*/
XSLTResultTarget(const char* fileName);
/**
* Create a new output target with a stream.
*
* @param byteStream a pointer to a std ostream for the output
*/
XSLTResultTarget(StreamType* theStream);
/**
* Create a new output target with a stream.
*
* @param byteStream a reference to a std ostream for the output
*/
XSLTResultTarget(StreamType& theStream);
/**
* Create a new output target with a character stream.
*
* @param characterStream pointer to character stream where the results
* will be written
*/
XSLTResultTarget(Writer* characterStream);
/**
* Create a new output target with a stream.
*
* @param characterStream pointer to character stream where the results
* will be written
*/
XSLTResultTarget(FILE* characterStream);
/**
* Create a new output target with a FormatterListener.
*
* @param flistener A FormatterListener instance for result tree events.
*/
XSLTResultTarget(FormatterListener& flistener);
~XSLTResultTarget();
/**
* Set the file name where the results will be written.
*
* @param fileName system identifier as a string
*/
void
setFileName(const char* fileName)
{
if (fileName == 0)
{
m_fileName.clear();
}
else
{
m_fileName = fileName;
}
}
/**
* Set the file name where the results will be written.
*
* @param fileName system identifier as a string
*/
void
setFileName(const XalanDOMString& fileName)
{
m_fileName = fileName;
}
/**
* Get the file name where the results will be written to.
*
* @return file name string
*/
const XalanDOMString&
getFileName() const
{
return m_fileName;
}
/**
* Set the byte stream for this output target.
*
* @param byteStream pointer to byte stream that will contain the result
* document
*/
void
setByteStream(StreamType* byteStream)
{
m_byteStream = byteStream;
}
/**
* Get the byte stream for this output target.
*
* @return pointer to byte stream, or null if none was supplied.
*/
StreamType*
getByteStream() const
{
return m_byteStream;
}
/**
* Set the character encoding, if known.
*
* @param encoding new encoding string
*/
void
setEncoding(const XalanDOMChar* encoding)
{
if (encoding == 0)
{
m_encoding.clear();
}
else
{
m_encoding = encoding;
}
}
/**
* Set the character encoding, if known.
*
* @param encoding new encoding string
*/
void
setEncoding(const XalanDOMString& encoding)
{
m_encoding = encoding;
}
/**
* Get the character encoding in use.
*
* @return encoding string, or empty string if none was supplied.
*/
const XalanDOMString&
getEncoding() const
{
return m_encoding;
}
/**
* Set the character stream for this output target.
*
* @param characterStream pointer to character stream that will contain
* the result document
*/
void
setCharacterStream(Writer* characterStream)
{
m_characterStream = characterStream;
}
/**
* Get the character stream for this output target.
*
* @return pointer to character stream, or null if none was supplied.
*/
Writer*
getCharacterStream() const
{
return m_characterStream;
}
/**
* Get the stream for this output target.
*
* @return pointer to stream, or null if none was supplied.
*/
FILE*
getStream() const
{
return m_stream;
}
/**
* Set a FormatterListener to process the result tree events.
*
* @param handler pointer to new listener
*/
void
setFormatterListener(FormatterListener* handler)
{
m_formatterListener = handler;
}
/**
* Get the FormatterListener that will process the result tree events.
*
* @return pointer to new listener
*/
FormatterListener*
getFormatterListener() const
{
return m_formatterListener;
}
private:
XalanDOMString m_fileName;
StreamType* m_byteStream;
XalanDOMString m_encoding;
Writer* m_characterStream;
FormatterListener* m_formatterListener;
FILE* m_stream;
};
XALAN_CPP_NAMESPACE_END
#endif // XALAN_XSLTRESULTTARGET_HEADER_GUARD
<commit_msg>Added missing set accessor.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. 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. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* $ Id: $
*/
#if !defined(XALAN_XSLTRESULTTARGET_HEADER_GUARD)
#define XALAN_XSLTRESULTTARGET_HEADER_GUARD
// Base include file. Must be first.
#include "XSLTDefinitions.hpp"
#include <cstdio>
#if defined(XALAN_CLASSIC_IOSTREAMS)
class ostream;
#else
#include <iosfwd>
#endif
#include <xalanc/XalanDOM/XalanDOMString.hpp>
XALAN_CPP_NAMESPACE_BEGIN
class FormatterListener;
class Writer;
class XALAN_XSLT_EXPORT XSLTResultTarget
{
public:
#if defined(XALAN_NO_STD_NAMESPACE)
typedef ostream StreamType;
#else
typedef std::ostream StreamType;
#endif
explicit
XSLTResultTarget();
/**
* Create a new output target with a file name.
*
* @param fileName valid system file name
*/
XSLTResultTarget(const XalanDOMString& fileName);
/**
* Create a new output target with a file name.
*
* @param fileName valid system file name
*/
XSLTResultTarget(const XalanDOMChar* fileName);
/**
* Create a new output target with a file name.
*
* @param fileName valid system file name
*/
XSLTResultTarget(const char* fileName);
/**
* Create a new output target with a stream.
*
* @param byteStream a pointer to a std ostream for the output
*/
XSLTResultTarget(StreamType* theStream);
/**
* Create a new output target with a stream.
*
* @param byteStream a reference to a std ostream for the output
*/
XSLTResultTarget(StreamType& theStream);
/**
* Create a new output target with a character stream.
*
* @param characterStream pointer to character stream where the results
* will be written
*/
XSLTResultTarget(Writer* characterStream);
/**
* Create a new output target with a stream.
*
* @param characterStream pointer to character stream where the results
* will be written
*/
XSLTResultTarget(FILE* characterStream);
/**
* Create a new output target with a FormatterListener.
*
* @param flistener A FormatterListener instance for result tree events.
*/
XSLTResultTarget(FormatterListener& flistener);
~XSLTResultTarget();
/**
* Set the file name where the results will be written.
*
* @param fileName system identifier as a string
*/
void
setFileName(const char* fileName)
{
if (fileName == 0)
{
m_fileName.clear();
}
else
{
m_fileName = fileName;
}
}
/**
* Set the file name where the results will be written.
*
* @param fileName system identifier as a string
*/
void
setFileName(const XalanDOMString& fileName)
{
m_fileName = fileName;
}
/**
* Get the file name where the results will be written to.
*
* @return file name string
*/
const XalanDOMString&
getFileName() const
{
return m_fileName;
}
/**
* Set the byte stream for this output target.
*
* @param byteStream pointer to byte stream that will contain the result
* document
*/
void
setByteStream(StreamType* byteStream)
{
m_byteStream = byteStream;
}
/**
* Get the byte stream for this output target.
*
* @return pointer to byte stream, or null if none was supplied.
*/
StreamType*
getByteStream() const
{
return m_byteStream;
}
/**
* Set the character encoding, if known.
*
* @param encoding new encoding string
*/
void
setEncoding(const XalanDOMChar* encoding)
{
if (encoding == 0)
{
m_encoding.clear();
}
else
{
m_encoding = encoding;
}
}
/**
* Set the character encoding, if known.
*
* @param encoding new encoding string
*/
void
setEncoding(const XalanDOMString& encoding)
{
m_encoding = encoding;
}
/**
* Get the character encoding in use.
*
* @return encoding string, or empty string if none was supplied.
*/
const XalanDOMString&
getEncoding() const
{
return m_encoding;
}
/**
* Set the character stream for this output target.
*
* @param characterStream pointer to character stream that will contain
* the result document
*/
void
setCharacterStream(Writer* characterStream)
{
m_characterStream = characterStream;
}
/**
* Get the character stream for this output target.
*
* @return pointer to character stream, or null if none was supplied.
*/
Writer*
getCharacterStream() const
{
return m_characterStream;
}
/**
* Get the stream for this output target.
*
* @return pointer to stream, or null if none was supplied.
*/
FILE*
getStream() const
{
return m_stream;
}
/**
* Set the stream for this output target.
*
* @theStream pointer to stream.
*/
void
setStream(FILE* theStream)
{
m_stream = theStream;
}
/**
* Set a FormatterListener to process the result tree events.
*
* @param handler pointer to new listener
*/
void
setFormatterListener(FormatterListener* handler)
{
m_formatterListener = handler;
}
/**
* Get the FormatterListener that will process the result tree events.
*
* @return pointer to new listener
*/
FormatterListener*
getFormatterListener() const
{
return m_formatterListener;
}
private:
XalanDOMString m_fileName;
StreamType* m_byteStream;
XalanDOMString m_encoding;
Writer* m_characterStream;
FormatterListener* m_formatterListener;
FILE* m_stream;
};
XALAN_CPP_NAMESPACE_END
#endif // XALAN_XSLTRESULTTARGET_HEADER_GUARD
<|endoftext|> |
<commit_before>/*
* Smithsonian Astrophysical Observatory, Cambridge, MA, USA
* This code has been modified under the terms listed below and is made
* available under the same terms.
*/
/*
* Copyright 1993-2004 George A Howlett.
*
* 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 <stdlib.h>
#include "bltGrPen.h"
#include "bltGraph.h"
using namespace Blt;
Pen::Pen(Graph* graphPtr, const char* name, Tcl_HashEntry* hPtr)
{
optionTable_ = NULL;
ops_ = NULL;
graphPtr_ = graphPtr;
name_ = dupstr(name);
hashPtr_ = hPtr;
refCount_ =0;
flags =0;
manageOptions_ =0;
}
Pen::~Pen()
{
if (name_)
delete [] name_;
if (hashPtr_)
Tcl_DeleteHashEntry(hashPtr_);
PenOptions* ops = (PenOptions*)ops_;
Blt_Ts_FreeStyle(graphPtr_->display_, &ops->valueStyle);
Tk_FreeConfigOptions((char*)ops_, optionTable_, graphPtr_->tkwin_);
if (manageOptions_)
free(ops_);
}
<commit_msg>*** empty log message ***<commit_after>/*
* Smithsonian Astrophysical Observatory, Cambridge, MA, USA
* This code has been modified under the terms listed below and is made
* available under the same terms.
*/
/*
* Copyright 1993-2004 George A Howlett.
*
* 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 <stdlib.h>
#include "bltGrPen.h"
#include "bltGraph.h"
using namespace Blt;
Pen::Pen(Graph* graphPtr, const char* name, Tcl_HashEntry* hPtr)
{
optionTable_ = NULL;
ops_ = NULL;
graphPtr_ = graphPtr;
name_ = dupstr(name);
hashPtr_ = hPtr;
refCount_ =0;
flags =0;
manageOptions_ =0;
}
Pen::~Pen()
{
if (name_)
delete [] name_;
if (hashPtr_)
Tcl_DeleteHashEntry(hashPtr_);
PenOptions* ops = (PenOptions*)ops_;
Blt_Ts_FreeStyle(graphPtr_->display_, &ops->valueStyle);
Tk_FreeConfigOptions((char*)ops_, optionTable_, graphPtr_->tkwin_);
if (manageOptions_)
free(ops_);
}
<|endoftext|> |
<commit_before>/*
* ConstantPropagation.cpp
*
* This file is part of the "XieXie 2.0 Project" (Copyright (c) 2014 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "ConstantPropagation.h"
#include "StringModifier.h"
#include "TACRelationInst.h"
#include "TACReturnInst.h"
#include "TACSwitchInst.h"
#include "TACStackInst.h"
#include "TACHeapInst.h"
namespace Optimization
{
using OpCodes = TACInst::OpCodes;
void ConstantPropagation::TransformBlock(BasicBlock& basicBlock)
{
/* Transform instructions (top-down) */
TransformInstsTopDown(basicBlock);
}
void ConstantPropagation::TransformCopyInst(TACInstPtr& inst)
{
auto copyInst = static_cast<TACCopyInst*>(inst.get());
/* Propagate constant */
FetchConst(copyInst->src);
PropagateConst(copyInst->dest, copyInst->src);
}
void ConstantPropagation::TransformModifyInst(TACInstPtr& inst)
{
auto modifyInst = static_cast<TACModifyInst*>(inst.get());
/* Propagate constants */
FetchConst(modifyInst->srcLhs);
FetchConst(modifyInst->srcRhs);
if (modifyInst->srcLhs.IsConst() && modifyInst->srcRhs.IsConst())
{
/* Constant folding */
auto newInst = ConstantFolding(*modifyInst);
if (newInst)
{
/* Propagate constant */
PropagateConst(newInst->dest, newInst->src);
inst = std::move(newInst);
Changed();
}
}
else if (IsNOP(*modifyInst))
{
/* Constant folding */
auto constVar = (modifyInst->srcLhs.IsConst() ? modifyInst->srcRhs : modifyInst->srcLhs);
auto newInst = MakeUnique<TACCopyInst>(modifyInst->dest, constVar);
/* Propagate constant */
PropagateConst(newInst->dest, newInst->src);
inst = std::move(newInst);
Changed();
}
else
{
/* Destination is now variable -> remove constant */
RemoveConst(modifyInst->dest);
}
}
void ConstantPropagation::TransformRelationInst(TACInstPtr& inst)
{
auto condInst = static_cast<TACRelationInst*>(inst.get());
/* Propagate constant */
FetchConst(condInst->srcLhs);
FetchConst(condInst->srcRhs);
}
void ConstantPropagation::TransformReturnInst(TACInstPtr& inst)
{
auto returnInst = static_cast<TACReturnInst*>(inst.get());
/* Propagate constant */
if (returnInst->hasVar)
FetchConst(returnInst->src);
}
void ConstantPropagation::TransformSwitchInst(TACInstPtr& inst)
{
auto switchInst = static_cast<TACSwitchInst*>(inst.get());
/* Propagate constant */
FetchConst(switchInst->src);
}
void ConstantPropagation::TransformStackInst(TACInstPtr& inst)
{
auto stackInst = static_cast<TACStackInst*>(inst.get());
/* Propagate constant */
if (stackInst->IsStoreOp())
FetchConst(stackInst->var);
else
RemoveConst(stackInst->var);
}
void ConstantPropagation::TransformHeapInst(TACInstPtr& inst)
{
auto heapInst = static_cast<TACHeapInst*>(inst.get());
/* Propagate constant */
if (heapInst->IsStoreOp())
FetchConst(heapInst->var);
else
RemoveConst(heapInst->var);
}
void ConstantPropagation::TransformDirectCallInst(TACInstPtr& inst)
{
/* Call instruction kills all constants */
vars_.clear();
}
bool ConstantPropagation::IsNOP(const TACModifyInst& inst) const
{
/* Get single constant */
const auto& lhs = inst.srcLhs;
const auto& rhs = inst.srcRhs;
TACVar constVar;
if (lhs.IsConst())
constVar = lhs;
else if (rhs.IsConst())
constVar = rhs;
else
return false;
/* Check if this is a no-operation instruction */
switch (inst.opcode)
{
case OpCodes::AND:
return constVar.Int() == ~0;
case OpCodes::OR:
case OpCodes::ADD:
case OpCodes::SUB:
return constVar.Int() == 0;
case OpCodes::MUL:
case OpCodes::DIV:
case OpCodes::MOD:
return constVar.Int() == 1;
case OpCodes::FADD:
case OpCodes::FSUB:
return constVar.Float() == 0.0f;
case OpCodes::FMUL:
case OpCodes::FDIV:
case OpCodes::FMOD:
return constVar.Float() == 1.0f;
default:
break;
}
return false;
}
std::unique_ptr<TACCopyInst> ConstantPropagation::ConstantFolding(const TACModifyInst& inst)
{
auto MakeInt = [&inst](int value)
{
return MakeUnique<TACCopyInst>(inst.dest, TACVar(ToStr(value)));
};
auto MakeFloat = [&inst](float value)
{
return MakeUnique<TACCopyInst>(inst.dest, TACVar(ToStr(value)));
};
const auto& lhs = inst.srcLhs;
const auto& rhs = inst.srcRhs;
switch (inst.opcode)
{
case OpCodes::AND:
return MakeInt(lhs.Int() & rhs.Int());
case OpCodes::OR:
return MakeInt(lhs.Int() | rhs.Int());
case OpCodes::XOR:
return MakeInt(lhs.Int() ^ rhs.Int());
case OpCodes::ADD:
return MakeInt(lhs.Int() + rhs.Int());
case OpCodes::FADD:
return MakeFloat(lhs.Float() + rhs.Float());
case OpCodes::SUB:
return MakeInt(lhs.Int() - rhs.Int());
case OpCodes::FSUB:
return MakeFloat(lhs.Float() - rhs.Float());
case OpCodes::MUL:
return MakeInt(lhs.Int() * rhs.Int());
case OpCodes::FMUL:
return MakeFloat(lhs.Float() * rhs.Float());
case OpCodes::DIV:
return rhs.Int() != 0 ? MakeInt(lhs.Int() / rhs.Int()) : nullptr;
case OpCodes::FDIV:
return MakeFloat(lhs.Float() / rhs.Float());
case OpCodes::MOD:
return rhs.Int() != 0 ? MakeInt(lhs.Int() % rhs.Int()) : nullptr;
case OpCodes::SLL:
return MakeInt(lhs.Int() << rhs.Int());
case OpCodes::SLR:
return MakeInt(lhs.Int() >> rhs.Int());
/*case OpCodes::CMPE:
return MakeInt(lhs.Int() == rhs.Int() ? 1 : 0);
case OpCodes::FCMPE:
return MakeInt(lhs.Float() == rhs.Float() ? 1 : 0);
case OpCodes::CMPNE:
return MakeInt(lhs.Int() != rhs.Int() ? 1 : 0);
case OpCodes::FCMPNE:
return MakeInt(lhs.Float() != rhs.Float() ? 1 : 0);
case OpCodes::CMPL:
return MakeInt(lhs.Int() < rhs.Int() ? 1 : 0);
case OpCodes::FCMPL:
return MakeInt(lhs.Float() < rhs.Float() ? 1 : 0);
case OpCodes::CMPLE:
return MakeInt(lhs.Int() <= rhs.Int() ? 1 : 0);
case OpCodes::FCMPLE:
return MakeInt(lhs.Float() <= rhs.Float() ? 1 : 0);
case OpCodes::CMPG:
return MakeInt(lhs.Int() > rhs.Int() ? 1 : 0);
case OpCodes::FCMPG:
return MakeInt(lhs.Float() > rhs.Float() ? 1 : 0);
case OpCodes::CMPGE:
return MakeInt(lhs.Int() >= rhs.Int() ? 1 : 0);
case OpCodes::FCMPGE:
return MakeInt(lhs.Float() >= rhs.Float() ? 1 : 0);*/
}
return nullptr;
}
void ConstantPropagation::FetchConst(TACVar& var)
{
if (!var.IsConst())
{
auto it = vars_.find(var);
if (it != vars_.end())
{
var = it->second;
Changed();
}
}
}
void ConstantPropagation::PropagateConst(const TACVar& dest, const TACVar& src)
{
if (src.IsConst())
vars_[dest] = src.value;
}
void ConstantPropagation::RemoveConst(const TACVar& dest)
{
auto it = vars_.find(dest);
if (it != vars_.end())
vars_.erase(it);
}
} // /namespace Optimization
// ================================================================================
<commit_msg>Bug fix in "ConstantPropagation::IsNOP" function.<commit_after>/*
* ConstantPropagation.cpp
*
* This file is part of the "XieXie 2.0 Project" (Copyright (c) 2014 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "ConstantPropagation.h"
#include "StringModifier.h"
#include "TACRelationInst.h"
#include "TACReturnInst.h"
#include "TACSwitchInst.h"
#include "TACStackInst.h"
#include "TACHeapInst.h"
namespace Optimization
{
using OpCodes = TACInst::OpCodes;
void ConstantPropagation::TransformBlock(BasicBlock& basicBlock)
{
/* Transform instructions (top-down) */
TransformInstsTopDown(basicBlock);
}
void ConstantPropagation::TransformCopyInst(TACInstPtr& inst)
{
auto copyInst = static_cast<TACCopyInst*>(inst.get());
/* Propagate constant */
FetchConst(copyInst->src);
PropagateConst(copyInst->dest, copyInst->src);
}
void ConstantPropagation::TransformModifyInst(TACInstPtr& inst)
{
auto modifyInst = static_cast<TACModifyInst*>(inst.get());
/* Propagate constants */
FetchConst(modifyInst->srcLhs);
FetchConst(modifyInst->srcRhs);
if (modifyInst->srcLhs.IsConst() && modifyInst->srcRhs.IsConst())
{
/* Constant folding */
auto newInst = ConstantFolding(*modifyInst);
if (newInst)
{
/* Propagate constant */
PropagateConst(newInst->dest, newInst->src);
inst = std::move(newInst);
Changed();
}
}
else if (IsNOP(*modifyInst))
{
/* Constant folding */
auto constVar = (modifyInst->srcLhs.IsConst() ? modifyInst->srcRhs : modifyInst->srcLhs);
auto newInst = MakeUnique<TACCopyInst>(modifyInst->dest, constVar);
/* Propagate constant */
PropagateConst(newInst->dest, newInst->src);
inst = std::move(newInst);
Changed();
}
else
{
/* Destination is now variable -> remove constant */
RemoveConst(modifyInst->dest);
}
}
void ConstantPropagation::TransformRelationInst(TACInstPtr& inst)
{
auto condInst = static_cast<TACRelationInst*>(inst.get());
/* Propagate constant */
FetchConst(condInst->srcLhs);
FetchConst(condInst->srcRhs);
}
void ConstantPropagation::TransformReturnInst(TACInstPtr& inst)
{
auto returnInst = static_cast<TACReturnInst*>(inst.get());
/* Propagate constant */
if (returnInst->hasVar)
FetchConst(returnInst->src);
}
void ConstantPropagation::TransformSwitchInst(TACInstPtr& inst)
{
auto switchInst = static_cast<TACSwitchInst*>(inst.get());
/* Propagate constant */
FetchConst(switchInst->src);
}
void ConstantPropagation::TransformStackInst(TACInstPtr& inst)
{
auto stackInst = static_cast<TACStackInst*>(inst.get());
/* Propagate constant */
if (stackInst->IsStoreOp())
FetchConst(stackInst->var);
else
RemoveConst(stackInst->var);
}
void ConstantPropagation::TransformHeapInst(TACInstPtr& inst)
{
auto heapInst = static_cast<TACHeapInst*>(inst.get());
/* Propagate constant */
if (heapInst->IsStoreOp())
FetchConst(heapInst->var);
else
RemoveConst(heapInst->var);
}
void ConstantPropagation::TransformDirectCallInst(TACInstPtr& inst)
{
/* Call instruction kills all constants */
vars_.clear();
}
bool ConstantPropagation::IsNOP(const TACModifyInst& inst) const
{
/* Get single constant */
const auto& lhs = inst.srcLhs;
const auto& rhs = inst.srcRhs;
TACVar constVar;
if (lhs.IsConst())
constVar = lhs;
else if (rhs.IsConst())
constVar = rhs;
else
return false;
/* Check if this is a no-operation instruction */
switch (inst.opcode)
{
case OpCodes::AND:
return constVar.Int() == ~0;
case OpCodes::OR:
case OpCodes::ADD:
return constVar.Int() == 0;
case OpCodes::SUB:
return rhs.Int() == 0;
case OpCodes::MUL:
return constVar.Int() == 1;
case OpCodes::DIV:
case OpCodes::MOD:
return rhs.Int() == 1;
case OpCodes::FADD:
return constVar.Float() == 0.0f;
case OpCodes::FSUB:
return rhs.Float() == 0.0f;
case OpCodes::FMUL:
return constVar.Float() == 1.0f;
case OpCodes::FDIV:
case OpCodes::FMOD:
return rhs.Float() == 1.0f;
default:
break;
}
return false;
}
std::unique_ptr<TACCopyInst> ConstantPropagation::ConstantFolding(const TACModifyInst& inst)
{
auto MakeInt = [&inst](int value)
{
return MakeUnique<TACCopyInst>(inst.dest, TACVar(ToStr(value)));
};
auto MakeFloat = [&inst](float value)
{
return MakeUnique<TACCopyInst>(inst.dest, TACVar(ToStr(value)));
};
const auto& lhs = inst.srcLhs;
const auto& rhs = inst.srcRhs;
switch (inst.opcode)
{
case OpCodes::AND:
return MakeInt(lhs.Int() & rhs.Int());
case OpCodes::OR:
return MakeInt(lhs.Int() | rhs.Int());
case OpCodes::XOR:
return MakeInt(lhs.Int() ^ rhs.Int());
case OpCodes::ADD:
return MakeInt(lhs.Int() + rhs.Int());
case OpCodes::FADD:
return MakeFloat(lhs.Float() + rhs.Float());
case OpCodes::SUB:
return MakeInt(lhs.Int() - rhs.Int());
case OpCodes::FSUB:
return MakeFloat(lhs.Float() - rhs.Float());
case OpCodes::MUL:
return MakeInt(lhs.Int() * rhs.Int());
case OpCodes::FMUL:
return MakeFloat(lhs.Float() * rhs.Float());
case OpCodes::DIV:
return rhs.Int() != 0 ? MakeInt(lhs.Int() / rhs.Int()) : nullptr;
case OpCodes::FDIV:
return MakeFloat(lhs.Float() / rhs.Float());
case OpCodes::MOD:
return rhs.Int() != 0 ? MakeInt(lhs.Int() % rhs.Int()) : nullptr;
case OpCodes::SLL:
return MakeInt(lhs.Int() << rhs.Int());
case OpCodes::SLR:
return MakeInt(lhs.Int() >> rhs.Int());
/*case OpCodes::CMPE:
return MakeInt(lhs.Int() == rhs.Int() ? 1 : 0);
case OpCodes::FCMPE:
return MakeInt(lhs.Float() == rhs.Float() ? 1 : 0);
case OpCodes::CMPNE:
return MakeInt(lhs.Int() != rhs.Int() ? 1 : 0);
case OpCodes::FCMPNE:
return MakeInt(lhs.Float() != rhs.Float() ? 1 : 0);
case OpCodes::CMPL:
return MakeInt(lhs.Int() < rhs.Int() ? 1 : 0);
case OpCodes::FCMPL:
return MakeInt(lhs.Float() < rhs.Float() ? 1 : 0);
case OpCodes::CMPLE:
return MakeInt(lhs.Int() <= rhs.Int() ? 1 : 0);
case OpCodes::FCMPLE:
return MakeInt(lhs.Float() <= rhs.Float() ? 1 : 0);
case OpCodes::CMPG:
return MakeInt(lhs.Int() > rhs.Int() ? 1 : 0);
case OpCodes::FCMPG:
return MakeInt(lhs.Float() > rhs.Float() ? 1 : 0);
case OpCodes::CMPGE:
return MakeInt(lhs.Int() >= rhs.Int() ? 1 : 0);
case OpCodes::FCMPGE:
return MakeInt(lhs.Float() >= rhs.Float() ? 1 : 0);*/
}
return nullptr;
}
void ConstantPropagation::FetchConst(TACVar& var)
{
if (!var.IsConst())
{
auto it = vars_.find(var);
if (it != vars_.end())
{
var = it->second;
Changed();
}
}
}
void ConstantPropagation::PropagateConst(const TACVar& dest, const TACVar& src)
{
if (src.IsConst())
vars_[dest] = src.value;
}
void ConstantPropagation::RemoveConst(const TACVar& dest)
{
auto it = vars_.find(dest);
if (it != vars_.end())
vars_.erase(it);
}
} // /namespace Optimization
// ================================================================================
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include <QtDebug>
#include <QApplication>
#include <QStringList>
#include <qt4nodeinstanceclientproxy.h>
#ifdef ENABLE_QT_BREAKPAD
#include <qtsystemexceptionhandler.h>
#endif
#ifdef Q_OS_WIN
#include <windows.h>
#endif
int main(int argc, char *argv[])
{
QApplication application(argc, argv);
if (application.arguments().count() != 4)
return -1;
QCoreApplication::setOrganizationName("Nokia");
QCoreApplication::setOrganizationDomain("nokia.com");
QCoreApplication::setApplicationName("QmlPuppet");
QCoreApplication::setApplicationVersion("1.1.0");
#ifdef ENABLE_QT_BREAKPAD
QtSystemExceptionHandler systemExceptionHandler;
#endif
new QmlDesigner::Qt4NodeInstanceClientProxy(&application);
#if defined(Q_OS_WIN) && defined(QT_NO_DEBUG)
SetErrorMode(SEM_NOGPFAULTERRORBOX); //We do not want to see any message boxes
#endif
return application.exec();
}
<commit_msg>QmlDesigner.qmlPuppet: SetErrorMode only if breakpad is disabled<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include <QtDebug>
#include <QApplication>
#include <QStringList>
#include <qt4nodeinstanceclientproxy.h>
#ifdef ENABLE_QT_BREAKPAD
#include <qtsystemexceptionhandler.h>
#endif
#ifdef Q_OS_WIN
#include <windows.h>
#endif
int main(int argc, char *argv[])
{
QApplication application(argc, argv);
if (application.arguments().count() != 4)
return -1;
QCoreApplication::setOrganizationName("Nokia");
QCoreApplication::setOrganizationDomain("nokia.com");
QCoreApplication::setApplicationName("QmlPuppet");
QCoreApplication::setApplicationVersion("1.1.0");
#ifdef ENABLE_QT_BREAKPAD
QtSystemExceptionHandler systemExceptionHandler;
#endif
new QmlDesigner::Qt4NodeInstanceClientProxy(&application);
#if defined(Q_OS_WIN) && defined(QT_NO_DEBUG) && !defined(ENABLE_QT_BREAKPAD)
SetErrorMode(SEM_NOGPFAULTERRORBOX); //We do not want to see any message boxes
#endif
return application.exec();
}
<|endoftext|> |
<commit_before>/*
* node-rdkafka - Node.js wrapper for RdKafka C/C++ library
*
* Copyright (c) 2016 Blizzard Entertainment
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE.txt file for details.
*/
#include <string>
#include <vector>
#include <list>
#include "src/config.h"
using Nan::MaybeLocal;
using Nan::Maybe;
using v8::Local;
using v8::String;
using v8::Object;
using std::cout;
using std::endl;
namespace NodeKafka {
void Conf::DumpConfig(std::list<std::string> *dump) {
for (std::list<std::string>::iterator it = dump->begin();
it != dump->end(); ) {
std::cout << *it << " = ";
it++;
std::cout << *it << std::endl;
it++;
}
std::cout << std::endl;
}
Conf * Conf::create(RdKafka::Conf::ConfType type, v8::Local<v8::Object> object, std::string &errstr) { // NOLINT
Conf* rdconf = static_cast<Conf*>(RdKafka::Conf::create(type));
v8::Local<v8::Array> property_names = object->GetOwnPropertyNames();
for (unsigned int i = 0; i < property_names->Length(); ++i) {
std::string string_value;
std::string string_key;
v8::Local<v8::Value> key = property_names->Get(i);
v8::Local<v8::Value> value = object->Get(key);
if (key->IsString()) {
Nan::Utf8String utf8_key(key);
string_key = std::string(*utf8_key);
} else {
continue;
}
if (!value->IsFunction()) {
Nan::Utf8String utf8_value(value.As<v8::String>());
string_value = std::string(*utf8_value);
if (rdconf->set(string_key, string_value, errstr)
!= Conf::CONF_OK) {
delete rdconf;
return NULL;
}
} else {
if (string_key.compare("rebalance_cb") == 0) {
v8::Local<v8::Function> cb = value.As<v8::Function>();
rdconf->m_rebalance_cb = new NodeKafka::Callbacks::Rebalance(cb);
rdconf->set(string_key, rdconf->m_rebalance_cb, errstr);
} else if (string_key.compare("offset_commit_cb") == 0) {
v8::Local<v8::Function> cb = value.As<v8::Function>();
rdconf->m_offset_commit_cb = new NodeKafka::Callbacks::OffsetCommit(cb);
rdconf->set(string_key, rdconf->m_offset_commit_cb, errstr);
}
}
}
return rdconf;
}
void Conf::listen() {
if (m_rebalance_cb) {
m_rebalance_cb->dispatcher.Activate();
}
if (m_offset_commit_cb) {
m_offset_commit_cb->dispatcher.Activate();
}
}
void Conf::stop() {
if (m_rebalance_cb) {
m_rebalance_cb->dispatcher.Deactivate();
}
if (m_offset_commit_cb) {
m_offset_commit_cb->dispatcher.Deactivate();
}
}
Conf::~Conf() {
if (m_rebalance_cb) {
delete m_rebalance_cb;
}
}
} // namespace NodeKafka
<commit_msg>Fixes exception being raised in the debug build while converting non-string configuration values to string.<commit_after>/*
* node-rdkafka - Node.js wrapper for RdKafka C/C++ library
*
* Copyright (c) 2016 Blizzard Entertainment
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE.txt file for details.
*/
#include <string>
#include <vector>
#include <list>
#include "src/config.h"
using Nan::MaybeLocal;
using Nan::Maybe;
using v8::Local;
using v8::String;
using v8::Object;
using std::cout;
using std::endl;
namespace NodeKafka {
void Conf::DumpConfig(std::list<std::string> *dump) {
for (std::list<std::string>::iterator it = dump->begin();
it != dump->end(); ) {
std::cout << *it << " = ";
it++;
std::cout << *it << std::endl;
it++;
}
std::cout << std::endl;
}
Conf * Conf::create(RdKafka::Conf::ConfType type, v8::Local<v8::Object> object, std::string &errstr) { // NOLINT
Conf* rdconf = static_cast<Conf*>(RdKafka::Conf::create(type));
v8::Local<v8::Array> property_names = object->GetOwnPropertyNames();
for (unsigned int i = 0; i < property_names->Length(); ++i) {
std::string string_value;
std::string string_key;
v8::Local<v8::Value> key = property_names->Get(i);
v8::Local<v8::Value> value = object->Get(key);
if (key->IsString()) {
Nan::Utf8String utf8_key(key);
string_key = std::string(*utf8_key);
} else {
continue;
}
if (!value->IsFunction()) {
#if NODE_MAJOR_VERSION > 6
if (value->IsInt32()) {
string_value = std::to_string(
value->Int32Value(Nan::GetCurrentContext()).ToChecked());
} else if (value->IsUint32()) {
string_value = std::to_string(
value->Uint32Value(Nan::GetCurrentContext()).ToChecked());
} else if (value->IsBoolean()) {
string_value = value->BooleanValue(
Nan::GetCurrentContext()).ToChecked() ? "true" : "false";
} else {
Nan::Utf8String utf8_value(value.As<v8::String>());
string_value = std::string(*utf8_value);
}
#else
Nan::Utf8String utf8_value(value.As<v8::String>());
string_value = std::string(*utf8_value);
#endif
if (rdconf->set(string_key, string_value, errstr)
!= Conf::CONF_OK) {
delete rdconf;
return NULL;
}
} else {
if (string_key.compare("rebalance_cb") == 0) {
v8::Local<v8::Function> cb = value.As<v8::Function>();
rdconf->m_rebalance_cb = new NodeKafka::Callbacks::Rebalance(cb);
rdconf->set(string_key, rdconf->m_rebalance_cb, errstr);
} else if (string_key.compare("offset_commit_cb") == 0) {
v8::Local<v8::Function> cb = value.As<v8::Function>();
rdconf->m_offset_commit_cb = new NodeKafka::Callbacks::OffsetCommit(cb);
rdconf->set(string_key, rdconf->m_offset_commit_cb, errstr);
}
}
}
return rdconf;
}
void Conf::listen() {
if (m_rebalance_cb) {
m_rebalance_cb->dispatcher.Activate();
}
if (m_offset_commit_cb) {
m_offset_commit_cb->dispatcher.Activate();
}
}
void Conf::stop() {
if (m_rebalance_cb) {
m_rebalance_cb->dispatcher.Deactivate();
}
if (m_offset_commit_cb) {
m_offset_commit_cb->dispatcher.Deactivate();
}
}
Conf::~Conf() {
if (m_rebalance_cb) {
delete m_rebalance_cb;
}
}
} // namespace NodeKafka
<|endoftext|> |
<commit_before>/**
* \file
* \remark This file is part of VITA.
*
* \copyright Copyright (C) 2013-2015 EOS di Manlio Morini.
*
* \license
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/
*/
#define MASTER_TEST_SET
#define BOOST_TEST_MODULE Master Test Suite
#include <boost/test/unit_test.hpp>
constexpr double epsilon(0.00001);
using namespace boost;
#include "test/factory_fixture1.h"
#include "test/factory_fixture2.h"
#include "test/factory_fixture3.h"
#include "test/factory_fixture4.h"
#include "test/factory_fixture5.h"
#include "test/evolution.cc"
#include "test/fitness.cc"
#include "test/ga.cc"
//#include "test_ga_perf.cc"
#include "test/i_mep.cc"
#include "test/i_ga.cc"
#include "test/lambda.cc"
#include "test/matrix.cc"
#include "test/population.cc"
#include "test/primitive_d.cc"
#include "test/primitive_i.cc"
#include "test/src_constant.cc"
#include "test/src_problem.cc"
#include "test/summary.cc"
#include "test/symbol_set.cc"
#include "test/team.cc"
#include "test/terminal.cc"
#include "test/ttable.cc"
#include "test/variant.cc"
<commit_msg>[REF] Now testing also small_vector<commit_after>/**
* \file
* \remark This file is part of VITA.
*
* \copyright Copyright (C) 2013-2015 EOS di Manlio Morini.
*
* \license
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/
*/
#define MASTER_TEST_SET
#define BOOST_TEST_MODULE Master Test Suite
#include <boost/test/unit_test.hpp>
constexpr double epsilon(0.00001);
using namespace boost;
#include "test/factory_fixture1.h"
#include "test/factory_fixture2.h"
#include "test/factory_fixture3.h"
#include "test/factory_fixture4.h"
#include "test/factory_fixture5.h"
#include "test/evolution.cc"
#include "test/fitness.cc"
#include "test/ga.cc"
//#include "test_ga_perf.cc"
#include "test/i_mep.cc"
#include "test/i_ga.cc"
#include "test/lambda.cc"
#include "test/matrix.cc"
#include "test/population.cc"
#include "test/primitive_d.cc"
#include "test/primitive_i.cc"
#include "test/small_vector.cc"
#include "test/src_constant.cc"
#include "test/src_problem.cc"
#include "test/summary.cc"
#include "test/symbol_set.cc"
#include "test/team.cc"
#include "test/terminal.cc"
#include "test/ttable.cc"
#include "test/variant.cc"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: localebackend.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-10-22 08:13:51 $
*
* 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 OOFTWARE 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 "localebackend.hxx"
#include "localelayer.hxx"
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_COMPONENTCHANGEEVENT_HPP_
#include <com/sun/star/configuration/backend/ComponentChangeEvent.hpp>
#endif
#ifndef _UNO_CURRENT_CONTEXT_HXX_
#include <uno/current_context.hxx>
#endif
#ifndef _OSL_TIME_H_
#include <osl/time.h>
#endif
#include <stdio.h>
#ifdef UNX
#include <rtl/ustrbuf.hxx>
#include <locale.h>
#include <string.h>
/*
* Note: setlocale is not at all thread safe, so is this code. It could
* especially interfere with the stuff VCL is doing, so make sure this
* is called from the main thread only.
*/
static rtl::OUString ImplGetLocale(int category)
{
const char *locale = setlocale(category, "");
// Return "en-US" for C locales
if( (locale == NULL) || ( locale[0] == 'C' && locale[1] == '\0' ) )
return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "en-US" ) );
const char *cp;
const char *uscore = NULL;
// locale string have the format lang[_ctry][.encoding][@modifier]
// we are only interested in the first two items, so we handle
// '.' and '@' as string end.
for (cp = locale; *cp; cp++)
{
if (*cp == '_')
uscore = cp;
if (*cp == '.' || *cp == '@')
break;
}
rtl::OUStringBuffer aLocaleBuffer;
if( uscore != NULL )
{
aLocaleBuffer.appendAscii(locale, uscore++ - locale);
aLocaleBuffer.appendAscii("-");
aLocaleBuffer.appendAscii(uscore, cp - uscore);
}
else
{
aLocaleBuffer.appendAscii(locale, cp - locale);
}
return aLocaleBuffer.makeStringAndClear();
}
#endif // UNX
// -------------------------------------------------------------------------------
#ifdef WNT
#ifdef WINVER
#undef WINVER
#endif
#define WINVER 0x0501
#include <windows.h>
rtl::OUString ImplGetLocale(LCID lcid)
{
TCHAR buffer[8];
LPTSTR cp = buffer;
cp += GetLocaleInfo( lcid, LOCALE_SISO639LANGNAME , buffer, 4 );
if( cp > buffer )
{
if( 0 < GetLocaleInfo( lcid, LOCALE_SISO3166CTRYNAME, cp, buffer + 8 - cp) )
*cp = '-';
return rtl::OUString::createFromAscii(buffer);
}
return rtl::OUString();
}
#endif // WNT
// -------------------------------------------------------------------------------
LocaleBackend::LocaleBackend(const uno::Reference<uno::XComponentContext>& xContext)
throw (backend::BackendAccessException) :
::cppu::WeakImplHelper2 < backend::XSingleLayerStratum, lang::XServiceInfo > (),
m_xContext(xContext)
{
}
//------------------------------------------------------------------------------
LocaleBackend::~LocaleBackend(void)
{
}
//------------------------------------------------------------------------------
LocaleBackend* LocaleBackend::createInstance(
const uno::Reference<uno::XComponentContext>& xContext
)
{
return new LocaleBackend(xContext);
}
// ---------------------------------------------------------------------------------------
rtl::OUString LocaleBackend::getLocale(void)
{
#ifdef UNX
return ImplGetLocale(LC_CTYPE);
#elif defined WNT
return ImplGetLocale( GetUserDefaultLCID() );
#endif
}
//------------------------------------------------------------------------------
rtl::OUString LocaleBackend::getUILocale(void)
{
#ifdef UNX
return ImplGetLocale(LC_MESSAGES);
#elif defined WNT
return ImplGetLocale( MAKELCID(GetUserDefaultUILanguage(), SORT_DEFAULT) );
#endif
}
//------------------------------------------------------------------------------
rtl::OUString LocaleBackend::createTimeStamp()
{
// the time stamp is free text, so just returning the values here.
return getLocale() + getUILocale();
}
//------------------------------------------------------------------------------
uno::Reference<backend::XLayer> SAL_CALL LocaleBackend::getLayer(
const rtl::OUString& aComponent, const rtl::OUString& aTimestamp)
throw (backend::BackendAccessException, lang::IllegalArgumentException)
{
if( aComponent.equals( getSupportedComponents()[0]) )
{
if( ! m_xSystemLayer.is() )
{
uno::Sequence<backend::PropertyInfo> aPropInfoList(2);
aPropInfoList[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.System/L10N/UILocale") );
aPropInfoList[0].Type = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "string" ) );
aPropInfoList[0].Protected = sal_False;
aPropInfoList[0].Value = uno::makeAny( getUILocale() );
aPropInfoList[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("org.openoffice.System/L10N/Locale") );
aPropInfoList[1].Type = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "string" ));
aPropInfoList[1].Protected = sal_False;
aPropInfoList[1].Value = uno::makeAny( getLocale() );
m_xSystemLayer = new LocaleLayer(aPropInfoList, createTimeStamp(), m_xContext);
}
return m_xSystemLayer;
}
return uno::Reference<backend::XLayer>();
}
//------------------------------------------------------------------------------
uno::Reference<backend::XUpdatableLayer> SAL_CALL
LocaleBackend::getUpdatableLayer(const rtl::OUString& aComponent)
throw (backend::BackendAccessException,lang::NoSupportException,
lang::IllegalArgumentException)
{
throw lang::NoSupportException(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
"LocaleBackend: No Update Operation allowed, Read Only access") ),
*this) ;
return NULL;
}
//------------------------------------------------------------------------------
rtl::OUString SAL_CALL LocaleBackend::getBackendName(void) {
return rtl::OUString::createFromAscii("com.sun.star.comp.configuration.backend.LocaleBackend") ;
}
//------------------------------------------------------------------------------
rtl::OUString SAL_CALL LocaleBackend::getImplementationName(void)
throw (uno::RuntimeException)
{
return getBackendName() ;
}
//------------------------------------------------------------------------------
uno::Sequence<rtl::OUString> SAL_CALL LocaleBackend::getBackendServiceNames(void)
{
uno::Sequence<rtl::OUString> aServiceNameList(2);
aServiceNameList[0] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.configuration.backend.LocaleBackend")) ;
aServiceNameList[1] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.configuration.backend.PlatformBackend")) ;
return aServiceNameList ;
}
//------------------------------------------------------------------------------
sal_Bool SAL_CALL LocaleBackend::supportsService(const rtl::OUString& aServiceName)
throw (uno::RuntimeException)
{
uno::Sequence< rtl::OUString > const svc = getBackendServiceNames();
for(sal_Int32 i = 0; i < svc.getLength(); ++i )
if(svc[i] == aServiceName)
return true;
return false;
}
//------------------------------------------------------------------------------
uno::Sequence<rtl::OUString> SAL_CALL LocaleBackend::getSupportedServiceNames(void)
throw (uno::RuntimeException)
{
return getBackendServiceNames() ;
}
// ---------------------------------------------------------------------------------------
uno::Sequence<rtl::OUString> SAL_CALL LocaleBackend::getSupportedComponents(void)
{
uno::Sequence<rtl::OUString> aSupportedComponentList(1);
aSupportedComponentList[0] = rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.System" )
);
return aSupportedComponentList;
}
<commit_msg>INTEGRATION: CWS macosx10 (1.3.58); FILE MERGED 2005/07/05 07:11:39 tra 1.3.58.1: #i51246#Detecting UI language and locale using Mac OS X API<commit_after>/*************************************************************************
*
* $RCSfile: localebackend.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-08-18 08:10:47 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE OOFTWARE 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 "localebackend.hxx"
#include "localelayer.hxx"
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_COMPONENTCHANGEEVENT_HPP_
#include <com/sun/star/configuration/backend/ComponentChangeEvent.hpp>
#endif
#ifndef _UNO_CURRENT_CONTEXT_HXX_
#include <uno/current_context.hxx>
#endif
#ifndef _OSL_TIME_H_
#include <osl/time.h>
#endif
#include <stdio.h>
#if defined(LINUX) || defined(SOLARIS) || defined(IRIX) || defined(NETBSD) || defined(FREEBSD)
#include <rtl/ustrbuf.hxx>
#include <locale.h>
#include <string.h>
/*
* Note: setlocale is not at all thread safe, so is this code. It could
* especially interfere with the stuff VCL is doing, so make sure this
* is called from the main thread only.
*/
static rtl::OUString ImplGetLocale(int category)
{
const char *locale = setlocale(category, "");
// Return "en-US" for C locales
if( (locale == NULL) || ( locale[0] == 'C' && locale[1] == '\0' ) )
return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "en-US" ) );
const char *cp;
const char *uscore = NULL;
// locale string have the format lang[_ctry][.encoding][@modifier]
// we are only interested in the first two items, so we handle
// '.' and '@' as string end.
for (cp = locale; *cp; cp++)
{
if (*cp == '_')
uscore = cp;
if (*cp == '.' || *cp == '@')
break;
}
rtl::OUStringBuffer aLocaleBuffer;
if( uscore != NULL )
{
aLocaleBuffer.appendAscii(locale, uscore++ - locale);
aLocaleBuffer.appendAscii("-");
aLocaleBuffer.appendAscii(uscore, cp - uscore);
}
else
{
aLocaleBuffer.appendAscii(locale, cp - locale);
}
return aLocaleBuffer.makeStringAndClear();
}
#elif defined(MACOSX)
#include <rtl/ustrbuf.hxx>
#include <locale.h>
#include <string.h>
#include <premac.h>
#include <CoreServices/CoreServices.h>
#include <CoreFoundation/CoreFoundation.h>
#include <postmac.h>
namespace /* private */
{
void OUStringBufferAppendCFString(rtl::OUStringBuffer& buffer, const CFStringRef s)
{
CFIndex lstr = CFStringGetLength(s);
for (CFIndex i = 0; i < lstr; i++)
buffer.append(CFStringGetCharacterAtIndex(s, i));
}
template <typename T>
class CFGuard
{
public:
explicit CFGuard(T* pT) : pT_(pT) {}
~CFGuard() { if (pT_) CFRelease(*pT_); }
private:
T* pT_;
};
typedef CFGuard<CFArrayRef> CFArrayGuard;
typedef CFGuard<CFStringRef> CFStringGuard;
typedef CFGuard<CFTypeRef> CFTypeRefGuard;
/* For more information on the Apple locale concept please refer to
http://developer.apple.com/documentation/CoreFoundation/Conceptual/CFLocales/Articles/CFLocaleConcepts.html
According to this documentation a locale identifier has the format: language[_country][_variant]*
e.g. es_ES_PREEURO -> spain prior Euro support
Note: The calling code should be able to handle locales with only language information e.g. 'en' for certain
UI languages just the language code will be returned.
*/
CFStringRef ImplGetAppPreference(const char* pref)
{
CFStringRef csPref = CFStringCreateWithCString(NULL, pref, kCFStringEncodingASCII);
CFStringGuard csRefGuard(&csPref);
CFTypeRef ref = CFPreferencesCopyAppValue(csPref, kCFPreferencesCurrentApplication);
CFTypeRefGuard refGuard(&ref);
if (ref == NULL)
return NULL;
CFStringRef sref = (CFGetTypeID(ref) == CFArrayGetTypeID()) ? (CFStringRef)CFArrayGetValueAtIndex((CFArrayRef)ref, 0) : (CFStringRef)ref;
CFRetain(sref); // caller is responsible for releasing reference
return sref;
}
rtl::OUString ImplGetLocale(const char* pref)
{
CFStringRef sref = ImplGetAppPreference(pref);
CFStringGuard srefGuard(&sref);
rtl::OUStringBuffer aLocaleBuffer;
aLocaleBuffer.appendAscii("en-US"); // initialize with fallback value
if (sref != NULL)
{
// split the string into substrings; the first two (if there are two) substrings
// are language and country
CFArrayRef subs = CFStringCreateArrayBySeparatingStrings(NULL, sref, CFSTR("_"));
CFArrayGuard subsGuard(&subs);
if (subs != NULL)
{
aLocaleBuffer.setLength(0); // clear buffer which still contains fallback value
CFStringRef lang = (CFStringRef)CFArrayGetValueAtIndex(subs, 0);
OUStringBufferAppendCFString(aLocaleBuffer, lang);
// country also available? Assumption: if the array contains more than one
// value the second value is always the country!
if (CFArrayGetCount(subs) > 1)
{
aLocaleBuffer.appendAscii("-");
CFStringRef country = (CFStringRef)CFArrayGetValueAtIndex(subs, 1);
OUStringBufferAppendCFString(aLocaleBuffer, country);
}
}
}
return aLocaleBuffer.makeStringAndClear();
}
} // namespace /* private */
#endif
// -------------------------------------------------------------------------------
#ifdef WNT
#ifdef WINVER
#undef WINVER
#endif
#define WINVER 0x0501
#include <windows.h>
rtl::OUString ImplGetLocale(LCID lcid)
{
TCHAR buffer[8];
LPTSTR cp = buffer;
cp += GetLocaleInfo( lcid, LOCALE_SISO639LANGNAME , buffer, 4 );
if( cp > buffer )
{
if( 0 < GetLocaleInfo( lcid, LOCALE_SISO3166CTRYNAME, cp, buffer + 8 - cp) )
*cp = '-';
return rtl::OUString::createFromAscii(buffer);
}
return rtl::OUString();
}
#endif // WNT
// -------------------------------------------------------------------------------
LocaleBackend::LocaleBackend(const uno::Reference<uno::XComponentContext>& xContext)
throw (backend::BackendAccessException) :
::cppu::WeakImplHelper2 < backend::XSingleLayerStratum, lang::XServiceInfo > (),
m_xContext(xContext)
{
}
//------------------------------------------------------------------------------
LocaleBackend::~LocaleBackend(void)
{
}
//------------------------------------------------------------------------------
LocaleBackend* LocaleBackend::createInstance(
const uno::Reference<uno::XComponentContext>& xContext
)
{
return new LocaleBackend(xContext);
}
// ---------------------------------------------------------------------------------------
rtl::OUString LocaleBackend::getLocale(void)
{
#if defined(LINUX) || defined(SOLARIS) || defined(IRIX) || defined(NETBSD) || defined(FREEBSD)
return ImplGetLocale(LC_CTYPE);
#elif defined (MACOSX)
return ImplGetLocale("AppleLocale");
#elif defined WNT
return ImplGetLocale( GetUserDefaultLCID() );
#endif
}
//------------------------------------------------------------------------------
rtl::OUString LocaleBackend::getUILocale(void)
{
#if defined(LINUX) || defined(SOLARIS) || defined(IRIX) || defined(NETBSD) || defined(FREEBSD)
return ImplGetLocale(LC_MESSAGES);
#elif defined(MACOSX)
return ImplGetLocale("AppleLanguages");
#elif defined WNT
return ImplGetLocale( MAKELCID(GetUserDefaultUILanguage(), SORT_DEFAULT) );
#endif
}
//------------------------------------------------------------------------------
rtl::OUString LocaleBackend::createTimeStamp()
{
// the time stamp is free text, so just returning the values here.
return getLocale() + getUILocale();
}
//------------------------------------------------------------------------------
uno::Reference<backend::XLayer> SAL_CALL LocaleBackend::getLayer(
const rtl::OUString& aComponent, const rtl::OUString& aTimestamp)
throw (backend::BackendAccessException, lang::IllegalArgumentException)
{
if( aComponent.equals( getSupportedComponents()[0]) )
{
if( ! m_xSystemLayer.is() )
{
uno::Sequence<backend::PropertyInfo> aPropInfoList(2);
aPropInfoList[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.System/L10N/UILocale") );
aPropInfoList[0].Type = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "string" ) );
aPropInfoList[0].Protected = sal_False;
aPropInfoList[0].Value = uno::makeAny( getUILocale() );
aPropInfoList[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("org.openoffice.System/L10N/Locale") );
aPropInfoList[1].Type = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "string" ));
aPropInfoList[1].Protected = sal_False;
aPropInfoList[1].Value = uno::makeAny( getLocale() );
m_xSystemLayer = new LocaleLayer(aPropInfoList, createTimeStamp(), m_xContext);
}
return m_xSystemLayer;
}
return uno::Reference<backend::XLayer>();
}
//------------------------------------------------------------------------------
uno::Reference<backend::XUpdatableLayer> SAL_CALL
LocaleBackend::getUpdatableLayer(const rtl::OUString& aComponent)
throw (backend::BackendAccessException,lang::NoSupportException,
lang::IllegalArgumentException)
{
throw lang::NoSupportException(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
"LocaleBackend: No Update Operation allowed, Read Only access") ),
*this) ;
return NULL;
}
//------------------------------------------------------------------------------
rtl::OUString SAL_CALL LocaleBackend::getBackendName(void) {
return rtl::OUString::createFromAscii("com.sun.star.comp.configuration.backend.LocaleBackend") ;
}
//------------------------------------------------------------------------------
rtl::OUString SAL_CALL LocaleBackend::getImplementationName(void)
throw (uno::RuntimeException)
{
return getBackendName() ;
}
//------------------------------------------------------------------------------
uno::Sequence<rtl::OUString> SAL_CALL LocaleBackend::getBackendServiceNames(void)
{
uno::Sequence<rtl::OUString> aServiceNameList(2);
aServiceNameList[0] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.configuration.backend.LocaleBackend")) ;
aServiceNameList[1] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.configuration.backend.PlatformBackend")) ;
return aServiceNameList ;
}
//------------------------------------------------------------------------------
sal_Bool SAL_CALL LocaleBackend::supportsService(const rtl::OUString& aServiceName)
throw (uno::RuntimeException)
{
uno::Sequence< rtl::OUString > const svc = getBackendServiceNames();
for(sal_Int32 i = 0; i < svc.getLength(); ++i )
if(svc[i] == aServiceName)
return true;
return false;
}
//------------------------------------------------------------------------------
uno::Sequence<rtl::OUString> SAL_CALL LocaleBackend::getSupportedServiceNames(void)
throw (uno::RuntimeException)
{
return getBackendServiceNames() ;
}
// ---------------------------------------------------------------------------------------
uno::Sequence<rtl::OUString> SAL_CALL LocaleBackend::getSupportedComponents(void)
{
uno::Sequence<rtl::OUString> aSupportedComponentList(1);
aSupportedComponentList[0] = rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.System" )
);
return aSupportedComponentList;
}
<|endoftext|> |
<commit_before>/*==========================================================================
SeqAn - The Library for Sequence Analysis
http://www.seqan.de
============================================================================
Copyright (C) 2007
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 3 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.
==========================================================================*/
#define SEQAN_PROFILE
#include <seqan/basic.h>
// Profiling
#ifdef SEQAN_PROFILE
SEQAN_PROTIMESTART(__myProfileTime);
#endif
#include <seqan/consensus.h>
#include <seqan/modifier.h>
#include <seqan/misc/misc_cmdparser.h>
#include <iostream>
#include <fstream>
using namespace seqan;
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
inline void
_addVersion(CommandLineParser& parser) {
::std::string rev = "$Revision: 4637 $";
addVersionLine(parser, "Version 0.21 (31. July 2009) Revision: " + rev.substr(11, 4) + "");
}
//////////////////////////////////////////////////////////////////////////////////
int main(int argc, const char *argv[]) {
// Command line parsing
CommandLineParser parser;
_addVersion(parser);
addTitleLine(parser, "***************************************");
addTitleLine(parser, "* Multi-read alignment - SeqCons *");
addTitleLine(parser, "* (c) Copyright 2009 by Tobias Rausch *");
addTitleLine(parser, "***************************************");
addUsageLine(parser, "-r <FASTA file with reads> [Options]");
addUsageLine(parser, "-a <AMOS message file> [Options]");
addSection(parser, "Main Options:");
addOption(parser, addArgumentText(CommandLineOption("r", "reads", "file with reads", OptionType::String), "<FASTA reads file>"));
addOption(parser, addArgumentText(CommandLineOption("a", "afg", "message file", OptionType::String), "<AMOS afg file>"));
addOption(parser, addArgumentText(CommandLineOption("o", "outfile", "output filename", OptionType::String, "align.txt"), "<Filename>"));
addOption(parser, addArgumentText(CommandLineOption("f", "format", "output format", OptionType::String, "seqan"), "[seqan | afg]"));
addOption(parser, addArgumentText(CommandLineOption("m", "method", "multi-read alignment method", OptionType::String, "realign"), "[realign | msa]"));
addOption(parser, addArgumentText(CommandLineOption("b", "bandwidth", "bandwidth", OptionType::Int, 8), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("c", "consensus", "consensus calling", OptionType::String, "majority"), "[majority | bayesian]"));
addOption(parser, CommandLineOption("n", "noalign", "no align, only convert input", OptionType::Boolean));
addSection(parser, "MSA Method Options:");
addOption(parser, addArgumentText(CommandLineOption("ma", "matchlength", "minimum overlap length", OptionType::Int, 15), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("qu", "quality", "minimum overlap precent identity", OptionType::Int, 80), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("ov", "overlaps", "minimum number of overlaps per read", OptionType::Int, 3), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("wi", "window", "window size", OptionType::Int, 0), "<Int>"));
addHelpLine(parser, "/*If this parameter is > 0 then all");
addHelpLine(parser, " overlaps within a given window");
addHelpLine(parser, " are computed.*/");
addSection(parser, "ReAlign Method Options:");
addOption(parser, CommandLineOption("in", "include", "include contig sequence", OptionType::Boolean));
addOption(parser, addArgumentText(CommandLineOption("rm", "rmethod", "realign method", OptionType::String, "gotoh"), "[nw | gotoh]"));
if (argc == 1)
{
shortHelp(parser, std::cerr); // print short help and exit
return 0;
}
if (!parse(parser, argc, argv, ::std::cerr)) return 1;
if (isSetLong(parser, "help") || isSetLong(parser, "version")) return 0; // print help or version and exit
// Get all command line options
ConsensusOptions consOpt;
// Main options
getOptionValueLong(parser, "reads", consOpt.readsfile);
getOptionValueLong(parser, "afg", consOpt.afgfile);
getOptionValueLong(parser, "outfile", consOpt.outfile);
String<char> optionVal;
getOptionValueLong(parser, "format", optionVal);
if (optionVal == "seqan") consOpt.output = 0;
else if (optionVal == "afg") consOpt.output = 1;
else if (optionVal == "frg") consOpt.output = 2;
else if (optionVal == "cgb") consOpt.output = 3;
getOptionValueLong(parser, "method", optionVal);
if (optionVal == "realign") consOpt.method = 0;
else if (optionVal == "msa") consOpt.method = 1;
getOptionValueLong(parser, "bandwidth", consOpt.bandwidth);
#ifdef CELERA_OFFSET
if (!isSetLong(parser, "bandwidth") consOpt.bandwidth = 15;
#endif
getOptionValueLong(parser, "consensus", optionVal);
if (optionVal == "majority") consOpt.consensus = 0;
else if (optionVal == "bayesian") consOpt.consensus = 1;
getOptionValueLong(parser, "noalign", consOpt.noalign);
// Msa options
getOptionValueLong(parser, "matchlength", consOpt.matchlength);
getOptionValueLong(parser, "quality", consOpt.quality);
getOptionValueLong(parser, "overlaps", consOpt.overlaps);
#ifdef CELERA_OFFSET
if (!isSetLong(parser, "overlaps") consOpt.overlaps = 5;
#endif
getOptionValueLong(parser, "window", consOpt.window);
// ReAlign options
getOptionValueLong(parser, "include", consOpt.include);
getOptionValueLong(parser, "rmethod", optionVal);
if (optionVal == "nw") consOpt.rmethod = 0;
else if (optionVal == "gotoh") consOpt.rmethod = 1;
// Create a new fragment store
typedef FragmentStore<> TFragmentStore;
typedef Size<TFragmentStore>::Type TSize;
TFragmentStore fragStore;
// Load the reads and layout positions
TSize numberOfContigs = 0;
if (!empty(consOpt.readsfile)) {
// Load simple read file
FILE* strmReads = fopen(consOpt.readsfile.c_str(), "rb");
bool success = _convertSimpleReadFile(strmReads, fragStore, consOpt.readsfile, true);
fclose(strmReads);
if (!success) {
shortHelp(parser, std::cerr);
return 0;
}
numberOfContigs = 1;
} else if (!empty(consOpt.afgfile)) {
// Load Amos message file
FILE* strmReads = fopen(consOpt.afgfile.c_str(), "rb");
read(strmReads, fragStore, Amos());
fclose(strmReads);
numberOfContigs = length(fragStore.contigStore);
} else {
shortHelp(parser, std::cerr);
return 0;
}
// Multi-realignment desired or just conversion of the input
if (!consOpt.noalign) {
// Profiling
#ifdef SEQAN_PROFILE
SEQAN_PROTIMEUPDATE(__myProfileTime);
#endif
// Iterate over all contigs
for(TSize currentContig = 0; currentContig < numberOfContigs; ++currentContig) {
if (consOpt.method == 0) {
#ifdef SEQAN_PROFILE
::std::cout << "ReAlign method" << ::std::endl;
if (consOpt.rmethod == 0) ::std::cout << "Realign algorithm: Needleman-Wunsch" << ::std::endl;
else if (consOpt.rmethod == 1) ::std::cout << "Realign algorithm: Gotoh" << ::std::endl;
::std::cout << "Bandwidth: " << consOpt.bandwidth << ::std::endl;
::std::cout << "Include reference: " << consOpt.include << ::std::endl;
#endif
Score<int, WeightedConsensusScore<Score<int, FractionalScore>, Score<int, ConsensusScore> > > combinedScore;
reAlign(fragStore, combinedScore, currentContig, consOpt.rmethod, consOpt.bandwidth, consOpt.include);
#ifdef SEQAN_PROFILE
::std::cout << "ReAlignment done: " << SEQAN_PROTIMEUPDATE(__myProfileTime) << " seconds" << ::std::endl;
#endif
} else {
#ifdef SEQAN_PROFILE
::std::cout << "MSA method" << ::std::endl;
::std::cout << "Bandwidth: " << consOpt.bandwidth << ::std::endl;
::std::cout << "Matchlength: " << consOpt.matchlength << ::std::endl;
::std::cout << "Quality: " << consOpt.quality << ::std::endl;
::std::cout << "Overlaps: " << consOpt.overlaps << ::std::endl;
::std::cout << "Window: " << consOpt.window << ::std::endl;
#endif
// Import all reads of the given contig
typedef TFragmentStore::TReadSeq TReadSeq;
StringSet<TReadSeq, Owner<> > readSet;
String<Pair<TSize, TSize> > begEndPos;
_loadContigReads(readSet, begEndPos, fragStore, currentContig);
if (!length(readSet)) continue;
#ifdef SEQAN_PROFILE
::std::cout << "Import sequences done: " << SEQAN_PROTIMEUPDATE(__myProfileTime) << " seconds" << ::std::endl;
#endif
// Align the reads
typedef StringSet<TReadSeq, Dependent<> > TStringSet;
typedef Graph<Alignment<TStringSet, void, WithoutEdgeId> > TAlignGraph;
TAlignGraph gOut(readSet);
consensusAlignment(gOut, begEndPos, consOpt);
#ifdef SEQAN_PROFILE
std::cout << "Multi-read Alignment done: " << SEQAN_PROTIMEUPDATE(__myProfileTime) << " seconds" << std::endl;
#endif
// Update the contig in the fragment store
updateContig(fragStore, gOut, currentContig);
clear(gOut);
#ifdef SEQAN_PROFILE
std::cout << "Update contig done: " << SEQAN_PROTIMEUPDATE(__myProfileTime) << " seconds" << std::endl;
#endif
//// Debug code for CA
//mtRandInit();
//String<char> fileTmp1 = "tmp1";
//String<char> fileTmp2 = "tmp2";
//for(int i = 0; i<10; ++i) {
// int file = (mtRand() % 20) + 65;
// appendValue(fileTmp1, char(file));
// appendValue(fileTmp2, char(file));
//}
//std::fstream strm3;
//strm3.open(toCString(fileTmp2), std::ios_base::out | std::ios_base::trunc);
//for(int i = 0;i<(int) length(origStrSet); ++i) {
// std::stringstream name;
// name << value(begEndPos, i).i1 << "," << value(begEndPos, i).i2;
// String<char> myTitle = name.str();
// write(strm3, origStrSet[i], myTitle, Fasta());
// if (value(begEndPos, i).i1 > value(begEndPos, i).i2) reverseComplementInPlace(origStrSet[i]);
//}
//strm3.close();
}
#ifdef SEQAN_PROFILE
if (consOpt.consensus == 0) ::std::cout << "Consensus calling: Majority vote" << ::std::endl;
else if (consOpt.consensus == 1) ::std::cout << "Consensus calling: Bayesian" << ::std::endl;
#endif
if (consOpt.consensus == 0) consensusCalling(fragStore, currentContig, Majority_Vote() );
else if (consOpt.consensus == 1) consensusCalling(fragStore, currentContig, Bayesian() );
#ifdef SEQAN_PROFILE
std::cout << "Consensus calling done: " << SEQAN_PROTIMEUPDATE(__myProfileTime) << " seconds" << std::endl;
#endif
} // end loop over all contigs
}
// Output
if (consOpt.output == 0) {
// Write old SeqAn multi-read alignment format
FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w");
write(strmWrite, fragStore, FastaReadFormat());
fclose(strmWrite);
} else if (consOpt.output == 1) {
// Write Amos
FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w");
write(strmWrite, fragStore, Amos());
fclose(strmWrite);
} else if (consOpt.output == 2) {
FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w");
_writeCeleraFrg(strmWrite, fragStore);
fclose(strmWrite);
} else if (consOpt.output == 3) {
FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w");
_writeCeleraCgb(strmWrite, fragStore);
fclose(strmWrite);
}
return 0;
}
<commit_msg><commit_after>/*==========================================================================
SeqAn - The Library for Sequence Analysis
http://www.seqan.de
============================================================================
Copyright (C) 2007
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 3 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.
==========================================================================*/
#define SEQAN_PROFILE
#include <seqan/basic.h>
// Profiling
#ifdef SEQAN_PROFILE
SEQAN_PROTIMESTART(__myProfileTime);
#endif
#include <seqan/consensus.h>
#include <seqan/modifier.h>
#include <seqan/misc/misc_cmdparser.h>
#include <iostream>
#include <fstream>
using namespace seqan;
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
inline void
_addVersion(CommandLineParser& parser) {
::std::string rev = "$Revision: 4637 $";
addVersionLine(parser, "Version 0.21 (31. July 2009) Revision: " + rev.substr(11, 4) + "");
}
//////////////////////////////////////////////////////////////////////////////////
int main(int argc, const char *argv[]) {
// Command line parsing
CommandLineParser parser;
_addVersion(parser);
addTitleLine(parser, "***************************************");
addTitleLine(parser, "* Multi-read alignment - SeqCons *");
addTitleLine(parser, "* (c) Copyright 2009 by Tobias Rausch *");
addTitleLine(parser, "***************************************");
addUsageLine(parser, "-r <FASTA file with reads> [Options]");
addUsageLine(parser, "-a <AMOS message file> [Options]");
addSection(parser, "Main Options:");
addOption(parser, addArgumentText(CommandLineOption("r", "reads", "file with reads", OptionType::String), "<FASTA reads file>"));
addOption(parser, addArgumentText(CommandLineOption("a", "afg", "message file", OptionType::String), "<AMOS afg file>"));
addOption(parser, addArgumentText(CommandLineOption("o", "outfile", "output filename", OptionType::String, "align.txt"), "<Filename>"));
addOption(parser, addArgumentText(CommandLineOption("f", "format", "output format", OptionType::String, "seqan"), "[seqan | afg]"));
addOption(parser, addArgumentText(CommandLineOption("m", "method", "multi-read alignment method", OptionType::String, "realign"), "[realign | msa]"));
addOption(parser, addArgumentText(CommandLineOption("b", "bandwidth", "bandwidth", OptionType::Int, 8), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("c", "consensus", "consensus calling", OptionType::String, "majority"), "[majority | bayesian]"));
addOption(parser, CommandLineOption("n", "noalign", "no align, only convert input", OptionType::Boolean));
addSection(parser, "MSA Method Options:");
addOption(parser, addArgumentText(CommandLineOption("ma", "matchlength", "minimum overlap length", OptionType::Int, 15), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("qu", "quality", "minimum overlap precent identity", OptionType::Int, 80), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("ov", "overlaps", "minimum number of overlaps per read", OptionType::Int, 3), "<Int>"));
addOption(parser, addArgumentText(CommandLineOption("wi", "window", "window size", OptionType::Int, 0), "<Int>"));
addHelpLine(parser, "/*If this parameter is > 0 then all");
addHelpLine(parser, " overlaps within a given window");
addHelpLine(parser, " are computed.*/");
addSection(parser, "ReAlign Method Options:");
addOption(parser, CommandLineOption("in", "include", "include contig sequence", OptionType::Boolean));
addOption(parser, addArgumentText(CommandLineOption("rm", "rmethod", "realign method", OptionType::String, "gotoh"), "[nw | gotoh]"));
if (argc == 1)
{
shortHelp(parser, std::cerr); // print short help and exit
return 0;
}
if (!parse(parser, argc, argv, ::std::cerr)) return 1;
if (isSetLong(parser, "help") || isSetLong(parser, "version")) return 0; // print help or version and exit
// Get all command line options
ConsensusOptions consOpt;
// Main options
getOptionValueLong(parser, "reads", consOpt.readsfile);
getOptionValueLong(parser, "afg", consOpt.afgfile);
getOptionValueLong(parser, "outfile", consOpt.outfile);
String<char> optionVal;
getOptionValueLong(parser, "format", optionVal);
if (optionVal == "seqan") consOpt.output = 0;
else if (optionVal == "afg") consOpt.output = 1;
else if (optionVal == "frg") consOpt.output = 2;
else if (optionVal == "cgb") consOpt.output = 3;
getOptionValueLong(parser, "method", optionVal);
if (optionVal == "realign") consOpt.method = 0;
else if (optionVal == "msa") consOpt.method = 1;
getOptionValueLong(parser, "bandwidth", consOpt.bandwidth);
#ifdef CELERA_OFFSET
if (!isSetLong(parser, "bandwidth")) consOpt.bandwidth = 15;
#endif
getOptionValueLong(parser, "consensus", optionVal);
if (optionVal == "majority") consOpt.consensus = 0;
else if (optionVal == "bayesian") consOpt.consensus = 1;
getOptionValueLong(parser, "noalign", consOpt.noalign);
// Msa options
getOptionValueLong(parser, "matchlength", consOpt.matchlength);
getOptionValueLong(parser, "quality", consOpt.quality);
getOptionValueLong(parser, "overlaps", consOpt.overlaps);
#ifdef CELERA_OFFSET
if (!isSetLong(parser, "overlaps")) consOpt.overlaps = 5;
#endif
getOptionValueLong(parser, "window", consOpt.window);
// ReAlign options
getOptionValueLong(parser, "include", consOpt.include);
getOptionValueLong(parser, "rmethod", optionVal);
if (optionVal == "nw") consOpt.rmethod = 0;
else if (optionVal == "gotoh") consOpt.rmethod = 1;
// Create a new fragment store
typedef FragmentStore<> TFragmentStore;
typedef Size<TFragmentStore>::Type TSize;
TFragmentStore fragStore;
// Load the reads and layout positions
TSize numberOfContigs = 0;
if (!empty(consOpt.readsfile)) {
// Load simple read file
FILE* strmReads = fopen(consOpt.readsfile.c_str(), "rb");
bool success = _convertSimpleReadFile(strmReads, fragStore, consOpt.readsfile, true);
fclose(strmReads);
if (!success) {
shortHelp(parser, std::cerr);
return 0;
}
numberOfContigs = 1;
} else if (!empty(consOpt.afgfile)) {
// Load Amos message file
FILE* strmReads = fopen(consOpt.afgfile.c_str(), "rb");
read(strmReads, fragStore, Amos());
fclose(strmReads);
numberOfContigs = length(fragStore.contigStore);
} else {
shortHelp(parser, std::cerr);
return 0;
}
// Multi-realignment desired or just conversion of the input
if (!consOpt.noalign) {
// Profiling
#ifdef SEQAN_PROFILE
SEQAN_PROTIMEUPDATE(__myProfileTime);
#endif
// Iterate over all contigs
for(TSize currentContig = 0; currentContig < numberOfContigs; ++currentContig) {
if (consOpt.method == 0) {
#ifdef SEQAN_PROFILE
::std::cout << "ReAlign method" << ::std::endl;
if (consOpt.rmethod == 0) ::std::cout << "Realign algorithm: Needleman-Wunsch" << ::std::endl;
else if (consOpt.rmethod == 1) ::std::cout << "Realign algorithm: Gotoh" << ::std::endl;
::std::cout << "Bandwidth: " << consOpt.bandwidth << ::std::endl;
::std::cout << "Include reference: " << consOpt.include << ::std::endl;
#endif
Score<int, WeightedConsensusScore<Score<int, FractionalScore>, Score<int, ConsensusScore> > > combinedScore;
reAlign(fragStore, combinedScore, currentContig, consOpt.rmethod, consOpt.bandwidth, consOpt.include);
#ifdef SEQAN_PROFILE
::std::cout << "ReAlignment done: " << SEQAN_PROTIMEUPDATE(__myProfileTime) << " seconds" << ::std::endl;
#endif
} else {
#ifdef SEQAN_PROFILE
::std::cout << "MSA method" << ::std::endl;
::std::cout << "Bandwidth: " << consOpt.bandwidth << ::std::endl;
::std::cout << "Matchlength: " << consOpt.matchlength << ::std::endl;
::std::cout << "Quality: " << consOpt.quality << ::std::endl;
::std::cout << "Overlaps: " << consOpt.overlaps << ::std::endl;
::std::cout << "Window: " << consOpt.window << ::std::endl;
#endif
// Import all reads of the given contig
typedef TFragmentStore::TReadSeq TReadSeq;
StringSet<TReadSeq, Owner<> > readSet;
String<Pair<TSize, TSize> > begEndPos;
_loadContigReads(readSet, begEndPos, fragStore, currentContig);
if (!length(readSet)) continue;
#ifdef SEQAN_PROFILE
::std::cout << "Import sequences done: " << SEQAN_PROTIMEUPDATE(__myProfileTime) << " seconds" << ::std::endl;
#endif
// Align the reads
typedef StringSet<TReadSeq, Dependent<> > TStringSet;
typedef Graph<Alignment<TStringSet, void, WithoutEdgeId> > TAlignGraph;
TAlignGraph gOut(readSet);
consensusAlignment(gOut, begEndPos, consOpt);
#ifdef SEQAN_PROFILE
std::cout << "Multi-read Alignment done: " << SEQAN_PROTIMEUPDATE(__myProfileTime) << " seconds" << std::endl;
#endif
// Update the contig in the fragment store
updateContig(fragStore, gOut, currentContig);
clear(gOut);
#ifdef SEQAN_PROFILE
std::cout << "Update contig done: " << SEQAN_PROTIMEUPDATE(__myProfileTime) << " seconds" << std::endl;
#endif
//// Debug code for CA
//mtRandInit();
//String<char> fileTmp1 = "tmp1";
//String<char> fileTmp2 = "tmp2";
//for(int i = 0; i<10; ++i) {
// int file = (mtRand() % 20) + 65;
// appendValue(fileTmp1, char(file));
// appendValue(fileTmp2, char(file));
//}
//std::fstream strm3;
//strm3.open(toCString(fileTmp2), std::ios_base::out | std::ios_base::trunc);
//for(int i = 0;i<(int) length(origStrSet); ++i) {
// std::stringstream name;
// name << value(begEndPos, i).i1 << "," << value(begEndPos, i).i2;
// String<char> myTitle = name.str();
// write(strm3, origStrSet[i], myTitle, Fasta());
// if (value(begEndPos, i).i1 > value(begEndPos, i).i2) reverseComplementInPlace(origStrSet[i]);
//}
//strm3.close();
}
#ifdef SEQAN_PROFILE
if (consOpt.consensus == 0) ::std::cout << "Consensus calling: Majority vote" << ::std::endl;
else if (consOpt.consensus == 1) ::std::cout << "Consensus calling: Bayesian" << ::std::endl;
#endif
if (consOpt.consensus == 0) consensusCalling(fragStore, currentContig, Majority_Vote() );
else if (consOpt.consensus == 1) consensusCalling(fragStore, currentContig, Bayesian() );
#ifdef SEQAN_PROFILE
std::cout << "Consensus calling done: " << SEQAN_PROTIMEUPDATE(__myProfileTime) << " seconds" << std::endl;
#endif
} // end loop over all contigs
}
// Output
if (consOpt.output == 0) {
// Write old SeqAn multi-read alignment format
FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w");
write(strmWrite, fragStore, FastaReadFormat());
fclose(strmWrite);
} else if (consOpt.output == 1) {
// Write Amos
FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w");
write(strmWrite, fragStore, Amos());
fclose(strmWrite);
} else if (consOpt.output == 2) {
FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w");
_writeCeleraFrg(strmWrite, fragStore);
fclose(strmWrite);
} else if (consOpt.output == 3) {
FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w");
_writeCeleraCgb(strmWrite, fragStore);
fclose(strmWrite);
}
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/jit/partially_decluster_pass.h"
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_set.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/compiler/jit/xla_cluster_util.h"
#include "tensorflow/compiler/tf2xla/const_analysis.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/framework/memory_types.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
namespace tensorflow {
namespace {
bool NotBackedge(const Edge& edge) { return !edge.src()->IsNextIteration(); }
namespace reduce_device_to_host_copies {
Status FindNodesToDecluster(const Graph& graph,
absl::flat_hash_set<Node*>* result,
absl::Span<Node* const> post_order) {
// Find nodes that have at least one user outside their cluster that expects
// hostmem output. These nodes should be cloned to outside the cluster to
// avoid the device-host copy we'd otherwise need.
MemoryTypeVector input_mtypes, output_mtypes;
for (Node* n : post_order) {
absl::optional<absl::string_view> from_cluster = GetXlaClusterForNode(*n);
if (!from_cluster) {
continue;
}
// We assume the only XLA-auto-clusterable operations with side effects are
// resource variable updates. We can't execute these twice.
if (HasResourceInputOrOutput(*n)) {
continue;
}
DeviceType device_type("");
TF_RETURN_IF_ERROR(
DeviceToDeviceType(n->assigned_device_name(), &device_type));
TF_RETURN_IF_ERROR(MemoryTypesForNode(graph.op_registry(), device_type,
n->def(), &input_mtypes,
&output_mtypes));
for (const Edge* e : n->out_edges()) {
Node* dst = e->dst();
if (e->IsControlEdge()) {
continue;
}
bool edge_incurs_extra_device_to_host_copy;
if (output_mtypes[e->src_output()] == DEVICE_MEMORY) {
// If the output of the *TensorFlow* operation is in DEVICE_MEMORY then
// keep the node clustered -- XLA will also produce the output in device
// memory and we will get some benefit from clustering.
edge_incurs_extra_device_to_host_copy = false;
} else {
MemoryTypeVector dst_input_mtypes, dst_output_mtypes;
DeviceType dst_device_type("");
TF_RETURN_IF_ERROR(
DeviceToDeviceType(dst->assigned_device_name(), &dst_device_type));
TF_RETURN_IF_ERROR(MemoryTypesForNode(graph.op_registry(), device_type,
dst->def(), &dst_input_mtypes,
&dst_output_mtypes));
edge_incurs_extra_device_to_host_copy =
dst_input_mtypes[e->dst_input()] == HOST_MEMORY;
}
if (!edge_incurs_extra_device_to_host_copy) {
continue;
}
// Check if `dst` is in a different cluster, unclustered, or about to be
// partially declustered (here we rely on the post-order traversal order).
// If yes, decluster `n` to avoid the device-to-host memcpy.
absl::optional<absl::string_view> dst_cluster =
result->count(dst) ? absl::nullopt : GetXlaClusterForNode(*dst);
if (from_cluster != dst_cluster) {
CHECK(result->insert(n).second);
break;
}
}
}
return Status::OK();
}
Status PartiallyDeclusterNode(Graph* graph, Node* n) {
absl::string_view cluster_name = *GetXlaClusterForNode(*n);
absl::InlinedVector<const Edge*, 6> out_edges_to_clone;
for (const Edge* out_edge : n->out_edges()) {
if (out_edge->IsControlEdge()) {
continue;
}
Node* dst = out_edge->dst();
absl::optional<absl::string_view> dst_cluster_name =
GetXlaClusterForNode(*dst);
if (dst_cluster_name != cluster_name) {
out_edges_to_clone.push_back(out_edge);
}
}
CHECK(!out_edges_to_clone.empty()) << n->DebugString();
NodeDef ndef = n->def();
ndef.set_name(absl::StrCat(n->name(), "/declustered"));
MergeDebugInfo(NodeDebugInfo(n->def()), &ndef);
RemoveFromXlaCluster(&ndef);
Status s;
Node* cloned_node = graph->AddNode(ndef, &s);
cloned_node->set_assigned_device_name(n->assigned_device_name());
TF_RETURN_IF_ERROR(s);
for (const Edge* in_edge : n->in_edges()) {
graph->AddEdge(in_edge->src(), in_edge->src_output(), cloned_node,
in_edge->dst_input());
}
for (const Edge* out_edge_to_clone : out_edges_to_clone) {
graph->AddEdge(cloned_node, out_edge_to_clone->src_output(),
out_edge_to_clone->dst(), out_edge_to_clone->dst_input());
graph->RemoveEdge(out_edge_to_clone);
}
if (n->out_edges().empty()) {
graph->RemoveNode(n);
}
return Status::OK();
}
// Clones nodes to outside their cluster to avoid device-to-host copies. For
// instance, converts this:
//
// .....
// |
// v
// A_Clustered ====> C_Unclustered
// |
// v
// B_Clustered
//
// to:
//
// .....
// | |
// | +-------------+
// | |
// v v
// A_Clustered A_Unclustered ====> C_Unclustered
// |
// v
// B_Clustered
//
// where the ===> arrow has a hostmem source and destination and would entail a
// device to host copy if the source and destination were not in the same XLA
// cluster.
Status PartiallyDeclusterGraph(Graph* graph) {
// When deciding whether to decluster a particular node, we base our decision
// on if we've decided that some of its consumers have to be declustered too.
// Iterating the graph in post-order guarantees that consumers have been
// visited before producers.
std::vector<Node*> post_order;
GetPostOrder(*graph, &post_order, /*stable_comparator=*/NodeComparatorName(),
/*edge_filter=*/NotBackedge);
absl::flat_hash_set<Node*> nodes_to_partially_decluster;
TF_RETURN_IF_ERROR(
FindNodesToDecluster(*graph, &nodes_to_partially_decluster, post_order));
if (VLOG_IS_ON(3)) {
for (Node* n : post_order) {
if (nodes_to_partially_decluster.count(n)) {
VLOG(3) << n->DebugString();
}
}
}
for (Node* n : post_order) {
if (nodes_to_partially_decluster.count(n)) {
TF_RETURN_IF_ERROR(PartiallyDeclusterNode(graph, n));
}
}
// Recompute post order since PartiallyDeclusterNode may have deleted nodes.
post_order.clear();
GetPostOrder(*graph, &post_order, /*stable_comparator=*/NodeComparatorName(),
/*edge_filter=*/NotBackedge);
nodes_to_partially_decluster.clear();
TF_RETURN_IF_ERROR(
FindNodesToDecluster(*graph, &nodes_to_partially_decluster, post_order));
CHECK(nodes_to_partially_decluster.empty());
return Status::OK();
}
} // namespace reduce_device_to_host_copies
namespace reduce_recompilation {
bool IsIntraClusterEdge(const Edge& edge) {
absl::optional<absl::string_view> src_cluster_name =
GetXlaClusterForNode(*edge.src());
absl::optional<absl::string_view> dst_cluster_name =
GetXlaClusterForNode(*edge.dst());
return src_cluster_name.has_value() && src_cluster_name == dst_cluster_name;
}
bool IsMustCompileDevice(const DeviceType& device_type) {
const XlaOpRegistry::DeviceRegistration* registration;
if (XlaOpRegistry::GetCompilationDevice(device_type.type(), ®istration)) {
return registration->autoclustering_policy ==
XlaOpRegistry::AutoclusteringPolicy::kAlways;
}
return false;
}
Status MustCompileNode(const Node* n, bool* must_compile) {
DeviceType device_type("");
TF_RETURN_IF_ERROR(
DeviceToDeviceType(n->assigned_device_name(), &device_type));
if (IsMustCompileDevice(device_type)) {
*must_compile = true;
return Status::OK();
}
// We must compile `n` if it does not have a TensorFlow kernel.
*must_compile = !FindKernelDef(device_type, n->def(), nullptr, nullptr).ok();
return Status::OK();
}
// Declusters nodes to reduce the number of times we think we need to recompile
// a TensorFlow graph.
//
// Abstractly, if we have a cluster of this form:
//
// x0 = arg0
// x1 = arg1
// ...
// shape = f(x0, x1, ...)
// result = Reshape(input=<something>, new_shape=shape)
//
// then pulling `f` out of the cluster may reduce the number of compilations and
// will never increase the number of compilations.
//
// We may reduce the number of compilations if f is many to one. For instance
// if f(x,y) = x-y then x=3,y=1 and x=4,y=2 will generate two different
// compilations if f is in the cluster but only one compilation if f is outside
// the cluster.
//
// Declustering f will increase the number of compilations only if f is a
// one-to-many "function" i.e. isn't a function at all. RNG is one possible
// example, depending on how we look at it. But we never create clusters where
// such f's would be marked as must-be-constant.
//
// We assume here that the extra repeated (repeated compared to a clustered f
// where it will always be constant folded) host-side computation of f does not
// regress performance in any significant manner. We will have to revisit this
// algorith with a more complex cost model if this assumption turns out to be
// incorrect.
Status PartiallyDeclusterGraph(Graph* graph) {
std::vector<bool> compile_time_const_nodes(graph->num_node_ids());
TF_RETURN_IF_ERROR(BackwardsConstAnalysis(
*graph, nullptr, &compile_time_const_nodes, IsIntraClusterEdge));
std::vector<Node*> rpo;
GetReversePostOrder(*graph, &rpo, /*stable_comparator=*/NodeComparatorName(),
/*edge_filter=*/NotBackedge);
for (Node* n : rpo) {
if (!compile_time_const_nodes[n->id()]) {
continue;
}
absl::string_view cluster_name = *GetXlaClusterForNode(*n);
bool node_on_cluster_edge =
absl::c_all_of(n->in_edges(), [&](const Edge* e) {
absl::optional<absl::string_view> incoming_cluster =
GetXlaClusterForNode(*e->src());
return !incoming_cluster || *incoming_cluster != cluster_name;
});
// We don't want to decluster F in a graph like
//
// Input -> OP -> Shape -> F -> Reshape
//
// Doing so will break up the cluster. Even if we were okay with breaking
// up the cluster we will at least have to relabel the two clusters to have
// different cluster names.
//
// We may want to revisit this in the future: we may have cases where OP is
// a small computation that does not benefit from XLA while XLA can optimize
// everything that follows the Reshape. In these cases it may be wise to
// remove Input, OP, Shape and F from the cluster, if F is a many-to-one
// function.
//
// Note that we do do the right thing for graphs like:
//
// Input -> F0 -> F1 -> Reshape
//
// Since we iterate in RPO, we'll first encounter F0, decluster it, then
// encounter F1, decluster it and so on.
if (node_on_cluster_edge) {
bool must_compile_node;
TF_RETURN_IF_ERROR(MustCompileNode(n, &must_compile_node));
if (!must_compile_node) {
VLOG(3) << "Declustering must-be-constant node " << n->name();
RemoveFromXlaCluster(n);
}
}
}
return Status::OK();
}
} // namespace reduce_recompilation
} // namespace
Status PartiallyDeclusterPass::Run(
const GraphOptimizationPassOptions& options) {
// NB! In this pass we assume the only XLA-auto-clusterable operations that
// may have side effects are resource variable operations so we don't cluster
// those. The pass will have to be updated if this assumption becomes
// invalid.
Graph* graph = options.graph->get();
TF_RETURN_IF_ERROR(
reduce_device_to_host_copies::PartiallyDeclusterGraph(graph));
TF_RETURN_IF_ERROR(reduce_recompilation::PartiallyDeclusterGraph(graph));
return Status::OK();
}
} // namespace tensorflow
<commit_msg>Update partially_decluster_pass.cc<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/jit/partially_decluster_pass.h"
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_set.h"
#include "absl/strings/str_cat.h"
#include "tensorflow/compiler/jit/xla_cluster_util.h"
#include "tensorflow/compiler/tf2xla/const_analysis.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/framework/memory_types.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
namespace tensorflow {
namespace {
bool NotBackedge(const Edge& edge) { return !edge.src()->IsNextIteration(); }
namespace reduce_device_to_host_copies {
Status FindNodesToDecluster(const Graph& graph,
absl::flat_hash_set<Node*>* result,
absl::Span<Node* const> post_order) {
// Find nodes that have at least one user outside their cluster that expects
// hostmem output. These nodes should be cloned to outside the cluster to
// avoid the device-host copy we'd otherwise need.
MemoryTypeVector input_mtypes, output_mtypes;
for (Node* n : post_order) {
absl::optional<absl::string_view> from_cluster = GetXlaClusterForNode(*n);
if (!from_cluster) {
continue;
}
// We assume the only XLA-auto-clusterable operations with side effects are
// resource variable updates. We can't execute these twice.
if (HasResourceInputOrOutput(*n)) {
continue;
}
DeviceType device_type("");
TF_RETURN_IF_ERROR(
DeviceToDeviceType(n->assigned_device_name(), &device_type));
TF_RETURN_IF_ERROR(MemoryTypesForNode(graph.op_registry(), device_type,
n->def(), &input_mtypes,
&output_mtypes));
for (const Edge* e : n->out_edges()) {
Node* dst = e->dst();
if (e->IsControlEdge()) {
continue;
}
bool edge_incurs_extra_device_to_host_copy;
if (output_mtypes[e->src_output()] == DEVICE_MEMORY) {
// If the output of the *TensorFlow* operation is in DEVICE_MEMORY then
// keep the node clustered -- XLA will also produce the output in device
// memory and we will get some benefit from clustering.
edge_incurs_extra_device_to_host_copy = false;
} else {
MemoryTypeVector dst_input_mtypes, dst_output_mtypes;
DeviceType dst_device_type("");
TF_RETURN_IF_ERROR(
DeviceToDeviceType(dst->assigned_device_name(), &dst_device_type));
TF_RETURN_IF_ERROR(MemoryTypesForNode(graph.op_registry(), device_type,
dst->def(), &dst_input_mtypes,
&dst_output_mtypes));
edge_incurs_extra_device_to_host_copy =
dst_input_mtypes[e->dst_input()] == HOST_MEMORY;
}
if (!edge_incurs_extra_device_to_host_copy) {
continue;
}
// Check if `dst` is in a different cluster, unclustered, or about to be
// partially declustered (here we rely on the post-order traversal order).
// If yes, decluster `n` to avoid the device-to-host memcpy.
absl::optional<absl::string_view> dst_cluster =
result->count(dst) ? absl::nullopt : GetXlaClusterForNode(*dst);
if (from_cluster != dst_cluster) {
CHECK(result->insert(n).second);
break;
}
}
}
return Status::OK();
}
Status PartiallyDeclusterNode(Graph* graph, Node* n) {
absl::string_view cluster_name = *GetXlaClusterForNode(*n);
absl::InlinedVector<const Edge*, 6> out_edges_to_clone;
for (const Edge* out_edge : n->out_edges()) {
if (out_edge->IsControlEdge()) {
continue;
}
Node* dst = out_edge->dst();
absl::optional<absl::string_view> dst_cluster_name =
GetXlaClusterForNode(*dst);
if (dst_cluster_name != cluster_name) {
out_edges_to_clone.push_back(out_edge);
}
}
CHECK(!out_edges_to_clone.empty()) << n->DebugString();
NodeDef ndef = n->def();
ndef.set_name(absl::StrCat(n->name(), "/declustered"));
MergeDebugInfo(NodeDebugInfo(n->def()), &ndef);
RemoveFromXlaCluster(&ndef);
Status s;
Node* cloned_node = graph->AddNode(ndef, &s);
cloned_node->set_assigned_device_name(n->assigned_device_name());
TF_RETURN_IF_ERROR(s);
for (const Edge* in_edge : n->in_edges()) {
graph->AddEdge(in_edge->src(), in_edge->src_output(), cloned_node,
in_edge->dst_input());
}
for (const Edge* out_edge_to_clone : out_edges_to_clone) {
graph->AddEdge(cloned_node, out_edge_to_clone->src_output(),
out_edge_to_clone->dst(), out_edge_to_clone->dst_input());
graph->RemoveEdge(out_edge_to_clone);
}
if (n->out_edges().empty()) {
graph->RemoveNode(n);
}
return Status::OK();
}
// Clones nodes to outside their cluster to avoid device-to-host copies. For
// instance, converts this:
//
// .....
// |
// v
// A_Clustered ====> C_Unclustered
// |
// v
// B_Clustered
//
// to:
//
// .....
// | |
// | +-------------+
// | |
// v v
// A_Clustered A_Unclustered ====> C_Unclustered
// |
// v
// B_Clustered
//
// where the ===> arrow has a hostmem source and destination and would entail a
// device to host copy if the source and destination were not in the same XLA
// cluster.
Status PartiallyDeclusterGraph(Graph* graph) {
// When deciding whether to decluster a particular node, we base our decision
// on if we've decided that some of its consumers have to be declustered too.
// Iterating the graph in post-order guarantees that consumers have been
// visited before producers.
std::vector<Node*> post_order;
GetPostOrder(*graph, &post_order, /*stable_comparator=*/NodeComparatorName(),
/*edge_filter=*/NotBackedge);
absl::flat_hash_set<Node*> nodes_to_partially_decluster;
TF_RETURN_IF_ERROR(
FindNodesToDecluster(*graph, &nodes_to_partially_decluster, post_order));
if (VLOG_IS_ON(3)) {
for (Node* n : post_order) {
if (nodes_to_partially_decluster.count(n)) {
VLOG(3) << n->DebugString();
}
}
}
for (Node* n : post_order) {
if (nodes_to_partially_decluster.count(n)) {
TF_RETURN_IF_ERROR(PartiallyDeclusterNode(graph, n));
}
}
// Recompute post order since PartiallyDeclusterNode may have deleted nodes.
post_order.clear();
GetPostOrder(*graph, &post_order, /*stable_comparator=*/NodeComparatorName(),
/*edge_filter=*/NotBackedge);
nodes_to_partially_decluster.clear();
TF_RETURN_IF_ERROR(
FindNodesToDecluster(*graph, &nodes_to_partially_decluster, post_order));
CHECK(nodes_to_partially_decluster.empty());
return Status::OK();
}
} // namespace reduce_device_to_host_copies
namespace reduce_recompilation {
bool IsIntraClusterEdge(const Edge& edge) {
absl::optional<absl::string_view> src_cluster_name =
GetXlaClusterForNode(*edge.src());
absl::optional<absl::string_view> dst_cluster_name =
GetXlaClusterForNode(*edge.dst());
return src_cluster_name.has_value() && src_cluster_name == dst_cluster_name;
}
bool IsMustCompileDevice(const DeviceType& device_type) {
const XlaOpRegistry::DeviceRegistration* registration;
if (XlaOpRegistry::GetCompilationDevice(device_type.type(), ®istration)) {
return registration->autoclustering_policy ==
XlaOpRegistry::AutoclusteringPolicy::kAlways;
}
return false;
}
Status MustCompileNode(const Node* n, bool* must_compile) {
DeviceType device_type("");
TF_RETURN_IF_ERROR(
DeviceToDeviceType(n->assigned_device_name(), &device_type));
if (IsMustCompileDevice(device_type)) {
*must_compile = true;
return Status::OK();
}
// We must compile `n` if it does not have a TensorFlow kernel.
*must_compile = !FindKernelDef(device_type, n->def(), nullptr, nullptr).ok();
return Status::OK();
}
// Declusters nodes to reduce the number of times we think we need to recompile
// a TensorFlow graph.
//
// Abstractly, if we have a cluster of this form:
//
// x0 = arg0
// x1 = arg1
// ...
// shape = f(x0, x1, ...)
// result = Reshape(input=<something>, new_shape=shape)
//
// then pulling `f` out of the cluster may reduce the number of compilations and
// will never increase the number of compilations.
//
// We may reduce the number of compilations if f is many to one. For instance
// if f(x,y) = x-y then x=3,y=1 and x=4,y=2 will generate two different
// compilations if f is in the cluster but only one compilation if f is outside
// the cluster.
//
// Declustering f will increase the number of compilations only if f is a
// one-to-many "function" i.e. isn't a function at all. RNG is one possible
// example, depending on how we look at it. But we never create clusters where
// such f's would be marked as must-be-constant.
//
// We assume here that the extra repeated (repeated compared to a clustered f
// where it will always be constant folded) host-side computation of f does not
// regress performance in any significant manner. We will have to revisit this
// algorithm with a more complex cost model if this assumption turns out to be
// incorrect.
Status PartiallyDeclusterGraph(Graph* graph) {
std::vector<bool> compile_time_const_nodes(graph->num_node_ids());
TF_RETURN_IF_ERROR(BackwardsConstAnalysis(
*graph, nullptr, &compile_time_const_nodes, IsIntraClusterEdge));
std::vector<Node*> rpo;
GetReversePostOrder(*graph, &rpo, /*stable_comparator=*/NodeComparatorName(),
/*edge_filter=*/NotBackedge);
for (Node* n : rpo) {
if (!compile_time_const_nodes[n->id()]) {
continue;
}
absl::string_view cluster_name = *GetXlaClusterForNode(*n);
bool node_on_cluster_edge =
absl::c_all_of(n->in_edges(), [&](const Edge* e) {
absl::optional<absl::string_view> incoming_cluster =
GetXlaClusterForNode(*e->src());
return !incoming_cluster || *incoming_cluster != cluster_name;
});
// We don't want to decluster F in a graph like
//
// Input -> OP -> Shape -> F -> Reshape
//
// Doing so will break up the cluster. Even if we were okay with breaking
// up the cluster we will at least have to relabel the two clusters to have
// different cluster names.
//
// We may want to revisit this in the future: we may have cases where OP is
// a small computation that does not benefit from XLA while XLA can optimize
// everything that follows the Reshape. In these cases it may be wise to
// remove Input, OP, Shape and F from the cluster, if F is a many-to-one
// function.
//
// Note that we do do the right thing for graphs like:
//
// Input -> F0 -> F1 -> Reshape
//
// Since we iterate in RPO, we'll first encounter F0, decluster it, then
// encounter F1, decluster it and so on.
if (node_on_cluster_edge) {
bool must_compile_node;
TF_RETURN_IF_ERROR(MustCompileNode(n, &must_compile_node));
if (!must_compile_node) {
VLOG(3) << "Declustering must-be-constant node " << n->name();
RemoveFromXlaCluster(n);
}
}
}
return Status::OK();
}
} // namespace reduce_recompilation
} // namespace
Status PartiallyDeclusterPass::Run(
const GraphOptimizationPassOptions& options) {
// NB! In this pass we assume the only XLA-auto-clusterable operations that
// may have side effects are resource variable operations so we don't cluster
// those. The pass will have to be updated if this assumption becomes
// invalid.
Graph* graph = options.graph->get();
TF_RETURN_IF_ERROR(
reduce_device_to_host_copies::PartiallyDeclusterGraph(graph));
TF_RETURN_IF_ERROR(reduce_recompilation::PartiallyDeclusterGraph(graph));
return Status::OK();
}
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2017 QReal Research Group
*
* 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 "structuralControlFlowGenerator.h"
#include <QtCore/QQueue>
#include <QtCore/QDebug>
#include <algorithm>
using namespace qReal;
using namespace generatorBase;
using namespace semantics;
StructuralControlFlowGenerator::StructuralControlFlowGenerator(const qrRepo::RepoApi &repo
, ErrorReporterInterface &errorReporter
, GeneratorCustomizer &customizer
, PrimaryControlFlowValidator &validator
, const Id &diagramId
, QObject *parent
, bool isThisDiagramMain)
: ControlFlowGeneratorBase(repo, errorReporter, customizer, validator, diagramId, parent, isThisDiagramMain)
, mStructurizator(nullptr)
{
}
ControlFlowGeneratorBase *StructuralControlFlowGenerator::cloneFor(const Id &diagramId, bool cloneForNewDiagram)
{
StructuralControlFlowGenerator * const copy = new StructuralControlFlowGenerator(mRepo
, mErrorReporter, mCustomizer, (cloneForNewDiagram ? *mValidator.clone() : mValidator)
, diagramId, parent(), false);
return copy;
}
void StructuralControlFlowGenerator::beforeSearch()
{
}
void StructuralControlFlowGenerator::visit(const Id &id, QList<LinkInfo> &links)
{
Q_UNUSED(links)
mIds.insert(id);
}
void StructuralControlFlowGenerator::visitRegular(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitConditional(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitLoop(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitSwitch(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitUnknown(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::afterSearch()
{
}
bool StructuralControlFlowGenerator::cantBeGeneratedIntoStructuredCode() const
{
return mCantBeGeneratedIntoStructuredCode;
}
SemanticTree *StructuralControlFlowGenerator::generate(const Id &initialNode, const QString &threadId)
{
ControlFlowGeneratorBase::generate(initialNode, threadId);
return mSemanticTree;
}
void StructuralControlFlowGenerator::performGeneration()
{
//isPerformingGeneration = false;
mCantBeGeneratedIntoStructuredCode = false;
ControlFlowGeneratorBase::performGeneration();
mStructurizator = new Structurizator(mRepo, mIds, this);
myUtils::IntermediateNode *tree = mStructurizator->performStructurization();
obtainSemanticTree(tree);
}
void StructuralControlFlowGenerator::obtainSemanticTree(myUtils::IntermediateNode *root)
{
Q_UNUSED(root)
}
// maybe use strategy to recursively handle this situation?
SemanticNode *StructuralControlFlowGenerator::transformNode(const myUtils::IntermediateNode *node)
{
switch (node->type()) {
case myUtils::IntermediateNode::Type::simple:
return transformSimple(node);
case myUtils::IntermediateNode::Type::block:
return transformBlock(node);
case myUtils::IntermediateNode::Type::ifThenElseCondition:
return transformIfThenElse(node);
default:
return nullptr;
}
}
SemanticNode *StructuralControlFlowGenerator::transformSimple(const myUtils::IntermediateNode *node)
{
const myUtils::SimpleNode *simpleNode = dynamic_cast<const myUtils::SimpleNode *>(node);
return mSemanticTree->produceNodeFor(simpleNode->id());
}
SemanticNode *StructuralControlFlowGenerator::transformBlock(const myUtils::IntermediateNode *node)
{
const myUtils::BlockNode *blockNode = dynamic_cast<const myUtils::BlockNode *>(node);
ZoneNode *zone = new ZoneNode(mSemanticTree);
if (blockNode->firstNode()->type() == myUtils::IntermediateNode::simple) {
const myUtils::SimpleNode *simpleNode = dynamic_cast<const myUtils::SimpleNode *>(blockNode->firstNode());
switch (semanticsOf(simpleNode->id())) {
case enums::semantics::conditionalBlock:
case enums::semantics::switchBlock:
break;
default:
zone->appendChild(transformSimple(simpleNode));
}
} else {
zone->appendChild(transformBlock(blockNode->firstNode()));
}
zone->appendChild(transformNode(blockNode->secondNode()));
return zone;
}
SemanticNode *StructuralControlFlowGenerator::transformIfThenElse(const myUtils::IntermediateNode *node)
{
const myUtils::IfNode *ifNode = dynamic_cast<const myUtils::IfNode *>(node);
const qReal::Id conditionId = ifNode->condition()->id();
const qReal::Id thenId = ifNode->thenBranch()->firstId();
switch (semanticsOf(conditionId)) {
case enums::semantics::conditionalBlock: {
IfNode *semanticIf = new IfNode(conditionId, mSemanticTree);
QPair<LinkInfo, LinkInfo> links = ifBranchesFor(conditionId);
if (links.first.target != ifNode->thenBranch()->firstId()) {
semanticIf->invertCondition();
}
semanticIf->thenZone()->appendChild(transformNode(ifNode->thenBranch()));
if (ifNode->elseBranch()) {
semanticIf->elseZone()->appendChild(transformNode(ifNode->elseBranch()));
}
return semanticIf;
}
case enums::semantics::switchBlock: {
SwitchNode *semanticSwitch = new SwitchNode(conditionId, mSemanticTree);
//const qReal::Id
// problem with if-then pattern when "default" branch leads to then
for (const qReal::Id &link : mRepo.outgoingLinks(conditionId)) {
const QString expression = mRepo.property(link, "Guard").toString();
const qReal::Id otherVertex = mRepo.otherEntityFromLink(link, conditionId);
if (otherVertex == thenId) {
semanticSwitch->addBranch(expression, transformNode(ifNode->thenBranch()));
} else {
semanticSwitch->addBranch(expression, transformNode(ifNode->elseBranch()));
}
}
if (ifNode->hasBreakInside()) {
semanticSwitch->generateIfs();
}
return semanticSwitch;
}
case enums::semantics::forkBlock: {
ForkNode *semanticFork = new ForkNode(conditionId, mSemanticTree);
if (!ifNode->elseBranch()) {
qDebug() << "Fork should have all branches";
mCantBeGeneratedIntoStructuredCode = true;
return nullptr;
}
for (const qReal::Id &link : mRepo.outgoingLinks(conditionId)) {
const QString expression = mRepo.property(link, "Guard").toString();
const qReal::Id otherVertex = mRepo.otherEntityFromLink(link, conditionId);
if (otherVertex == thenId) {
semanticFork->appendThread(ifNode->thenBranch()->firstId(), expression);
} else {
semanticFork->appendThread(ifNode->elseBranch()->firstId(), expression);
}
}
return semanticFork;
}
default:
break;
}
qDebug() << "Problem: couldn't transform if-then-else";
mCantBeGeneratedIntoStructuredCode = true;
return nullptr;
}
SemanticNode *StructuralControlFlowGenerator::transformSelfLoop(const myUtils::IntermediateNode *node)
{
const myUtils::SelfLoopNode *selfLoopNode = dynamic_cast<const myUtils::SelfLoopNode *>(node);
LoopNode *semanticLoop = new LoopNode(qReal::Id(), mSemanticTree);
semanticLoop->bodyZone()->appendChild(transformNode(selfLoopNode->bodyNode()));
return semanticLoop;
}
SemanticNode *StructuralControlFlowGenerator::transformWhileLoop(const myUtils::IntermediateNode *node)
{
const myUtils::WhileNode *whileNode = dynamic_cast<const myUtils::WhileNode *>(node);
LoopNode *semanticLoop= nullptr;
if (whileNode->headNode()->type() == myUtils::IntermediateNode::Type::simple
&& semanticsOf(whileNode->headNode()->firstId()) == enums::semantics::conditionalBlock) {
semanticLoop = new LoopNode(whileNode->headNode()->firstId(), mSemanticTree);
} else {
semanticLoop = new LoopNode(qReal::Id(), mSemanticTree);
semanticLoop->bodyZone()->appendChild(transformNode(whileNode->headNode()));
}
semanticLoop->bodyZone()->appendChild(transformNode(whileNode->bodyNode()));
return semanticLoop;
}
SemanticNode *StructuralControlFlowGenerator::transformSwitch(const myUtils::IntermediateNode *node)
{
const myUtils::SwitchNode *switchNode = dynamic_cast<const myUtils::SwitchNode *>(node);
const qReal::Id &conditionId = switchNode->condition()->firstId();
QList<myUtils::IntermediateNode *> branches = switchNode->branches();
if (semanticsOf(conditionId) == enums::semantics::switchBlock) {
SwitchNode *semanticSwitch = new SwitchNode(conditionId, mSemanticTree);
for (const qReal::Id &link : mRepo.outgoingLinks(conditionId)) {
const QString expression = mRepo.property(link, "Guard").toString();
const qReal::Id otherVertex = mRepo.otherEntityFromLink(link, conditionId);
for (const myUtils::IntermediateNode *branchNode : branches) {
if (node->firstId() == otherVertex) {
semanticSwitch->addBranch(expression, transformNode(branchNode));
break;
}
}
}
if (switchNode->hasBreakInside()) {
semanticSwitch->generateIfs();
}
return semanticSwitch;
} else if (semanticsOf(conditionId) == enums::semantics::forkBlock) {
ForkNode *semanticFork = new ForkNode(conditionId, mSemanticTree);
for (const qReal::Id &link : mRepo.outgoingLinks(conditionId)) {
const QString expression = mRepo.property(link, "Expression").toString();
const qReal::Id otherVertex = mRepo.otherEntityFromLink(link, conditionId);
semanticFork->appendThread(otherVertex, expression);
}
return semanticFork;
}
qDebug() << "Problem: couldn't identidy semantics id for switchNode";
mCantBeGeneratedIntoStructuredCode = true;
return nullptr;
}
SemanticNode *StructuralControlFlowGenerator::transformIfWithBreak(const myUtils::IntermediateNode *node)
{
const myUtils::IfWithBreakNode *ifWithBreakNode = dynamic_cast<const myUtils::IfWithBreakNode *>(node);
const qReal::Id conditionId = ifWithBreakNode->condition()->firstId();
if (semanticsOf(conditionId) == enums::semantics::conditionalBlock) {
IfNode *semanticIf= new IfNode(conditionId, mSemanticTree);
QPair<LinkInfo, LinkInfo> branches = ifBranchesFor(conditionId);
if (ifWithBreakNode->actionsBeforeBreak()) {
semanticIf->thenZone()->appendChild(transformNode(ifWithBreakNode->actionsBeforeBreak()));
}
// check inverting condition
if (branches.first.target != ifWithBreakNode->nodeThatIsConnectedWithCondition()->firstId()) {
semanticIf->invertCondition();
}
semanticIf->thenZone()->appendChild(semantics::SimpleNode::createBreakNode(mSemanticTree));
return semanticIf;
} else if (semanticsOf(conditionId) == enums::semantics::switchBlock) {
SwitchNode *semanticSwitch = new SwitchNode(conditionId, mSemanticTree);
// deal with semanticSwitch
return semanticSwitch;
}
qDebug() << "Problem: couldn't identify semantics id for If with break";
mCantBeGeneratedIntoStructuredCode = true;
return nullptr;
}
/*
IfNode *StructuralControlFlowGenerator::createIfFromSwitch(int v, int bodyNumber)
{
qReal::Id vId = mMapVertexLabel.key(v);
bool needInverting = true;
QList<qReal::Id> links;
bool hasDefaultBranch = false;
for (const int edge : mFollowers2[v][bodyNumber]) {
links.append(mEdges[edge]);
if (mRepo.property(mEdges[edge], "Guard").toString().isEmpty()) {
hasDefaultBranch = true;
}
}
if (hasDefaultBranch) {
needInverting = false;
links.clear();
for (const int u : mFollowers2[v].keys()) {
if (u == bodyNumber) {
continue;
}
for (const int edge : mFollowers2[v][u]) {
links.append(mEdges[edge]);
}
}
}
IfNode *ifNode = IfNode::fromSwitchCase(vId, links);
if (needInverting) {
ifNode->invertCondition();
}
ifNode->setCondition(constructConditionFromSwitch(vId, links));
return ifNode;
}
QString StructuralControlFlowGenerator::constructConditionFromSwitch(const Id &id, const QList<Id> &links) const
{
const QString expression = mRepo.property(id, "Expression").toString();
QString condition = "";
for (const qReal::Id &link : links) {
condition += "(" + expression + " == " + mRepo.property(link, "Guard").toString() + ") || ";
}
condition.chop(4);
return condition;
}
*/
<commit_msg>Obtaining tree<commit_after>/* Copyright 2017 QReal Research Group
*
* 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 "structuralControlFlowGenerator.h"
#include <QtCore/QQueue>
#include <QtCore/QDebug>
#include <algorithm>
using namespace qReal;
using namespace generatorBase;
using namespace semantics;
StructuralControlFlowGenerator::StructuralControlFlowGenerator(const qrRepo::RepoApi &repo
, ErrorReporterInterface &errorReporter
, GeneratorCustomizer &customizer
, PrimaryControlFlowValidator &validator
, const Id &diagramId
, QObject *parent
, bool isThisDiagramMain)
: ControlFlowGeneratorBase(repo, errorReporter, customizer, validator, diagramId, parent, isThisDiagramMain)
, mStructurizator(nullptr)
{
}
ControlFlowGeneratorBase *StructuralControlFlowGenerator::cloneFor(const Id &diagramId, bool cloneForNewDiagram)
{
StructuralControlFlowGenerator * const copy = new StructuralControlFlowGenerator(mRepo
, mErrorReporter, mCustomizer, (cloneForNewDiagram ? *mValidator.clone() : mValidator)
, diagramId, parent(), false);
return copy;
}
void StructuralControlFlowGenerator::beforeSearch()
{
}
void StructuralControlFlowGenerator::visit(const Id &id, QList<LinkInfo> &links)
{
Q_UNUSED(links)
mIds.insert(id);
}
void StructuralControlFlowGenerator::visitRegular(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitConditional(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitLoop(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitSwitch(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::visitUnknown(const Id &id, const QList<LinkInfo> &links)
{
Q_UNUSED(id)
Q_UNUSED(links)
}
void StructuralControlFlowGenerator::afterSearch()
{
}
bool StructuralControlFlowGenerator::cantBeGeneratedIntoStructuredCode() const
{
return mCantBeGeneratedIntoStructuredCode;
}
SemanticTree *StructuralControlFlowGenerator::generate(const Id &initialNode, const QString &threadId)
{
ControlFlowGeneratorBase::generate(initialNode, threadId);
return mSemanticTree;
}
void StructuralControlFlowGenerator::performGeneration()
{
//isPerformingGeneration = false;
mCantBeGeneratedIntoStructuredCode = false;
ControlFlowGeneratorBase::performGeneration();
mStructurizator = new Structurizator(mRepo, mIds, this);
myUtils::IntermediateNode *tree = mStructurizator->performStructurization();
obtainSemanticTree(tree);
}
void StructuralControlFlowGenerator::obtainSemanticTree(myUtils::IntermediateNode *root)
{
SemanticNode * semanticNode = transformNode(root);
mSemanticTree->setRoot(new RootNode(semanticNode, mSemanticTree));
}
// maybe use strategy to recursively handle this situation?
SemanticNode *StructuralControlFlowGenerator::transformNode(const myUtils::IntermediateNode *node)
{
switch (node->type()) {
case myUtils::IntermediateNode::Type::simple:
return transformSimple(node);
case myUtils::IntermediateNode::Type::block:
return transformBlock(node);
case myUtils::IntermediateNode::Type::ifThenElseCondition:
return transformIfThenElse(node);
case myUtils::IntermediateNode::Type::ifWithBreakCondition:
return transformIfWithBreak(node);
case myUtils::IntermediateNode::Type::switchCondition:
return transformSwitch(node);
case myUtils::IntermediateNode::Type::infiniteloop:
return transformSelfLoop(node);
case myUtils::IntermediateNode::Type::whileloop:
return transformWhileLoop(node);
default:
qDebug() << "Undefined type of Intermediate node!";
mCantBeGeneratedIntoStructuredCode = true;
return nullptr;
}
}
SemanticNode *StructuralControlFlowGenerator::transformSimple(const myUtils::IntermediateNode *node)
{
const myUtils::SimpleNode *simpleNode = dynamic_cast<const myUtils::SimpleNode *>(node);
return mSemanticTree->produceNodeFor(simpleNode->id());
}
SemanticNode *StructuralControlFlowGenerator::transformBlock(const myUtils::IntermediateNode *node)
{
const myUtils::BlockNode *blockNode = dynamic_cast<const myUtils::BlockNode *>(node);
ZoneNode *zone = new ZoneNode(mSemanticTree);
if (blockNode->firstNode()->type() == myUtils::IntermediateNode::simple) {
const myUtils::SimpleNode *simpleNode = dynamic_cast<const myUtils::SimpleNode *>(blockNode->firstNode());
switch (semanticsOf(simpleNode->id())) {
case enums::semantics::conditionalBlock:
case enums::semantics::switchBlock:
break;
default:
zone->appendChild(transformSimple(simpleNode));
}
} else {
zone->appendChild(transformBlock(blockNode->firstNode()));
}
zone->appendChild(transformNode(blockNode->secondNode()));
return zone;
}
SemanticNode *StructuralControlFlowGenerator::transformIfThenElse(const myUtils::IntermediateNode *node)
{
const myUtils::IfNode *ifNode = dynamic_cast<const myUtils::IfNode *>(node);
const qReal::Id conditionId = ifNode->condition()->id();
const qReal::Id thenId = ifNode->thenBranch()->firstId();
switch (semanticsOf(conditionId)) {
case enums::semantics::conditionalBlock: {
IfNode *semanticIf = new IfNode(conditionId, mSemanticTree);
QPair<LinkInfo, LinkInfo> links = ifBranchesFor(conditionId);
if (links.first.target != ifNode->thenBranch()->firstId()) {
semanticIf->invertCondition();
}
semanticIf->thenZone()->appendChild(transformNode(ifNode->thenBranch()));
if (ifNode->elseBranch()) {
semanticIf->elseZone()->appendChild(transformNode(ifNode->elseBranch()));
}
return semanticIf;
}
case enums::semantics::switchBlock: {
SwitchNode *semanticSwitch = new SwitchNode(conditionId, mSemanticTree);
//const qReal::Id
// problem with if-then pattern when "default" branch leads to then
for (const qReal::Id &link : mRepo.outgoingLinks(conditionId)) {
const QString expression = mRepo.property(link, "Guard").toString();
const qReal::Id otherVertex = mRepo.otherEntityFromLink(link, conditionId);
if (otherVertex == thenId) {
semanticSwitch->addBranch(expression, transformNode(ifNode->thenBranch()));
} else {
semanticSwitch->addBranch(expression, transformNode(ifNode->elseBranch()));
}
}
if (ifNode->hasBreakInside()) {
semanticSwitch->generateIfs();
}
return semanticSwitch;
}
case enums::semantics::forkBlock: {
ForkNode *semanticFork = new ForkNode(conditionId, mSemanticTree);
if (!ifNode->elseBranch()) {
qDebug() << "Fork should have all branches";
mCantBeGeneratedIntoStructuredCode = true;
return nullptr;
}
for (const qReal::Id &link : mRepo.outgoingLinks(conditionId)) {
const QString expression = mRepo.property(link, "Guard").toString();
const qReal::Id otherVertex = mRepo.otherEntityFromLink(link, conditionId);
if (otherVertex == thenId) {
semanticFork->appendThread(ifNode->thenBranch()->firstId(), expression);
} else {
semanticFork->appendThread(ifNode->elseBranch()->firstId(), expression);
}
}
return semanticFork;
}
default:
break;
}
qDebug() << "Problem: couldn't transform if-then-else";
mCantBeGeneratedIntoStructuredCode = true;
return nullptr;
}
SemanticNode *StructuralControlFlowGenerator::transformSelfLoop(const myUtils::IntermediateNode *node)
{
const myUtils::SelfLoopNode *selfLoopNode = dynamic_cast<const myUtils::SelfLoopNode *>(node);
LoopNode *semanticLoop = new LoopNode(qReal::Id(), mSemanticTree);
semanticLoop->bodyZone()->appendChild(transformNode(selfLoopNode->bodyNode()));
return semanticLoop;
}
SemanticNode *StructuralControlFlowGenerator::transformWhileLoop(const myUtils::IntermediateNode *node)
{
const myUtils::WhileNode *whileNode = dynamic_cast<const myUtils::WhileNode *>(node);
LoopNode *semanticLoop= nullptr;
if (whileNode->headNode()->type() == myUtils::IntermediateNode::Type::simple
&& semanticsOf(whileNode->headNode()->firstId()) == enums::semantics::conditionalBlock) {
semanticLoop = new LoopNode(whileNode->headNode()->firstId(), mSemanticTree);
} else {
semanticLoop = new LoopNode(qReal::Id(), mSemanticTree);
semanticLoop->bodyZone()->appendChild(transformNode(whileNode->headNode()));
}
semanticLoop->bodyZone()->appendChild(transformNode(whileNode->bodyNode()));
return semanticLoop;
}
SemanticNode *StructuralControlFlowGenerator::transformSwitch(const myUtils::IntermediateNode *node)
{
const myUtils::SwitchNode *switchNode = dynamic_cast<const myUtils::SwitchNode *>(node);
const qReal::Id &conditionId = switchNode->condition()->firstId();
QList<myUtils::IntermediateNode *> branches = switchNode->branches();
if (semanticsOf(conditionId) == enums::semantics::switchBlock) {
SwitchNode *semanticSwitch = new SwitchNode(conditionId, mSemanticTree);
for (const qReal::Id &link : mRepo.outgoingLinks(conditionId)) {
const QString expression = mRepo.property(link, "Guard").toString();
const qReal::Id otherVertex = mRepo.otherEntityFromLink(link, conditionId);
for (const myUtils::IntermediateNode *branchNode : branches) {
if (node->firstId() == otherVertex) {
semanticSwitch->addBranch(expression, transformNode(branchNode));
break;
}
}
}
if (switchNode->hasBreakInside()) {
semanticSwitch->generateIfs();
}
return semanticSwitch;
} else if (semanticsOf(conditionId) == enums::semantics::forkBlock) {
ForkNode *semanticFork = new ForkNode(conditionId, mSemanticTree);
for (const qReal::Id &link : mRepo.outgoingLinks(conditionId)) {
const QString expression = mRepo.property(link, "Expression").toString();
const qReal::Id otherVertex = mRepo.otherEntityFromLink(link, conditionId);
semanticFork->appendThread(otherVertex, expression);
}
return semanticFork;
}
qDebug() << "Problem: couldn't identidy semantics id for switchNode";
mCantBeGeneratedIntoStructuredCode = true;
return nullptr;
}
SemanticNode *StructuralControlFlowGenerator::transformIfWithBreak(const myUtils::IntermediateNode *node)
{
const myUtils::IfWithBreakNode *ifWithBreakNode = dynamic_cast<const myUtils::IfWithBreakNode *>(node);
const qReal::Id conditionId = ifWithBreakNode->condition()->firstId();
if (semanticsOf(conditionId) == enums::semantics::conditionalBlock) {
IfNode *semanticIf= new IfNode(conditionId, mSemanticTree);
QPair<LinkInfo, LinkInfo> branches = ifBranchesFor(conditionId);
if (ifWithBreakNode->actionsBeforeBreak()) {
semanticIf->thenZone()->appendChild(transformNode(ifWithBreakNode->actionsBeforeBreak()));
}
// check inverting condition
if (branches.first.target != ifWithBreakNode->nodeThatIsConnectedWithCondition()->firstId()) {
semanticIf->invertCondition();
}
semanticIf->thenZone()->appendChild(semantics::SimpleNode::createBreakNode(mSemanticTree));
return semanticIf;
} else if (semanticsOf(conditionId) == enums::semantics::switchBlock) {
SwitchNode *semanticSwitch = new SwitchNode(conditionId, mSemanticTree);
// deal with semanticSwitch
return semanticSwitch;
}
qDebug() << "Problem: couldn't identify semantics id for If with break";
mCantBeGeneratedIntoStructuredCode = true;
return nullptr;
}
/*
IfNode *StructuralControlFlowGenerator::createIfFromSwitch(int v, int bodyNumber)
{
qReal::Id vId = mMapVertexLabel.key(v);
bool needInverting = true;
QList<qReal::Id> links;
bool hasDefaultBranch = false;
for (const int edge : mFollowers2[v][bodyNumber]) {
links.append(mEdges[edge]);
if (mRepo.property(mEdges[edge], "Guard").toString().isEmpty()) {
hasDefaultBranch = true;
}
}
if (hasDefaultBranch) {
needInverting = false;
links.clear();
for (const int u : mFollowers2[v].keys()) {
if (u == bodyNumber) {
continue;
}
for (const int edge : mFollowers2[v][u]) {
links.append(mEdges[edge]);
}
}
}
IfNode *ifNode = IfNode::fromSwitchCase(vId, links);
if (needInverting) {
ifNode->invertCondition();
}
ifNode->setCondition(constructConditionFromSwitch(vId, links));
return ifNode;
}
QString StructuralControlFlowGenerator::constructConditionFromSwitch(const Id &id, const QList<Id> &links) const
{
const QString expression = mRepo.property(id, "Expression").toString();
QString condition = "";
for (const qReal::Id &link : links) {
condition += "(" + expression + " == " + mRepo.property(link, "Guard").toString() + ") || ";
}
condition.chop(4);
return condition;
}
*/
<|endoftext|> |
<commit_before>#include <string.h>
#include <node.h>
#include <node_internals.h>
#include <node_buffer.h>
#include <v8.h>
extern "C" {
#include "scrypt_platform.h"
#include "crypto_scrypt.h"
}
#define ASSERT_IS_BUFFER(val) \
if (!Buffer::HasInstance(val)) { \
return ThrowException(Exception::TypeError(String::New("Not a buffer"))); \
}
#define ASSERT_IS_NUMBER(val) \
if (!val->IsNumber()) { \
type_error = "not a number"; \
goto err; \
}
using namespace v8;
using namespace node;
struct scrypt_req {
uv_work_t work_req;
int err;
char* pass;
size_t pass_len;
char* salt;
size_t salt_len;
uint64_t N;
uint32_t r;
uint32_t p;
char* buf;
size_t buf_len;
Persistent<Object> obj;
};
void EIO_Scrypt(uv_work_t* work_req) {
scrypt_req* req = container_of(work_req, scrypt_req, work_req);
req->err = crypto_scrypt(
(const uint8_t*)req->pass,
req->pass_len,
(const uint8_t*)req->salt,
req->salt_len,
req->N,
req->r,
req->p,
(uint8_t*)req->buf,
req->buf_len);
memset(req->pass, 0, req->pass_len);
memset(req->salt, 0, req->salt_len);
}
void EIO_ScryptAfter(uv_work_t* work_req, int status) {
assert(status == 0);
scrypt_req* req = container_of(work_req, scrypt_req, work_req);
HandleScope scope;
Local<Value> argv[2];
Persistent<Object> obj = req->obj;
if (req->err) {
argv[0] = Exception::Error(String::New("Scrypt error"));
argv[1] = Local<Value>::New(Undefined());
}
else {
argv[0] = Local<Value>::New(Undefined());
argv[1] = Encode(req->buf, req->buf_len, BUFFER);
}
MakeCallback(obj, "ondone", ARRAY_SIZE(argv), argv);
obj.Dispose();
delete[] req->pass;
delete[] req->salt;
delete[] req->buf;
delete req;
}
Handle<Value> Scrypt(const Arguments& args) {
HandleScope scope;
const char* type_error = NULL;
char* pass = NULL;
ssize_t pass_len = -1;
ssize_t pass_written = -1;
char* salt = NULL;
ssize_t salt_len = -1;
ssize_t salt_written = -1;
uint64_t N = 0;
uint32_t r = 0;
uint32_t p = 0;
uint8_t buf_len = 0;
scrypt_req* req = NULL;
if (args.Length() != 7) {
type_error = "Bad parameters";
goto err;
}
ASSERT_IS_BUFFER(args[0]);
pass_len = Buffer::Length(args[0]);
if (pass_len < 0) {
type_error = "Bad data";
goto err;
}
pass = new char[pass_len];
pass_written = DecodeWrite(pass, pass_len, args[0], BINARY);
assert(pass_len == pass_written);
ASSERT_IS_BUFFER(args[1]);
salt_len = Buffer::Length(args[1]);
if (salt_len < 0) {
type_error = "Bad salt";
goto err;
}
salt = new char[salt_len];
salt_written = DecodeWrite(salt, salt_len, args[1], BINARY);
assert(salt_len == salt_written);
ASSERT_IS_NUMBER(args[2]);
N = args[2]->Int32Value();
ASSERT_IS_NUMBER(args[3]);
r = args[3]->Int32Value();
ASSERT_IS_NUMBER(args[4]);
p = args[4]->Int32Value();
ASSERT_IS_NUMBER(args[5]);
buf_len = args[5]->Int32Value();
if (!args[6]->IsFunction()) {
type_error = "callback not a function";
goto err;
}
req = new scrypt_req;
req->err = 0;
req->pass = pass;
req->pass_len = pass_len;
req->salt = salt;
req->salt_len = salt_len;
req->N = N;
req->r = r;
req->p = p;
req->buf = new char[buf_len];
req->buf_len = buf_len;
req->obj = Persistent<Object>::New(Object::New());
req->obj->Set(String::New("ondone"), args[6]);
uv_queue_work(uv_default_loop(), &req->work_req, EIO_Scrypt, EIO_ScryptAfter);
return Undefined();
err:
delete[] salt;
delete[] pass;
return ThrowException(Exception::TypeError(String::New(type_error)));
}
void init(Handle<Object> target) {
NODE_SET_METHOD(target, "scrypt", Scrypt);
}
NODE_MODULE(scrypt, init);
<commit_msg>fixed a tab<commit_after>#include <string.h>
#include <node.h>
#include <node_internals.h>
#include <node_buffer.h>
#include <v8.h>
extern "C" {
#include "scrypt_platform.h"
#include "crypto_scrypt.h"
}
#define ASSERT_IS_BUFFER(val) \
if (!Buffer::HasInstance(val)) { \
return ThrowException(Exception::TypeError(String::New("Not a buffer"))); \
}
#define ASSERT_IS_NUMBER(val) \
if (!val->IsNumber()) { \
type_error = "not a number"; \
goto err; \
}
using namespace v8;
using namespace node;
struct scrypt_req {
uv_work_t work_req;
int err;
char* pass;
size_t pass_len;
char* salt;
size_t salt_len;
uint64_t N;
uint32_t r;
uint32_t p;
char* buf;
size_t buf_len;
Persistent<Object> obj;
};
void EIO_Scrypt(uv_work_t* work_req) {
scrypt_req* req = container_of(work_req, scrypt_req, work_req);
req->err = crypto_scrypt(
(const uint8_t*)req->pass,
req->pass_len,
(const uint8_t*)req->salt,
req->salt_len,
req->N,
req->r,
req->p,
(uint8_t*)req->buf,
req->buf_len);
memset(req->pass, 0, req->pass_len);
memset(req->salt, 0, req->salt_len);
}
void EIO_ScryptAfter(uv_work_t* work_req, int status) {
assert(status == 0);
scrypt_req* req = container_of(work_req, scrypt_req, work_req);
HandleScope scope;
Local<Value> argv[2];
Persistent<Object> obj = req->obj;
if (req->err) {
argv[0] = Exception::Error(String::New("Scrypt error"));
argv[1] = Local<Value>::New(Undefined());
}
else {
argv[0] = Local<Value>::New(Undefined());
argv[1] = Encode(req->buf, req->buf_len, BUFFER);
}
MakeCallback(obj, "ondone", ARRAY_SIZE(argv), argv);
obj.Dispose();
delete[] req->pass;
delete[] req->salt;
delete[] req->buf;
delete req;
}
Handle<Value> Scrypt(const Arguments& args) {
HandleScope scope;
const char* type_error = NULL;
char* pass = NULL;
ssize_t pass_len = -1;
ssize_t pass_written = -1;
char* salt = NULL;
ssize_t salt_len = -1;
ssize_t salt_written = -1;
uint64_t N = 0;
uint32_t r = 0;
uint32_t p = 0;
uint8_t buf_len = 0;
scrypt_req* req = NULL;
if (args.Length() != 7) {
type_error = "Bad parameters";
goto err;
}
ASSERT_IS_BUFFER(args[0]);
pass_len = Buffer::Length(args[0]);
if (pass_len < 0) {
type_error = "Bad data";
goto err;
}
pass = new char[pass_len];
pass_written = DecodeWrite(pass, pass_len, args[0], BINARY);
assert(pass_len == pass_written);
ASSERT_IS_BUFFER(args[1]);
salt_len = Buffer::Length(args[1]);
if (salt_len < 0) {
type_error = "Bad salt";
goto err;
}
salt = new char[salt_len];
salt_written = DecodeWrite(salt, salt_len, args[1], BINARY);
assert(salt_len == salt_written);
ASSERT_IS_NUMBER(args[2]);
N = args[2]->Int32Value();
ASSERT_IS_NUMBER(args[3]);
r = args[3]->Int32Value();
ASSERT_IS_NUMBER(args[4]);
p = args[4]->Int32Value();
ASSERT_IS_NUMBER(args[5]);
buf_len = args[5]->Int32Value();
if (!args[6]->IsFunction()) {
type_error = "callback not a function";
goto err;
}
req = new scrypt_req;
req->err = 0;
req->pass = pass;
req->pass_len = pass_len;
req->salt = salt;
req->salt_len = salt_len;
req->N = N;
req->r = r;
req->p = p;
req->buf = new char[buf_len];
req->buf_len = buf_len;
req->obj = Persistent<Object>::New(Object::New());
req->obj->Set(String::New("ondone"), args[6]);
uv_queue_work(uv_default_loop(), &req->work_req, EIO_Scrypt, EIO_ScryptAfter);
return Undefined();
err:
delete[] salt;
delete[] pass;
return ThrowException(Exception::TypeError(String::New(type_error)));
}
void init(Handle<Object> target) {
NODE_SET_METHOD(target, "scrypt", Scrypt);
}
NODE_MODULE(scrypt, init);
<|endoftext|> |
<commit_before>/*********************************************************************
* Copyright (C) 2015 Francisco Javier Paz Menendez
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
********************************************************************/
#include "../common/TestData.h"
#include "test_doubles/AcceptanceAppFactory.h"
#include "test_doubles/SignalSpy.h"
#include <KronApplication/App.h>
#include <KronApplication/viewmodels/ComicReaderVM.h>
#include <gtest/gtest.h>
#include <QCryptographicHash>
#include <QUrl>
#include <functional>
#include <memory>
using namespace kron;
// As a comic reader
// I want to navigate through pages
// So that I can read any page of the comic
class PageNavigationTest : public ::testing::Test
{
protected:
std::unique_ptr<AppFactory> appFactory_;
std::unique_ptr<App> app_;
ComicReaderVM* comicReaderVM_ = nullptr;
virtual void SetUp()
{
appFactory_.reset(new AcceptanceAppFactory);
app_.reset(appFactory_->createApp());
comicReaderVM_ = static_cast<ComicReaderVM*>(&app_->contexProperty("model"));
QUrl comicUrl = QUrl::fromLocalFile("TestComic.cbz");
comicReaderVM_->openComic(comicUrl.toString());
}
virtual void TearDown()
{
app_.release();
appFactory_.release();
}
};
TEST_F(PageNavigationTest,
Given_any_page_being_shown_\
When_user_requests_to_go_to_first_page_\
Then_show_first_page)
{
SignalSpy spy(comicReaderVM_, SIGNAL(pageUpdated(QByteArray)));
comicReaderVM_->goToFirstPage();
ASSERT_TRUE(spy.signalReceived());
QByteArray currentPage = spy.firstParameter().toByteArray();
QByteArray currentPageMd5 = QCryptographicHash::hash(currentPage, QCryptographicHash::Md5);
EXPECT_EQ(testdata::page01Md5, currentPageMd5);
}
TEST_F(PageNavigationTest,
Given_last_page_is_not_being_shown_currently_\
When_user_requests_to_go_forward_\
Then_show_next_page)
{
SignalSpy spyFirst(comicReaderVM_, SIGNAL(pageUpdated(QByteArray)));
comicReaderVM_->goToFirstPage();
ASSERT_TRUE(spyFirst.signalReceived());
SignalSpy spyForward(comicReaderVM_, SIGNAL(pageUpdated(QByteArray)));
comicReaderVM_->goForward();
ASSERT_TRUE(spyForward.signalReceived());
QByteArray currentPage = spyForward.firstParameter().toByteArray();
QByteArray currentPageMd5 = QCryptographicHash::hash(currentPage, QCryptographicHash::Md5);
EXPECT_EQ(testdata::page02Md5, currentPageMd5);
}
/*
TEST_F(PageNavigationTest,
Given_last_page_is_being_shown_currently_\
When_user_requests_to_go_forward_\
Then_keep_showing_current_page)
{
SignalSpy spy(comicReaderVM_, SIGNAL(pageUpdated(QByteArray)));
comicReaderVM_->goForward();
EXPECT_TRUE(spy.signalReceived());
}
*/
<commit_msg>Test names in one line to be detected as AutoTest by Qt Creator<commit_after>/*********************************************************************
* Copyright (C) 2015 Francisco Javier Paz Menendez
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
********************************************************************/
#include "../common/TestData.h"
#include "test_doubles/AcceptanceAppFactory.h"
#include "test_doubles/SignalSpy.h"
#include <KronApplication/App.h>
#include <KronApplication/viewmodels/ComicReaderVM.h>
#include <gtest/gtest.h>
#include <QCryptographicHash>
#include <QUrl>
#include <functional>
#include <memory>
using namespace kron;
// As a comic reader
// I want to navigate through pages
// So that I can read any page of the comic
class PageNavigationTest : public ::testing::Test
{
protected:
std::unique_ptr<AppFactory> appFactory_;
std::unique_ptr<App> app_;
ComicReaderVM* comicReaderVM_ = nullptr;
virtual void SetUp()
{
appFactory_.reset(new AcceptanceAppFactory);
app_.reset(appFactory_->createApp());
comicReaderVM_ = static_cast<ComicReaderVM*>(&app_->contexProperty("model"));
QUrl comicUrl = QUrl::fromLocalFile("TestComic.cbz");
comicReaderVM_->openComic(comicUrl.toString());
}
virtual void TearDown()
{
app_.release();
appFactory_.release();
}
};
TEST_F(PageNavigationTest, Given_any_page_being_shown_When_user_requests_to_go_to_first_page_Then_show_first_page)
{
SignalSpy spy(comicReaderVM_, SIGNAL(pageUpdated(QByteArray)));
comicReaderVM_->goToFirstPage();
ASSERT_TRUE(spy.signalReceived());
QByteArray currentPage = spy.firstParameter().toByteArray();
QByteArray currentPageMd5 = QCryptographicHash::hash(currentPage, QCryptographicHash::Md5);
EXPECT_EQ(testdata::page01Md5, currentPageMd5);
}
TEST_F(PageNavigationTest, Given_last_page_is_not_being_shown_currently_When_user_requests_to_go_forward_Then_show_next_page)
{
SignalSpy spyFirst(comicReaderVM_, SIGNAL(pageUpdated(QByteArray)));
comicReaderVM_->goToFirstPage();
ASSERT_TRUE(spyFirst.signalReceived());
SignalSpy spyForward(comicReaderVM_, SIGNAL(pageUpdated(QByteArray)));
comicReaderVM_->goForward();
ASSERT_TRUE(spyForward.signalReceived());
QByteArray currentPage = spyForward.firstParameter().toByteArray();
QByteArray currentPageMd5 = QCryptographicHash::hash(currentPage, QCryptographicHash::Md5);
EXPECT_EQ(testdata::page02Md5, currentPageMd5);
}
/*
TEST_F(PageNavigationTest, Given_last_page_is_being_shown_currently_When_user_requests_to_go_forward_Then_keep_showing_current_page)
{
SignalSpy spy(comicReaderVM_, SIGNAL(pageUpdated(QByteArray)));
comicReaderVM_->goForward();
EXPECT_TRUE(spy.signalReceived());
}
*/
<|endoftext|> |
<commit_before>/**
* \file
* \brief MutexRecursiveOperationsTestCase class implementation
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-10-27
*/
#include "MutexRecursiveOperationsTestCase.hpp"
#include "mutexTestUnlockFromWrongThread.hpp"
#include "mutexTestTryLockWhenLocked.hpp"
#include "waitForNextTick.hpp"
#include "distortos/Mutex.hpp"
#include <cerrno>
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// single duration used in tests
constexpr auto singleDuration = TickClock::duration{1};
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool MutexRecursiveOperationsTestCase::run_() const
{
Mutex mutex {Mutex::Type::Recursive};
size_t lockCount {};
{
// simple lock - must succeed immediately
++lockCount;
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.lock();
if (ret != 0 || start != TickClock::now())
return false;
}
const auto maxRecursiveLocks = mutex.getMaxRecursiveLocks();
if (maxRecursiveLocks < 4)
return false;
{
// recursive lock - must succeed immediately
++lockCount;
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.lock();
if (ret != 0 || start != TickClock::now())
return false;
}
{
// recursive lock - must succeed immediately
++lockCount;
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.tryLock();
if (ret != 0 || start != TickClock::now())
return false;
}
{
// recursive lock - must succeed immediately
++lockCount;
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.tryLockFor(singleDuration);
if (ret != 0 || start != TickClock::now())
return false;
}
{
// recursive lock - must succeed immediately
++lockCount;
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.tryLockUntil(start + singleDuration);
if (ret != 0 || start != TickClock::now())
return false;
}
while (lockCount < maxRecursiveLocks + 1)
{
// recursive lock - must succeed
++lockCount;
const auto ret = mutex.tryLock();
if (ret != 0)
return false;
}
{
// excessive recursive lock - must fail with EAGAIN immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.lock();
if (ret != EAGAIN || start != TickClock::now())
return false;
}
{
// excessive recursive lock - must fail with EAGAIN immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.tryLock();
if (ret != EAGAIN || start != TickClock::now())
return false;
}
{
// excessive recursive lock - must fail with EAGAIN immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.tryLockFor(singleDuration);
if (ret != EAGAIN || start != TickClock::now())
return false;
}
{
// excessive recursive lock - must fail with EAGAIN immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.tryLockUntil(start + singleDuration);
if (ret != EAGAIN || start != TickClock::now())
return false;
}
{
const auto ret = mutexTestTryLockWhenLocked(mutex);
if (ret != true)
return ret;
}
{
const auto ret = mutexTestUnlockFromWrongThread(mutex);
if (ret != true)
return ret;
}
{
// simple unlock - must succeed immediately
--lockCount;
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.unlock();
if (ret != 0 || start != TickClock::now())
return false;
}
{
const auto ret = mutexTestTryLockWhenLocked(mutex);
if (ret != true)
return ret;
}
while (lockCount > 0)
{
// simple unlock - must succeed
--lockCount;
const auto ret = mutex.unlock();
if (ret != 0)
return false;
}
{
// excessive unlock - must fail with EPERM immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.unlock();
if (ret != EPERM || start != TickClock::now())
return false;
}
return true;
}
} // namespace test
} // namespace distortos
<commit_msg>test: move actual test code from MutexRecursiveOperationsTestCase::run_() to new local testRunner_() function<commit_after>/**
* \file
* \brief MutexRecursiveOperationsTestCase class implementation
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-11-09
*/
#include "MutexRecursiveOperationsTestCase.hpp"
#include "mutexTestUnlockFromWrongThread.hpp"
#include "mutexTestTryLockWhenLocked.hpp"
#include "waitForNextTick.hpp"
#include "distortos/Mutex.hpp"
#include <cerrno>
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// single duration used in tests
constexpr auto singleDuration = TickClock::duration{1};
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Runs the test case.
*
* \return true if the test case succeeded, false otherwise
*/
bool testRunner_()
{
Mutex mutex {Mutex::Type::Recursive};
size_t lockCount {};
{
// simple lock - must succeed immediately
++lockCount;
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.lock();
if (ret != 0 || start != TickClock::now())
return false;
}
const auto maxRecursiveLocks = mutex.getMaxRecursiveLocks();
if (maxRecursiveLocks < 4)
return false;
{
// recursive lock - must succeed immediately
++lockCount;
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.lock();
if (ret != 0 || start != TickClock::now())
return false;
}
{
// recursive lock - must succeed immediately
++lockCount;
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.tryLock();
if (ret != 0 || start != TickClock::now())
return false;
}
{
// recursive lock - must succeed immediately
++lockCount;
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.tryLockFor(singleDuration);
if (ret != 0 || start != TickClock::now())
return false;
}
{
// recursive lock - must succeed immediately
++lockCount;
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.tryLockUntil(start + singleDuration);
if (ret != 0 || start != TickClock::now())
return false;
}
while (lockCount < maxRecursiveLocks + 1)
{
// recursive lock - must succeed
++lockCount;
const auto ret = mutex.tryLock();
if (ret != 0)
return false;
}
{
// excessive recursive lock - must fail with EAGAIN immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.lock();
if (ret != EAGAIN || start != TickClock::now())
return false;
}
{
// excessive recursive lock - must fail with EAGAIN immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.tryLock();
if (ret != EAGAIN || start != TickClock::now())
return false;
}
{
// excessive recursive lock - must fail with EAGAIN immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.tryLockFor(singleDuration);
if (ret != EAGAIN || start != TickClock::now())
return false;
}
{
// excessive recursive lock - must fail with EAGAIN immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.tryLockUntil(start + singleDuration);
if (ret != EAGAIN || start != TickClock::now())
return false;
}
{
const auto ret = mutexTestTryLockWhenLocked(mutex);
if (ret != true)
return ret;
}
{
const auto ret = mutexTestUnlockFromWrongThread(mutex);
if (ret != true)
return ret;
}
{
// simple unlock - must succeed immediately
--lockCount;
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.unlock();
if (ret != 0 || start != TickClock::now())
return false;
}
{
const auto ret = mutexTestTryLockWhenLocked(mutex);
if (ret != true)
return ret;
}
while (lockCount > 0)
{
// simple unlock - must succeed
--lockCount;
const auto ret = mutex.unlock();
if (ret != 0)
return false;
}
{
// excessive unlock - must fail with EPERM immediately
waitForNextTick();
const auto start = TickClock::now();
const auto ret = mutex.unlock();
if (ret != EPERM || start != TickClock::now())
return false;
}
return true;
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool MutexRecursiveOperationsTestCase::run_() const
{
return testRunner_();
}
} // namespace test
} // namespace distortos
<|endoftext|> |
<commit_before>//Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "DistributedBeadingStrategy.h"
namespace cura
{
DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
{
Beading ret;
ret.total_thickness = thickness;
if (bead_count == 1)
{
ret.bead_widths.emplace_back(thickness);
ret.toolpath_locations.emplace_back(thickness / 2);
ret.left_over = 0;
}
else if (bead_count > 1)
{
// Outer wall, always the same size:
ret.bead_widths.emplace_back(optimal_width_outer);
ret.toolpath_locations.emplace_back(optimal_width_outer / 2);
// Evenly distributed inner walls:
const coord_t distributed_width_inner = std::max(optimal_width_outer / 2, (thickness - optimal_width_outer) / (bead_count - 1));
for (coord_t bead_idx = 1; bead_idx < bead_count; bead_idx++)
{
ret.bead_widths.emplace_back(distributed_width_inner);
ret.toolpath_locations.emplace_back(optimal_width_outer + distributed_width_inner * ((bead_idx - 1) * 2 + 1) / 2);
}
ret.left_over = std::max(0LL, thickness - (ret.toolpath_locations.back() + optimal_width_inner / 2));
}
else
{
ret.left_over = thickness;
}
return ret;
}
coord_t DistributedBeadingStrategy::getOptimalThickness(coord_t bead_count) const
{
return std::max(0LL, (bead_count - 1)) * optimal_width_inner + std::min(1LL, bead_count) * optimal_width_outer;
}
coord_t DistributedBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const
{
// TODO: doesnt take min and max width into account
const coord_t optimal_thickness = this->getOptimalThickness(lower_bead_count);
return optimal_thickness + (optimal_thickness < 1 ? optimal_width_outer : optimal_width_inner) / 2;
}
coord_t DistributedBeadingStrategy::getOptimalBeadCount(coord_t thickness) const
{
coord_t thickness_left = thickness;
coord_t count = std::min(1LL, (thickness + optimal_width_outer / 2) / optimal_width_outer);
thickness_left -= count * optimal_width_outer;
if (thickness_left >= (optimal_width_inner / 2))
{
count += (thickness_left + optimal_width_inner / 2) / optimal_width_inner;
}
return count;
}
} // namespace cura
<commit_msg>Smaller fixes.<commit_after>//Copyright (c) 2020 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "DistributedBeadingStrategy.h"
namespace cura
{
DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const
{
Beading ret;
ret.total_thickness = thickness;
if (bead_count == 1)
{
ret.bead_widths.emplace_back(thickness);
ret.toolpath_locations.emplace_back(thickness / 2);
ret.left_over = 0;
}
else if (bead_count > 1)
{
// Outer wall, always the same size:
ret.bead_widths.emplace_back(optimal_width_outer);
ret.toolpath_locations.emplace_back(optimal_width_outer / 2);
// Evenly distributed inner walls:
const coord_t distributed_width_inner = std::max(optimal_width_inner / 2, (thickness - optimal_width_outer) / (bead_count - 1));
for (coord_t bead_idx = 1; bead_idx < bead_count; bead_idx++)
{
ret.bead_widths.emplace_back(distributed_width_inner);
ret.toolpath_locations.emplace_back(optimal_width_outer + (distributed_width_inner * (bead_idx - 1) * 2 + 1) / 2);
}
ret.left_over = std::max(0LL, thickness - (ret.toolpath_locations.back() + optimal_width_inner / 2));
}
else
{
ret.left_over = thickness;
}
return ret;
}
coord_t DistributedBeadingStrategy::getOptimalThickness(coord_t bead_count) const
{
return std::max(0LL, (bead_count - 1)) * optimal_width_inner + std::min(1LL, bead_count) * optimal_width_outer;
}
coord_t DistributedBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const
{
// TODO: doesnt take min and max width into account
const coord_t optimal_thickness = this->getOptimalThickness(lower_bead_count);
return optimal_thickness + (optimal_thickness < 1 ? optimal_width_outer : optimal_width_inner) / 2;
}
coord_t DistributedBeadingStrategy::getOptimalBeadCount(coord_t thickness) const
{
coord_t thickness_left = thickness;
coord_t count = std::min(1LL, (thickness + optimal_width_outer / 2) / optimal_width_outer);
thickness_left -= count * optimal_width_outer;
if (thickness_left >= (optimal_width_inner / 2))
{
count += (thickness_left + optimal_width_inner / 2) / optimal_width_inner;
}
return count;
}
} // namespace cura
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2014 Jamis Hoo
* Distributed under the MIT license
* (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
*
* Project:
* Filename: test.cc
* Version: 1.0
* Author: Jamis Hoo
* E-mail: hjm211324@gmail.com
* Date: Dec. 29, 2014
* Time: 11:10:09
* Description:
*****************************************************************************/
#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
}
<commit_msg>--allow-empty_message<commit_after>/******************************************************************************
* Copyright (c) 2014 Jamis Hoo
* Distributed under the MIT license
* (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
*
* Project:
* Filename: test.cc
* Version: 1.0
* Author: Jamis Hoo
* E-mail: hjm211324@gmail.com
* Date: Dec. 29, 2014
* Time: 11:10:09
* Description:
*****************************************************************************/
#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
}
<|endoftext|> |
<commit_before>#include "AmsRouter.h"
#include "Log.h"
#include <algorithm>
AmsRouter::AmsRouter(AmsNetId netId)
: localAddr(netId)
{}
long AmsRouter::AddRoute(AmsNetId ams, const IpV4& ip)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
const auto oldConnection = GetConnection(ams);
auto conn = connections.find(ip);
if (conn == connections.end()) {
conn = connections.emplace(ip, std::unique_ptr<AmsConnection>(new AmsConnection { *this, ip })).first;
}
mapping[ams] = conn->second.get();
DeleteIfLastConnection(oldConnection);
return 0;
}
void AmsRouter::DelRoute(const AmsNetId& ams)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
auto route = mapping.find(ams);
if (route != mapping.end()) {
const AmsConnection* conn = route->second;
mapping.erase(route);
DeleteIfLastConnection(conn);
}
}
void AmsRouter::SetNetId(AmsNetId ams)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
localAddr = ams;
}
void AmsRouter::DeleteIfLastConnection(const AmsConnection* conn)
{
if (conn) {
for (const auto& r : mapping) {
if (r.second == conn) {
return;
}
}
connections.erase(conn->destIp);
}
}
uint16_t AmsRouter::OpenPort()
{
std::lock_guard<std::recursive_mutex> lock(mutex);
for (uint16_t i = 0; i < NUM_PORTS_MAX; ++i) {
if (!ports[i].IsOpen()) {
return ports[i].Open(PORT_BASE + i);
}
}
return 0;
}
long AmsRouter::ClosePort(uint16_t port)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
if ((port < PORT_BASE) || (port >= PORT_BASE + NUM_PORTS_MAX) || !ports[port - PORT_BASE].IsOpen()) {
return ADSERR_CLIENT_PORTNOTOPEN;
}
ports[port - PORT_BASE].Close();
return 0;
}
long AmsRouter::GetLocalAddress(uint16_t port, AmsAddr* pAddr)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
if ((port < PORT_BASE) || (port >= PORT_BASE + NUM_PORTS_MAX)) {
return ADSERR_CLIENT_PORTNOTOPEN;
}
if (ports[port - PORT_BASE].IsOpen()) {
memcpy(&pAddr->netId, &localAddr, sizeof(localAddr));
pAddr->port = port;
return 0;
}
return ADSERR_CLIENT_PORTNOTOPEN;
}
long AmsRouter::GetTimeout(uint16_t port, uint32_t& timeout)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
if ((port < PORT_BASE) || (port >= PORT_BASE + NUM_PORTS_MAX)) {
return ADSERR_CLIENT_PORTNOTOPEN;
}
timeout = ports[port - PORT_BASE].tmms;
return 0;
}
long AmsRouter::SetTimeout(uint16_t port, uint32_t timeout)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
if ((port < PORT_BASE) || (port >= PORT_BASE + NUM_PORTS_MAX)) {
return ADSERR_CLIENT_PORTNOTOPEN;
}
ports[port - PORT_BASE].tmms = timeout;
return 0;
}
AmsConnection* AmsRouter::GetConnection(const AmsNetId& amsDest)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
const auto it = __GetConnection(amsDest);
if (it == connections.end()) {
return nullptr;
}
return it->second.get();
}
std::map<IpV4, std::unique_ptr<AmsConnection> >::iterator AmsRouter::__GetConnection(const AmsNetId& amsDest)
{
const auto it = mapping.find(amsDest);
if (it != mapping.end()) {
return connections.find(it->second->destIp);
}
return connections.end();
}
long AmsRouter::AddNotification(AmsRequest& request, uint32_t* pNotification, Notification& notify)
{
if (request.bytesRead) {
*request.bytesRead = 0;
}
auto ads = GetConnection(request.destAddr.netId);
if (!ads) {
return GLOBALERR_MISSING_ROUTE;
}
auto& port = ports[request.port - Router::PORT_BASE];
const long status = ads->AdsRequest<AoEResponseHeader>(request, port.tmms);
if (!status) {
*pNotification = qFromLittleEndian<uint32_t>((uint8_t*)request.buffer);
const auto notifyId = ads->CreateNotifyMapping(*pNotification, notify);
port.AddNotification(notifyId);
}
return status;
}
long AmsRouter::DelNotification(uint16_t port, const AmsAddr* pAddr, uint32_t hNotification)
{
auto& p = ports[port - Router::PORT_BASE];
return p.DelNotification(*pAddr, hNotification) ? ADSERR_NOERR : ADSERR_CLIENT_REMOVEHASH;
}
template<class T> T extractLittleEndian(Frame& frame)
{
const auto value = qFromLittleEndian<T>(frame.data());
frame.remove(sizeof(T));
return value;
}
<commit_msg>remove orphaned extractFromLittleEndian()<commit_after>#include "AmsRouter.h"
#include "Log.h"
#include <algorithm>
AmsRouter::AmsRouter(AmsNetId netId)
: localAddr(netId)
{}
long AmsRouter::AddRoute(AmsNetId ams, const IpV4& ip)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
const auto oldConnection = GetConnection(ams);
auto conn = connections.find(ip);
if (conn == connections.end()) {
conn = connections.emplace(ip, std::unique_ptr<AmsConnection>(new AmsConnection { *this, ip })).first;
}
mapping[ams] = conn->second.get();
DeleteIfLastConnection(oldConnection);
return 0;
}
void AmsRouter::DelRoute(const AmsNetId& ams)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
auto route = mapping.find(ams);
if (route != mapping.end()) {
const AmsConnection* conn = route->second;
mapping.erase(route);
DeleteIfLastConnection(conn);
}
}
void AmsRouter::SetNetId(AmsNetId ams)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
localAddr = ams;
}
void AmsRouter::DeleteIfLastConnection(const AmsConnection* conn)
{
if (conn) {
for (const auto& r : mapping) {
if (r.second == conn) {
return;
}
}
connections.erase(conn->destIp);
}
}
uint16_t AmsRouter::OpenPort()
{
std::lock_guard<std::recursive_mutex> lock(mutex);
for (uint16_t i = 0; i < NUM_PORTS_MAX; ++i) {
if (!ports[i].IsOpen()) {
return ports[i].Open(PORT_BASE + i);
}
}
return 0;
}
long AmsRouter::ClosePort(uint16_t port)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
if ((port < PORT_BASE) || (port >= PORT_BASE + NUM_PORTS_MAX) || !ports[port - PORT_BASE].IsOpen()) {
return ADSERR_CLIENT_PORTNOTOPEN;
}
ports[port - PORT_BASE].Close();
return 0;
}
long AmsRouter::GetLocalAddress(uint16_t port, AmsAddr* pAddr)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
if ((port < PORT_BASE) || (port >= PORT_BASE + NUM_PORTS_MAX)) {
return ADSERR_CLIENT_PORTNOTOPEN;
}
if (ports[port - PORT_BASE].IsOpen()) {
memcpy(&pAddr->netId, &localAddr, sizeof(localAddr));
pAddr->port = port;
return 0;
}
return ADSERR_CLIENT_PORTNOTOPEN;
}
long AmsRouter::GetTimeout(uint16_t port, uint32_t& timeout)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
if ((port < PORT_BASE) || (port >= PORT_BASE + NUM_PORTS_MAX)) {
return ADSERR_CLIENT_PORTNOTOPEN;
}
timeout = ports[port - PORT_BASE].tmms;
return 0;
}
long AmsRouter::SetTimeout(uint16_t port, uint32_t timeout)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
if ((port < PORT_BASE) || (port >= PORT_BASE + NUM_PORTS_MAX)) {
return ADSERR_CLIENT_PORTNOTOPEN;
}
ports[port - PORT_BASE].tmms = timeout;
return 0;
}
AmsConnection* AmsRouter::GetConnection(const AmsNetId& amsDest)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
const auto it = __GetConnection(amsDest);
if (it == connections.end()) {
return nullptr;
}
return it->second.get();
}
std::map<IpV4, std::unique_ptr<AmsConnection> >::iterator AmsRouter::__GetConnection(const AmsNetId& amsDest)
{
const auto it = mapping.find(amsDest);
if (it != mapping.end()) {
return connections.find(it->second->destIp);
}
return connections.end();
}
long AmsRouter::AddNotification(AmsRequest& request, uint32_t* pNotification, Notification& notify)
{
if (request.bytesRead) {
*request.bytesRead = 0;
}
auto ads = GetConnection(request.destAddr.netId);
if (!ads) {
return GLOBALERR_MISSING_ROUTE;
}
auto& port = ports[request.port - Router::PORT_BASE];
const long status = ads->AdsRequest<AoEResponseHeader>(request, port.tmms);
if (!status) {
*pNotification = qFromLittleEndian<uint32_t>((uint8_t*)request.buffer);
const auto notifyId = ads->CreateNotifyMapping(*pNotification, notify);
port.AddNotification(notifyId);
}
return status;
}
long AmsRouter::DelNotification(uint16_t port, const AmsAddr* pAddr, uint32_t hNotification)
{
auto& p = ports[port - Router::PORT_BASE];
return p.DelNotification(*pAddr, hNotification) ? ADSERR_NOERR : ADSERR_CLIENT_REMOVEHASH;
}
<|endoftext|> |
<commit_before>#include "../tlang.h"
#include <taichi/util.h>
#include <taichi/visual/gui.h>
#include <taichi/system/profiler.h>
#include <taichi/visualization/particle_visualization.h>
TC_NAMESPACE_BEGIN
using namespace Tlang;
auto cnn = []() {
CoreState::set_trigger_gdb_when_crash(true);
Program prog(Arch::gpu);
constexpr int dim = 3;
constexpr int n = 256;
Global(layer1, f32);
Global(layer2, f32);
Global(weights, f32);
layout([&]() {
auto ijkl = Indices(0, 1, 2, 3);
root.dense(ijkl, {n, n, n, 4}).place(layer1);
root.dense(ijkl, {3, 3, 3, 16}).place(weights);
});
Kernel(forward).def([&] {
BlockDim(1024);
For(layer2, [&](Expr i, Expr j, Expr k, Expr c_out) {
// layer1[]
});
});
};
TC_REGISTER_TASK(cnn);
TC_NAMESPACE_END
<commit_msg>cnn visualization<commit_after>#include "../tlang.h"
#include <taichi/util.h>
#include <taichi/visual/gui.h>
#include <taichi/system/profiler.h>
#include <taichi/visualization/particle_visualization.h>
TC_NAMESPACE_BEGIN
using namespace Tlang;
auto cnn = []() {
CoreState::set_trigger_gdb_when_crash(true);
Program prog(Arch::gpu);
constexpr int dim = 3;
constexpr int n = 256;
constexpr int num_ch1 = 4, num_ch2 = 4;
Global(layer1, f32);
Global(layer2, f32);
Global(weights, f32);
layout([&]() {
auto ijkl = Indices(0, 1, 2, 3);
root.dense(ijkl, {n, n, n, 4}).place(layer1);
root.dense(ijkl, {n, n, n, 4}).place(layer2);
root.dense(ijkl, {4, 4, 4, 16}).place(weights);
});
Kernel(forward).def([&] {
BlockDim(1024);
For(layer2, [&](Expr i, Expr j, Expr k, Expr c_out) {
// layer1[]
});
});
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
auto len = (Vector3i(i, j, k) - Vector3i(n / 2)).length() / (float32)n;
if (0.4 < len && len < 0.5) {
layer1.val<float32>(i, j, k, 0) = len;
}
}
}
}
int gui_res = 512;
GUI gui("FEM", Vector2i(gui_res + 200, gui_res), false);
int layer = 1;
int k = 0;
int channel = 0;
gui.slider("z", k, 0, n - 1).slider("Layer", layer, 1, 2);
int scale = gui_res / n;
auto &canvas = gui.get_canvas();
for (int frame = 1;; frame++) {
for (int i = 0; i < gui_res - scale; i++) {
for (int j = 0; j < gui_res - scale; j++) {
real dx;
if (layer == 1) {
dx = layer1.val<float32>(i / scale, j / scale, k, channel);
} else {
dx = layer2.val<float32>(i / scale, j / scale, k, channel);
}
canvas.img[i][j] = Vector4(0.5f) + Vector4(dx) * 0.5f;
}
}
gui.update();
}
};
TC_REGISTER_TASK(cnn);
TC_NAMESPACE_END
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 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
*
*****************************************************************************/
// mapnik
#include <mapnik/text/face.hpp>
#include <mapnik/debug.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
extern "C"
{
#include FT_GLYPH_H
}
#pragma GCC diagnostic pop
namespace mapnik
{
font_face::font_face(FT_Face face)
: face_(face), unscaled_ascender_(get_ascender()) {}
bool font_face::set_character_sizes(double size)
{
return (FT_Set_Char_Size(face_,0,static_cast<FT_F26Dot6>(size * (1<<6)),0,0) == 0);
}
bool font_face::set_unscaled_character_sizes()
{
return (FT_Set_Char_Size(face_,0,face_->units_per_EM,0,0) == 0);
}
bool font_face::glyph_dimensions(glyph_info & glyph) const
{
FT_Vector pen;
pen.x = 0;
pen.y = 0;
FT_Set_Transform(face_, 0, &pen);
if (FT_Load_Glyph(face_, glyph.glyph_index, FT_LOAD_NO_HINTING))
{
MAPNIK_LOG_ERROR(font_face) << "FT_Load_Glyph failed";
return false;
}
FT_Glyph image;
if (FT_Get_Glyph(face_->glyph, &image))
{
MAPNIK_LOG_ERROR(font_face) << "FT_Get_Glyph failed";
return false;
}
FT_BBox glyph_bbox;
FT_Glyph_Get_CBox(image, FT_GLYPH_BBOX_TRUNCATE, &glyph_bbox);
FT_Done_Glyph(image);
glyph.unscaled_ymin = glyph_bbox.yMin;
glyph.unscaled_ymax = glyph_bbox.yMax;
glyph.unscaled_advance = face_->glyph->advance.x;
glyph.unscaled_line_height = face_->size->metrics.height;
glyph.unscaled_ascender = unscaled_ascender_;
return true;
}
font_face::~font_face()
{
MAPNIK_LOG_DEBUG(font_face) <<
"font_face: Clean up face \"" << family_name() <<
" " << style_name() << "\"";
FT_Done_Face(face_);
}
// https://github.com/mapnik/mapnik/issues/2578
double font_face::get_ascender()
{
set_unscaled_character_sizes();
unsigned glyph_index = FT_Get_Char_Index(face_, 'X');
FT_Vector pen;
pen.x = 0;
pen.y = 0;
FT_Set_Transform(face_, 0, &pen);
int e = 0;
if (!(e = FT_Load_Glyph(face_, glyph_index, FT_LOAD_NO_HINTING)))
{
FT_Glyph image;
if (!FT_Get_Glyph(face_->glyph, &image))
{
FT_BBox glyph_bbox;
FT_Glyph_Get_CBox(image, FT_GLYPH_BBOX_TRUNCATE, &glyph_bbox);
FT_Done_Glyph(image);
return 64.0 * (glyph_bbox.yMax - glyph_bbox.yMin);
}
}
return face_->ascender;
}
/******************************************************************************/
void font_face_set::add(face_ptr face)
{
faces_.push_back(face);
}
void font_face_set::set_character_sizes(double size)
{
for (face_ptr const& face : faces_)
{
face->set_character_sizes(size);
}
}
void font_face_set::set_unscaled_character_sizes()
{
for (face_ptr const& face : faces_)
{
face->set_unscaled_character_sizes();
}
}
/******************************************************************************/
void stroker::init(double radius)
{
FT_Stroker_Set(s_, static_cast<FT_Fixed>(radius * (1<<6)),
FT_STROKER_LINECAP_ROUND,
FT_STROKER_LINEJOIN_ROUND,
0);
}
stroker::~stroker()
{
MAPNIK_LOG_DEBUG(font_engine_freetype) << "stroker: Destroy stroker=" << s_;
FT_Stroker_Done(s_);
}
}//ns mapnik
<commit_msg>use FT_Load_Sfnt_Table to identify color fonts + load color glyphs with FT_LOAD_COLOR<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2015 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
*
*****************************************************************************/
// mapnik
#include <mapnik/text/face.hpp>
#include <mapnik/debug.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
extern "C"
{
#include FT_GLYPH_H
#include FT_TRUETYPE_TABLES_H
}
#pragma GCC diagnostic pop
namespace mapnik
{
font_face::font_face(FT_Face face)
: face_(face), unscaled_ascender_(get_ascender())
{
static const uint32_t tag = FT_MAKE_TAG('C', 'B', 'D', 'T');
unsigned long length = 0;
FT_Load_Sfnt_Table(face_, tag, 0, nullptr, &length);
if (length) color_font_ = true;
}
bool font_face::set_character_sizes(double size)
{
return (FT_Set_Char_Size(face_, 0, static_cast<FT_F26Dot6>(size * (1 << 6)), 0, 0) == 0);
}
bool font_face::set_unscaled_character_sizes()
{
FT_F26Dot6 char_height = face_->units_per_EM > 0 ? face_->units_per_EM : 2048.0;
return (FT_Set_Char_Size(face_, 0, char_height, 0, 0) == 0);
}
bool font_face::glyph_dimensions(glyph_info & glyph) const
{
FT_Vector pen;
pen.x = 0;
pen.y = 0;
if (color_font_) FT_Select_Size(face_, 0);
FT_Set_Transform(face_, 0, &pen);
FT_Int32 load_flags = FT_LOAD_DEFAULT;// | FT_LOAD_NO_HINTING;
if (color_font_) load_flags |= FT_LOAD_COLOR ;
if (FT_Load_Glyph(face_, glyph.glyph_index, load_flags))
{
MAPNIK_LOG_ERROR(font_face) << "FT_Load_Glyph failed :( index=" << glyph.glyph_index << " " << load_flags
<< " " << face_->family_name << " " << face_->style_name ;
return false;
}
FT_Glyph image;
if (FT_Get_Glyph(face_->glyph, &image))
{
MAPNIK_LOG_ERROR(font_face) << "FT_Get_Glyph failed";
return false;
}
FT_BBox glyph_bbox;
FT_Glyph_Get_CBox(image, FT_GLYPH_BBOX_TRUNCATE, &glyph_bbox);
FT_Done_Glyph(image);
glyph.unscaled_ymin = glyph_bbox.yMin;
glyph.unscaled_ymax = glyph_bbox.yMax;
glyph.unscaled_advance = face_->glyph->advance.x;
glyph.unscaled_line_height = face_->size->metrics.height;
glyph.unscaled_ascender = unscaled_ascender_;
return true;
}
font_face::~font_face()
{
MAPNIK_LOG_DEBUG(font_face) <<
"font_face: Clean up face \"" << family_name() <<
" " << style_name() << "\"";
FT_Done_Face(face_);
}
// https://github.com/mapnik/mapnik/issues/2578
double font_face::get_ascender()
{
set_unscaled_character_sizes();
unsigned glyph_index = FT_Get_Char_Index(face_, 'X');
FT_Vector pen;
pen.x = 0;
pen.y = 0;
FT_Set_Transform(face_, 0, &pen);
int e = 0;
if (!(e = FT_Load_Glyph(face_, glyph_index, FT_LOAD_NO_HINTING)))
{
FT_Glyph image;
if (!FT_Get_Glyph(face_->glyph, &image))
{
FT_BBox glyph_bbox;
FT_Glyph_Get_CBox(image, FT_GLYPH_BBOX_TRUNCATE, &glyph_bbox);
FT_Done_Glyph(image);
return 64.0 * (glyph_bbox.yMax - glyph_bbox.yMin);
}
}
return face_->ascender;
}
/******************************************************************************/
void font_face_set::add(face_ptr face)
{
faces_.push_back(face);
}
void font_face_set::set_character_sizes(double size)
{
for (face_ptr const& face : faces_)
{
face->set_character_sizes(size);
}
}
void font_face_set::set_unscaled_character_sizes()
{
for (face_ptr const& face : faces_)
{
face->set_unscaled_character_sizes();
}
}
/******************************************************************************/
void stroker::init(double radius)
{
FT_Stroker_Set(s_, static_cast<FT_Fixed>(radius * (1<<6)),
FT_STROKER_LINECAP_ROUND,
FT_STROKER_LINEJOIN_ROUND,
0);
}
stroker::~stroker()
{
MAPNIK_LOG_DEBUG(font_engine_freetype) << "stroker: Destroy stroker=" << s_;
FT_Stroker_Done(s_);
}
}//ns mapnik
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of 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.
*
* $Id: texture_mapping.hpp 1006 2011-07-13 13:07:00 ktran $
*
*/
/** \author Khai Tran */
#ifndef PCL_SURFACE_IMPL_TEXTURE_MAPPING_HPP_
#define PCL_SURFACE_IMPL_TEXTURE_MAPPING_HPP_
#include "pcl/surface/texture_mapping.h"
///////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> float
pcl::TextureMapping<PointInT>::getDistance (Eigen::Vector3f &p1, Eigen::Vector3f &p2)
{
return std::sqrt((p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) + (p1[2]-p2[2])*(p1[2]-p2[2]));
}
///////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> std::vector<Eigen::Vector2f>
pcl::TextureMapping<PointInT>::mapTexture2Face (Eigen::Vector3f &p1, Eigen::Vector3f &p2, Eigen::Vector3f &p3)
{
std::vector<Eigen::Vector2f> tex_coordinates;
// process for each face
Eigen::Vector3f p1p2(p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2]);
Eigen::Vector3f p1p3(p3[0] - p1[0], p3[1] - p1[1], p3[2] - p1[2]);
Eigen::Vector3f p2p3(p3[0] - p2[0], p3[1] - p2[1], p3[2] - p2[2]);
// Normalize
p1p2 = p1p2/std::sqrt(p1p2.dot(p1p2));
p1p3 = p1p3/std::sqrt(p1p3.dot(p1p3));
p2p3 = p2p3/std::sqrt(p2p3.dot(p2p3));
// compute vector normal of a face
Eigen::Vector3f f_normal = p1p2.cross(p1p3);
f_normal = f_normal/std::sqrt(f_normal.dot(f_normal));
// project vector field onto the face: vector v1_projected = v1 - Dot(v1, n) * n;
Eigen::Vector3f f_vector_field = vector_field_ - vector_field_.dot(f_normal) * f_normal;
// Normalize
f_vector_field = f_vector_field/std::sqrt(f_vector_field.dot(f_vector_field));
// texture coordinates
Eigen::Vector2f tp1, tp2, tp3;
double alpha = std::acos(f_vector_field.dot(p1p2));
// distance between 3 vertices of triangles
double e1 = getDistance(p2, p3)/f_;
double e2 = getDistance(p1, p3)/f_;
double e3 = getDistance(p1, p2)/f_;
// initialize
tp1[0] = 0.0;
tp1[1] = 0.0;
tp2[0] = e3;
tp2[1] = 0.0;
// determine texture coordinate tp3;
double cos_p1 = (e2*e2+e3*e3-e1*e1)/(2*e2*e3);
double sin_p1 = sqrt(1-(cos_p1*cos_p1));
tp3[0] = cos_p1*e2;
tp3[1] = sin_p1*e2;
// rotating by alpha (angle between V and pp1 & pp2)
Eigen::Vector2f r_tp2, r_tp3;
r_tp2[0] = tp2[0]*std::cos(alpha) - tp2[1]*std::sin(alpha);
r_tp2[1] = tp2[0]*std::sin(alpha) + tp2[1]*std::cos(alpha);
r_tp3[0] = tp3[0]*std::cos(alpha) - tp3[1]*std::sin(alpha);
r_tp3[1] = tp3[0]*std::sin(alpha) + tp3[1]*std::cos(alpha);
// shifting
tp1[0] = tp1[0];
tp2[0] = r_tp2[0];
tp3[0] = r_tp3[0];
tp1[1] = tp1[1];
tp2[1] = r_tp2[1];
tp3[1] = r_tp3[1];
float min_x = tp1[0];
float min_y = tp1[1];
if (min_x > tp2[0]) min_x = tp2[0];
if (min_x > tp3[0]) min_x = tp3[0];
if (min_y > tp2[1]) min_y = tp2[1];
if (min_y > tp3[1]) min_y = tp3[1];
if(min_x < 0)
{
tp1[0] = tp1[0] - min_x;
tp2[0] = tp2[0] - min_x;
tp3[0] = tp3[0] - min_x;
}
if(min_y < 0)
{
tp1[1] = tp1[1] - min_y;
tp2[1] = tp2[1] - min_y;
tp3[1] = tp3[1] - min_y;
}
tex_coordinates.push_back(tp1);
tex_coordinates.push_back(tp2);
tex_coordinates.push_back(tp3);
return tex_coordinates;
}
///////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::TextureMapping<PointInT>::mapTexture2Mesh (pcl::TextureMesh &tex_mesh)
{
// mesh information
int nr_points = tex_mesh.cloud.width * tex_mesh.cloud.height;
int point_size = tex_mesh.cloud.data.size () / nr_points;
// temporary PointXYZ
float x, y, z;
// temporary face
Eigen::Vector3f facet[3];
// texture coordinates for each mesh
std::vector< std::vector<Eigen::Vector2f> > texture_map;
for (size_t m = 0; m < tex_mesh.tex_polygons.size(); ++m)
{
// texture coordinates for each mesh
std::vector<Eigen::Vector2f> texture_map_tmp;
// processing for each face
for (size_t i=0; i < tex_mesh.tex_polygons[m].size(); ++i)
{
size_t idx;
// get facet information
for (size_t j=0; j < tex_mesh.tex_polygons[m][i].vertices.size(); ++j)
{
idx = tex_mesh.tex_polygons[m][i].vertices[j];
memcpy (&x, &tex_mesh.cloud.data[idx * point_size + tex_mesh.cloud.fields[0].offset], sizeof (float));
memcpy (&y, &tex_mesh.cloud.data[idx * point_size + tex_mesh.cloud.fields[1].offset], sizeof (float));
memcpy (&z, &tex_mesh.cloud.data[idx * point_size + tex_mesh.cloud.fields[2].offset], sizeof (float));
facet[j][0] = x;
facet[j][1] = y;
facet[j][2] = z;
}
// get texture coordinates of each face
std::vector<Eigen::Vector2f> tex_coordinates = mapTexture2Face(facet[0], facet[1], facet[2]);
for(size_t n = 0; n < tex_coordinates.size(); ++n)
texture_map_tmp.push_back(tex_coordinates[n]);
}// end faces
// texture materials
std::stringstream tex_name;
tex_name << "material_"<< m;
tex_name >> tex_material_.tex_name;
tex_material_.tex_file = tex_files_[m];
tex_mesh.tex_materials.push_back(tex_material_);
// texture coordinates
tex_mesh.tex_coordinates.push_back(texture_map_tmp);
}// end meshes
}
///////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::TextureMapping<PointInT>::mapTexture2MeshUV (pcl::TextureMesh &tex_mesh){
// mesh information
int nr_points = tex_mesh.cloud.width * tex_mesh.cloud.height;
int point_size = tex_mesh.cloud.data.size () / nr_points;
float x_lowest = 100000;
float x_highest = 0 ;
float y_lowest = 100000;
float y_highest = 0 ;
float z_lowest = 100000;
float z_highest = 0;
float x_, y_, z_;
for (int i =0; i < nr_points; ++i)
{
memcpy (&x_, &tex_mesh.cloud.data[i * point_size + tex_mesh.cloud.fields[0].offset], sizeof (float));
memcpy (&y_, &tex_mesh.cloud.data[i * point_size + tex_mesh.cloud.fields[1].offset], sizeof (float));
memcpy (&z_, &tex_mesh.cloud.data[i * point_size + tex_mesh.cloud.fields[2].offset], sizeof (float));
// x
if (x_ <= x_lowest) x_lowest = x_;
if (x_ > x_lowest) x_highest = x_;
// y
if (y_ <= y_lowest) y_lowest = y_;
if (y_ > y_lowest) y_highest = y_;
// z
if (z_ <= z_lowest) z_lowest = z_;
if (z_ > z_lowest) z_highest = z_;
}
// x
float x_range = (x_lowest - x_highest)*-1;
float x_offset = 0 - x_lowest;
// x
//float y_range = (y_lowest - y_highest)*-1;
//float y_offset = 0 - y_lowest;
// z
float z_range = (z_lowest - z_highest)*-1;
float z_offset = 0 - z_lowest;
// texture coordinates for each mesh
std::vector< std::vector<Eigen::Vector2f> > texture_map;
for (size_t m = 0; m < tex_mesh.tex_polygons.size(); ++m)
{
// texture coordinates for each mesh
std::vector<Eigen::Vector2f> texture_map_tmp;
// processing for each face
for (size_t i=0; i < tex_mesh.tex_polygons[m].size(); ++i)
{
size_t idx;
Eigen::Vector2f tmp_VT;
for (size_t j=0; j < tex_mesh.tex_polygons[m][i].vertices.size(); ++j)
{
idx = tex_mesh.tex_polygons[m][i].vertices[j];
memcpy (&x_, &tex_mesh.cloud.data[idx * point_size + tex_mesh.cloud.fields[0].offset], sizeof (float));
memcpy (&y_, &tex_mesh.cloud.data[idx * point_size + tex_mesh.cloud.fields[1].offset], sizeof (float));
memcpy (&z_, &tex_mesh.cloud.data[idx * point_size + tex_mesh.cloud.fields[2].offset], sizeof (float));
// calculate uv coordinates
tmp_VT[0] = (x_ + x_offset)/x_range;
tmp_VT[1] = (z_ + z_offset)/z_range;
texture_map_tmp.push_back(tmp_VT);
}
}// end faces
// texture materials
std::stringstream tex_name;
tex_name << "material_"<< m;
tex_name >> tex_material_.tex_name;
tex_material_.tex_file = tex_files_[m];
tex_mesh.tex_materials.push_back(tex_material_);
// texture coordinates
tex_mesh.tex_coordinates.push_back(texture_map_tmp);
}// end meshes
}
#define PCL_INSTANTIATE_TextureMapping(T) \
template class PCL_EXPORTS pcl::TextureMapping<T>;
#endif /* TEXTURE_MAPPING_HPP_ */
<commit_msg>fixed a compiler warning<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of 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.
*
* $Id: texture_mapping.hpp 1006 2011-07-13 13:07:00 ktran $
*
*/
/** \author Khai Tran */
#ifndef PCL_SURFACE_IMPL_TEXTURE_MAPPING_HPP_
#define PCL_SURFACE_IMPL_TEXTURE_MAPPING_HPP_
#include "pcl/surface/texture_mapping.h"
///////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> float
pcl::TextureMapping<PointInT>::getDistance (Eigen::Vector3f &p1, Eigen::Vector3f &p2)
{
return std::sqrt((p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) + (p1[2]-p2[2])*(p1[2]-p2[2]));
}
///////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> std::vector<Eigen::Vector2f>
pcl::TextureMapping<PointInT>::mapTexture2Face (Eigen::Vector3f &p1, Eigen::Vector3f &p2, Eigen::Vector3f &p3)
{
std::vector<Eigen::Vector2f> tex_coordinates;
// process for each face
Eigen::Vector3f p1p2(p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2]);
Eigen::Vector3f p1p3(p3[0] - p1[0], p3[1] - p1[1], p3[2] - p1[2]);
Eigen::Vector3f p2p3(p3[0] - p2[0], p3[1] - p2[1], p3[2] - p2[2]);
// Normalize
p1p2 = p1p2/std::sqrt(p1p2.dot(p1p2));
p1p3 = p1p3/std::sqrt(p1p3.dot(p1p3));
p2p3 = p2p3/std::sqrt(p2p3.dot(p2p3));
// compute vector normal of a face
Eigen::Vector3f f_normal = p1p2.cross(p1p3);
f_normal = f_normal/std::sqrt(f_normal.dot(f_normal));
// project vector field onto the face: vector v1_projected = v1 - Dot(v1, n) * n;
Eigen::Vector3f f_vector_field = vector_field_ - vector_field_.dot(f_normal) * f_normal;
// Normalize
f_vector_field = f_vector_field/std::sqrt(f_vector_field.dot(f_vector_field));
// texture coordinates
Eigen::Vector2f tp1, tp2, tp3;
double alpha = std::acos(f_vector_field.dot(p1p2));
// distance between 3 vertices of triangles
double e1 = getDistance(p2, p3)/f_;
double e2 = getDistance(p1, p3)/f_;
double e3 = getDistance(p1, p2)/f_;
// initialize
tp1[0] = 0.0;
tp1[1] = 0.0;
tp2[0] = e3;
tp2[1] = 0.0;
// determine texture coordinate tp3;
double cos_p1 = (e2*e2+e3*e3-e1*e1)/(2*e2*e3);
double sin_p1 = sqrt(1-(cos_p1*cos_p1));
tp3[0] = cos_p1*e2;
tp3[1] = sin_p1*e2;
// rotating by alpha (angle between V and pp1 & pp2)
Eigen::Vector2f r_tp2, r_tp3;
r_tp2[0] = tp2[0]*std::cos(alpha) - tp2[1]*std::sin(alpha);
r_tp2[1] = tp2[0]*std::sin(alpha) + tp2[1]*std::cos(alpha);
r_tp3[0] = tp3[0]*std::cos(alpha) - tp3[1]*std::sin(alpha);
r_tp3[1] = tp3[0]*std::sin(alpha) + tp3[1]*std::cos(alpha);
// shifting
tp1[0] = tp1[0];
tp2[0] = r_tp2[0];
tp3[0] = r_tp3[0];
tp1[1] = tp1[1];
tp2[1] = r_tp2[1];
tp3[1] = r_tp3[1];
float min_x = tp1[0];
float min_y = tp1[1];
if (min_x > tp2[0]) min_x = tp2[0];
if (min_x > tp3[0]) min_x = tp3[0];
if (min_y > tp2[1]) min_y = tp2[1];
if (min_y > tp3[1]) min_y = tp3[1];
if(min_x < 0)
{
tp1[0] = tp1[0] - min_x;
tp2[0] = tp2[0] - min_x;
tp3[0] = tp3[0] - min_x;
}
if(min_y < 0)
{
tp1[1] = tp1[1] - min_y;
tp2[1] = tp2[1] - min_y;
tp3[1] = tp3[1] - min_y;
}
tex_coordinates.push_back(tp1);
tex_coordinates.push_back(tp2);
tex_coordinates.push_back(tp3);
return tex_coordinates;
}
///////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::TextureMapping<PointInT>::mapTexture2Mesh (pcl::TextureMesh &tex_mesh)
{
// mesh information
int nr_points = tex_mesh.cloud.width * tex_mesh.cloud.height;
int point_size = tex_mesh.cloud.data.size () / nr_points;
// temporary PointXYZ
float x, y, z;
// temporary face
Eigen::Vector3f facet[3];
// texture coordinates for each mesh
std::vector< std::vector<Eigen::Vector2f> > texture_map;
for (size_t m = 0; m < tex_mesh.tex_polygons.size(); ++m)
{
// texture coordinates for each mesh
std::vector<Eigen::Vector2f> texture_map_tmp;
// processing for each face
for (size_t i=0; i < tex_mesh.tex_polygons[m].size(); ++i)
{
size_t idx;
// get facet information
for (size_t j=0; j < tex_mesh.tex_polygons[m][i].vertices.size(); ++j)
{
idx = tex_mesh.tex_polygons[m][i].vertices[j];
memcpy (&x, &tex_mesh.cloud.data[idx * point_size + tex_mesh.cloud.fields[0].offset], sizeof (float));
memcpy (&y, &tex_mesh.cloud.data[idx * point_size + tex_mesh.cloud.fields[1].offset], sizeof (float));
memcpy (&z, &tex_mesh.cloud.data[idx * point_size + tex_mesh.cloud.fields[2].offset], sizeof (float));
facet[j][0] = x;
facet[j][1] = y;
facet[j][2] = z;
}
// get texture coordinates of each face
std::vector<Eigen::Vector2f> tex_coordinates = mapTexture2Face(facet[0], facet[1], facet[2]);
for(size_t n = 0; n < tex_coordinates.size(); ++n)
texture_map_tmp.push_back(tex_coordinates[n]);
}// end faces
// texture materials
std::stringstream tex_name;
tex_name << "material_"<< m;
tex_name >> tex_material_.tex_name;
tex_material_.tex_file = tex_files_[m];
tex_mesh.tex_materials.push_back(tex_material_);
// texture coordinates
tex_mesh.tex_coordinates.push_back(texture_map_tmp);
}// end meshes
}
///////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::TextureMapping<PointInT>::mapTexture2MeshUV (pcl::TextureMesh &tex_mesh){
// mesh information
int nr_points = tex_mesh.cloud.width * tex_mesh.cloud.height;
int point_size = tex_mesh.cloud.data.size () / nr_points;
float x_lowest = 100000;
float x_highest = 0 ;
float y_lowest = 100000;
//float y_highest = 0 ;
float z_lowest = 100000;
float z_highest = 0;
float x_, y_, z_;
for (int i =0; i < nr_points; ++i)
{
memcpy (&x_, &tex_mesh.cloud.data[i * point_size + tex_mesh.cloud.fields[0].offset], sizeof (float));
memcpy (&y_, &tex_mesh.cloud.data[i * point_size + tex_mesh.cloud.fields[1].offset], sizeof (float));
memcpy (&z_, &tex_mesh.cloud.data[i * point_size + tex_mesh.cloud.fields[2].offset], sizeof (float));
// x
if (x_ <= x_lowest) x_lowest = x_;
if (x_ > x_lowest) x_highest = x_;
// y
if (y_ <= y_lowest) y_lowest = y_;
//if (y_ > y_lowest) y_highest = y_;
// z
if (z_ <= z_lowest) z_lowest = z_;
if (z_ > z_lowest) z_highest = z_;
}
// x
float x_range = (x_lowest - x_highest)*-1;
float x_offset = 0 - x_lowest;
// x
//float y_range = (y_lowest - y_highest)*-1;
//float y_offset = 0 - y_lowest;
// z
float z_range = (z_lowest - z_highest)*-1;
float z_offset = 0 - z_lowest;
// texture coordinates for each mesh
std::vector< std::vector<Eigen::Vector2f> > texture_map;
for (size_t m = 0; m < tex_mesh.tex_polygons.size(); ++m)
{
// texture coordinates for each mesh
std::vector<Eigen::Vector2f> texture_map_tmp;
// processing for each face
for (size_t i=0; i < tex_mesh.tex_polygons[m].size(); ++i)
{
size_t idx;
Eigen::Vector2f tmp_VT;
for (size_t j=0; j < tex_mesh.tex_polygons[m][i].vertices.size(); ++j)
{
idx = tex_mesh.tex_polygons[m][i].vertices[j];
memcpy (&x_, &tex_mesh.cloud.data[idx * point_size + tex_mesh.cloud.fields[0].offset], sizeof (float));
memcpy (&y_, &tex_mesh.cloud.data[idx * point_size + tex_mesh.cloud.fields[1].offset], sizeof (float));
memcpy (&z_, &tex_mesh.cloud.data[idx * point_size + tex_mesh.cloud.fields[2].offset], sizeof (float));
// calculate uv coordinates
tmp_VT[0] = (x_ + x_offset)/x_range;
tmp_VT[1] = (z_ + z_offset)/z_range;
texture_map_tmp.push_back(tmp_VT);
}
}// end faces
// texture materials
std::stringstream tex_name;
tex_name << "material_"<< m;
tex_name >> tex_material_.tex_name;
tex_material_.tex_file = tex_files_[m];
tex_mesh.tex_materials.push_back(tex_material_);
// texture coordinates
tex_mesh.tex_coordinates.push_back(texture_map_tmp);
}// end meshes
}
#define PCL_INSTANTIATE_TextureMapping(T) \
template class PCL_EXPORTS pcl::TextureMapping<T>;
#endif /* TEXTURE_MAPPING_HPP_ */
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
// Copyright (c) 2016-2026
// -------------------------------------------------------------------------
// Module: luabind_plus_test
// File name: main.cpp
// Created: 2016/04/01 by Albert D Yang
// Description:
// -------------------------------------------------------------------------
// 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 <vld.h>
#include <vtd/rtti.h>
extern "C"
{
# include <lua/lua.h>
# include <lua/lualib.h>
# include <lua/lauxlib.h>
}
#include <assert.h>
#include <luabind/luabind.h>
#include <stdio.h>
class A
{
public:
vtd_rtti_decl(A);
virtual ~A() {}
int a = 5;
};
vtd_rtti_impl(A);
class B
{
public:
vtd_rtti_decl(B);
virtual ~B() {}
int b = 8;
};
vtd_rtti_impl(B);
class C : public A, public B
{
public:
vtd_rtti_decl(C, A, B);
virtual ~C() {}
int c = 11;
};
vtd_rtti_impl(C, A, B);
void test_rtti()
{
C* pkC = new C;
A* pkA = static_cast<A*>(pkC);
B* pkB = static_cast<B*>(pkC);
bool b = vtd_is_kind_of(B, pkA);
b = vtd_is_exact_kind_of(B, pkA);
A* pkA2 = vtd_dynamic_cast(A, pkB);
B* pkB2 = vtd_dynamic_cast(B, pkB);
C* pkC2 = vtd_dynamic_cast(C, pkC);
C* pkC3 = vtd_dynamic_cast(C, pkB);
printf("RTTI TEST: %d,%d,%d,%d,%d\n", pkA2->a, pkB2->b, pkC2->c, pkC3->c, b);
delete pkC;
}
int lua_print(lua_State* L) noexcept
{
lua_writestring("--->", 4);
int n = lua_gettop(L); /* number of arguments */
int i;
lua_getglobal(L, "tostring");
for (i = 1; i <= n; i++) {
const char *s;
size_t l;
lua_pushvalue(L, -1); /* function to be called */
lua_pushvalue(L, i); /* value to print */
lua_call(L, 1, 1);
s = lua_tolstring(L, -1, &l); /* get result */
if (s == NULL)
return luaL_error(L, "'tostring' must return a string to 'print'");
if (i > 1) lua_writestring("\t", 1);
lua_writestring(s, l);
lua_pop(L, 1); /* pop result */
}
lua_writeline();
return 0;
}
enum Test
{
TEST_A,
TEST_B,
TEST_C
};
int main()
{
int a = luabind::default_maker<int>::make();
bool b = luabind::default_maker<bool>::make();
Test t = luabind::default_maker<Test>::make();
test_rtti();
lua_State* L = luaL_newstate();
if (L)
{
luaL_openlibs(L);
lua_pushcfunction(L, &lua_print);
lua_setglobal(L, "print");
char input_buf[65536];
while (true)
{
printf("LUA>");
scanf("%s", input_buf);
int err = luaL_dostring(L, input_buf);
if (err)
{
fprintf(stderr, "ERR>%s\n", lua_tostring(L, -1));
lua_pop(L, 1);
}
}
lua_close(L);
L = nullptr;
}
return 0;
}
<commit_msg>vld for win32<commit_after>////////////////////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
// Copyright (c) 2016-2026
// -------------------------------------------------------------------------
// Module: luabind_plus_test
// File name: main.cpp
// Created: 2016/04/01 by Albert D Yang
// Description:
// -------------------------------------------------------------------------
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// -------------------------------------------------------------------------
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
// -------------------------------------------------------------------------
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////
#ifdef WIN32
# include <vld.h>
#endif
#include <vtd/rtti.h>
extern "C"
{
# include <lua/lua.h>
# include <lua/lualib.h>
# include <lua/lauxlib.h>
}
#include <assert.h>
#include <luabind/luabind.h>
#include <stdio.h>
class A
{
public:
vtd_rtti_decl(A);
virtual ~A() {}
int a = 5;
};
vtd_rtti_impl(A);
class B
{
public:
vtd_rtti_decl(B);
virtual ~B() {}
int b = 8;
};
vtd_rtti_impl(B);
class C : public A, public B
{
public:
vtd_rtti_decl(C, A, B);
virtual ~C() {}
int c = 11;
};
vtd_rtti_impl(C, A, B);
void test_rtti()
{
C* pkC = new C;
A* pkA = static_cast<A*>(pkC);
B* pkB = static_cast<B*>(pkC);
bool b = vtd_is_kind_of(B, pkA);
b = vtd_is_exact_kind_of(B, pkA);
A* pkA2 = vtd_dynamic_cast(A, pkB);
B* pkB2 = vtd_dynamic_cast(B, pkB);
C* pkC2 = vtd_dynamic_cast(C, pkC);
C* pkC3 = vtd_dynamic_cast(C, pkB);
printf("RTTI TEST: %d,%d,%d,%d,%d\n", pkA2->a, pkB2->b, pkC2->c, pkC3->c, b);
delete pkC;
}
int lua_print(lua_State* L) noexcept
{
lua_writestring("--->", 4);
int n = lua_gettop(L); /* number of arguments */
int i;
lua_getglobal(L, "tostring");
for (i = 1; i <= n; i++) {
const char *s;
size_t l;
lua_pushvalue(L, -1); /* function to be called */
lua_pushvalue(L, i); /* value to print */
lua_call(L, 1, 1);
s = lua_tolstring(L, -1, &l); /* get result */
if (s == NULL)
return luaL_error(L, "'tostring' must return a string to 'print'");
if (i > 1) lua_writestring("\t", 1);
lua_writestring(s, l);
lua_pop(L, 1); /* pop result */
}
lua_writeline();
return 0;
}
enum Test
{
TEST_A,
TEST_B,
TEST_C
};
int main()
{
int a = luabind::default_maker<int>::make();
bool b = luabind::default_maker<bool>::make();
Test t = luabind::default_maker<Test>::make();
test_rtti();
lua_State* L = luaL_newstate();
if (L)
{
luaL_openlibs(L);
lua_pushcfunction(L, &lua_print);
lua_setglobal(L, "print");
char input_buf[65536];
while (true)
{
printf("LUA>");
scanf("%s", input_buf);
int err = luaL_dostring(L, input_buf);
if (err)
{
fprintf(stderr, "ERR>%s\n", lua_tostring(L, -1));
lua_pop(L, 1);
}
}
lua_close(L);
L = nullptr;
}
return 0;
}
<|endoftext|> |
<commit_before>//
// ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0
//
// Author: Markus Konrad <post@mkonrad.net>, Winter 2014/2015
// http://www.mkonrad.net
//
// See LICENSE file in project repository root for the license.
//
#include "memtransfer_ios.h"
#import <CoreVideo/CoreVideo.h>
#include "../../common/core.h"
#include "../../common/proc/yuv2rgb.h"
/**
* Most code as from http://allmybrain.com/2011/12/08/rendering-to-a-texture-with-ios-5-texture-cache-api/
*/
using namespace std;
using namespace ogles_gpgpu;
#pragma mark static methods
bool MemTransferIOS::initPlatformOptimizations() {
#if TARGET_IPHONE_SIMULATOR
OG_LOGERR("MemTransferIOS", "platform optimizations not available in simulator");
return false; // not CV texture cache API not available in simulator
#else
return true; // CV texture cache API available, but nothing to initialize, just return true
#endif
}
#pragma mark constructor / deconstructor
MemTransferIOS::~MemTransferIOS() {
// release in- and outputs
releaseInput();
releaseOutput();
// release texture cache and buffer attributes
CFRelease(textureCache);
CFRelease(bufferAttr);
}
#pragma mark public methods
void MemTransferIOS::releaseInput() {
if (inputPixelBuffer) {
CVPixelBufferRelease(inputPixelBuffer);
inputPixelBuffer = NULL;
}
if (inputTexture) {
CFRelease(inputTexture);
inputTexture = NULL;
}
if (lumaTexture) {
CFRelease(lumaTexture);
lumaTexture = NULL;
}
if (chromaTexture) {
CFRelease(chromaTexture);
chromaTexture = NULL;
}
CVOpenGLESTextureCacheFlush(textureCache, 0);
preparedInput = false;
}
void MemTransferIOS::releaseOutput() {
if (outputPixelBuffer) {
CVPixelBufferRelease(outputPixelBuffer);
outputPixelBuffer = NULL;
}
if (outputTexture) {
CFRelease(outputTexture);
outputTexture = NULL;
}
CVOpenGLESTextureCacheFlush(textureCache, 0);
preparedOutput = false;
}
void MemTransferIOS::init() {
assert(!initialized);
CFDictionaryRef empty;
empty = CFDictionaryCreate(kCFAllocatorDefault, // our empty IOSurface properties dictionary
NULL,
NULL,
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
bufferAttr = CFDictionaryCreateMutable(kCFAllocatorDefault,
1,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(bufferAttr,
kCVPixelBufferIOSurfacePropertiesKey,
empty);
// create texture cache
void *glCtxPtr = Core::getInstance()->getGLContextPtr();
OG_LOGINF("MemTransferIOS", "OpenGL ES context at %p", glCtxPtr);
assert(glCtxPtr);
CVReturn res = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault,
NULL,
(CVEAGLContext)glCtxPtr,
NULL,
&textureCache);
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVOpenGLESTextureCacheCreate error %d", res);
}
// call parent init
MemTransfer::init();
}
GLuint MemTransferIOS::prepareInput(int inTexW, int inTexH, GLenum inputPxFormat, void *inputDataPtr) {
assert(initialized && inTexW > 0 && inTexH > 0);
if (inputDataPtr == NULL && inputW == inTexW && inputH == inTexH && inputPixelFormat == inputPxFormat) {
return inputTexId; // no change
}
if (preparedInput) { // already prepared -- release buffers!
releaseInput();
}
// set attributes
inputW = inTexW;
inputH = inTexH;
inputPixelFormat = inputPxFormat;
int bytesPerLine = 0;
// define pixel format
OSType pxBufFmt;
if (inputPixelFormat == GL_BGRA) {
bytesPerLine = inputW * 4;
pxBufFmt = kCVPixelFormatType_32BGRA;
} else if(inputPixelFormat == 0) {
bytesPerLine = inputW;
pxBufFmt = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange;
} else {
OG_LOGERR("MemTransferIOS", "unsupported input pixel format %d", inputPixelFormat);
preparedInput = false;
return 0;
}
// prepare
CVPixelBufferRef bufRef;
CVOpenGLESTextureRef texRef = 0;
CVOpenGLESTextureRef luminanceTextureRef = 0;
CVOpenGLESTextureRef chrominanceTextureRef = 0;
CVReturn res;
if(inputDataPtr) {
if(useRawPixels) {
if(pxBufFmt == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) {
res = CVPixelBufferCreate(kCFAllocatorDefault,
inputW,
inputH,
pxBufFmt,
bufferAttr,
&bufRef);
CVPixelBufferLockBaseAddress(bufRef, 0);
assert(CVPixelBufferGetPlaneCount(bufRef) == 2);
// get plane addresses
unsigned char *baseAddressY = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(bufRef, 0);
size_t bufferHeight0 = CVPixelBufferGetHeightOfPlane(bufRef, 0);
size_t bufferWidth0 = CVPixelBufferGetWidthOfPlane(bufRef, 0);
size_t bytesPerRow0 = CVPixelBufferGetBytesPerRowOfPlane(bufRef, 0);
unsigned char *baseAddressUV = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(bufRef, 1);
size_t bufferHeight1 = CVPixelBufferGetHeightOfPlane(bufRef, 1);
size_t bufferWidth1 = CVPixelBufferGetWidthOfPlane(bufRef, 1);
size_t bytesPerRow1 = CVPixelBufferGetBytesPerRowOfPlane(bufRef, 1);
uint8_t *yPtr = reinterpret_cast<uint8_t *>(inputDataPtr);
uint8_t *uvPtr = yPtr + (bytesPerRow0 * bufferHeight0);
//TODO: copy your data buffers to the newly allocated memory locations
memcpy(baseAddressY, yPtr, bytesPerRow0 * bufferHeight0);
memcpy(baseAddressUV, uvPtr, bytesPerRow1 * bufferHeight1);
// unlock pixel buffer address
CVPixelBufferUnlockBaseAddress(bufRef, 0);
}
else {
res = CVPixelBufferCreateWithBytes(
kCFAllocatorDefault,
inputW,
inputH,
pxBufFmt,
inputDataPtr,
bytesPerLine,
nullptr, // releaseCallback
nullptr, // releaseRefCon
bufferAttr, // pixelBufferAttributes
&bufRef);
}
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVPixelBufferCreate error %d (input)", res);
preparedInput = false;
return 0;
}
}
else {
bufRef = (CVPixelBufferRef)inputDataPtr;
}
}
else {
// create input pixel buffer if necessary
res = CVPixelBufferCreate(kCFAllocatorDefault,
inputW,
inputH,
pxBufFmt,
bufferAttr,
&bufRef);
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVPixelBufferCreate error %d (input)", res);
preparedInput = false;
return 0;
}
}
// create input texture
if(inputDataPtr) {
if(inputPixelFormat == GL_BGRA) {
res = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
textureCache,
bufRef,
NULL, // texture attributes
GL_TEXTURE_2D,
GL_RGBA, // opengl format
inputW,
inputH,
inputPixelFormat,
GL_UNSIGNED_BYTE,
0,
&texRef);
if (res != kCVReturnSuccess) {
Core::printCVPixelBuffer("Texture creation failed", bufRef);
OG_LOGERR("MemTransferIOS", "CVOpenGLESTextureCacheCreateTextureFromImage error %d (input)", res);
preparedInput = false;
return 0;
}
inputPixelBufferSize = inputW * inputH * 4; // always assume 4 channels of 8 bit data
// get created texture id
inputTexId = CVOpenGLESTextureGetName(texRef);
OG_LOGINF("MemTransferIOS", "created input tex with id %d", inputTexId);
// set texture parameters
setCommonTextureParams(inputTexId);
}
else {
inputPixelBufferSize = (inpuW * inputH) * 3 / 2;
glActiveTexture(GL_TEXTURE4);
res = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
textureCache,
bufRef,
NULL,
GL_TEXTURE_2D,
GL_LUMINANCE,
inputW,
inputH,
GL_LUMINANCE,
GL_UNSIGNED_BYTE,
0,
&luminanceTextureRef);
if (res != kCVReturnSuccess) {
Core::printCVPixelBuffer("Texture creation failed", bufRef);
OG_LOGERR("MemTransferIOS", "CVOpenGLESTextureCacheCreateTextureFromImage error %d (input)", res);
preparedInput = false;
return 0;
}
luminanceTexId = CVOpenGLESTextureGetName(luminanceTextureRef);
glBindTexture(GL_TEXTURE_2D, luminanceTexId);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glActiveTexture(GL_TEXTURE5);
res = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
textureCache,
bufRef,
NULL,
GL_TEXTURE_2D,
GL_LUMINANCE_ALPHA,
inputW/2,
inputH/2,
GL_LUMINANCE_ALPHA,
GL_UNSIGNED_BYTE,
1,
&chrominanceTextureRef);
if (res != kCVReturnSuccess) {
Core::printCVPixelBuffer("Texture creation failed", bufRef);
OG_LOGERR("MemTransferIOS", "CVOpenGLESTextureCacheCreateTextureFromImage error %d (input)", res);
preparedInput = false;
return 0;
}
chrominanceTexId = CVOpenGLESTextureGetName(chrominanceTextureRef);
glBindTexture(GL_TEXTURE_2D, chrominanceTexId);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
lumaTexture = luminanceTextureRef;
chromaTexture = chrominanceTextureRef;
}
// set member variables
if (inputDataPtr == NULL || useRawPixels) {
// only necessary if we did not specify our own pixel buffer via <inputDataPtr>
// ...or if we are using a raw image pointer as an input, in which cas we are
// internally allocating a CVPixelBuferRef
inputPixelBuffer = bufRef;
}
inputTexture = texRef;
preparedInput = true;
return inputTexId;
}
GLuint MemTransferIOS::prepareOutput(int outTexW, int outTexH) {
assert(initialized && outTexW > 0 && outTexH > 0);
if (outputW == outTexW && outputH == outTexH) {
return outputTexId; // no change
}
if (preparedOutput) { // already prepared -- release buffers!
releaseOutput();
}
// set attributes
outputW = outTexW;
outputH = outTexH;
// prepare
CVPixelBufferRef bufRef;
CVOpenGLESTextureRef texRef;
CVReturn res;
// create output pixel buffer
res = CVPixelBufferCreate(kCFAllocatorDefault,
outputW, outputH,
kCVPixelFormatType_32BGRA,
bufferAttr,
&bufRef);
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVPixelBufferCreate error %d (output)", res);
preparedOutput = false;
return 0;
}
outputPixelBufferSize = outputW * outputH * 4; // always assume 4 channels of 8 bit data
// create output texture
res = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
textureCache,
bufRef,
NULL, // texture attributes
GL_TEXTURE_2D,
GL_RGBA, // opengl format
outputW,
outputH,
GL_RGBA, // opengl format
GL_UNSIGNED_BYTE,
0,
&texRef);
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVOpenGLESTextureCacheCreateTextureFromImage error %d (output)", res);
preparedOutput = false;
return 0;
}
// get created texture id
outputTexId = CVOpenGLESTextureGetName(texRef);
OG_LOGINF("MemTransferIOS", "created output tex with id %d", outputTexId);
// set texture parameters
setCommonTextureParams(outputTexId);
// set member variables
outputPixelBuffer = bufRef;
outputTexture = texRef;
preparedOutput = true;
return outputTexId;
}
void MemTransferIOS::toGPU(const unsigned char *buf) {
assert(preparedInput && inputPixelBuffer && inputTexId > 0 && buf);
// copy data to pixel buffer
void *pixelBufferAddr = lockBufferAndGetPtr(BUF_TYPE_INPUT);
memcpy(pixelBufferAddr, buf, inputPixelBufferSize);
unlockBuffer(BUF_TYPE_INPUT);
// bind the texture
glBindTexture(GL_TEXTURE_2D, inputTexId);
}
void MemTransferIOS::fromGPU(unsigned char *buf) {
assert(preparedOutput && outputPixelBuffer && outputTexId > 0 && buf);
// bind the texture
glBindTexture(GL_TEXTURE_2D, outputTexId);
const void *pixelBufferAddr = lockBufferAndGetPtr(BUF_TYPE_OUTPUT);
memcpy(buf, pixelBufferAddr, outputPixelBufferSize);
unlockBuffer(BUF_TYPE_OUTPUT);
}
#pragma mark private methods
void *MemTransferIOS::lockBufferAndGetPtr(BufType bufType) {
// get the buffer reference and lock options
CVPixelBufferRef buf;
CVOptionFlags lockOpt;
getPixelBufferAndLockFlags(bufType, &buf, &lockOpt);
// lock
CVReturn res = CVPixelBufferLockBaseAddress(buf, lockOpt);
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVPixelBufferLockBaseAddress error %d", res);
return NULL;
}
// return address
return CVPixelBufferGetBaseAddress(buf);
}
void MemTransferIOS::unlockBuffer(BufType bufType) {
// get the buffer reference and lock options
CVPixelBufferRef buf;
CVOptionFlags lockOpt;
getPixelBufferAndLockFlags(bufType, &buf, &lockOpt);
// unlock
CVReturn res = CVPixelBufferUnlockBaseAddress(buf, lockOpt);
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVPixelBufferUnlockBaseAddress error %d", res);
}
}
void MemTransferIOS::getPixelBufferAndLockFlags(BufType bufType, CVPixelBufferRef *buf, CVOptionFlags *lockOpt) {
if (bufType == BUF_TYPE_INPUT) {
*buf = inputPixelBuffer;
*lockOpt = 0; // read and write
} else {
*buf = outputPixelBuffer;
*lockOpt = kCVPixelBufferLock_ReadOnly; // read only
}
}
<commit_msg>Fix misprint<commit_after>//
// ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0
//
// Author: Markus Konrad <post@mkonrad.net>, Winter 2014/2015
// http://www.mkonrad.net
//
// See LICENSE file in project repository root for the license.
//
#include "memtransfer_ios.h"
#import <CoreVideo/CoreVideo.h>
#include "../../common/core.h"
#include "../../common/proc/yuv2rgb.h"
/**
* Most code as from http://allmybrain.com/2011/12/08/rendering-to-a-texture-with-ios-5-texture-cache-api/
*/
using namespace std;
using namespace ogles_gpgpu;
#pragma mark static methods
bool MemTransferIOS::initPlatformOptimizations() {
#if TARGET_IPHONE_SIMULATOR
OG_LOGERR("MemTransferIOS", "platform optimizations not available in simulator");
return false; // not CV texture cache API not available in simulator
#else
return true; // CV texture cache API available, but nothing to initialize, just return true
#endif
}
#pragma mark constructor / deconstructor
MemTransferIOS::~MemTransferIOS() {
// release in- and outputs
releaseInput();
releaseOutput();
// release texture cache and buffer attributes
CFRelease(textureCache);
CFRelease(bufferAttr);
}
#pragma mark public methods
void MemTransferIOS::releaseInput() {
if (inputPixelBuffer) {
CVPixelBufferRelease(inputPixelBuffer);
inputPixelBuffer = NULL;
}
if (inputTexture) {
CFRelease(inputTexture);
inputTexture = NULL;
}
if (lumaTexture) {
CFRelease(lumaTexture);
lumaTexture = NULL;
}
if (chromaTexture) {
CFRelease(chromaTexture);
chromaTexture = NULL;
}
CVOpenGLESTextureCacheFlush(textureCache, 0);
preparedInput = false;
}
void MemTransferIOS::releaseOutput() {
if (outputPixelBuffer) {
CVPixelBufferRelease(outputPixelBuffer);
outputPixelBuffer = NULL;
}
if (outputTexture) {
CFRelease(outputTexture);
outputTexture = NULL;
}
CVOpenGLESTextureCacheFlush(textureCache, 0);
preparedOutput = false;
}
void MemTransferIOS::init() {
assert(!initialized);
CFDictionaryRef empty;
empty = CFDictionaryCreate(kCFAllocatorDefault, // our empty IOSurface properties dictionary
NULL,
NULL,
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
bufferAttr = CFDictionaryCreateMutable(kCFAllocatorDefault,
1,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(bufferAttr,
kCVPixelBufferIOSurfacePropertiesKey,
empty);
// create texture cache
void *glCtxPtr = Core::getInstance()->getGLContextPtr();
OG_LOGINF("MemTransferIOS", "OpenGL ES context at %p", glCtxPtr);
assert(glCtxPtr);
CVReturn res = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault,
NULL,
(CVEAGLContext)glCtxPtr,
NULL,
&textureCache);
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVOpenGLESTextureCacheCreate error %d", res);
}
// call parent init
MemTransfer::init();
}
GLuint MemTransferIOS::prepareInput(int inTexW, int inTexH, GLenum inputPxFormat, void *inputDataPtr) {
assert(initialized && inTexW > 0 && inTexH > 0);
if (inputDataPtr == NULL && inputW == inTexW && inputH == inTexH && inputPixelFormat == inputPxFormat) {
return inputTexId; // no change
}
if (preparedInput) { // already prepared -- release buffers!
releaseInput();
}
// set attributes
inputW = inTexW;
inputH = inTexH;
inputPixelFormat = inputPxFormat;
int bytesPerLine = 0;
// define pixel format
OSType pxBufFmt;
if (inputPixelFormat == GL_BGRA) {
bytesPerLine = inputW * 4;
pxBufFmt = kCVPixelFormatType_32BGRA;
} else if(inputPixelFormat == 0) {
bytesPerLine = inputW;
pxBufFmt = kCVPixelFormatType_420YpCbCr8BiPlanarFullRange;
} else {
OG_LOGERR("MemTransferIOS", "unsupported input pixel format %d", inputPixelFormat);
preparedInput = false;
return 0;
}
// prepare
CVPixelBufferRef bufRef;
CVOpenGLESTextureRef texRef = 0;
CVOpenGLESTextureRef luminanceTextureRef = 0;
CVOpenGLESTextureRef chrominanceTextureRef = 0;
CVReturn res;
if(inputDataPtr) {
if(useRawPixels) {
if(pxBufFmt == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) {
res = CVPixelBufferCreate(kCFAllocatorDefault,
inputW,
inputH,
pxBufFmt,
bufferAttr,
&bufRef);
CVPixelBufferLockBaseAddress(bufRef, 0);
assert(CVPixelBufferGetPlaneCount(bufRef) == 2);
// get plane addresses
unsigned char *baseAddressY = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(bufRef, 0);
size_t bufferHeight0 = CVPixelBufferGetHeightOfPlane(bufRef, 0);
size_t bufferWidth0 = CVPixelBufferGetWidthOfPlane(bufRef, 0);
size_t bytesPerRow0 = CVPixelBufferGetBytesPerRowOfPlane(bufRef, 0);
unsigned char *baseAddressUV = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(bufRef, 1);
size_t bufferHeight1 = CVPixelBufferGetHeightOfPlane(bufRef, 1);
size_t bufferWidth1 = CVPixelBufferGetWidthOfPlane(bufRef, 1);
size_t bytesPerRow1 = CVPixelBufferGetBytesPerRowOfPlane(bufRef, 1);
uint8_t *yPtr = reinterpret_cast<uint8_t *>(inputDataPtr);
uint8_t *uvPtr = yPtr + (bytesPerRow0 * bufferHeight0);
//TODO: copy your data buffers to the newly allocated memory locations
memcpy(baseAddressY, yPtr, bytesPerRow0 * bufferHeight0);
memcpy(baseAddressUV, uvPtr, bytesPerRow1 * bufferHeight1);
// unlock pixel buffer address
CVPixelBufferUnlockBaseAddress(bufRef, 0);
}
else {
res = CVPixelBufferCreateWithBytes(
kCFAllocatorDefault,
inputW,
inputH,
pxBufFmt,
inputDataPtr,
bytesPerLine,
nullptr, // releaseCallback
nullptr, // releaseRefCon
bufferAttr, // pixelBufferAttributes
&bufRef);
}
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVPixelBufferCreate error %d (input)", res);
preparedInput = false;
return 0;
}
}
else {
bufRef = (CVPixelBufferRef)inputDataPtr;
}
}
else {
// create input pixel buffer if necessary
res = CVPixelBufferCreate(kCFAllocatorDefault,
inputW,
inputH,
pxBufFmt,
bufferAttr,
&bufRef);
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVPixelBufferCreate error %d (input)", res);
preparedInput = false;
return 0;
}
}
// create input texture
if(inputDataPtr) {
if(inputPixelFormat == GL_BGRA) {
res = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
textureCache,
bufRef,
NULL, // texture attributes
GL_TEXTURE_2D,
GL_RGBA, // opengl format
inputW,
inputH,
inputPixelFormat,
GL_UNSIGNED_BYTE,
0,
&texRef);
if (res != kCVReturnSuccess) {
Core::printCVPixelBuffer("Texture creation failed", bufRef);
OG_LOGERR("MemTransferIOS", "CVOpenGLESTextureCacheCreateTextureFromImage error %d (input)", res);
preparedInput = false;
return 0;
}
inputPixelBufferSize = inputW * inputH * 4; // always assume 4 channels of 8 bit data
// get created texture id
inputTexId = CVOpenGLESTextureGetName(texRef);
OG_LOGINF("MemTransferIOS", "created input tex with id %d", inputTexId);
// set texture parameters
setCommonTextureParams(inputTexId);
}
else {
inputPixelBufferSize = (inputW * inputH) * 3 / 2;
glActiveTexture(GL_TEXTURE4);
res = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
textureCache,
bufRef,
NULL,
GL_TEXTURE_2D,
GL_LUMINANCE,
inputW,
inputH,
GL_LUMINANCE,
GL_UNSIGNED_BYTE,
0,
&luminanceTextureRef);
if (res != kCVReturnSuccess) {
Core::printCVPixelBuffer("Texture creation failed", bufRef);
OG_LOGERR("MemTransferIOS", "CVOpenGLESTextureCacheCreateTextureFromImage error %d (input)", res);
preparedInput = false;
return 0;
}
luminanceTexId = CVOpenGLESTextureGetName(luminanceTextureRef);
glBindTexture(GL_TEXTURE_2D, luminanceTexId);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glActiveTexture(GL_TEXTURE5);
res = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
textureCache,
bufRef,
NULL,
GL_TEXTURE_2D,
GL_LUMINANCE_ALPHA,
inputW/2,
inputH/2,
GL_LUMINANCE_ALPHA,
GL_UNSIGNED_BYTE,
1,
&chrominanceTextureRef);
if (res != kCVReturnSuccess) {
Core::printCVPixelBuffer("Texture creation failed", bufRef);
OG_LOGERR("MemTransferIOS", "CVOpenGLESTextureCacheCreateTextureFromImage error %d (input)", res);
preparedInput = false;
return 0;
}
chrominanceTexId = CVOpenGLESTextureGetName(chrominanceTextureRef);
glBindTexture(GL_TEXTURE_2D, chrominanceTexId);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
lumaTexture = luminanceTextureRef;
chromaTexture = chrominanceTextureRef;
}
// set member variables
if (inputDataPtr == NULL || useRawPixels) {
// only necessary if we did not specify our own pixel buffer via <inputDataPtr>
// ...or if we are using a raw image pointer as an input, in which cas we are
// internally allocating a CVPixelBuferRef
inputPixelBuffer = bufRef;
}
inputTexture = texRef;
preparedInput = true;
return inputTexId;
}
GLuint MemTransferIOS::prepareOutput(int outTexW, int outTexH) {
assert(initialized && outTexW > 0 && outTexH > 0);
if (outputW == outTexW && outputH == outTexH) {
return outputTexId; // no change
}
if (preparedOutput) { // already prepared -- release buffers!
releaseOutput();
}
// set attributes
outputW = outTexW;
outputH = outTexH;
// prepare
CVPixelBufferRef bufRef;
CVOpenGLESTextureRef texRef;
CVReturn res;
// create output pixel buffer
res = CVPixelBufferCreate(kCFAllocatorDefault,
outputW, outputH,
kCVPixelFormatType_32BGRA,
bufferAttr,
&bufRef);
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVPixelBufferCreate error %d (output)", res);
preparedOutput = false;
return 0;
}
outputPixelBufferSize = outputW * outputH * 4; // always assume 4 channels of 8 bit data
// create output texture
res = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault,
textureCache,
bufRef,
NULL, // texture attributes
GL_TEXTURE_2D,
GL_RGBA, // opengl format
outputW,
outputH,
GL_RGBA, // opengl format
GL_UNSIGNED_BYTE,
0,
&texRef);
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVOpenGLESTextureCacheCreateTextureFromImage error %d (output)", res);
preparedOutput = false;
return 0;
}
// get created texture id
outputTexId = CVOpenGLESTextureGetName(texRef);
OG_LOGINF("MemTransferIOS", "created output tex with id %d", outputTexId);
// set texture parameters
setCommonTextureParams(outputTexId);
// set member variables
outputPixelBuffer = bufRef;
outputTexture = texRef;
preparedOutput = true;
return outputTexId;
}
void MemTransferIOS::toGPU(const unsigned char *buf) {
assert(preparedInput && inputPixelBuffer && inputTexId > 0 && buf);
// copy data to pixel buffer
void *pixelBufferAddr = lockBufferAndGetPtr(BUF_TYPE_INPUT);
memcpy(pixelBufferAddr, buf, inputPixelBufferSize);
unlockBuffer(BUF_TYPE_INPUT);
// bind the texture
glBindTexture(GL_TEXTURE_2D, inputTexId);
}
void MemTransferIOS::fromGPU(unsigned char *buf) {
assert(preparedOutput && outputPixelBuffer && outputTexId > 0 && buf);
// bind the texture
glBindTexture(GL_TEXTURE_2D, outputTexId);
const void *pixelBufferAddr = lockBufferAndGetPtr(BUF_TYPE_OUTPUT);
memcpy(buf, pixelBufferAddr, outputPixelBufferSize);
unlockBuffer(BUF_TYPE_OUTPUT);
}
#pragma mark private methods
void *MemTransferIOS::lockBufferAndGetPtr(BufType bufType) {
// get the buffer reference and lock options
CVPixelBufferRef buf;
CVOptionFlags lockOpt;
getPixelBufferAndLockFlags(bufType, &buf, &lockOpt);
// lock
CVReturn res = CVPixelBufferLockBaseAddress(buf, lockOpt);
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVPixelBufferLockBaseAddress error %d", res);
return NULL;
}
// return address
return CVPixelBufferGetBaseAddress(buf);
}
void MemTransferIOS::unlockBuffer(BufType bufType) {
// get the buffer reference and lock options
CVPixelBufferRef buf;
CVOptionFlags lockOpt;
getPixelBufferAndLockFlags(bufType, &buf, &lockOpt);
// unlock
CVReturn res = CVPixelBufferUnlockBaseAddress(buf, lockOpt);
if (res != kCVReturnSuccess) {
OG_LOGERR("MemTransferIOS", "CVPixelBufferUnlockBaseAddress error %d", res);
}
}
void MemTransferIOS::getPixelBufferAndLockFlags(BufType bufType, CVPixelBufferRef *buf, CVOptionFlags *lockOpt) {
if (bufType == BUF_TYPE_INPUT) {
*buf = inputPixelBuffer;
*lockOpt = 0; // read and write
} else {
*buf = outputPixelBuffer;
*lockOpt = kCVPixelBufferLock_ReadOnly; // read only
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <mpi.h>
#define MASTER 0
#define TAG 0
#define MSGSIZE 10
#define MAX 25
int main(int argc, char *argv[]) {
int my_rank, source, num_nodes;
char my_host[MAX];
char message[MSGSIZE];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_nodes);
if (my_rank != MASTER) {
gethostname(my_host, MAX);
////sprintf(message, "Hello from process %d on host %s!", my_rank, my_host);
////MPI_Send(message, strlen(message) + 1, MPI_CHAR, MASTER, TAG,
//// MPI_COMM_WORLD);
double message_sent = MPI_Wtime();
MPI_Send(&message_sent, MSGSIZE, MPI_DOUBLE, MASTER, TAG, MPI_COMM_WORLD);
} else {
printf("Num_nodes: %d\n", num_nodes);
printf("Hello from Master (process %d)!\n", my_rank);
double message_sent = 0;
MPI_Status status;
for (source = 1; source < num_nodes; source++) {
MPI_Recv(&message_sent, MSGSIZE, MPI_LONG_INT, source, TAG,
MPI_COMM_WORLD, &status);
double message_received = MPI_Wtime();
double elapsed = message_received - message_sent;
printf("Host: %d Message Ticks: %f Now: %f Elapsed time: %f\n",
status.MPI_SOURCE, message_sent, message_received, elapsed);
}
}
MPI_Finalize();
return 0;
}
<commit_msg>fix msgsize<commit_after>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <mpi.h>
#define MASTER 0
#define TAG 0
#define MSGSIZE 1
#define MAX 25
int main(int argc, char *argv[]) {
int my_rank, source, num_nodes;
char my_host[MAX];
char message[MSGSIZE];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_nodes);
if (my_rank != MASTER) {
gethostname(my_host, MAX);
////sprintf(message, "Hello from process %d on host %s!", my_rank, my_host);
////MPI_Send(message, strlen(message) + 1, MPI_CHAR, MASTER, TAG,
//// MPI_COMM_WORLD);
double message_sent = MPI_Wtime();
MPI_Send(&message_sent, MSGSIZE, MPI_DOUBLE, MASTER, TAG, MPI_COMM_WORLD);
} else {
printf("Num_nodes: %d\n", num_nodes);
printf("Hello from Master (process %d)!\n", my_rank);
double message_sent = 0;
MPI_Status status;
for (source = 1; source < num_nodes; source++) {
MPI_Recv(&message_sent, MSGSIZE, MPI_LONG_INT, source, TAG,
MPI_COMM_WORLD, &status);
double message_received = MPI_Wtime();
double elapsed = message_received - message_sent;
printf("Host: %d Message Ticks: %f Now: %f Elapsed time: %f\n",
status.MPI_SOURCE, message_sent, message_received, elapsed);
}
}
MPI_Finalize();
return 0;
}
<|endoftext|> |
<commit_before>/* ************************************************
* GEANT4 VCGLIB/CAD INTERFACE
*
* File: CADMesh.cc
*
* Author: Christopher M Poole,
* Email: mail@christopherpoole.net
*
* Date: 7th March, 2011
**************************************************/
// USER //
#include "CADMesh.hh"
// GEANT4 //
#include "G4String.hh"
#include "G4UIcommand.hh"
#include "G4ThreeVector.hh"
#include "G4LogicalVolume.hh"
#include "G4TessellatedSolid.hh"
#include "G4TriangularFacet.hh"
#include "G4Tet.hh"
#ifndef NOVCGLIB
// VCGLIB //
#include "wrap/io_trimesh/import.h"
#include "wrap/io_trimesh/import_ply.h"
#include "wrap/io_trimesh/import_stl.h"
#include "wrap/io_trimesh/import_off.h"
#include "wrap/ply/plylib.h"
#endif
#ifndef NOVCGLIB
using namespace vcg::tri::io;
#endif
CADMesh::CADMesh(char * file_name, char * file_type, double units, G4ThreeVector offset, G4bool reverse)
{
units_ = units;
offset_ = offset;
reverse_ = reverse;
file_name_ = file_name;
file_type_ = file_type;
file_type_.toUpper();
material_ = NULL;
quality_ = 0;
has_mesh_ = false;
has_solid_ = false;
verbose_ = 0;
}
CADMesh::CADMesh(char * file_name, char * file_type, G4Material * material, double quality)
{
units_ = mm;
offset_ = G4ThreeVector();
reverse_ = false;
file_name_ = file_name;
file_type_ = file_type;
file_type_.toUpper();
material_ = material;
quality_ = quality;
has_mesh_ = false;
has_solid_ = false;
verbose_ = 0;
}
CADMesh::CADMesh(char * file_name, char * file_type)
{
units_ = mm;
offset_ = G4ThreeVector();
reverse_ = false;
file_name_ = file_name;
file_type_ = file_type;
file_type_.toUpper();
material_ = NULL;
quality_ = 0;
has_mesh_ = false;
has_solid_ = false;
verbose_ = 0;
}
CADMesh::CADMesh(char * file_name, char * file_type, G4Material * material)
{
units_ = mm;
offset_ = G4ThreeVector();
reverse_ = false;
file_name_ = file_name;
file_type_ = file_type;
file_type_.toUpper();
material_ = material;
quality_ = 0;
has_mesh_ = false;
has_solid_ = false;
verbose_ = 0;
}
CADMesh::~CADMesh()
{
}
#ifndef NOVCGLIB
G4VSolid* CADMesh::TessellatedMesh()
{
if (!has_mesh_) {
if (file_type_ == "STL") {
ImporterSTL<CADTriMesh>::Open(m, file_name_);
} else if (file_type_ == "PLY") {
ImporterPLY<CADTriMesh>::Open(m, file_name_);
} else if (file_type_ == "OFF") {
ImporterOFF<CADTriMesh>::Open(m, file_name_);
} else {
G4cerr << "CADMesh/LoadSTL: "
<< "No G4TessellatedSoild to return. Specify valid mesh type (STL, PLY, OFF), not: "
<< file_type_
<< G4endl;
has_mesh_ = false;
return 0;
}
has_mesh_ = true;
} else {
G4cerr << "CADMesh/LoadSTL: "
<< "Mesh already loaded from "
<< file_name_
<< ", not loading. Use CADMesh/GetSolid to get the currently loaded mesh as a G4TessellatedSolid"
<< G4endl;
return 0;
}
if (!has_mesh_) {
G4cerr << "CADMesh/BuildSolid: "
<< "Load a mesh of type STL, PLY or OFF first."
<< G4endl;
return 0;
}
volume_solid = new G4TessellatedSolid(file_name_);
G4ThreeVector point_1 = G4ThreeVector();
G4ThreeVector point_2 = G4ThreeVector();
G4ThreeVector point_3 = G4ThreeVector();
CADTriMesh::FaceIterator face_iterator;
for(face_iterator=m.face.begin(); face_iterator!=m.face.end(); ++face_iterator)
{
point_1 = G4ThreeVector(
(*face_iterator).V(0)->P()[0] * units_ - offset_.x(),
(*face_iterator).V(0)->P()[1] * units_ - offset_.y(),
(*face_iterator).V(0)->P()[2] * units_ - offset_.z());
point_2 = G4ThreeVector(
(*face_iterator).V(1)->P()[0] * units_ - offset_.x(),
(*face_iterator).V(1)->P()[1] * units_ - offset_.y(),
(*face_iterator).V(1)->P()[2] * units_ - offset_.z());
point_3 = G4ThreeVector(
(*face_iterator).V(2)->P()[0] * units_ - offset_.x(),
(*face_iterator).V(2)->P()[1] * units_ - offset_.y(),
(*face_iterator).V(2)->P()[2] * units_ - offset_.z());
G4TriangularFacet * facet;
if (reverse_ == false) {
facet = new G4TriangularFacet(point_1, point_2, point_3, ABSOLUTE);
} else {
facet = new G4TriangularFacet(point_2, point_1, point_3, ABSOLUTE);
}
volume_solid->AddFacet((G4VFacet*) facet);
}
volume_solid->SetSolidClosed(true);
return volume_solid;
}
#endif
#ifndef NOTET
G4AssemblyVolume * CADMesh::TetrahedralMesh()
{
// USAGE: assembly->MakeImprint(world_logical, assembly_transform_3d, 0); //
G4bool do_tet = true;
if (file_type_ == "STL") {
G4bool state = in.load_stl(file_name_);
} else if (file_type_ == "PLY") {
G4bool state = in.load_ply(file_name_);
} else if (file_type_ == "OFF") {
G4bool state = out.load_tetmesh(file_name_);
do_tet = false;
}
if (do_tet)
{
G4String config = G4String("Yp");
if (quality_ > 0) config = config + G4String("q") + G4UIcommand::ConvertToString(quality_);
tetrahedralize((char *) config.c_str(), &in, &out);
}
assembly = new G4AssemblyVolume();
G4RotationMatrix * element_rotation = new G4RotationMatrix();
G4ThreeVector element_position = G4ThreeVector();
G4Transform3D assembly_transform = G4Translate3D();
for (int i=0; i<out.numberoftetrahedra; i++) {
int offset = i * 4; /* For a tetrahedron, out.numberofcorners == 4 */
G4ThreeVector p1 = GetTetPoint(offset);
G4ThreeVector p2 = GetTetPoint(offset + 1);
G4ThreeVector p3 = GetTetPoint(offset + 2);
G4ThreeVector p4 = GetTetPoint(offset + 3);
G4VSolid * tet_solid = new G4Tet(G4String("tet_solid_") + G4UIcommand::ConvertToString(i), p1, p2, p3, p4, 0);
G4LogicalVolume * tet_logical = new G4LogicalVolume(tet_solid, material_, G4String("tet_logical_") + G4UIcommand::ConvertToString(i), 0, 0, 0);
assembly->AddPlacedVolume(tet_logical, element_position, element_rotation);
#ifdef DEBUG
if (i%1000 == 0) G4cout << "Tetrahedrons added: " << i << G4endl;
#endif
}
#ifdef DEBUG
G4cout << "Loading of " << out.numberoftetrahedra << "tetrahedrons complete." << G4endl;
#endif
return assembly;
}
G4ThreeVector CADMesh::GetTetPoint(G4int offset)
{
return G4ThreeVector(out.pointlist[out.tetrahedronlist[offset]*3],
out.pointlist[out.tetrahedronlist[offset]*3+1],
out.pointlist[out.tetrahedronlist[offset]*3+2]);
}
#endif
<commit_msg>added load_tetmesh with TET type (looks for .node and .ele)<commit_after>/* ************************************************
* GEANT4 VCGLIB/CAD INTERFACE
*
* File: CADMesh.cc
*
* Author: Christopher M Poole,
* Email: mail@christopherpoole.net
*
* Date: 7th March, 2011
**************************************************/
// USER //
#include "CADMesh.hh"
// GEANT4 //
#include "G4String.hh"
#include "G4UIcommand.hh"
#include "G4ThreeVector.hh"
#include "G4LogicalVolume.hh"
#include "G4TessellatedSolid.hh"
#include "G4TriangularFacet.hh"
#include "G4Tet.hh"
#ifndef NOVCGLIB
// VCGLIB //
#include "wrap/io_trimesh/import.h"
#include "wrap/io_trimesh/import_ply.h"
#include "wrap/io_trimesh/import_stl.h"
#include "wrap/io_trimesh/import_off.h"
#include "wrap/ply/plylib.h"
#endif
#ifndef NOVCGLIB
using namespace vcg::tri::io;
#endif
CADMesh::CADMesh(char * file_name, char * file_type, double units, G4ThreeVector offset, G4bool reverse)
{
units_ = units;
offset_ = offset;
reverse_ = reverse;
file_name_ = file_name;
file_type_ = file_type;
file_type_.toUpper();
material_ = NULL;
quality_ = 0;
has_mesh_ = false;
has_solid_ = false;
verbose_ = 0;
}
CADMesh::CADMesh(char * file_name, char * file_type, G4Material * material, double quality)
{
units_ = mm;
offset_ = G4ThreeVector();
reverse_ = false;
file_name_ = file_name;
file_type_ = file_type;
file_type_.toUpper();
material_ = material;
quality_ = quality;
has_mesh_ = false;
has_solid_ = false;
verbose_ = 0;
}
CADMesh::CADMesh(char * file_name, char * file_type)
{
units_ = mm;
offset_ = G4ThreeVector();
reverse_ = false;
file_name_ = file_name;
file_type_ = file_type;
file_type_.toUpper();
material_ = NULL;
quality_ = 0;
has_mesh_ = false;
has_solid_ = false;
verbose_ = 0;
}
CADMesh::CADMesh(char * file_name, char * file_type, G4Material * material)
{
units_ = mm;
offset_ = G4ThreeVector();
reverse_ = false;
file_name_ = file_name;
file_type_ = file_type;
file_type_.toUpper();
material_ = material;
quality_ = 0;
has_mesh_ = false;
has_solid_ = false;
verbose_ = 0;
}
CADMesh::~CADMesh()
{
}
#ifndef NOVCGLIB
G4VSolid* CADMesh::TessellatedMesh()
{
if (!has_mesh_) {
if (file_type_ == "STL") {
ImporterSTL<CADTriMesh>::Open(m, file_name_);
} else if (file_type_ == "PLY") {
ImporterPLY<CADTriMesh>::Open(m, file_name_);
} else if (file_type_ == "OFF") {
ImporterOFF<CADTriMesh>::Open(m, file_name_);
} else {
G4cerr << "CADMesh/LoadSTL: "
<< "No G4TessellatedSoild to return. Specify valid mesh type (STL, PLY, OFF), not: "
<< file_type_
<< G4endl;
has_mesh_ = false;
return 0;
}
has_mesh_ = true;
} else {
G4cerr << "CADMesh/LoadSTL: "
<< "Mesh already loaded from "
<< file_name_
<< ", not loading. Use CADMesh/GetSolid to get the currently loaded mesh as a G4TessellatedSolid"
<< G4endl;
return 0;
}
if (!has_mesh_) {
G4cerr << "CADMesh/BuildSolid: "
<< "Load a mesh of type STL, PLY or OFF first."
<< G4endl;
return 0;
}
volume_solid = new G4TessellatedSolid(file_name_);
G4ThreeVector point_1 = G4ThreeVector();
G4ThreeVector point_2 = G4ThreeVector();
G4ThreeVector point_3 = G4ThreeVector();
CADTriMesh::FaceIterator face_iterator;
for(face_iterator=m.face.begin(); face_iterator!=m.face.end(); ++face_iterator)
{
point_1 = G4ThreeVector(
(*face_iterator).V(0)->P()[0] * units_ - offset_.x(),
(*face_iterator).V(0)->P()[1] * units_ - offset_.y(),
(*face_iterator).V(0)->P()[2] * units_ - offset_.z());
point_2 = G4ThreeVector(
(*face_iterator).V(1)->P()[0] * units_ - offset_.x(),
(*face_iterator).V(1)->P()[1] * units_ - offset_.y(),
(*face_iterator).V(1)->P()[2] * units_ - offset_.z());
point_3 = G4ThreeVector(
(*face_iterator).V(2)->P()[0] * units_ - offset_.x(),
(*face_iterator).V(2)->P()[1] * units_ - offset_.y(),
(*face_iterator).V(2)->P()[2] * units_ - offset_.z());
G4TriangularFacet * facet;
if (reverse_ == false) {
facet = new G4TriangularFacet(point_1, point_2, point_3, ABSOLUTE);
} else {
facet = new G4TriangularFacet(point_2, point_1, point_3, ABSOLUTE);
}
volume_solid->AddFacet((G4VFacet*) facet);
}
volume_solid->SetSolidClosed(true);
return volume_solid;
}
#endif
#ifndef NOTET
G4AssemblyVolume * CADMesh::TetrahedralMesh()
{
// USAGE: assembly->MakeImprint(world_logical, assembly_transform_3d, 0); //
G4bool do_tet = true;
if (file_type_ == "STL") {
G4bool state = in.load_stl(file_name_);
} else if (file_type_ == "PLY") {
G4bool state = in.load_ply(file_name_);
} else if (file_type_ == "TET") {
G4bool state = in.load_tetmesh(file_name_);
} else if (file_type_ == "OFF") {
G4bool state = out.load_off(file_name_);
do_tet = false;
}
if (do_tet)
{
G4String config = G4String("Yp");
if (quality_ > 0) config = config + G4String("q") + G4UIcommand::ConvertToString(quality_);
tetrahedralize((char *) config.c_str(), &in, &out);
}
assembly = new G4AssemblyVolume();
G4RotationMatrix * element_rotation = new G4RotationMatrix();
G4ThreeVector element_position = G4ThreeVector();
G4Transform3D assembly_transform = G4Translate3D();
for (int i=0; i<out.numberoftetrahedra; i++) {
int offset = i * 4; /* For a tetrahedron, out.numberofcorners == 4 */
G4ThreeVector p1 = GetTetPoint(offset);
G4ThreeVector p2 = GetTetPoint(offset + 1);
G4ThreeVector p3 = GetTetPoint(offset + 2);
G4ThreeVector p4 = GetTetPoint(offset + 3);
G4VSolid * tet_solid = new G4Tet(G4String("tet_solid_") + G4UIcommand::ConvertToString(i), p1, p2, p3, p4, 0);
G4LogicalVolume * tet_logical = new G4LogicalVolume(tet_solid, material_, G4String("tet_logical_") + G4UIcommand::ConvertToString(i), 0, 0, 0);
assembly->AddPlacedVolume(tet_logical, element_position, element_rotation);
#ifdef DEBUG
if (i%1000 == 0) G4cout << "Tetrahedrons added: " << i << G4endl;
#endif
}
#ifdef DEBUG
G4cout << "Loading of " << out.numberoftetrahedra << "tetrahedrons complete." << G4endl;
#endif
return assembly;
}
G4ThreeVector CADMesh::GetTetPoint(G4int offset)
{
return G4ThreeVector(out.pointlist[out.tetrahedronlist[offset]*3],
out.pointlist[out.tetrahedronlist[offset]*3+1],
out.pointlist[out.tetrahedronlist[offset]*3+2]);
}
#endif
<|endoftext|> |
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Ben van Klinken <bvklinken@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "archiveenginehandler.h"
#include "fsfileinputstream.h"
#include "archivereader.h"
#include <QtCore/QAbstractFileEngine>
#include <QtCore/QFSFileEngine>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
using namespace jstreams;
#include <iostream>
using namespace std;
#include <dirent.h>
class QFileStreamOpener : public StreamOpener {
public:
~QFileStreamOpener() {}
StreamBase<char>* openStream(const string& url);
int stat(const string& url, EntryInfo& e);
};
StreamBase<char>*
QFileStreamOpener::openStream(const string& url) {
StreamBase<char>* stream = new FSFileInputStream(QString(url.c_str()));
if (stream->getStatus() != Ok) {
delete stream;
stream = 0;
}
return stream;
}
int
QFileStreamOpener::stat(const string& url, EntryInfo& e) {
QFSFileEngine f(url.c_str());
QAbstractFileEngine::FileFlags flags = f.fileFlags(
QAbstractFileEngine::ExistsFlag|
QAbstractFileEngine::FileType|QAbstractFileEngine::DirectoryType);
if (!(QAbstractFileEngine::ExistsFlag&flags)) {
return -1;
}
e.type = EntryInfo::Unknown;
if (flags & QAbstractFileEngine::FileType) {
e.type = EntryInfo::File;
}
if (flags & QAbstractFileEngine::DirectoryType) {
e.type = EntryInfo::Dir;
}
e.size = f.size();
e.mtime = f.fileTime(QAbstractFileEngine::ModificationTime).toTime_t();
QByteArray filename = f.fileName(QAbstractFileEngine::BaseName).toUtf8();
e.filename.assign((const char*)filename, filename.length());
// printf("name:'%s'\n", e.filename.c_str());
return 0;
}
class StreamFileEngine : public QAbstractFileEngine {
private:
const string url;
ArchiveReader* reader;
StreamBase<char>* stream;
EntryInfo entryinfo;
public:
StreamFileEngine(ArchiveReader* r, const string& u) :url(u) {
reader = r;
stream = 0;
reader->stat(u, entryinfo);
}
~StreamFileEngine();
bool isSequential () const {
return true;
}
bool open(QIODevice::OpenMode mode) {
if (mode & QIODevice::WriteOnly && !(mode & QIODevice::ReadOnly)) {
return false;
}
stream = reader->openStream(url);
// printf("open %s\n", url.c_str());
return stream;
}
bool close () {
if (stream) {
reader->closeStream(stream);
stream=0;
}
return true;
}
bool isRelativePath () const {
return false;
}
bool caseSensitive () const { return true; }
qint64 size() const { return entryinfo.size; }
QDateTime fileTime ( FileTime time ) const {
QDateTime d;
d.setTime_t(entryinfo.mtime);
return d;
}
QStringList entryList(QDir::Filters filters,
const QStringList & filterNames) const {
QStringList l;
DirLister dl = reader->getDirEntries(url);
EntryInfo e;
while (dl.nextEntry(e)) {
l << e.filename.c_str();
}
return l;
}
QString fileName ( FileName file) const {
switch(file) {
case PathName:
return url.c_str();
case BaseName:
return entryinfo.filename.c_str();
case DefaultName:
default:
return url.c_str();
}
return QString(entryinfo.filename.c_str());
}
FileFlags fileFlags(FileFlags type) const;
qint64 read(char* data, qint64 maxlen) {
int nread = -1;
if (stream && stream->getStatus() == Ok) {
if (maxlen > 0) {
const char* c;
nread = stream->read(c, maxlen, maxlen);
if (nread > 0) {
memcpy(data, c, nread);
} else if (nread < 0) {
nread = -1;
}
} else {
nread = 0;
}
}
// cout << "read " << url << " maxlen " << maxlen << " " << nread << endl;
return nread;
}
};
StreamFileEngine::~StreamFileEngine() {
close();
}
QAbstractFileEngine::FileFlags
StreamFileEngine::fileFlags(FileFlags type) const {
FileFlags f = 0;
if (entryinfo.type & EntryInfo::Dir) {
f |= DirectoryType;
}
if (entryinfo.type & EntryInfo::File) {
f |= FileType;
}
return f;
}
ArchiveEngineHandler::ArchiveEngineHandler() {
reader = new ArchiveReader();
opener = new QFileStreamOpener();
reader->addStreamOpener(opener);
}
ArchiveEngineHandler::~ArchiveEngineHandler() {
delete reader;
delete opener;
}
QAbstractFileEngine *
ArchiveEngineHandler::create(const QString &fileName) const {
string name((const char*)fileName.toUtf8());
if (reader->canHandle(name)) {
return new StreamFileEngine(reader, name);
}
return 0;
}
<commit_msg>if you realy need dirent.h here, please mask it with ifndef _WIN32<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Ben van Klinken <bvklinken@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "archiveenginehandler.h"
#include "fsfileinputstream.h"
#include "archivereader.h"
#include <QtCore/QAbstractFileEngine>
#include <QtCore/QFSFileEngine>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
using namespace jstreams;
#include <iostream>
using namespace std;
class QFileStreamOpener : public StreamOpener {
public:
~QFileStreamOpener() {}
StreamBase<char>* openStream(const string& url);
int stat(const string& url, EntryInfo& e);
};
StreamBase<char>*
QFileStreamOpener::openStream(const string& url) {
StreamBase<char>* stream = new FSFileInputStream(QString(url.c_str()));
if (stream->getStatus() != Ok) {
delete stream;
stream = 0;
}
return stream;
}
int
QFileStreamOpener::stat(const string& url, EntryInfo& e) {
QFSFileEngine f(url.c_str());
QAbstractFileEngine::FileFlags flags = f.fileFlags(
QAbstractFileEngine::ExistsFlag|
QAbstractFileEngine::FileType|QAbstractFileEngine::DirectoryType);
if (!(QAbstractFileEngine::ExistsFlag&flags)) {
return -1;
}
e.type = EntryInfo::Unknown;
if (flags & QAbstractFileEngine::FileType) {
e.type = EntryInfo::File;
}
if (flags & QAbstractFileEngine::DirectoryType) {
e.type = EntryInfo::Dir;
}
e.size = f.size();
e.mtime = f.fileTime(QAbstractFileEngine::ModificationTime).toTime_t();
QByteArray filename = f.fileName(QAbstractFileEngine::BaseName).toUtf8();
e.filename.assign((const char*)filename, filename.length());
// printf("name:'%s'\n", e.filename.c_str());
return 0;
}
class StreamFileEngine : public QAbstractFileEngine {
private:
const string url;
ArchiveReader* reader;
StreamBase<char>* stream;
EntryInfo entryinfo;
public:
StreamFileEngine(ArchiveReader* r, const string& u) :url(u) {
reader = r;
stream = 0;
reader->stat(u, entryinfo);
}
~StreamFileEngine();
bool isSequential () const {
return true;
}
bool open(QIODevice::OpenMode mode) {
if (mode & QIODevice::WriteOnly && !(mode & QIODevice::ReadOnly)) {
return false;
}
stream = reader->openStream(url);
// printf("open %s\n", url.c_str());
return stream;
}
bool close () {
if (stream) {
reader->closeStream(stream);
stream=0;
}
return true;
}
bool isRelativePath () const {
return false;
}
bool caseSensitive () const { return true; }
qint64 size() const { return entryinfo.size; }
QDateTime fileTime ( FileTime time ) const {
QDateTime d;
d.setTime_t(entryinfo.mtime);
return d;
}
QStringList entryList(QDir::Filters filters,
const QStringList & filterNames) const {
QStringList l;
DirLister dl = reader->getDirEntries(url);
EntryInfo e;
while (dl.nextEntry(e)) {
l << e.filename.c_str();
}
return l;
}
QString fileName ( FileName file) const {
switch(file) {
case PathName:
return url.c_str();
case BaseName:
return entryinfo.filename.c_str();
case DefaultName:
default:
return url.c_str();
}
return QString(entryinfo.filename.c_str());
}
FileFlags fileFlags(FileFlags type) const;
qint64 read(char* data, qint64 maxlen) {
int nread = -1;
if (stream && stream->getStatus() == Ok) {
if (maxlen > 0) {
const char* c;
nread = stream->read(c, maxlen, maxlen);
if (nread > 0) {
memcpy(data, c, nread);
} else if (nread < 0) {
nread = -1;
}
} else {
nread = 0;
}
}
// cout << "read " << url << " maxlen " << maxlen << " " << nread << endl;
return nread;
}
};
StreamFileEngine::~StreamFileEngine() {
close();
}
QAbstractFileEngine::FileFlags
StreamFileEngine::fileFlags(FileFlags type) const {
FileFlags f = 0;
if (entryinfo.type & EntryInfo::Dir) {
f |= DirectoryType;
}
if (entryinfo.type & EntryInfo::File) {
f |= FileType;
}
return f;
}
ArchiveEngineHandler::ArchiveEngineHandler() {
reader = new ArchiveReader();
opener = new QFileStreamOpener();
reader->addStreamOpener(opener);
}
ArchiveEngineHandler::~ArchiveEngineHandler() {
delete reader;
delete opener;
}
QAbstractFileEngine *
ArchiveEngineHandler::create(const QString &fileName) const {
string name((const char*)fileName.toUtf8());
if (reader->canHandle(name)) {
return new StreamFileEngine(reader, name);
}
return 0;
}
<|endoftext|> |
<commit_before>#include "nany/nany.h"
#include <yuni/io/file.h>
#include <yuni/core/math.h>
#include <yuni/core/process/program.h>
#include "libnanyc-config.h"
#include "common-debuginfo.hxx"
#include <string.h>
#include <iostream>
#ifdef YUNI_OS_LINUX
#include <sys/utsname.h>
#endif
using namespace Yuni;
namespace // anonymous
{
template<class S> void printNanyVersion(S& out)
{
out << "> nanyc {c++/bootstrap} v" << nylib_version();
if (debugmode)
out << " {debug}";
out << '\n';
}
template<class S> void printCompiler(S& out)
{
out << "> compiled with ";
nany_details_export_compiler_version(out);
out << '\n';
}
template<class S> void printBuildFlags(S& out)
{
out << "> config: ";
out << "params:" << Nany::Config::maxFuncDeclParameterCount;
out << ", pushedparams:" << Nany::Config::maxPushedParameters;
out << ", nmspc depth:" << Nany::Config::maxNamespaceDepth;
out << ", symbol:" << Nany::Config::maxSymbolNameLength;
out << ", nsl:" << Nany::Config::importNSL;
out << '\n';
}
template<class S> void printOS(S& out)
{
out << "> os: ";
bool osDetected = false;
#ifdef YUNI_OS_LINUX
{
String distribName;
if (IO::errNone == IO::File::LoadFromFile(distribName, "/etc/issue.net"))
{
distribName.replace('\n', ' ');
distribName.trim();
if (not distribName.empty())
out << distribName << ", ";
}
osDetected = true;
struct utsname un;
if (uname(&un) == 0)
out << un.sysname << ' ' << un.release << " (" << un.machine << ')';
else
out << "(unknown linux)";
}
#endif
if (not osDetected)
nany_details_export_system(out);
out << '\n';
}
template<class S> void printCPU(S& out)
{
ShortString64 cpustr;
cpustr << System::CPU::Count() << " cpu(s)/core(s)";
bool cpuAdded = false;
if (System::linux)
{
auto cpus = Process::System("sh -c \"grep 'model name' /proc/cpuinfo | cut -d':' -f 2 | sort -u\"");
cpus.words("\n", [&](AnyString line) -> bool
{
line.trim();
if (not line.empty())
{
out << "> cpu: " << line;
if (not cpuAdded)
{
out << " (" << cpustr << ')';
cpuAdded = true;
}
out << '\n';
}
return true;
});
}
if (not cpuAdded)
out << "> cpu: " << cpustr << '\n';
}
template<class S> void printMemory(S& out)
{
out << "> ";
nany_details_export_memory_usage(out);
out << '\n';
}
template<class S> void buildBugReport(S& out)
{
printNanyVersion(out);
printCompiler(out);
printBuildFlags(out);
printOS(out);
printCPU(out);
printMemory(out);
}
} // anonymous namespace
extern "C" void nylib_print_info_for_bugreport()
{
buildBugReport(std::cout);
}
extern "C" char* nylib_get_info_for_bugreport(uint32_t* length)
{
String string;
string.reserve(512);
buildBugReport(string);
char* result = (char*)::malloc(sizeof(char) * (string.sizeInBytes() + 1));
if (!result)
{
if (length)
*length = 0u;
return nullptr;
}
memcpy(result, string.data(), string.sizeInBytes());
result[string.sizeInBytes()] = '\0';
if (length)
*length = string.size();
return result;
}
<commit_msg>bugreport: removed templates<commit_after>#include "nany/nany.h"
#include <yuni/io/file.h>
#include <yuni/core/math.h>
#include <yuni/core/process/program.h>
#include "libnanyc-config.h"
#include "common-debuginfo.hxx"
#include <string.h>
#include <iostream>
#ifdef YUNI_OS_LINUX
#include <sys/utsname.h>
#endif
using namespace Yuni;
namespace // anonymous
{
void printNanyVersion(String& out)
{
out << "> nanyc {c++/bootstrap} v" << nylib_version();
if (debugmode)
out << " {debug}";
out << '\n';
}
void printCompiler(String& out)
{
out << "> compiled with ";
nany_details_export_compiler_version(out);
out << '\n';
}
void printBuildFlags(String& out)
{
out << "> config: ";
out << "params:" << Nany::Config::maxFuncDeclParameterCount;
out << ", pushedparams:" << Nany::Config::maxPushedParameters;
out << ", nmspc depth:" << Nany::Config::maxNamespaceDepth;
out << ", symbol:" << Nany::Config::maxSymbolNameLength;
out << ", nsl:" << Nany::Config::importNSL;
out << '\n';
}
void printOS(String& out)
{
out << "> os: ";
bool osDetected = false;
#ifdef YUNI_OS_LINUX
{
String distribName;
if (IO::errNone == IO::File::LoadFromFile(distribName, "/etc/issue.net"))
{
distribName.replace('\n', ' ');
distribName.trim();
if (not distribName.empty())
out << distribName << ", ";
}
osDetected = true;
struct utsname un;
if (uname(&un) == 0)
out << un.sysname << ' ' << un.release << " (" << un.machine << ')';
else
out << "(unknown linux)";
}
#endif
if (not osDetected)
nany_details_export_system(out);
out << '\n';
}
void printCPU(String& out)
{
ShortString64 cpustr;
cpustr << System::CPU::Count() << " cpu(s)/core(s)";
bool cpuAdded = false;
if (System::linux)
{
auto cpus = Process::System("sh -c \"grep 'model name' /proc/cpuinfo | cut -d':' -f 2 | sort -u\"");
cpus.words("\n", [&](AnyString line) -> bool
{
line.trim();
if (not line.empty())
{
out << "> cpu: " << line;
if (not cpuAdded)
{
out << " (" << cpustr << ')';
cpuAdded = true;
}
out << '\n';
}
return true;
});
}
if (not cpuAdded)
out << "> cpu: " << cpustr << '\n';
}
void printMemory(String& out)
{
out << "> ";
nany_details_export_memory_usage(out);
out << '\n';
}
void buildBugReport(String& out)
{
printNanyVersion(out);
printCompiler(out);
printBuildFlags(out);
printOS(out);
printCPU(out);
printMemory(out);
}
} // anonymous namespace
extern "C" void nylib_print_info_for_bugreport()
{
String out;
buildBugReport(out);
std::cout << out;
}
extern "C" char* nylib_get_info_for_bugreport(uint32_t* length)
{
String string;
string.reserve(512);
buildBugReport(string);
char* result = (char*)::malloc(sizeof(char) * (string.sizeInBytes() + 1));
if (!result)
{
if (length)
*length = 0u;
return nullptr;
}
memcpy(result, string.data(), string.sizeInBytes());
result[string.sizeInBytes()] = '\0';
if (length)
*length = string.size();
return result;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: appchild.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-17 16:14: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#ifndef GCC
#endif
#ifndef _SFX_WHITER_HXX //autogen
#include <svtools/whiter.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#include "app.hxx"
#include "appdata.hxx"
#include "workwin.hxx"
#include "childwin.hxx"
#include "arrdecl.hxx"
#include "templdlg.hxx"
#include "request.hxx"
#include "bindings.hxx"
#include "dispatch.hxx"
#include "sfxtypes.hxx"
#include "module.hxx"
#include "sfxsids.hrc"
//=========================================================================
void SfxApplication::RegisterChildWindow_Impl( SfxModule *pMod, SfxChildWinFactory *pFact )
{
if ( pMod )
{
pMod->RegisterChildWindow( pFact );
return;
}
if (!pAppData_Impl->pFactArr)
pAppData_Impl->pFactArr = new SfxChildWinFactArr_Impl;
//#ifdef DBG_UTIL
for (USHORT nFactory=0; nFactory<pAppData_Impl->pFactArr->Count(); ++nFactory)
{
if (pFact->nId == (*pAppData_Impl->pFactArr)[nFactory]->nId)
{
pAppData_Impl->pFactArr->Remove( nFactory );
// DBG_ERROR("ChildWindow mehrfach registriert!");
// return;
}
}
//#endif
pAppData_Impl->pFactArr->C40_INSERT(
SfxChildWinFactory, pFact, pAppData_Impl->pFactArr->Count() );
}
void SfxApplication::RegisterChildWindowContext_Impl( SfxModule *pMod, USHORT nId,
SfxChildWinContextFactory *pFact)
{
SfxChildWinFactArr_Impl *pFactories;
SfxChildWinFactory *pF = NULL;
if ( pMod )
{
// Modul "ubergeben, ChildwindowFactory dort suchen
pFactories = pMod->GetChildWinFactories_Impl();
if ( pFactories )
{
USHORT nCount = pFactories->Count();
for (USHORT nFactory=0; nFactory<nCount; ++nFactory)
{
SfxChildWinFactory *pFac = (*pFactories)[nFactory];
if ( nId == pFac->nId )
{
// Factory gefunden, Context dort registrieren
pF = pFac;
break;
}
}
}
}
if ( !pF )
{
// Factory an der Application suchen
DBG_ASSERT( pAppData_Impl, "Keine AppDaten!" );
DBG_ASSERT( pAppData_Impl->pFactArr, "Keine Factories!" );
pFactories = pAppData_Impl->pFactArr;
USHORT nCount = pFactories->Count();
for (USHORT nFactory=0; nFactory<nCount; ++nFactory)
{
SfxChildWinFactory *pFac = (*pFactories)[nFactory];
if ( nId == pFac->nId )
{
if ( pMod )
{
// Wenn der Context von einem Modul registriert wurde,
// mu\s die ChildwindowFactory auch dort zur Verf"ugung
// stehen, sonst m"u\ste sich die Contextfactory im DLL-Exit
// wieder abmelden !
pF = new SfxChildWinFactory( pFac->pCtor, pFac->nId,
pFac->nPos );
pMod->RegisterChildWindow( pF );
}
else
pF = pFac;
break;
}
}
}
if ( pF )
{
if ( !pF->pArr )
pF->pArr = new SfxChildWinContextArr_Impl;
pF->pArr->C40_INSERT( SfxChildWinContextFactory, pFact, pF->pArr->Count() );
return;
}
DBG_ERROR( "Kein ChildWindow fuer diesen Context!" );
}
//--------------------------------------------------------------------
SfxChildWinFactArr_Impl& SfxApplication::GetChildWinFactories_Impl() const
{
return ( *(pAppData_Impl->pFactArr));
}
//--------------------------------------------------------------------
SfxTemplateDialog* SfxApplication::GetTemplateDialog()
{
if ( pAppData_Impl->pViewFrame )
{
SfxChildWindow *pChild = pAppData_Impl->pViewFrame->GetChildWindow(SfxTemplateDialogWrapper::GetChildWindowId());
return pChild ? (SfxTemplateDialog*) pChild->GetWindow() : 0;
}
return NULL;
}
//--------------------------------------------------------------------
SfxWorkWindow* SfxApplication::GetWorkWindow_Impl(const SfxViewFrame *pFrame) const
{
if ( pFrame )
return pFrame->GetFrame()->GetWorkWindow_Impl();
else if ( pAppData_Impl->pViewFrame )
return pAppData_Impl->pViewFrame->GetFrame()->GetWorkWindow_Impl();
else
return NULL;
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.8.218); FILE MERGED 2007/06/04 13:34:37 vg 1.8.218.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: appchild.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2007-06-27 22:55:19 $
*
* 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_sfx2.hxx"
#ifndef GCC
#endif
#ifndef _SFX_WHITER_HXX //autogen
#include <svtools/whiter.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#include <sfx2/app.hxx>
#include "appdata.hxx"
#include "workwin.hxx"
#include <sfx2/childwin.hxx>
#include "arrdecl.hxx"
#include <sfx2/templdlg.hxx>
#include <sfx2/request.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include "sfxtypes.hxx"
#include <sfx2/module.hxx>
#include <sfx2/sfxsids.hrc>
//=========================================================================
void SfxApplication::RegisterChildWindow_Impl( SfxModule *pMod, SfxChildWinFactory *pFact )
{
if ( pMod )
{
pMod->RegisterChildWindow( pFact );
return;
}
if (!pAppData_Impl->pFactArr)
pAppData_Impl->pFactArr = new SfxChildWinFactArr_Impl;
//#ifdef DBG_UTIL
for (USHORT nFactory=0; nFactory<pAppData_Impl->pFactArr->Count(); ++nFactory)
{
if (pFact->nId == (*pAppData_Impl->pFactArr)[nFactory]->nId)
{
pAppData_Impl->pFactArr->Remove( nFactory );
// DBG_ERROR("ChildWindow mehrfach registriert!");
// return;
}
}
//#endif
pAppData_Impl->pFactArr->C40_INSERT(
SfxChildWinFactory, pFact, pAppData_Impl->pFactArr->Count() );
}
void SfxApplication::RegisterChildWindowContext_Impl( SfxModule *pMod, USHORT nId,
SfxChildWinContextFactory *pFact)
{
SfxChildWinFactArr_Impl *pFactories;
SfxChildWinFactory *pF = NULL;
if ( pMod )
{
// Modul "ubergeben, ChildwindowFactory dort suchen
pFactories = pMod->GetChildWinFactories_Impl();
if ( pFactories )
{
USHORT nCount = pFactories->Count();
for (USHORT nFactory=0; nFactory<nCount; ++nFactory)
{
SfxChildWinFactory *pFac = (*pFactories)[nFactory];
if ( nId == pFac->nId )
{
// Factory gefunden, Context dort registrieren
pF = pFac;
break;
}
}
}
}
if ( !pF )
{
// Factory an der Application suchen
DBG_ASSERT( pAppData_Impl, "Keine AppDaten!" );
DBG_ASSERT( pAppData_Impl->pFactArr, "Keine Factories!" );
pFactories = pAppData_Impl->pFactArr;
USHORT nCount = pFactories->Count();
for (USHORT nFactory=0; nFactory<nCount; ++nFactory)
{
SfxChildWinFactory *pFac = (*pFactories)[nFactory];
if ( nId == pFac->nId )
{
if ( pMod )
{
// Wenn der Context von einem Modul registriert wurde,
// mu\s die ChildwindowFactory auch dort zur Verf"ugung
// stehen, sonst m"u\ste sich die Contextfactory im DLL-Exit
// wieder abmelden !
pF = new SfxChildWinFactory( pFac->pCtor, pFac->nId,
pFac->nPos );
pMod->RegisterChildWindow( pF );
}
else
pF = pFac;
break;
}
}
}
if ( pF )
{
if ( !pF->pArr )
pF->pArr = new SfxChildWinContextArr_Impl;
pF->pArr->C40_INSERT( SfxChildWinContextFactory, pFact, pF->pArr->Count() );
return;
}
DBG_ERROR( "Kein ChildWindow fuer diesen Context!" );
}
//--------------------------------------------------------------------
SfxChildWinFactArr_Impl& SfxApplication::GetChildWinFactories_Impl() const
{
return ( *(pAppData_Impl->pFactArr));
}
//--------------------------------------------------------------------
SfxTemplateDialog* SfxApplication::GetTemplateDialog()
{
if ( pAppData_Impl->pViewFrame )
{
SfxChildWindow *pChild = pAppData_Impl->pViewFrame->GetChildWindow(SfxTemplateDialogWrapper::GetChildWindowId());
return pChild ? (SfxTemplateDialog*) pChild->GetWindow() : 0;
}
return NULL;
}
//--------------------------------------------------------------------
SfxWorkWindow* SfxApplication::GetWorkWindow_Impl(const SfxViewFrame *pFrame) const
{
if ( pFrame )
return pFrame->GetFrame()->GetWorkWindow_Impl();
else if ( pAppData_Impl->pViewFrame )
return pAppData_Impl->pViewFrame->GetFrame()->GetWorkWindow_Impl();
else
return NULL;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include <tools/debug.hxx>
#include "bitset.hxx"
#include <string.h> // memset(), memcpy()
#include <limits.h> // USHRT_MAX
//====================================================================
// add nOffset to each bit-value in the set
BitSet BitSet::operator<<( sal_uInt16 nOffset ) const
{
DBG_MEMTEST();
// create a work-copy, return it if nothing to shift
BitSet aSet(*this);
if ( nOffset == 0 )
return aSet;
// compute the shiftment in long-words and bits
sal_uInt16 nBlockDiff = nOffset / 32;
sal_uIntPtr nBitValDiff = nOffset % 32;
// compute the new number of bits
for ( sal_uInt16 nBlock = 0; nBlock < nBlockDiff; ++nBlock )
aSet.nCount = aSet.nCount - CountBits( *(aSet.pBitmap+nBlock) );
aSet.nCount = aSet.nCount -
CountBits( *(aSet.pBitmap+nBlockDiff) >> (32-nBitValDiff) );
// shift complete long-words
sal_uInt16 nTarget, nSource;
for ( nTarget = 0, nSource = nBlockDiff;
(nSource+1) < aSet.nBlocks;
++nTarget, ++nSource )
*(aSet.pBitmap+nTarget) =
( *(aSet.pBitmap+nSource) << nBitValDiff ) |
( *(aSet.pBitmap+nSource+1) >> (32-nBitValDiff) );
// shift the remainder (if in total minor 32 bits, only this)
*(aSet.pBitmap+nTarget) = *(aSet.pBitmap+nSource) << nBitValDiff;
// determine the last used block
while ( *(aSet.pBitmap+nTarget) == 0 )
--nTarget;
// shorten the block-array
if ( nTarget < aSet.nBlocks )
{
sal_uIntPtr* pNewMap = new sal_uIntPtr[nTarget];
memcpy( pNewMap, aSet.pBitmap, 4 * nTarget );
delete [] aSet.pBitmap;
aSet.pBitmap = pNewMap;
aSet.nBlocks = nTarget;
}
return aSet;
}
//--------------------------------------------------------------------
// substracts nOffset from each bit-value in the set
BitSet BitSet::operator>>( sal_uInt16 ) const
{
DBG_MEMTEST();
return BitSet();
}
//--------------------------------------------------------------------
// internal code for operator= and copy-ctor
void BitSet::CopyFrom( const BitSet& rSet )
{
DBG_MEMTEST();
nCount = rSet.nCount;
nBlocks = rSet.nBlocks;
if ( rSet.nBlocks )
{
DBG_MEMTEST();
pBitmap = new sal_uIntPtr[nBlocks];
memcpy( pBitmap, rSet.pBitmap, 4 * nBlocks );
}
else
pBitmap = 0;
}
//--------------------------------------------------------------------
// creates an empty bitset
BitSet::BitSet()
{
DBG_MEMTEST();
nCount = 0;
nBlocks = 0;
pBitmap = 0;
}
//--------------------------------------------------------------------
// creates a copy of bitset rOrig
BitSet::BitSet( const BitSet& rOrig )
{
DBG_MEMTEST();
CopyFrom(rOrig);
}
//--------------------------------------------------------------------
// creates a bitset from an array
BitSet::BitSet( sal_uInt16* pArray, sal_uInt16 nSize ):
nCount(nSize)
{
DBG_MEMTEST();
// find the highest bit to set
sal_uInt16 nMax = 0;
for ( sal_uInt16 n = 0; n < nCount; ++n )
if ( pArray[n] > nMax )
nMax = pArray[n];
// if there are bits at all
if ( nMax > 0 )
{
// allocate memory for all blocks needed
nBlocks = nMax / 32 + 1;
pBitmap = new sal_uIntPtr[nBlocks];
memset( pBitmap, 0, 4 * nBlocks );
// set all the bits
for ( sal_uInt16 n = 0; n < nCount; ++n )
{
// compute the block no. and bitvalue
sal_uInt16 nBlock = n / 32;
sal_uIntPtr nBitVal = 1L << (n % 32);
// set a single bit
if ( ( *(pBitmap+nBlock) & nBitVal ) == 0 )
{
*(pBitmap+nBlock) |= nBitVal;
++nCount;
}
}
}
else
{
// initalize emtpy set
nBlocks = 0;
pBitmap = 0;
}
}
//--------------------------------------------------------------------
// frees the storage
BitSet::~BitSet()
{
DBG_MEMTEST();
delete [] pBitmap;
}
//--------------------------------------------------------------------
// creates a bitmap with all bits in rRange set
BitSet::BitSet( const Range& )
{
DBG_MEMTEST();
}
//--------------------------------------------------------------------
// assignment from another bitset
BitSet& BitSet::operator=( const BitSet& rOrig )
{
DBG_MEMTEST();
if ( this != &rOrig )
{
delete [] pBitmap;
CopyFrom(rOrig);
}
return *this;
}
//--------------------------------------------------------------------
// assignment from a single bit
BitSet& BitSet::operator=( sal_uInt16 nBit )
{
DBG_MEMTEST();
delete [] pBitmap;
nBlocks = nBit / 32;
sal_uIntPtr nBitVal = 1L << (nBit % 32);
nCount = 1;
pBitmap = new sal_uIntPtr[nBlocks];
memset( pBitmap + nBlocks, 0, 4 * nBlocks );
*(pBitmap+nBlocks) = nBitVal;
return *this;
}
//--------------------------------------------------------------------
// creates the asymetric difference with another bitset
BitSet& BitSet::operator-=(sal_uInt16 nBit)
{
DBG_MEMTEST();
sal_uInt16 nBlock = nBit / 32;
sal_uIntPtr nBitVal = 1L << (nBit % 32);
if ( nBlock >= nBlocks )
return *this;
if ( (*(pBitmap+nBlock) & nBitVal) )
{
*(pBitmap+nBlock) &= ~nBitVal;
--nCount;
}
return *this;
}
//--------------------------------------------------------------------
// unites with the bits of rSet
BitSet& BitSet::operator|=( const BitSet& rSet )
{
DBG_MEMTEST();
sal_uInt16 nMax = Min(nBlocks, rSet.nBlocks);
// expand the bitmap
if ( nBlocks < rSet.nBlocks )
{
sal_uIntPtr *pNewMap = new sal_uIntPtr[rSet.nBlocks];
memset( pNewMap + nBlocks, 0, 4 * (rSet.nBlocks - nBlocks) );
if ( pBitmap )
{
memcpy( pNewMap, pBitmap, 4 * nBlocks );
delete [] pBitmap;
}
pBitmap = pNewMap;
nBlocks = rSet.nBlocks;
}
// add the bits blocks by block
for ( sal_uInt16 nBlock = 0; nBlock < nMax; ++nBlock )
{
// compute numberof additional bits
sal_uIntPtr nDiff = ~*(pBitmap+nBlock) & *(rSet.pBitmap+nBlock);
nCount = nCount + CountBits(nDiff);
*(pBitmap+nBlock) |= *(rSet.pBitmap+nBlock);
}
return *this;
}
//--------------------------------------------------------------------
// unites with a single bit
BitSet& BitSet::operator|=( sal_uInt16 nBit )
{
DBG_MEMTEST();
sal_uInt16 nBlock = nBit / 32;
sal_uIntPtr nBitVal = 1L << (nBit % 32);
if ( nBlock >= nBlocks )
{
sal_uIntPtr *pNewMap = new sal_uIntPtr[nBlock+1];
memset( pNewMap + nBlocks, 0, 4 * (nBlock - nBlocks + 1) );
if ( pBitmap )
{
memcpy( pNewMap, pBitmap, 4 * nBlocks );
delete [] pBitmap;
}
pBitmap = pNewMap;
nBlocks = nBlock+1;
}
if ( (*(pBitmap+nBlock) & nBitVal) == 0 )
{
*(pBitmap+nBlock) |= nBitVal;
++nCount;
}
return *this;
}
//--------------------------------------------------------------------
// determines if the bit is set (may be the only one)
sal_Bool BitSet::Contains( sal_uInt16 nBit ) const
{
DBG_MEMTEST();
sal_uInt16 nBlock = nBit / 32;
sal_uIntPtr nBitVal = 1L << (nBit % 32);
if ( nBlock >= nBlocks )
return sal_False;
return ( nBitVal & *(pBitmap+nBlock) ) == nBitVal;
}
//--------------------------------------------------------------------
// determines if the bitsets are equal
sal_Bool BitSet::operator==( const BitSet& rSet ) const
{
DBG_MEMTEST();
if ( nBlocks != rSet.nBlocks )
return sal_False;
sal_uInt16 nBlock = nBlocks;
while ( nBlock-- > 0 )
if ( *(pBitmap+nBlock) != *(rSet.pBitmap+nBlock) )
return sal_False;
return sal_True;
}
//--------------------------------------------------------------------
// counts the number of 1-bits in the parameter
sal_uInt16 BitSet::CountBits( sal_uIntPtr nBits )
{
sal_uInt16 nCount = 0;
int nBit = 32;
while ( nBit-- && nBits )
{ if ( ( (long)nBits ) < 0 )
++nCount;
nBits = nBits << 1;
}
return nCount;
}
//--------------------------------------------------------------------
sal_uInt16 IndexBitSet::GetFreeIndex()
{
for(sal_uInt16 i=0;i<USHRT_MAX;i++)
if(!Contains(i))
{
*this|=i;
return i;
}
DBG_ASSERT(sal_False, "IndexBitSet enthaelt mehr als USHRT_MAX Eintraege");
return 0;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix array overflow<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include <tools/debug.hxx>
#include "bitset.hxx"
#include <string.h> // memset(), memcpy()
#include <limits.h> // USHRT_MAX
//====================================================================
// add nOffset to each bit-value in the set
BitSet BitSet::operator<<( sal_uInt16 nOffset ) const
{
DBG_MEMTEST();
// create a work-copy, return it if nothing to shift
BitSet aSet(*this);
if ( nOffset == 0 )
return aSet;
// compute the shiftment in long-words and bits
sal_uInt16 nBlockDiff = nOffset / 32;
sal_uIntPtr nBitValDiff = nOffset % 32;
// compute the new number of bits
for ( sal_uInt16 nBlock = 0; nBlock < nBlockDiff; ++nBlock )
aSet.nCount = aSet.nCount - CountBits( *(aSet.pBitmap+nBlock) );
aSet.nCount = aSet.nCount -
CountBits( *(aSet.pBitmap+nBlockDiff) >> (32-nBitValDiff) );
// shift complete long-words
sal_uInt16 nTarget, nSource;
for ( nTarget = 0, nSource = nBlockDiff;
(nSource+1) < aSet.nBlocks;
++nTarget, ++nSource )
*(aSet.pBitmap+nTarget) =
( *(aSet.pBitmap+nSource) << nBitValDiff ) |
( *(aSet.pBitmap+nSource+1) >> (32-nBitValDiff) );
// shift the remainder (if in total minor 32 bits, only this)
*(aSet.pBitmap+nTarget) = *(aSet.pBitmap+nSource) << nBitValDiff;
// determine the last used block
while ( *(aSet.pBitmap+nTarget) == 0 )
--nTarget;
// shorten the block-array
if ( nTarget < aSet.nBlocks )
{
sal_uIntPtr* pNewMap = new sal_uIntPtr[nTarget];
memcpy( pNewMap, aSet.pBitmap, 4 * nTarget );
delete [] aSet.pBitmap;
aSet.pBitmap = pNewMap;
aSet.nBlocks = nTarget;
}
return aSet;
}
//--------------------------------------------------------------------
// substracts nOffset from each bit-value in the set
BitSet BitSet::operator>>( sal_uInt16 ) const
{
DBG_MEMTEST();
return BitSet();
}
//--------------------------------------------------------------------
// internal code for operator= and copy-ctor
void BitSet::CopyFrom( const BitSet& rSet )
{
DBG_MEMTEST();
nCount = rSet.nCount;
nBlocks = rSet.nBlocks;
if ( rSet.nBlocks )
{
DBG_MEMTEST();
pBitmap = new sal_uIntPtr[nBlocks];
memcpy( pBitmap, rSet.pBitmap, 4 * nBlocks );
}
else
pBitmap = 0;
}
//--------------------------------------------------------------------
// creates an empty bitset
BitSet::BitSet()
{
DBG_MEMTEST();
nCount = 0;
nBlocks = 0;
pBitmap = 0;
}
//--------------------------------------------------------------------
// creates a copy of bitset rOrig
BitSet::BitSet( const BitSet& rOrig )
{
DBG_MEMTEST();
CopyFrom(rOrig);
}
//--------------------------------------------------------------------
// creates a bitset from an array
BitSet::BitSet( sal_uInt16* pArray, sal_uInt16 nSize ):
nCount(nSize)
{
DBG_MEMTEST();
// find the highest bit to set
sal_uInt16 nMax = 0;
for ( sal_uInt16 n = 0; n < nCount; ++n )
if ( pArray[n] > nMax )
nMax = pArray[n];
// if there are bits at all
if ( nMax > 0 )
{
// allocate memory for all blocks needed
nBlocks = nMax / 32 + 1;
pBitmap = new sal_uIntPtr[nBlocks];
memset( pBitmap, 0, 4 * nBlocks );
// set all the bits
for ( sal_uInt16 n = 0; n < nCount; ++n )
{
// compute the block no. and bitvalue
sal_uInt16 nBlock = n / 32;
sal_uIntPtr nBitVal = 1L << (n % 32);
// set a single bit
if ( ( *(pBitmap+nBlock) & nBitVal ) == 0 )
{
*(pBitmap+nBlock) |= nBitVal;
++nCount;
}
}
}
else
{
// initalize emtpy set
nBlocks = 0;
pBitmap = 0;
}
}
//--------------------------------------------------------------------
// frees the storage
BitSet::~BitSet()
{
DBG_MEMTEST();
delete [] pBitmap;
}
//--------------------------------------------------------------------
// creates a bitmap with all bits in rRange set
BitSet::BitSet( const Range& )
{
DBG_MEMTEST();
}
//--------------------------------------------------------------------
// assignment from another bitset
BitSet& BitSet::operator=( const BitSet& rOrig )
{
DBG_MEMTEST();
if ( this != &rOrig )
{
delete [] pBitmap;
CopyFrom(rOrig);
}
return *this;
}
//--------------------------------------------------------------------
// assignment from a single bit
BitSet& BitSet::operator=( sal_uInt16 nBit )
{
DBG_MEMTEST();
delete [] pBitmap;
nBlocks = nBit / 32;
sal_uIntPtr nBitVal = 1L << (nBit % 32);
nCount = 1;
pBitmap = new sal_uIntPtr[nBlocks + 1];
memset( pBitmap, 0, 4 * (nBlocks + 1) );
*(pBitmap+nBlocks) = nBitVal;
return *this;
}
//--------------------------------------------------------------------
// creates the asymetric difference with another bitset
BitSet& BitSet::operator-=(sal_uInt16 nBit)
{
DBG_MEMTEST();
sal_uInt16 nBlock = nBit / 32;
sal_uIntPtr nBitVal = 1L << (nBit % 32);
if ( nBlock >= nBlocks )
return *this;
if ( (*(pBitmap+nBlock) & nBitVal) )
{
*(pBitmap+nBlock) &= ~nBitVal;
--nCount;
}
return *this;
}
//--------------------------------------------------------------------
// unites with the bits of rSet
BitSet& BitSet::operator|=( const BitSet& rSet )
{
DBG_MEMTEST();
sal_uInt16 nMax = Min(nBlocks, rSet.nBlocks);
// expand the bitmap
if ( nBlocks < rSet.nBlocks )
{
sal_uIntPtr *pNewMap = new sal_uIntPtr[rSet.nBlocks];
memset( pNewMap + nBlocks, 0, 4 * (rSet.nBlocks - nBlocks) );
if ( pBitmap )
{
memcpy( pNewMap, pBitmap, 4 * nBlocks );
delete [] pBitmap;
}
pBitmap = pNewMap;
nBlocks = rSet.nBlocks;
}
// add the bits blocks by block
for ( sal_uInt16 nBlock = 0; nBlock < nMax; ++nBlock )
{
// compute numberof additional bits
sal_uIntPtr nDiff = ~*(pBitmap+nBlock) & *(rSet.pBitmap+nBlock);
nCount = nCount + CountBits(nDiff);
*(pBitmap+nBlock) |= *(rSet.pBitmap+nBlock);
}
return *this;
}
//--------------------------------------------------------------------
// unites with a single bit
BitSet& BitSet::operator|=( sal_uInt16 nBit )
{
DBG_MEMTEST();
sal_uInt16 nBlock = nBit / 32;
sal_uIntPtr nBitVal = 1L << (nBit % 32);
if ( nBlock >= nBlocks )
{
sal_uIntPtr *pNewMap = new sal_uIntPtr[nBlock+1];
memset( pNewMap + nBlocks, 0, 4 * (nBlock - nBlocks + 1) );
if ( pBitmap )
{
memcpy( pNewMap, pBitmap, 4 * nBlocks );
delete [] pBitmap;
}
pBitmap = pNewMap;
nBlocks = nBlock+1;
}
if ( (*(pBitmap+nBlock) & nBitVal) == 0 )
{
*(pBitmap+nBlock) |= nBitVal;
++nCount;
}
return *this;
}
//--------------------------------------------------------------------
// determines if the bit is set (may be the only one)
sal_Bool BitSet::Contains( sal_uInt16 nBit ) const
{
DBG_MEMTEST();
sal_uInt16 nBlock = nBit / 32;
sal_uIntPtr nBitVal = 1L << (nBit % 32);
if ( nBlock >= nBlocks )
return sal_False;
return ( nBitVal & *(pBitmap+nBlock) ) == nBitVal;
}
//--------------------------------------------------------------------
// determines if the bitsets are equal
sal_Bool BitSet::operator==( const BitSet& rSet ) const
{
DBG_MEMTEST();
if ( nBlocks != rSet.nBlocks )
return sal_False;
sal_uInt16 nBlock = nBlocks;
while ( nBlock-- > 0 )
if ( *(pBitmap+nBlock) != *(rSet.pBitmap+nBlock) )
return sal_False;
return sal_True;
}
//--------------------------------------------------------------------
// counts the number of 1-bits in the parameter
sal_uInt16 BitSet::CountBits( sal_uIntPtr nBits )
{
sal_uInt16 nCount = 0;
int nBit = 32;
while ( nBit-- && nBits )
{ if ( ( (long)nBits ) < 0 )
++nCount;
nBits = nBits << 1;
}
return nCount;
}
//--------------------------------------------------------------------
sal_uInt16 IndexBitSet::GetFreeIndex()
{
for(sal_uInt16 i=0;i<USHRT_MAX;i++)
if(!Contains(i))
{
*this|=i;
return i;
}
DBG_ASSERT(sal_False, "IndexBitSet enthaelt mehr als USHRT_MAX Eintraege");
return 0;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before><commit_msg>`Model`: remove unused member variable `std::string triangulation_type`.<commit_after><|endoftext|> |
<commit_before><commit_msg>`Scene` constructor: cleaning up code.<commit_after><|endoftext|> |
<commit_before>#include "codectabswidget.h"
#include "ui_codectabswidget.h"
CodecTabsWidget::CodecTabsWidget(QWidget *parent)
: QWidget(parent), ui(new Ui::CodecTabsWidget) {
ui->setupUi(this);
ui->tabWidget->setCurrentIndex(0);
connect(ui->tabWidget, &QTabWidget::currentChanged, this,
CodecTabsWidget::onTabChange);
codecManagers.push_back(ui->mjpegtab);
codecManagers.push_back(ui->h261tab);
codecManagers.push_back(ui->mpeg1tab);
codecManagers.push_back(ui->mpeg2tab);
codecManagers.push_back(ui->h264tab);
codecManagers.push_back(ui->h265tab);
for (int i = 0; i < codecManagers.size(); i++) {
codecManagers.at(i)->setCodecTabs(this);
}
/*commonParamsWidgets.push_back(ui->mjpegtab->getCommonParams());
commonParamsWidgets.push_back(ui->h261tab->getCommonParams());
commonParamsWidgets.push_back(ui->mpeg1tab->getCommonParams());
commonParamsWidgets.push_back(ui->mpeg2tab->getCommonParams());
commonParamsWidgets.push_back(ui->h264tab->getCommonParams());
commonParamsWidgets.push_back(ui->h265tab->getCommonParams());*/
}
CodecTabsWidget::~CodecTabsWidget() { delete ui; }
void CodecTabsWidget::setSelectedCodecs(int first, int second, int third) {
qDebug() << "Selected codecs: " << first << second << third;
QString streamingParameters1 = "-c:v copy -f nut -an";
QString streamingParameters2 =
parametersToString(codecManagers.at(first)->getStreamingParameters()) +
" -an";
QString streamingParameters3 =
parametersToString(codecManagers.at(second)->getStreamingParameters()) +
" -an";
QString streamingParameters4 =
parametersToString(codecManagers.at(third)->getStreamingParameters()) +
" -an";
qDebug() << "Streaming parameters:";
qDebug() << streamingParameters1;
qDebug() << streamingParameters2;
qDebug() << streamingParameters3;
qDebug() << streamingParameters4;
QString streamingCommand1 = buildStreamingCommand(
inputParameters, inputLocation, {streamingParameters1},
{VIDEO_PROTOCOLS[0] + "://" + VIDEO_HOSTS[0] + ":" + VIDEO_PORTS[0]});
QString streamingCommand2 = buildStreamingCommand(
inputParameters, inputLocation, {streamingParameters2},
{VIDEO_PROTOCOLS[1] + "://" + VIDEO_HOSTS[1] + ":" + VIDEO_PORTS[1]});
QString streamingCommand3 = buildStreamingCommand(
inputParameters, inputLocation, {streamingParameters3},
{VIDEO_PROTOCOLS[2] + "://" + VIDEO_HOSTS[2] + ":" + VIDEO_PORTS[2]});
QString streamingCommand4 = buildStreamingCommand(
inputParameters, inputLocation, {streamingParameters4},
{VIDEO_PROTOCOLS[3] + "://" + VIDEO_HOSTS[3] + ":" + VIDEO_PORTS[3]});
qDebug() << "Streaming commands:";
qDebug() << streamingCommand1;
qDebug() << streamingCommand2;
qDebug() << streamingCommand3;
qDebug() << streamingCommand4;
showCodecs.show();
showCodecs.broadcast(streamingCommand1, streamingCommand2,
streamingCommand3, streamingCommand4);
}
//QVector<CodecManager *> CodecTabsWidget::getCodecManagers() {
// return codecManagers;
//}
void CodecTabsWidget::stopStreaming() {
streamingProcess.kill();
streamingProcess.waitForFinished();
}
QString CodecTabsWidget::buildStreamingCommand(
QString inputParameters, QString inputLocation,
QVector<QString> outputPrameters, QVector<QString> outputLocations) {
QStringList list;
list << FFMPEG;
list << inputParameters;
list << "-i " << inputLocation;
for (int i = 0;
i < outputPrameters.length() && i < outputLocations.length(); i++) {
list << outputPrameters[i] << outputLocations[i];
}
QString command = list.join(" ");
qDebug() << "Produced the following encoding command:\n"
<< command.toUtf8().constData();
return command;
}
QString CodecTabsWidget::buildProbeCommand(QString location, QString params) {
QStringList list;
list << FFPROBE;
list << location;
list << params;
QString command = list.join(" ");
qDebug() << "Produced the following probe command:\n"
<< command.toUtf8().constData();
return command;
}
QString CodecTabsWidget::parametersToString(QMap<QString, QString> parameters) {
QStringList result;
for (auto key : parameters.keys()) {
result << "-" + key << parameters.value(key);
}
return result.join(" ");
}
void CodecTabsWidget::openFromFile(QString filePath) {
if (!filePath.isEmpty()) {
inputParameters = "-re";
inputLocation = "\"" + filePath + "\"";
settingsChanged();
}
}
void CodecTabsWidget::openFromCamera() {
#ifdef Q_OS_WIN
inputParameters = "-f dshow";
inputLocation = "video=\"Lenovo EasyCamera\"";
settingsChanged();
#else
inputParameters = "-f v4l2";
inputLocation = "/dev/video0";
settingsChanged();
#endif
}
void CodecTabsWidget::onTabChange() { currentTabChanged(); }
QString CodecTabsWidget::getStreamingParameters() {
if (inputLocation.isEmpty()) {
qDebug() << "Input location is missing! Not starting player.";
return "";
}
if (inputParameters.isEmpty()) {
qDebug() << "Input parameters are missing! Not starting player.";
return "";
}
QMap<QString, QString> streamingParametersMap =
codecManagers.at(ui->tabWidget->currentIndex())
->getStreamingParameters();
if (streamingParametersMap.isEmpty()) {
qDebug() << "Encoding parameters are missing! Not starting player.";
return "";
}
QString streamingParameters =
parametersToString(streamingParametersMap) + " -an";
return streamingParameters;
}
void CodecTabsWidget::startStreaming(QString streamingParameters) {
qDebug() << "Starting the encoding process...";
QString streamingCommand = buildStreamingCommand(
inputParameters, inputLocation,
{"-c:v copy -f nut -an", streamingParameters, streamingParameters,
streamingParameters},
{RAW_VIDEO_PROTOCOL + "://" + RAW_VIDEO_HOST + ":" + RAW_VIDEO_PORT,
ENCODED_VIDEO_PROTOCOL + "://" + ENCODED_VIDEO_HOST + ":" +
ENCODED_VIDEO_PORT,
VIDEO_PROBE_PROTOCOL + "://" + VIDEO_PROBE_HOST + ":" +
VIDEO_PROBE_PORT,
STREAM_PROBE_PROTOCOL + "://" + STREAM_PROBE_HOST + ":" +
STREAM_PROBE_PORT});
streamingProcess.start(streamingCommand);
}
QString CodecTabsWidget::getProbeCommand() {
qDebug() << "Starting the probe process...";
QString frameProbeCommand = buildProbeCommand(
VIDEO_PROBE_PROTOCOL + "://" + VIDEO_PROBE_HOST + ":" +
VIDEO_PROBE_PORT,
"-show_frames -show_entries frame=pict_type,width,height");
return frameProbeCommand;
}
QString CodecTabsWidget::getStreamCommand() {
QString streamProbeCommand =
buildProbeCommand(STREAM_PROBE_PROTOCOL + "://" + STREAM_PROBE_HOST +
":" + STREAM_PROBE_PORT,
"-show_streams -select_streams v:0");
return streamProbeCommand;
}
void CodecTabsWidget::setCRF(QString value) {
codecManagers.at(ui->tabWidget->currentIndex())->setCRF(value);
settingsChanged();
}
<commit_msg>Add a missing &<commit_after>#include "codectabswidget.h"
#include "ui_codectabswidget.h"
CodecTabsWidget::CodecTabsWidget(QWidget *parent)
: QWidget(parent), ui(new Ui::CodecTabsWidget) {
ui->setupUi(this);
ui->tabWidget->setCurrentIndex(0);
connect(ui->tabWidget, &QTabWidget::currentChanged, this,
&CodecTabsWidget::onTabChange);
codecManagers.push_back(ui->mjpegtab);
codecManagers.push_back(ui->h261tab);
codecManagers.push_back(ui->mpeg1tab);
codecManagers.push_back(ui->mpeg2tab);
codecManagers.push_back(ui->h264tab);
codecManagers.push_back(ui->h265tab);
for (int i = 0; i < codecManagers.size(); i++) {
codecManagers.at(i)->setCodecTabs(this);
}
/*commonParamsWidgets.push_back(ui->mjpegtab->getCommonParams());
commonParamsWidgets.push_back(ui->h261tab->getCommonParams());
commonParamsWidgets.push_back(ui->mpeg1tab->getCommonParams());
commonParamsWidgets.push_back(ui->mpeg2tab->getCommonParams());
commonParamsWidgets.push_back(ui->h264tab->getCommonParams());
commonParamsWidgets.push_back(ui->h265tab->getCommonParams());*/
}
CodecTabsWidget::~CodecTabsWidget() { delete ui; }
void CodecTabsWidget::setSelectedCodecs(int first, int second, int third) {
qDebug() << "Selected codecs: " << first << second << third;
QString streamingParameters1 = "-c:v copy -f nut -an";
QString streamingParameters2 =
parametersToString(codecManagers.at(first)->getStreamingParameters()) +
" -an";
QString streamingParameters3 =
parametersToString(codecManagers.at(second)->getStreamingParameters()) +
" -an";
QString streamingParameters4 =
parametersToString(codecManagers.at(third)->getStreamingParameters()) +
" -an";
qDebug() << "Streaming parameters:";
qDebug() << streamingParameters1;
qDebug() << streamingParameters2;
qDebug() << streamingParameters3;
qDebug() << streamingParameters4;
QString streamingCommand1 = buildStreamingCommand(
inputParameters, inputLocation, {streamingParameters1},
{VIDEO_PROTOCOLS[0] + "://" + VIDEO_HOSTS[0] + ":" + VIDEO_PORTS[0]});
QString streamingCommand2 = buildStreamingCommand(
inputParameters, inputLocation, {streamingParameters2},
{VIDEO_PROTOCOLS[1] + "://" + VIDEO_HOSTS[1] + ":" + VIDEO_PORTS[1]});
QString streamingCommand3 = buildStreamingCommand(
inputParameters, inputLocation, {streamingParameters3},
{VIDEO_PROTOCOLS[2] + "://" + VIDEO_HOSTS[2] + ":" + VIDEO_PORTS[2]});
QString streamingCommand4 = buildStreamingCommand(
inputParameters, inputLocation, {streamingParameters4},
{VIDEO_PROTOCOLS[3] + "://" + VIDEO_HOSTS[3] + ":" + VIDEO_PORTS[3]});
qDebug() << "Streaming commands:";
qDebug() << streamingCommand1;
qDebug() << streamingCommand2;
qDebug() << streamingCommand3;
qDebug() << streamingCommand4;
showCodecs.show();
showCodecs.broadcast(streamingCommand1, streamingCommand2,
streamingCommand3, streamingCommand4);
}
// QVector<CodecManager *> CodecTabsWidget::getCodecManagers() {
// return codecManagers;
//}
void CodecTabsWidget::stopStreaming() {
streamingProcess.kill();
streamingProcess.waitForFinished();
}
QString CodecTabsWidget::buildStreamingCommand(
QString inputParameters, QString inputLocation,
QVector<QString> outputPrameters, QVector<QString> outputLocations) {
QStringList list;
list << FFMPEG;
list << inputParameters;
list << "-i " << inputLocation;
for (int i = 0;
i < outputPrameters.length() && i < outputLocations.length(); i++) {
list << outputPrameters[i] << outputLocations[i];
}
QString command = list.join(" ");
qDebug() << "Produced the following encoding command:\n"
<< command.toUtf8().constData();
return command;
}
QString CodecTabsWidget::buildProbeCommand(QString location, QString params) {
QStringList list;
list << FFPROBE;
list << location;
list << params;
QString command = list.join(" ");
qDebug() << "Produced the following probe command:\n"
<< command.toUtf8().constData();
return command;
}
QString CodecTabsWidget::parametersToString(QMap<QString, QString> parameters) {
QStringList result;
for (auto key : parameters.keys()) {
result << "-" + key << parameters.value(key);
}
return result.join(" ");
}
void CodecTabsWidget::openFromFile(QString filePath) {
if (!filePath.isEmpty()) {
inputParameters = "-re";
inputLocation = "\"" + filePath + "\"";
settingsChanged();
}
}
void CodecTabsWidget::openFromCamera() {
#ifdef Q_OS_WIN
inputParameters = "-f dshow";
inputLocation = "video=\"Lenovo EasyCamera\"";
settingsChanged();
#else
inputParameters = "-f v4l2";
inputLocation = "/dev/video0";
settingsChanged();
#endif
}
void CodecTabsWidget::onTabChange() { currentTabChanged(); }
QString CodecTabsWidget::getStreamingParameters() {
if (inputLocation.isEmpty()) {
qDebug() << "Input location is missing! Not starting player.";
return "";
}
if (inputParameters.isEmpty()) {
qDebug() << "Input parameters are missing! Not starting player.";
return "";
}
QMap<QString, QString> streamingParametersMap =
codecManagers.at(ui->tabWidget->currentIndex())
->getStreamingParameters();
if (streamingParametersMap.isEmpty()) {
qDebug() << "Encoding parameters are missing! Not starting player.";
return "";
}
QString streamingParameters =
parametersToString(streamingParametersMap) + " -an";
return streamingParameters;
}
void CodecTabsWidget::startStreaming(QString streamingParameters) {
qDebug() << "Starting the encoding process...";
QString streamingCommand = buildStreamingCommand(
inputParameters, inputLocation,
{"-c:v copy -f nut -an", streamingParameters, streamingParameters,
streamingParameters},
{RAW_VIDEO_PROTOCOL + "://" + RAW_VIDEO_HOST + ":" + RAW_VIDEO_PORT,
ENCODED_VIDEO_PROTOCOL + "://" + ENCODED_VIDEO_HOST + ":" +
ENCODED_VIDEO_PORT,
VIDEO_PROBE_PROTOCOL + "://" + VIDEO_PROBE_HOST + ":" +
VIDEO_PROBE_PORT,
STREAM_PROBE_PROTOCOL + "://" + STREAM_PROBE_HOST + ":" +
STREAM_PROBE_PORT});
streamingProcess.start(streamingCommand);
}
QString CodecTabsWidget::getProbeCommand() {
qDebug() << "Starting the probe process...";
QString frameProbeCommand = buildProbeCommand(
VIDEO_PROBE_PROTOCOL + "://" + VIDEO_PROBE_HOST + ":" +
VIDEO_PROBE_PORT,
"-show_frames -show_entries frame=pict_type,width,height");
return frameProbeCommand;
}
QString CodecTabsWidget::getStreamCommand() {
QString streamProbeCommand =
buildProbeCommand(STREAM_PROBE_PROTOCOL + "://" + STREAM_PROBE_HOST +
":" + STREAM_PROBE_PORT,
"-show_streams -select_streams v:0");
return streamProbeCommand;
}
void CodecTabsWidget::setCRF(QString value) {
codecManagers.at(ui->tabWidget->currentIndex())->setCRF(value);
settingsChanged();
}
<|endoftext|> |
<commit_before>/** -*- C++ -*-
* union_dataset.cc
* Mich, 2016-09-14
* This file is part of MLDB. Copyright 2016 Datacratic. All rights reserved.
**/
#include "union_dataset.h"
#include <thread>
#include <math.h>
#include "mldb/builtin/id_hash.h"
#include "mldb/builtin/merge_hash_entries.h"
#include "mldb/types/any_impl.h"
#include "mldb/types/structure_description.h"
#include "mldb/types/vector_description.h"
using namespace std;
namespace MLDB {
/*****************************************************************************/
/* UNION DATASET CONFIG */
/*****************************************************************************/
DEFINE_STRUCTURE_DESCRIPTION(UnionDatasetConfig);
UnionDatasetConfigDescription::
UnionDatasetConfigDescription()
{
nullAccepted = true;
addField("datasets", &UnionDatasetConfig::datasets,
"Datasets to unify together");
}
static RegisterDatasetType<UnionDataset, UnionDatasetConfig>
regUnion(builtinPackage(),
"union",
"Unify together several datasets",
"datasets/UnionDataset.md.html");
std::shared_ptr<Dataset> createUnionDataset(
MldbServer * server, vector<std::shared_ptr<Dataset> > datasets)
{
return std::make_shared<UnionDataset>(server, datasets);
}
struct UnionDataset::Itl
: public MatrixView, public ColumnIndex {
Lightweight_Hash<RowHash, pair<int, RowHash> > rowIndex;
IdHashes columnIndex;
// Datasets that it was constructed with
vector<std::shared_ptr<Dataset> > datasets;
Itl(MldbServer * server, vector<std::shared_ptr<Dataset> > datasets) {
if (datasets.empty()) {
throw MLDB::Exception("Attempt to unify no datasets together");
}
this->datasets = datasets;
int indexWidth = getIndexBinaryWidth();
if (indexWidth > 31) {
throw MLDB::Exception("Too many datasets in the union");
}
for (int i = 0; i < datasets.size(); ++i) {
for (const auto & rowPath: datasets[i]->getMatrixView()->getRowPaths()) {
rowIndex[RowHash(PathElement(i) + rowPath)] =
make_pair(i, RowHash(rowPath));
}
}
auto getColumnHashes = [&] (int datasetIndex)
{
auto dataset = datasets[datasetIndex];
MergeHashEntries result;
vector<ColumnPath> cols = dataset->getMatrixView()->getColumnPaths();
std::sort(cols.begin(), cols.end());
ExcAssert(std::unique(cols.begin(), cols.end()) == cols.end());
result.reserve(cols.size());
for (auto c: cols)
result.add(c.hash(), 1ULL << datasetIndex);
return result;
};
auto initColumnBucket = [&] (int i, MergeHashEntryBucket & b)
{
auto & b2 = columnIndex.buckets[i];
b2.reserve(b.size());
for (auto & e: b) {
uint64_t h = e.hash;
uint32_t bm = e.bitmap;
b2.insert(make_pair(h, bm));
}
};
std::thread mergeColumns([&] () {
extractAndMerge(datasets.size(), getColumnHashes, initColumnBucket);
});
mergeColumns.join();
}
int getIndexBinaryWidth() const {
return ceil(log(datasets.size()) / log(2));
}
int getIdxFromRowPath(const RowPath & rowPath) const {
// Returns idx > -1 if the index is valid, -1 otherwise
if (rowPath.size() < 2) {
return -1;
}
int idx = static_cast<int>(rowPath.at(0).toIndex());
if (idx > datasets.size()) {
return -1;
}
ExcAssert(idx == -1 || idx <= datasets.size());
return idx;
}
struct UnionRowStream : public RowStream {
UnionRowStream(const UnionDataset::Itl* source) : source(source), datasetIndex(0)
{
}
virtual std::shared_ptr<RowStream> clone() const override
{
return make_shared<UnionRowStream>(source);
}
/* set where the stream should start*/
virtual void initAt(size_t start) override
{
cerr << "IUNIONROWSTREAM" << endl;
datasetIndex = 0;
size_t currentTotal = 0;
std::shared_ptr<Dataset> currentDataset = source->datasets[0];
size_t currentRowCount = currentDataset->getRowCount();
while (currentTotal + currentRowCount < start) {
currentTotal += currentRowCount;
++datasetIndex;
currentDataset = source->datasets[datasetIndex];
currentRowCount = currentDataset->getRowCount();
}
currentSubRowStream = currentDataset->getRowStream();
subRowIndex = start - currentTotal;
currentSubRowStream->initAt(subRowIndex);
subNumRow = currentRowCount;
}
virtual RowPath next() override
{
RowPath mynext = PathElement(datasetIndex) + currentSubRowStream->next();
++subRowIndex;
if (subRowIndex == subNumRow) {
++datasetIndex;
if (datasetIndex < source->datasets.size()) {
currentSubRowStream = source->datasets[datasetIndex]->getRowStream();
currentSubRowStream->initAt(0);
subRowIndex = 0;
subNumRow = source->datasets[datasetIndex]->getRowCount();
}
}
return mynext;
}
virtual const RowPath & rowName(RowPath & storage) const override
{
RowPath sub = currentSubRowStream->rowName(storage);
return storage = PathElement(datasetIndex) + sub;
}
const UnionDataset::Itl* source;
size_t datasetIndex;
size_t subRowIndex;
size_t subNumRow;
std::shared_ptr<RowStream> currentSubRowStream;
};
virtual vector<Path>
getRowPaths(ssize_t start = 0, ssize_t limit = -1) const
{
// Row names are idx.rowPath where idx is the index of the dataset
// in the union and rowPath is the original rowPath.
vector<RowPath> result;
for (int i = 0; i < datasets.size(); ++i) {
const auto & d = datasets[i];
for (const auto & name: d->getMatrixView()->getRowPaths()) {
result.emplace_back(PathElement(i) + name);
}
}
return result;
}
virtual vector<RowHash>
getRowHashes(ssize_t start = 0, ssize_t limit = -1) const
{
std::vector<RowHash> result;
for (const auto & it: rowIndex) {
result.emplace_back(it.first);
}
return result;
}
virtual bool knownRow(const Path & rowPath) const
{
int idx = getIdxFromRowPath(rowPath);
if (idx == -1) {
return false;
}
return datasets[idx]->getMatrixView()->knownRow(rowPath.tail());
}
virtual bool knownRowHash(const RowHash & rowHash) const
{
// Unused ?
return rowIndex.find(rowHash) != rowIndex.end();
//return rowIndex.getDefault(rowHash, 0) != 0;
}
virtual RowPath getRowPath(const RowHash & rowHash) const
{
const auto & it = rowIndex.find(rowHash);
if (it == rowIndex.end()) {
throw MLDB::Exception("Row not known");
}
const auto & idxAndHash = it->second;
Path subRowName = datasets[idxAndHash.first]->getMatrixView()->getRowPath(idxAndHash.second);
return PathElement(idxAndHash.second) + subRowName;
}
// DEPRECATED
virtual MatrixNamedRow getRow(const RowPath & rowPath) const
{
throw MLDB::Exception("Unimplemented %s : %d", __FILE__, __LINE__);
}
virtual bool knownColumn(const Path & column) const
{
for (const auto & d: datasets) {
if (d->getMatrixView()->knownColumn(column)) {
return true;
}
}
return false;
}
uint32_t getColumnBitmap(ColumnHash columnHash) const
{
return columnIndex.getDefault(columnHash, 0);
}
virtual ColumnPath getColumnPath(ColumnHash columnHash) const
{
uint32_t bitmap = getColumnBitmap(columnHash);
if (bitmap == 0)
throw MLDB::Exception("Column not found in union dataset");
int bit = ML::lowest_bit(bitmap, -1);
return datasets[bit]->getMatrixView()->getColumnPath(columnHash);
}
/** Return a list of all columns. */
virtual vector<ColumnPath> getColumnPaths() const
{
std::set<ColumnPath> preResult;
for (const auto & d: datasets) {
auto columnPaths = d->getColumnPaths();
preResult.insert(columnPaths.begin(), columnPaths.end());
}
return vector<ColumnPath>(preResult.begin(), preResult.end());
}
virtual MatrixColumn getColumn(const ColumnPath & columnPath) const
{
MatrixColumn result;
result.columnName = columnPath;
result.columnHash = columnPath;
vector<std::tuple<RowPath, CellValue> > res;
for (int i = 0; i < datasets.size(); ++i) {
const auto & d = datasets[i];
const auto & subCol = d->getColumnIndex()->getColumn(columnPath);
for (const auto & curr: subCol.rows) {
result.rows.emplace_back(PathElement(i) + std::get<0>(curr),
std::get<1>(curr),
std::get<2>(curr));
}
}
return result;
}
/** Return the value of the column for all rows and timestamps. */
virtual vector<std::tuple<RowPath, CellValue> >
getColumnValues(const ColumnPath & columnPath,
const std::function<bool (const CellValue &)> & filter) const
{
vector<std::tuple<RowPath, CellValue> > res;
for (int i = 0; i < datasets.size(); ++i) {
const auto & d = datasets[i];
for (const auto curr: d->getColumnIndex()->getColumnValues(columnPath)) {
res.emplace_back(
PathElement(i) + std::get<0>(curr).toUtf8String().rawString(),
std::get<1>(curr));
}
}
return res;
}
virtual size_t getRowCount() const
{
size_t count = 0;
for (const auto & d: datasets) {
count += d->getRowCount();
}
return count;
}
virtual size_t getColumnCount() const
{
return columnIndex.size();
}
std::pair<Date, Date> getTimestampRange() const
{
std::pair<Date, Date> result(Date::notADate(), Date::notADate());
bool first = true;
for (auto & d: datasets) {
std::pair<Date, Date> dsRange = d->getTimestampRange();
if (!dsRange.first.isADate() || !dsRange.second.isADate()) {
continue;
}
if (first) {
result = dsRange;
first = false;
}
else {
result.first.setMin(dsRange.first);
result.second.setMax(dsRange.second);
}
}
return result;
}
};
UnionDataset::
UnionDataset(MldbServer * owner,
PolyConfig config,
const std::function<bool (const Json::Value &)> & onProgress)
: Dataset(owner)
{
auto unionConfig = config.params.convert<UnionDatasetConfig>();
vector<std::shared_ptr<Dataset> > datasets;
for (auto & d: unionConfig.datasets) {
datasets.emplace_back(obtainDataset(owner, d, onProgress));
}
itl.reset(new Itl(server, datasets));
}
UnionDataset::
UnionDataset(MldbServer * owner,
vector<std::shared_ptr<Dataset> > datasetsToMerge)
: Dataset(owner)
{
itl.reset(new Itl(server, datasetsToMerge));
}
UnionDataset::
~UnionDataset()
{
}
Any
UnionDataset::
getStatus() const
{
vector<Any> result;
for (auto & d: itl->datasets) {
result.emplace_back(d->getStatus());
}
return result;
}
std::pair<Date, Date>
UnionDataset::
getTimestampRange() const
{
return itl->getTimestampRange();
}
std::shared_ptr<MatrixView>
UnionDataset::
getMatrixView() const
{
return itl;
}
std::shared_ptr<ColumnIndex>
UnionDataset::
getColumnIndex() const
{
return itl;
}
std::shared_ptr<RowStream>
UnionDataset::
getRowStream() const
{
return make_shared<UnionDataset::Itl::UnionRowStream>(itl.get());
}
ExpressionValue
UnionDataset::
getRowExpr(const RowPath & rowPath) const
{
int idx = itl->getIdxFromRowPath(rowPath);
if (idx == -1) {
return ExpressionValue{};
}
return itl->datasets[idx]->getRowExpr(
Path(rowPath.begin() + 1, rowPath.end()));
}
} // namespace MLDB
<commit_msg>remove debug display submitted by error<commit_after>/** -*- C++ -*-
* union_dataset.cc
* Mich, 2016-09-14
* This file is part of MLDB. Copyright 2016 Datacratic. All rights reserved.
**/
#include "union_dataset.h"
#include <thread>
#include <math.h>
#include "mldb/builtin/id_hash.h"
#include "mldb/builtin/merge_hash_entries.h"
#include "mldb/types/any_impl.h"
#include "mldb/types/structure_description.h"
#include "mldb/types/vector_description.h"
using namespace std;
namespace MLDB {
/*****************************************************************************/
/* UNION DATASET CONFIG */
/*****************************************************************************/
DEFINE_STRUCTURE_DESCRIPTION(UnionDatasetConfig);
UnionDatasetConfigDescription::
UnionDatasetConfigDescription()
{
nullAccepted = true;
addField("datasets", &UnionDatasetConfig::datasets,
"Datasets to unify together");
}
static RegisterDatasetType<UnionDataset, UnionDatasetConfig>
regUnion(builtinPackage(),
"union",
"Unify together several datasets",
"datasets/UnionDataset.md.html");
std::shared_ptr<Dataset> createUnionDataset(
MldbServer * server, vector<std::shared_ptr<Dataset> > datasets)
{
return std::make_shared<UnionDataset>(server, datasets);
}
struct UnionDataset::Itl
: public MatrixView, public ColumnIndex {
Lightweight_Hash<RowHash, pair<int, RowHash> > rowIndex;
IdHashes columnIndex;
// Datasets that it was constructed with
vector<std::shared_ptr<Dataset> > datasets;
Itl(MldbServer * server, vector<std::shared_ptr<Dataset> > datasets) {
if (datasets.empty()) {
throw MLDB::Exception("Attempt to unify no datasets together");
}
this->datasets = datasets;
int indexWidth = getIndexBinaryWidth();
if (indexWidth > 31) {
throw MLDB::Exception("Too many datasets in the union");
}
for (int i = 0; i < datasets.size(); ++i) {
for (const auto & rowPath: datasets[i]->getMatrixView()->getRowPaths()) {
rowIndex[RowHash(PathElement(i) + rowPath)] =
make_pair(i, RowHash(rowPath));
}
}
auto getColumnHashes = [&] (int datasetIndex)
{
auto dataset = datasets[datasetIndex];
MergeHashEntries result;
vector<ColumnPath> cols = dataset->getMatrixView()->getColumnPaths();
std::sort(cols.begin(), cols.end());
ExcAssert(std::unique(cols.begin(), cols.end()) == cols.end());
result.reserve(cols.size());
for (auto c: cols)
result.add(c.hash(), 1ULL << datasetIndex);
return result;
};
auto initColumnBucket = [&] (int i, MergeHashEntryBucket & b)
{
auto & b2 = columnIndex.buckets[i];
b2.reserve(b.size());
for (auto & e: b) {
uint64_t h = e.hash;
uint32_t bm = e.bitmap;
b2.insert(make_pair(h, bm));
}
};
std::thread mergeColumns([&] () {
extractAndMerge(datasets.size(), getColumnHashes, initColumnBucket);
});
mergeColumns.join();
}
int getIndexBinaryWidth() const {
return ceil(log(datasets.size()) / log(2));
}
int getIdxFromRowPath(const RowPath & rowPath) const {
// Returns idx > -1 if the index is valid, -1 otherwise
if (rowPath.size() < 2) {
return -1;
}
int idx = static_cast<int>(rowPath.at(0).toIndex());
if (idx > datasets.size()) {
return -1;
}
ExcAssert(idx == -1 || idx <= datasets.size());
return idx;
}
struct UnionRowStream : public RowStream {
UnionRowStream(const UnionDataset::Itl* source) : source(source), datasetIndex(0)
{
}
virtual std::shared_ptr<RowStream> clone() const override
{
return make_shared<UnionRowStream>(source);
}
/* set where the stream should start*/
virtual void initAt(size_t start) override
{
datasetIndex = 0;
size_t currentTotal = 0;
std::shared_ptr<Dataset> currentDataset = source->datasets[0];
size_t currentRowCount = currentDataset->getRowCount();
while (currentTotal + currentRowCount < start) {
currentTotal += currentRowCount;
++datasetIndex;
currentDataset = source->datasets[datasetIndex];
currentRowCount = currentDataset->getRowCount();
}
currentSubRowStream = currentDataset->getRowStream();
subRowIndex = start - currentTotal;
currentSubRowStream->initAt(subRowIndex);
subNumRow = currentRowCount;
}
virtual RowPath next() override
{
RowPath mynext = PathElement(datasetIndex) + currentSubRowStream->next();
++subRowIndex;
if (subRowIndex == subNumRow) {
++datasetIndex;
if (datasetIndex < source->datasets.size()) {
currentSubRowStream = source->datasets[datasetIndex]->getRowStream();
currentSubRowStream->initAt(0);
subRowIndex = 0;
subNumRow = source->datasets[datasetIndex]->getRowCount();
}
}
return mynext;
}
virtual const RowPath & rowName(RowPath & storage) const override
{
RowPath sub = currentSubRowStream->rowName(storage);
return storage = PathElement(datasetIndex) + sub;
}
const UnionDataset::Itl* source;
size_t datasetIndex;
size_t subRowIndex;
size_t subNumRow;
std::shared_ptr<RowStream> currentSubRowStream;
};
virtual vector<Path>
getRowPaths(ssize_t start = 0, ssize_t limit = -1) const
{
// Row names are idx.rowPath where idx is the index of the dataset
// in the union and rowPath is the original rowPath.
vector<RowPath> result;
for (int i = 0; i < datasets.size(); ++i) {
const auto & d = datasets[i];
for (const auto & name: d->getMatrixView()->getRowPaths()) {
result.emplace_back(PathElement(i) + name);
}
}
return result;
}
virtual vector<RowHash>
getRowHashes(ssize_t start = 0, ssize_t limit = -1) const
{
std::vector<RowHash> result;
for (const auto & it: rowIndex) {
result.emplace_back(it.first);
}
return result;
}
virtual bool knownRow(const Path & rowPath) const
{
int idx = getIdxFromRowPath(rowPath);
if (idx == -1) {
return false;
}
return datasets[idx]->getMatrixView()->knownRow(rowPath.tail());
}
virtual bool knownRowHash(const RowHash & rowHash) const
{
// Unused ?
return rowIndex.find(rowHash) != rowIndex.end();
//return rowIndex.getDefault(rowHash, 0) != 0;
}
virtual RowPath getRowPath(const RowHash & rowHash) const
{
const auto & it = rowIndex.find(rowHash);
if (it == rowIndex.end()) {
throw MLDB::Exception("Row not known");
}
const auto & idxAndHash = it->second;
Path subRowName = datasets[idxAndHash.first]->getMatrixView()->getRowPath(idxAndHash.second);
return PathElement(idxAndHash.second) + subRowName;
}
// DEPRECATED
virtual MatrixNamedRow getRow(const RowPath & rowPath) const
{
throw MLDB::Exception("Unimplemented %s : %d", __FILE__, __LINE__);
}
virtual bool knownColumn(const Path & column) const
{
for (const auto & d: datasets) {
if (d->getMatrixView()->knownColumn(column)) {
return true;
}
}
return false;
}
uint32_t getColumnBitmap(ColumnHash columnHash) const
{
return columnIndex.getDefault(columnHash, 0);
}
virtual ColumnPath getColumnPath(ColumnHash columnHash) const
{
uint32_t bitmap = getColumnBitmap(columnHash);
if (bitmap == 0)
throw MLDB::Exception("Column not found in union dataset");
int bit = ML::lowest_bit(bitmap, -1);
return datasets[bit]->getMatrixView()->getColumnPath(columnHash);
}
/** Return a list of all columns. */
virtual vector<ColumnPath> getColumnPaths() const
{
std::set<ColumnPath> preResult;
for (const auto & d: datasets) {
auto columnPaths = d->getColumnPaths();
preResult.insert(columnPaths.begin(), columnPaths.end());
}
return vector<ColumnPath>(preResult.begin(), preResult.end());
}
virtual MatrixColumn getColumn(const ColumnPath & columnPath) const
{
MatrixColumn result;
result.columnName = columnPath;
result.columnHash = columnPath;
vector<std::tuple<RowPath, CellValue> > res;
for (int i = 0; i < datasets.size(); ++i) {
const auto & d = datasets[i];
const auto & subCol = d->getColumnIndex()->getColumn(columnPath);
for (const auto & curr: subCol.rows) {
result.rows.emplace_back(PathElement(i) + std::get<0>(curr),
std::get<1>(curr),
std::get<2>(curr));
}
}
return result;
}
/** Return the value of the column for all rows and timestamps. */
virtual vector<std::tuple<RowPath, CellValue> >
getColumnValues(const ColumnPath & columnPath,
const std::function<bool (const CellValue &)> & filter) const
{
vector<std::tuple<RowPath, CellValue> > res;
for (int i = 0; i < datasets.size(); ++i) {
const auto & d = datasets[i];
for (const auto curr: d->getColumnIndex()->getColumnValues(columnPath)) {
res.emplace_back(
PathElement(i) + std::get<0>(curr).toUtf8String().rawString(),
std::get<1>(curr));
}
}
return res;
}
virtual size_t getRowCount() const
{
size_t count = 0;
for (const auto & d: datasets) {
count += d->getRowCount();
}
return count;
}
virtual size_t getColumnCount() const
{
return columnIndex.size();
}
std::pair<Date, Date> getTimestampRange() const
{
std::pair<Date, Date> result(Date::notADate(), Date::notADate());
bool first = true;
for (auto & d: datasets) {
std::pair<Date, Date> dsRange = d->getTimestampRange();
if (!dsRange.first.isADate() || !dsRange.second.isADate()) {
continue;
}
if (first) {
result = dsRange;
first = false;
}
else {
result.first.setMin(dsRange.first);
result.second.setMax(dsRange.second);
}
}
return result;
}
};
UnionDataset::
UnionDataset(MldbServer * owner,
PolyConfig config,
const std::function<bool (const Json::Value &)> & onProgress)
: Dataset(owner)
{
auto unionConfig = config.params.convert<UnionDatasetConfig>();
vector<std::shared_ptr<Dataset> > datasets;
for (auto & d: unionConfig.datasets) {
datasets.emplace_back(obtainDataset(owner, d, onProgress));
}
itl.reset(new Itl(server, datasets));
}
UnionDataset::
UnionDataset(MldbServer * owner,
vector<std::shared_ptr<Dataset> > datasetsToMerge)
: Dataset(owner)
{
itl.reset(new Itl(server, datasetsToMerge));
}
UnionDataset::
~UnionDataset()
{
}
Any
UnionDataset::
getStatus() const
{
vector<Any> result;
for (auto & d: itl->datasets) {
result.emplace_back(d->getStatus());
}
return result;
}
std::pair<Date, Date>
UnionDataset::
getTimestampRange() const
{
return itl->getTimestampRange();
}
std::shared_ptr<MatrixView>
UnionDataset::
getMatrixView() const
{
return itl;
}
std::shared_ptr<ColumnIndex>
UnionDataset::
getColumnIndex() const
{
return itl;
}
std::shared_ptr<RowStream>
UnionDataset::
getRowStream() const
{
return make_shared<UnionDataset::Itl::UnionRowStream>(itl.get());
}
ExpressionValue
UnionDataset::
getRowExpr(const RowPath & rowPath) const
{
int idx = itl->getIdxFromRowPath(rowPath);
if (idx == -1) {
return ExpressionValue{};
}
return itl->datasets[idx]->getRowExpr(
Path(rowPath.begin() + 1, rowPath.end()));
}
} // namespace MLDB
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_FUN_IDENTITY_FREE_HPP
#define STAN_MATH_PRIM_FUN_IDENTITY_FREE_HPP
#include <stan/math/prim/meta.hpp>
namespace stan {
namespace math {
/**
* Returns the result of applying the inverse of the identity
* constraint transform to the input. This promotes the input to the least upper
* bound of the input types.
*
*
* @tparam T type of value to promote
* @tparam Types Other types.
* @param[in] y value to promote
* @return value
*/
template <typename T, typename... Types,
require_all_not_var_matrix_t<T, Types...>* = nullptr>
inline auto identity_free(T&& x, Types&&... /* args */) {
return promote_scalar_t<return_type_t<T, Types...>, T>(x);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>fix identity_constrain docs<commit_after>#ifndef STAN_MATH_PRIM_FUN_IDENTITY_FREE_HPP
#define STAN_MATH_PRIM_FUN_IDENTITY_FREE_HPP
#include <stan/math/prim/meta.hpp>
namespace stan {
namespace math {
/**
* Returns the result of applying the inverse of the identity
* constraint transform to the input. This promotes the input to the least upper
* bound of the input types.
*
*
* @tparam T type of value to promote
* @tparam Types Other types.
* @param[in] x value to promote
* @return value
*/
template <typename T, typename... Types,
require_all_not_var_matrix_t<T, Types...>* = nullptr>
inline auto identity_free(T&& x, Types&&... /* args */) {
return promote_scalar_t<return_type_t<T, Types...>, T>(x);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>// #include "condor_config.h"
#include "classad_package.h"
#include <ctype.h>
enum Commands {
_NO_CMD_,
CLEAR_TOPLEVEL,
DEEP_INSERT_ATTRIBUTE,
DEEP_REMOVE_ATTRIBUTE,
EVALUATE,
EVALUATE_WITH_SIGNIFICANCE,
FLATTEN,
HELP,
INSERT_ATTRIBUTE,
NEW_TOPLEVEL,
OUTPUT_TOPLEVEL,
QUIT,
REMOVE_ATTRIBUTE,
SET_CONDOR_TOPLEVEL,
_LAST_COMMAND_
};
char CommandWords[][32] = {
"",
"clear_toplevel",
"deep_insert",
"deep_remove",
"evaluate",
"sigeval",
"flatten",
"help",
"insert_attribute",
"new_toplevel",
"output_toplevel",
"quit",
"remove_attribute",
"set_condor_toplevel",
""
};
void help( void );
int findCommand( char* );
int
main( void )
{
ClassAd *ad, *adptr;
char cmdString[128], buffer1[2048], buffer2[2048];
// char *tmp;
ExprTree *expr=NULL, *fexpr=NULL;
int command;
Value value;
Source src;
Sink snk;
snk.setSink( stdout );
// config( 0 );
ad = new ClassAd();
printf( "'h' for help\n# " );
while( 1 ) {
scanf( "%s", cmdString );
command = findCommand( cmdString );
switch( command ) {
case CLEAR_TOPLEVEL:
ad->clear();
fgets( buffer1, 2048, stdin );
break;
case DEEP_INSERT_ATTRIBUTE:
if( scanf( "%s", buffer1 ) != 1 ) { // expr
printf( "Error reading primary expression\n" );
break;
}
src.setSource( buffer1, 2048 );
if( !src.parseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", buffer1 );
break;
}
if( scanf( "%s", buffer1 ) != 1 ) {
printf( "Error reading attribute name\n" );
break;
}
fgets( buffer2, 2048, stdin );
src.setSource( buffer2, 2048 );
if( !src.parseExpression( fexpr, true ) ) {
printf( "Error parsing expression: %s\n", buffer2 );
break;
}
expr->setParentScope( ad );
ad->evaluateExpr( expr, value );
if( !value.isClassAdValue( adptr ) ) {
printf( "Error: Primary expression was not a classad\n" );
delete expr;
expr = NULL;
break;
}
if( !adptr->insert( buffer1, fexpr ) ) {
printf( "Error inserting expression\n" );
}
delete expr;
adptr = NULL;
expr = NULL;
break;
case DEEP_REMOVE_ATTRIBUTE:
if( scanf( "%s", buffer1 ) != 1 ) { // expr
printf( "Error reading primary expression\n" );
break;
}
src.setSource( buffer1, 2048 );
if( !src.parseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", buffer1 );
break;
}
fgets( buffer2, 2048, stdin ); // name
expr->setParentScope( ad );
ad->evaluateExpr( expr, value );
if( !value.isClassAdValue( adptr ) ) {
printf( "Error: Primary expression was not a classad\n" );
delete expr;
expr = NULL;
break;
}
if( !adptr->remove( buffer2 ) ) {
printf( "Warning: Attribute %s not found\n", buffer2 );
}
delete expr;
expr = NULL;
break;
case EVALUATE:
fgets( buffer1, 2048, stdin );
src.setSource( buffer1, 2048 );
if( !src.parseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", buffer1 );
break;
}
expr->setParentScope( ad );
ad->evaluateExpr( expr, value );
value.toSink( snk );
snk.flushSink();
delete expr;
expr = NULL;
break;
case EVALUATE_WITH_SIGNIFICANCE:
fgets( buffer1, 2048, stdin );
src.setSource( buffer1, 2048 );
if( !src.parseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", buffer1 );
break;
}
expr->setParentScope( ad );
ad->evaluateExpr( expr, value, fexpr );
value.toSink( snk );
snk.flushSink();
printf( "\n" );
fexpr->toSink( snk );
snk.flushSink();
delete expr;
expr = NULL;
delete fexpr;
fexpr = NULL;
break;
case FLATTEN:
fgets( buffer1, 2048, stdin );
src.setSource( buffer1, 2048 );
if( !src.parseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", buffer1 );
break;
}
expr->setParentScope( ad );
if( ad->flatten( expr, value, fexpr ) ) {
if( fexpr ) {
fexpr->toSink( snk );
delete fexpr;
fexpr = NULL;
} else {
value.toSink( snk );
}
snk.flushSink();
} else {
printf( "Error flattening expression\n" );
}
break;
case HELP:
help();
fgets( buffer1, 2048, stdin );
break;
case INSERT_ATTRIBUTE:
if( scanf( "%s", buffer1 ) != 1 ) {
printf( "Error reading attribute name\n" );
break;
}
fgets( buffer2, 2048, stdin );
src.setSource( buffer2, 2048 );
if( !src.parseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", buffer2 );
break;
}
if( !ad->insert( buffer1, expr ) ) {
printf( "Error inserting expression\n" );
}
expr = NULL;
break;
case NEW_TOPLEVEL:
ad->clear();
fgets( buffer1, 2048, stdin );
src.setSource( buffer1, 2048 );
if( !src.parseClassAd( ad, true ) ) {
printf( "Error parsing classad\n" );
}
break;
case OUTPUT_TOPLEVEL:
ad->toSink( snk );
snk.flushSink();
fgets( buffer1, 2048, stdin );
break;
/*
case 'p':
fgets( buffer1, 2048, stdin );
if( !( tmp = param( buffer1 ) ) ) {
printf( "Did not find %s in config file\n", buffer1 );
break;
}
src.setSource( tmp, strlen( tmp ) );
if( !src.parseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", tmp );
free( tmp );
break;
}
if( !ad->insert( buffer1, expr ) ) {
printf( "Error inserting: %s = %s\n", buffer1, tmp );
}
delete tmp;
expr = NULL;
break;
*/
case QUIT:
printf( "Done\n\n" );
exit( 0 );
case REMOVE_ATTRIBUTE:
if( scanf( "%s", buffer1 ) != 1 ) {
printf( "Error reading attribute name\n" );
break;
}
if( !ad->remove( buffer1 ) ) {
printf( "Error removing attribute %s\n", buffer1 );
}
fgets( buffer1, 2048, stdin );
break;
case SET_CONDOR_TOPLEVEL:
delete ad;
ad = CondorClassAd::makeCondorClassAd( NULL, NULL );
fgets( buffer1, 2048, stdin );
break;
default:
fflush( stdin );
}
printf( "\n# " );
}
exit( 0 );
}
// Print help information for the hapless user
void
help( void )
{
printf( "\nCommands are:\n" );
printf( "clear_toplevel\n\tClear toplevel ad\n\n" );
printf( "deep_insert <expr1> <name> <expr2>\n\tInsert (<name>,<expr2>) into"
" classad <expr1>. (No inter-token spaces\n\tallowed in <expr1>.)\n\n");
printf( "deep_remove <expr> <name>\n\tRemove <name> from classad "
"<expr>. (No inter-token spaces allowed\n\tin <expr>.\n\n" );
printf( "evaluate <expr>\n\tEvaluate <expr> (in toplevel ad)\n\n" );
printf( "sigeval <expr>\n\tEvaluate <expr> (in toplevel) and "
"identify significant\n\tsubexpressions\n\n" );
printf( "flatten <expr>\n\tFlatten <expr> (in toplevel ad)\n\n" );
printf( "help\n\tHelp --- this screen\n\n" );
printf( "insert_attribute <name> <expr>\n\tInsert attribute (<name>,<expr>)"
"into toplevel\n\n" );
printf( "new_toplevel <classad>\n\tEnter new toplevel ad\n\n" );
printf( "output_toplevel\n\tOutput toplevel ad\n\n" );
/*
printf( "p <name>\t- (P)aram from config file and insert in toplevel\n" );
*/
printf( "quit\n\tQuit\n\n" );
printf( "remove_attribute <name>\n\tRemove attribute <name> from "
"toplevel\n\n" );
printf( "set_condor_toplevel\n\tSetup a toplevel ad for matching\n\n" );
printf( "\nA command may be specified by an unambiguous prefix\n\n" );
}
int
findCommand( char *cmdStr )
{
int cmd = 0, len = strlen( cmdStr );
for( int i = 0 ; i < len ; i++ ) {
cmdStr[i] = tolower( cmdStr[i] );
}
for( int i = _NO_CMD_+1 ; i < _LAST_COMMAND_ ; i++ ) {
if( strncmp( cmdStr, CommandWords[i], len ) == 0 ) {
if( cmd == 0 ) {
cmd = i;
} else if( cmd > 0 ) {
cmd = -1;
}
}
}
if( cmd > 0 ) return cmd;
if( cmd == 0 ) {
printf( "\nUnknown command %s\n", cmdStr );
return -1;
}
printf( "\nAmbiguous command %s; matches\n", cmdStr );
for( int i = _NO_CMD_+1 ; i < _LAST_COMMAND_ ; i++ ) {
if( strncmp( cmdStr, CommandWords[i], len ) == 0 ) {
printf( "\t%s\n", CommandWords[i] );
}
}
return -1;
}
<commit_msg>+ Changed names to calls of classad functions (start with uppercase) + Params from config file<commit_after>#include "condor_config.h"
#include "classad_package.h"
#include <ctype.h>
enum Commands {
_NO_CMD_,
CLEAR_TOPLEVEL,
DEEP_INSERT_ATTRIBUTE,
DEEP_DELETE_ATTRIBUTE,
EVALUATE,
EVALUATE_WITH_SIGNIFICANCE,
FLATTEN,
HELP,
INSERT_ATTRIBUTE,
NEW_TOPLEVEL,
OUTPUT_TOPLEVEL,
PARAM,
QUIT,
REMOVE_ATTRIBUTE,
SET_MATCH_TOPLEVEL,
_LAST_COMMAND_
};
char CommandWords[][32] = {
"",
"clear_toplevel",
"deep_insert",
"deep_delete",
"evaluate",
"sigeval",
"flatten",
"help",
"insert_attribute",
"new_toplevel",
"output_toplevel",
"param",
"quit",
"delete_attribute",
"set_match_toplevel",
""
};
void help( void );
int findCommand( char* );
int
main( void )
{
ClassAd *ad, *adptr;
char cmdString[128], buffer1[2048], buffer2[2048], buffer3[2048];
char *paramStr, *attrName;
ExprTree *expr=NULL, *fexpr=NULL;
int command;
Value value;
Source src;
Sink snk;
FormatOptions pp;
// set formatter options
pp.SetClassAdIndentation( true , 4 );
pp.SetListIndentation( true , 4 );
pp.SetMinimalParentheses( true );
snk.SetSink( stdout );
snk.SetFormatOptions( &pp );
config( 0 );
ad = new ClassAd();
printf( "'h' for help\n# " );
while( 1 ) {
scanf( "%s", cmdString );
command = findCommand( cmdString );
switch( command ) {
case CLEAR_TOPLEVEL:
ad->Clear();
fgets( buffer1, 2048, stdin );
break;
case DEEP_INSERT_ATTRIBUTE:
if( scanf( "%s", buffer1 ) != 1 ) { // expr
printf( "Error reading primary expression\n" );
break;
}
src.SetSource( buffer1, 2048 );
if( !src.ParseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", buffer1 );
break;
}
if( scanf( "%s", buffer2 ) != 1 ) {
printf( "Error reading attribute name\n" );
break;
}
fgets( buffer3, 2048, stdin );
src.SetSource( buffer3, 2048 );
if( !src.ParseExpression( fexpr, true ) ) {
printf( "Error parsing expression: %s\n", buffer3 );
break;
}
expr->SetParentScope( ad );
if( !ad->EvaluateExpr( expr, value ) ) {
printf( "Error evaluating expression: %s\n", buffer1 );
delete expr;
delete fexpr;
expr = NULL;
fexpr = NULL;
break;
}
if( !value.IsClassAdValue( adptr ) ) {
printf( "Error: Primary expression was not a classad\n" );
delete expr;
expr = NULL;
delete fexpr;
fexpr = NULL;
break;
}
if( !adptr->Insert( buffer2, fexpr ) ) {
printf( "Error Inserting expression: %s\n", buffer3 );
delete fexpr;
delete expr;
fexpr = NULL;
expr = NULL;
}
delete expr;
adptr = NULL;
expr = NULL;
break;
case DEEP_DELETE_ATTRIBUTE:
if( scanf( "%s", buffer1 ) != 1 ) { // expr
printf( "Error reading primary expression\n" );
break;
}
src.SetSource( buffer1, 2048 );
if( !src.ParseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", buffer1 );
break;
}
fgets( buffer2, 2048, stdin ); // name
expr->SetParentScope( ad );
if( !ad->EvaluateExpr( expr, value ) ) {
printf( "Error evaluating expression: %s\n", buffer1 );
delete expr;
break;
}
if( !value.IsClassAdValue( adptr ) ) {
printf( "Error: Primary expression was not a classad\n" );
delete expr;
expr = NULL;
break;
}
if( !adptr->Remove( buffer2 ) ) {
printf( "Warning: Attribute %s not found\n", buffer2 );
}
delete expr;
expr = NULL;
break;
case EVALUATE:
fgets( buffer1, 2048, stdin );
src.SetSource( buffer1, 2048 );
if( !src.ParseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", buffer1 );
break;
}
expr->SetParentScope( ad );
if( !ad->EvaluateExpr( expr, value ) ) {
printf( "Error evaluating expression: %s\n", buffer1 );
delete expr;
expr = NULL;
break;
}
if( !value.ToSink( snk ) ) {
printf( "Error writing evaluation result to sink\n" );
}
snk.FlushSink();
delete expr;
expr = NULL;
break;
case EVALUATE_WITH_SIGNIFICANCE:
fgets( buffer1, 2048, stdin );
src.SetSource( buffer1, 2048 );
if( !src.ParseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", buffer1 );
break;
}
expr->SetParentScope( ad );
if( !ad->EvaluateExpr( expr, value, fexpr ) ) {
printf( "Error evaluating expression: %s\n", buffer1 );
delete expr;
delete fexpr;
expr = NULL;
fexpr = NULL;
break;
}
if( !value.ToSink( snk ) ) {
printf( "Error writing result to sink\n" );
}
snk.FlushSink();
printf( "\n" );
if( !fexpr->ToSink( snk ) ) {
printf( "Error writing expression to sink\n" );
}
snk.FlushSink();
delete expr;
expr = NULL;
delete fexpr;
fexpr = NULL;
break;
case FLATTEN:
fgets( buffer1, 2048, stdin );
src.SetSource( buffer1, 2048 );
if( !src.ParseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", buffer1 );
break;
}
expr->SetParentScope( ad );
if( ad->Flatten( expr, value, fexpr ) ) {
if( fexpr ) {
if( !fexpr->ToSink( snk ) ) {
printf( "Error writing flattened expression to "
"sink\n" );
}
delete fexpr;
fexpr = NULL;
} else {
if( !value.ToSink( snk ) ) {
printf( "Error writing value to sink\n" );
}
}
snk.FlushSink();
} else {
printf( "Error flattening expression\n" );
}
delete expr;
expr = NULL;
break;
case HELP:
help();
fgets( buffer1, 2048, stdin );
break;
case INSERT_ATTRIBUTE:
if( scanf( "%s", buffer1 ) != 1 ) {
printf( "Error reading attribute name\n" );
break;
}
fgets( buffer2, 2048, stdin );
src.SetSource( buffer2, 2048 );
if( !src.ParseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", buffer2 );
break;
}
if( !ad->Insert( buffer1, expr ) ) {
printf( "Error Inserting expression\n" );
}
expr = NULL;
break;
case NEW_TOPLEVEL:
ad->Clear();
fgets( buffer1, 2048, stdin );
src.SetSource( buffer1, 2048 );
if( !src.ParseClassAd( ad, true ) ) {
printf( "Error parsing classad\n" );
}
break;
case OUTPUT_TOPLEVEL:
if( !ad->ToSink( snk ) ) {
printf( "Error writing to sink\n" );
}
snk.FlushSink();
fgets( buffer1, 2048, stdin );
break;
case PARAM:
fgets( buffer1, 2048, stdin );
attrName = strtok( buffer1, " \t\n" );
if( !( paramStr = param( attrName ) ) ) {
printf( "Did not find %s in config file\n", buffer1 );
break;
}
src.SetSource( paramStr, strlen( paramStr ) );
if( !src.ParseExpression( expr, true ) ) {
printf( "Error parsing expression: %s\n", paramStr );
free( paramStr );
break;
}
if( !ad->Insert( buffer1, expr ) ) {
printf( "Error Inserting: %s = %s\n", buffer1, paramStr );
}
free( paramStr );
expr = NULL;
break;
case QUIT:
printf( "Done\n\n" );
exit( 0 );
case REMOVE_ATTRIBUTE:
if( scanf( "%s", buffer1 ) != 1 ) {
printf( "Error reading attribute name\n" );
break;
}
if( !ad->Remove( buffer1 ) ) {
printf( "Error removing attribute %s\n", buffer1 );
}
fgets( buffer1, 2048, stdin );
break;
case SET_MATCH_TOPLEVEL:
delete ad;
if( !( ad = MatchClassAd::MakeMatchClassAd( NULL, NULL ) ) ){
printf( "Error making classad\n" );
}
fgets( buffer1, 2048, stdin );
break;
default:
fflush( stdin );
}
printf( "\n# " );
}
exit( 0 );
}
// Print help information for the hapless user
void
help( void )
{
printf( "\nCommands are:\n" );
printf( "clear_toplevel\n\tClear toplevel ad\n\n" );
printf( "deep_insert <expr1> <name> <expr2>\n\tInsert (<name>,<expr2>) into"
" classad <expr1>. (No inter-token spaces\n\tallowed in <expr1>.)\n\n");
printf( "deep_delete <expr> <name>\n\tDelete <name> from classad "
"<expr>. (No inter-token spaces allowed\n\tin <expr>.\n\n" );
printf( "evaluate <expr>\n\tEvaluate <expr> (in toplevel ad)\n\n" );
printf( "sigeval <expr>\n\tEvaluate <expr> (in toplevel) and "
"identify significant\n\tsubexpressions\n\n" );
printf( "flatten <expr>\n\tFlatten <expr> (in toplevel ad)\n\n" );
printf( "help\n\tHelp --- this screen\n\n" );
printf( "insert_attribute <name> <expr>\n\tInsert attribute (<name>,<expr>)"
"into toplevel\n\n" );
printf( "new_toplevel <classad>\n\tEnter new toplevel ad\n\n" );
printf( "output_toplevel\n\tOutput toplevel ad\n\n" );
printf("param <name>\n\tParam from config file and insert in toplevel\n\n");
printf( "quit\n\tQuit\n\n" );
printf( "delete_attribute <name>\n\tDelete attribute <name> from "
"toplevel\n\n" );
printf( "set_condor_toplevel\n\tSetup a toplevel ad for matching\n\n" );
printf( "\nA command may be specified by an unambiguous prefix\n\n" );
}
int
findCommand( char *cmdStr )
{
int cmd = 0, len = strlen( cmdStr );
for( int i = 0 ; i < len ; i++ ) {
cmdStr[i] = tolower( cmdStr[i] );
}
for( int i = _NO_CMD_+1 ; i < _LAST_COMMAND_ ; i++ ) {
if( strncmp( cmdStr, CommandWords[i], len ) == 0 ) {
if( cmd == 0 ) {
cmd = i;
} else if( cmd > 0 ) {
cmd = -1;
}
}
}
if( cmd > 0 ) return cmd;
if( cmd == 0 ) {
printf( "\nUnknown command %s\n", cmdStr );
return -1;
}
printf( "\nAmbiguous command %s; matches\n", cmdStr );
for( int i = _NO_CMD_+1 ; i < _LAST_COMMAND_ ; i++ ) {
if( strncmp( cmdStr, CommandWords[i], len ) == 0 ) {
printf( "\t%s\n", CommandWords[i] );
}
}
return -1;
}
<|endoftext|> |
<commit_before>#include "util.h"
#include <iostream>
#include <iomanip>
using namespace std;
void
print_stock_table(mysqlpp::Query& query)
{
query.reset();
query << "select * from stock";
// You can write to the query object like you would any other ostrem
mysqlpp::Result res = query.store();
// Query::store() executes the query and returns the results
cout << "Query: " << query.preview() << endl;
// Query::preview() simply returns a string with the current query
// string in it.
cout << "Records Found: " << res.size() << endl << endl;
mysqlpp::Row row;
cout.setf(ios::left);
cout << setw(20) << "Item"
<< setw(9) << "Num"
<< setw(9) << "Weight"
<< setw(9) << "Price" << "Date" << endl << endl;
mysqlpp::Result::iterator i;
// The Result class has a read-only Random Access Iterator
for (i = res.begin(); i != res.end(); i++) {
row = *i;
cout << setw(20) << row[0].c_str()
<< setw(9) << row[1].c_str()
<< setw(9) << row.lookup_by_name("weight").c_str()
// you can use either the index number or column name when
// retrieving the colume data as demonstrated above.
<< setw(9) << row[3].c_str()
<< row[4] << endl;
}
}
bool
connect_sample_db(int argc, char *argv[], mysqlpp::Connection& con,
const char *kdb)
{
if (argv[1][0] == '-') {
cout << "usage: " << argv[0] << " [host] [user] [password]" <<
endl;
cout << endl << "\tConnects to database \"" << kdb <<
"\" on localhost using your user" << endl;
cout << "\tname and no password by default." << endl << endl;
return false;
}
else {
bool success;
if (argc == 1) {
success = con.connect(kdb);
}
else if (argc == 2) {
success = con.connect(kdb, argv[1]);
}
else if (argc == 3) {
success = con.connect(kdb, argv[1], argv[2]);
}
else if (argc >= 4) {
success = con.connect(kdb, argv[1], argv[2], argv[3]);
}
else {
cerr << "Bad argument count " << argc << '!' << endl;
return false;
}
if (!success) {
cerr << "Database connection failed." << endl << endl;
}
}
}
<commit_msg>Fixed a silly segfault and reorganized the code for clarity.<commit_after>#include "util.h"
#include <iostream>
#include <iomanip>
using namespace std;
void
print_stock_table(mysqlpp::Query& query)
{
query.reset();
query << "select * from stock";
// You can write to the query object like you would any other ostrem
mysqlpp::Result res = query.store();
// Query::store() executes the query and returns the results
cout << "Query: " << query.preview() << endl;
// Query::preview() simply returns a string with the current query
// string in it.
cout << "Records Found: " << res.size() << endl << endl;
mysqlpp::Row row;
cout.setf(ios::left);
cout << setw(20) << "Item"
<< setw(9) << "Num"
<< setw(9) << "Weight"
<< setw(9) << "Price" << "Date" << endl << endl;
mysqlpp::Result::iterator i;
// The Result class has a read-only Random Access Iterator
for (i = res.begin(); i != res.end(); i++) {
row = *i;
cout << setw(20) << row[0].c_str()
<< setw(9) << row[1].c_str()
<< setw(9) << row.lookup_by_name("weight").c_str()
// you can use either the index number or column name when
// retrieving the colume data as demonstrated above.
<< setw(9) << row[3].c_str()
<< row[4] << endl;
}
}
bool
connect_sample_db(int argc, char *argv[], mysqlpp::Connection& con,
const char *kdb)
{
if (argc < 1) {
cerr << "Bad argument count: " << argc << '!' << endl;
return false;
}
if ((argc > 1) && (argv[1][0] == '-')) {
cout << "usage: " << argv[0] << " [host] [user] [password]" <<
endl;
cout << endl << "\tConnects to database \"" << kdb <<
"\" on localhost using your user" << endl;
cout << "\tname and no password by default." << endl << endl;
return false;
}
bool success;
if (argc == 1) {
success = con.connect(kdb);
}
else if (argc == 2) {
success = con.connect(kdb, argv[1]);
}
else if (argc == 3) {
success = con.connect(kdb, argv[1], argv[2]);
}
else if (argc >= 4) {
success = con.connect(kdb, argv[1], argv[2], argv[3]);
}
if (!success) {
cerr << "Database connection failed." << endl << endl;
}
return success;
}
<|endoftext|> |
<commit_before>/* Copyright wangchw(wangox@gmail.com). All right reserved.
* Use of this source code is governed by BSD-style license
* that can be found in the LICENSE file.
*/
#include <wrpc/channel.h>
#include <wrpc/client.h>
#include <wrpc/wrpc.pb.h>
#include <google/protobuf/descriptor.h>
#include <istream>
#include <ostream>
namespace wrpc {
unsigned long long Channel::seq_id_ = 0;
Channel::Channel(Client* client) : client_(client) {
}
Channel::~Channel() {
}
void Channel::CallMethod(const google::protobuf::MethodDescriptor* method,
google::protobuf::RpcController* controller,
const google::protobuf::Message* request,
google::protobuf::Message* response,
google::protobuf::Closure* done) {
RpcRequest rpc_req;
rpc_req.set_id(++seq_id_);
rpc_req.set_service(method->service()->full_name());
rpc_req.set_method(method->full_name());
int len = request->ByteSize();
char* p = new char[len];
if (!request->SerializeToArray(p, len)) {
delete [] p;
return;
}
rpc_req.set_req(p, len);
delete [] p;
RpcResponse rpc_res;
client_->Call(controller, &rpc_req, &rpc_res);
std::string e(controller->ErrorText());
auto err = rpc_res.err();
if (err.code() != 0) {
e += err.reason();
controller->SetFailed(e);
}
const std::string& r = rpc_res.res();
if (!response->ParseFromArray(r.c_str(), r.size())) {
controller->SetFailed(e + "Error: google::protobuf::Message::ParseFromArray error.");
}
if (done) {
done->Run();
}
}
}
<commit_msg>add check the result value of Client::Call method<commit_after>/* Copyright wangchw(wangox@gmail.com). All right reserved.
* Use of this source code is governed by BSD-style license
* that can be found in the LICENSE file.
*/
#include <wrpc/channel.h>
#include <wrpc/client.h>
#include <wrpc/wrpc.pb.h>
#include <google/protobuf/descriptor.h>
#include <istream>
#include <ostream>
namespace wrpc {
unsigned long long Channel::seq_id_ = 0;
Channel::Channel(Client* client) : client_(client) {
}
Channel::~Channel() {
}
void Channel::CallMethod(const google::protobuf::MethodDescriptor* method,
google::protobuf::RpcController* controller,
const google::protobuf::Message* request,
google::protobuf::Message* response,
google::protobuf::Closure* done) {
RpcRequest rpc_req;
rpc_req.set_id(++seq_id_);
rpc_req.set_service(method->service()->full_name());
rpc_req.set_method(method->full_name());
int len = request->ByteSize();
char* p = new char[len];
if (!request->SerializeToArray(p, len)) {
delete [] p;
return;
}
rpc_req.set_req(p, len);
delete [] p;
RpcResponse rpc_res;
int r = client_->Call(controller, &rpc_req, &rpc_res);
if (r != 0) {
if (done) {
done->Run();
}
return -1;
}
std::string e(controller->ErrorText());
auto err = rpc_res.err();
if (err.code() != 0) {
e += err.reason();
controller->SetFailed(e);
}
const std::string& r = rpc_res.res();
if (!response->ParseFromArray(r.c_str(), r.size())) {
controller->SetFailed(e + "Error: google::protobuf::Message::ParseFromArray error.");
}
if (done) {
done->Run();
}
}
}
<|endoftext|> |
<commit_before>//===------------------------- chrono.cpp ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "chrono"
#include "cerrno" // errno
#include "system_error" // __throw_system_error
#include <time.h> // clock_gettime, CLOCK_MONOTONIC and CLOCK_REALTIME
#if !defined(CLOCK_REALTIME)
#include <sys/time.h> // for gettimeofday and timeval
#endif
#if !defined(_LIBCPP_HAS_NO_MONOTONIC_CLOCK) && !defined(CLOCK_MONOTONIC)
#if __APPLE__
#include <mach/mach_time.h> // mach_absolute_time, mach_timebase_info_data_t
#else
#error "Monotonic clock not implemented"
#endif
#endif
_LIBCPP_BEGIN_NAMESPACE_STD
namespace chrono
{
// system_clock
const bool system_clock::is_steady;
system_clock::time_point
system_clock::now() _NOEXCEPT
{
#ifdef CLOCK_REALTIME
struct timespec tp;
if (0 != clock_gettime(CLOCK_REALTIME, &tp))
__throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
return time_point(seconds(tp.tv_sec) + microseconds(tp.tv_nsec / 1000));
#else // !CLOCK_REALTIME
timeval tv;
gettimeofday(&tv, 0);
return time_point(seconds(tv.tv_sec) + microseconds(tv.tv_usec));
#endif // CLOCK_REALTIME
}
time_t
system_clock::to_time_t(const time_point& t) _NOEXCEPT
{
return time_t(duration_cast<seconds>(t.time_since_epoch()).count());
}
system_clock::time_point
system_clock::from_time_t(time_t t) _NOEXCEPT
{
return system_clock::time_point(seconds(t));
}
#ifndef _LIBCPP_HAS_NO_MONOTONIC_CLOCK
// steady_clock
//
// Warning: If this is not truly steady, then it is non-conforming. It is
// better for it to not exist and have the rest of libc++ use system_clock
// instead.
const bool steady_clock::is_steady;
#ifdef CLOCK_MONOTONIC
steady_clock::time_point
steady_clock::now() _NOEXCEPT
{
struct timespec tp;
if (0 != clock_gettime(CLOCK_MONOTONIC, &tp))
__throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC) failed");
return time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
}
#elif defined(__APPLE__)
// mach_absolute_time() * MachInfo.numer / MachInfo.denom is the number of
// nanoseconds since the computer booted up. MachInfo.numer and MachInfo.denom
// are run time constants supplied by the OS. This clock has no relationship
// to the Gregorian calendar. It's main use is as a high resolution timer.
// MachInfo.numer / MachInfo.denom is often 1 on the latest equipment. Specialize
// for that case as an optimization.
#pragma GCC visibility push(hidden)
static
steady_clock::rep
steady_simplified()
{
return static_cast<steady_clock::rep>(mach_absolute_time());
}
static
double
compute_steady_factor()
{
mach_timebase_info_data_t MachInfo;
mach_timebase_info(&MachInfo);
return static_cast<double>(MachInfo.numer) / MachInfo.denom;
}
static
steady_clock::rep
steady_full()
{
static const double factor = compute_steady_factor();
return static_cast<steady_clock::rep>(mach_absolute_time() * factor);
}
typedef steady_clock::rep (*FP)();
static
FP
init_steady_clock()
{
mach_timebase_info_data_t MachInfo;
mach_timebase_info(&MachInfo);
if (MachInfo.numer == MachInfo.denom)
return &steady_simplified;
return &steady_full;
}
#pragma GCC visibility pop
steady_clock::time_point
steady_clock::now() _NOEXCEPT
{
static FP fp = init_steady_clock();
return time_point(duration(fp()));
}
#else
#error "Monotonic clock not implemented"
#endif
#endif // !_LIBCPP_HAS_NO_MONOTONIC_CLOCK
}
_LIBCPP_END_NAMESPACE_STD
<commit_msg>Work around ABI break caused by C++17 inline variables.<commit_after>//===------------------------- chrono.cpp ---------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#define _LIBCPP_BUILDING_CHRONO
#include "chrono"
#include "cerrno" // errno
#include "system_error" // __throw_system_error
#include <time.h> // clock_gettime, CLOCK_MONOTONIC and CLOCK_REALTIME
#if !defined(CLOCK_REALTIME)
#include <sys/time.h> // for gettimeofday and timeval
#endif
#if !defined(_LIBCPP_HAS_NO_MONOTONIC_CLOCK) && !defined(CLOCK_MONOTONIC)
#if __APPLE__
#include <mach/mach_time.h> // mach_absolute_time, mach_timebase_info_data_t
#else
#error "Monotonic clock not implemented"
#endif
#endif
_LIBCPP_BEGIN_NAMESPACE_STD
namespace chrono
{
// system_clock
const bool system_clock::is_steady;
// Make is_steady non-discardable in C++17
// See PR28395 (https://llvm.org/bugs/show_bug.cgi?id=28395)
static const bool& __is_steady_force_use1 __attribute__((used)) = system_clock::is_steady;
system_clock::time_point
system_clock::now() _NOEXCEPT
{
#ifdef CLOCK_REALTIME
struct timespec tp;
if (0 != clock_gettime(CLOCK_REALTIME, &tp))
__throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
return time_point(seconds(tp.tv_sec) + microseconds(tp.tv_nsec / 1000));
#else // !CLOCK_REALTIME
timeval tv;
gettimeofday(&tv, 0);
return time_point(seconds(tv.tv_sec) + microseconds(tv.tv_usec));
#endif // CLOCK_REALTIME
}
time_t
system_clock::to_time_t(const time_point& t) _NOEXCEPT
{
return time_t(duration_cast<seconds>(t.time_since_epoch()).count());
}
system_clock::time_point
system_clock::from_time_t(time_t t) _NOEXCEPT
{
return system_clock::time_point(seconds(t));
}
#ifndef _LIBCPP_HAS_NO_MONOTONIC_CLOCK
// steady_clock
//
// Warning: If this is not truly steady, then it is non-conforming. It is
// better for it to not exist and have the rest of libc++ use system_clock
// instead.
const bool steady_clock::is_steady;
// Make is_steady non-discardable in C++17
// See PR28395 (https://llvm.org/bugs/show_bug.cgi?id=28395)
static const bool& __is_steady_force_use2 __attribute__((used)) = steady_clock::is_steady;
#ifdef CLOCK_MONOTONIC
steady_clock::time_point
steady_clock::now() _NOEXCEPT
{
struct timespec tp;
if (0 != clock_gettime(CLOCK_MONOTONIC, &tp))
__throw_system_error(errno, "clock_gettime(CLOCK_MONOTONIC) failed");
return time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
}
#elif defined(__APPLE__)
// mach_absolute_time() * MachInfo.numer / MachInfo.denom is the number of
// nanoseconds since the computer booted up. MachInfo.numer and MachInfo.denom
// are run time constants supplied by the OS. This clock has no relationship
// to the Gregorian calendar. It's main use is as a high resolution timer.
// MachInfo.numer / MachInfo.denom is often 1 on the latest equipment. Specialize
// for that case as an optimization.
#pragma GCC visibility push(hidden)
static
steady_clock::rep
steady_simplified()
{
return static_cast<steady_clock::rep>(mach_absolute_time());
}
static
double
compute_steady_factor()
{
mach_timebase_info_data_t MachInfo;
mach_timebase_info(&MachInfo);
return static_cast<double>(MachInfo.numer) / MachInfo.denom;
}
static
steady_clock::rep
steady_full()
{
static const double factor = compute_steady_factor();
return static_cast<steady_clock::rep>(mach_absolute_time() * factor);
}
typedef steady_clock::rep (*FP)();
static
FP
init_steady_clock()
{
mach_timebase_info_data_t MachInfo;
mach_timebase_info(&MachInfo);
if (MachInfo.numer == MachInfo.denom)
return &steady_simplified;
return &steady_full;
}
#pragma GCC visibility pop
steady_clock::time_point
steady_clock::now() _NOEXCEPT
{
static FP fp = init_steady_clock();
return time_point(duration(fp()));
}
#else
#error "Monotonic clock not implemented"
#endif
#endif // !_LIBCPP_HAS_NO_MONOTONIC_CLOCK
}
_LIBCPP_END_NAMESPACE_STD
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015 Zamarin Arthur
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 <QApplication>
#include <QDir>
#include <QLibrary>
#include <QSettings>
#if defined(Q_OS_WIN)
#elif defined(Q_OS_UNIX)
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#endif
#include "about_plugins.h"
#include "EthernetPacket.h"
#include "preferences.h"
#include "sniff_window.h"
#include <hs_plugin.h>
#ifndef PLUGINS_DIR
#define PLUGINS_DIR "/usr/share/hungry-sniffer/plugins/"
#endif
void addPrefs(HungrySniffer_Core& core);
using namespace hungry_sniffer;
inline void loadLibs(const QString& path)
{
typedef void (*add_function_t)(HungrySniffer_Core&);
typedef uint32_t (*info_uint32_t)();
QDir dir(path);
QStringList allFiles = dir.entryList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files);
allFiles.sort(Qt::CaseInsensitive);
for(const auto& iter : allFiles)
{
QLibrary lib(dir.absoluteFilePath(iter));
info_uint32_t info_version = (info_uint32_t)lib.resolve("PLUGIN_VERSION");
if(info_version && info_version() != API_VERSION)
{
#ifndef QT_NO_DEBUG
qDebug("plugin %s version isn't matching", iter.toLatin1().constData());
#endif
continue;
}
add_function_t foo = (add_function_t)lib.resolve("add");
if(foo)
{
try {
foo(*SniffWindow::core);
#ifndef QT_NO_DEBUG
} catch (const std::exception& e) {
qDebug("error with %s: %s", iter.toLatin1().constData(), e.what());
#endif
continue;
} catch (...) {
#ifndef QT_NO_DEBUG
qDebug("error with %s:", iter.toLatin1().constData());
#endif
continue;
}
}
Preferences::reloadFunc_t reload = (Preferences::reloadFunc_t)lib.resolve("reload");
if(reload)
Preferences::reloadFunctions.push_back(reload);
AboutPlugins::window->addPlugin(lib);
}
}
HungrySniffer_Core* SniffWindow::core = nullptr;
QSettings* Preferences::settings = nullptr;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setApplicationVersion(APP_VERSION);
AboutPlugins::init();
Protocol base(init<EthernetPacket>, "Ethernet", Protocol::getFlags(true, true));
base.addFilter("^dst *== *([^ ]+)$", EthernetPacket::filter_dstMac);
base.addFilter("^src *== *([^ ]+)$", EthernetPacket::filter_srcMac);
HungrySniffer_Core core(base);
SniffWindow::core = &core;
#ifdef QT_NO_DEBUG
QSettings settings(QSettings::IniFormat, QSettings::UserScope, QStringLiteral("hungrysniffer"));
#else
QSettings settings(QStringLiteral("settings.conf"), QSettings::IniFormat);
#endif
Preferences::settings = &settings;
{ // plugins load
loadLibs(QStringLiteral(PLUGINS_DIR));
settings.beginGroup(QStringLiteral("General"));
settings.beginGroup(QStringLiteral("Modules"));
QVariant var = settings.value(QStringLiteral("plugins_dir"));
if(!var.isNull())
{
for(const QString& path : var.toStringList())
loadLibs(path);
}
settings.endGroup();
settings.endGroup();
}
addPrefs(*SniffWindow::core);
SniffWindow w;
bool notEndCmdOption = true;
for(int i = 1; i < argc; i++)
{
if((argv[i][0] == '-') & notEndCmdOption)
{
if(strcmp(argv[i] + 1, "-") == 0)
notEndCmdOption = false;
else if(i + 1 < argc && strcmp(argv[i] + 1, "i") == 0)
w.runLivePcap(argv[++i], 0, QString());
#if defined(Q_OS_UNIX)
else if(strcmp(argv[i] + 1, "quiet") == 0)
{
::close(STDOUT_FILENO);
::close(STDERR_FILENO);
}
#endif
}
else
{
w.runOfflineFile(argv[i]);
}
}
w.show();
return a.exec();
}
<commit_msg>Fix bug with plugins on Release<commit_after>/*
Copyright (c) 2015 Zamarin Arthur
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 <QApplication>
#include <QDir>
#include <QLibrary>
#include <QSettings>
#if defined(Q_OS_WIN)
#elif defined(Q_OS_UNIX)
#include <unistd.h>
#endif
#include "about_plugins.h"
#include "EthernetPacket.h"
#include "preferences.h"
#include "sniff_window.h"
#include <hs_plugin.h>
#ifndef PLUGINS_DIR
#define PLUGINS_DIR "/usr/share/hungry-sniffer/plugins/"
#endif
void addPrefs(HungrySniffer_Core& core);
using namespace hungry_sniffer;
inline void loadLibs(const QString& path)
{
typedef void (*add_function_t)(HungrySniffer_Core&);
typedef uint32_t (*info_uint32_t)();
QDir dir(path);
QStringList allFiles = dir.entryList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files);
allFiles.sort(Qt::CaseInsensitive);
for(const auto& iter : allFiles)
{
QLibrary lib(dir.absoluteFilePath(iter));
info_uint32_t info_version = (info_uint32_t)lib.resolve("PLUGIN_VERSION");
if(info_version && info_version() != API_VERSION)
{
#ifndef QT_NO_DEBUG
qDebug("plugin %s version isn't matching", iter.toLatin1().constData());
#endif
continue;
}
add_function_t foo = (add_function_t)lib.resolve("add");
if(foo)
{
try {
foo(*SniffWindow::core);
#ifndef QT_NO_DEBUG
} catch (const std::exception& e) {
qDebug("error with %s: %s", iter.toLatin1().constData(), e.what());
continue;
#endif
} catch (...) {
#ifndef QT_NO_DEBUG
qDebug("error with %s:", iter.toLatin1().constData());
#endif
continue;
}
}
Preferences::reloadFunc_t reload = (Preferences::reloadFunc_t)lib.resolve("reload");
if(reload)
Preferences::reloadFunctions.push_back(reload);
AboutPlugins::window->addPlugin(lib);
}
}
HungrySniffer_Core* SniffWindow::core = nullptr;
QSettings* Preferences::settings = nullptr;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setApplicationVersion(APP_VERSION);
AboutPlugins::init();
Protocol base(init<EthernetPacket>, "Ethernet", Protocol::getFlags(true, true));
base.addFilter("^dst *== *([^ ]+)$", EthernetPacket::filter_dstMac);
base.addFilter("^src *== *([^ ]+)$", EthernetPacket::filter_srcMac);
HungrySniffer_Core core(base);
SniffWindow::core = &core;
#ifdef QT_NO_DEBUG
QSettings settings(QSettings::IniFormat, QSettings::UserScope, QStringLiteral("hungrysniffer"));
#else
QSettings settings(QStringLiteral("settings.conf"), QSettings::IniFormat);
#endif
Preferences::settings = &settings;
{ // plugins load
loadLibs(QStringLiteral(PLUGINS_DIR));
settings.beginGroup(QStringLiteral("General"));
settings.beginGroup(QStringLiteral("Modules"));
QVariant var = settings.value(QStringLiteral("plugins_dir"));
if(!var.isNull())
{
for(const QString& path : var.toStringList())
loadLibs(path);
}
settings.endGroup();
settings.endGroup();
}
addPrefs(*SniffWindow::core);
SniffWindow w;
bool notEndCmdOption = true;
for(int i = 1; i < argc; i++)
{
if((argv[i][0] == '-') & notEndCmdOption)
{
if(strcmp(argv[i] + 1, "-") == 0)
notEndCmdOption = false;
else if(i + 1 < argc && strcmp(argv[i] + 1, "i") == 0)
w.runLivePcap(argv[++i], 0, QString());
#if defined(Q_OS_UNIX)
else if(strcmp(argv[i] + 1, "quiet") == 0)
{
::close(STDOUT_FILENO);
::close(STDERR_FILENO);
}
#endif
}
else
{
w.runOfflineFile(argv[i]);
}
}
w.show();
return a.exec();
}
<|endoftext|> |
<commit_before>#ifndef TEST_UNIT_MATH_MIX_MAT_UTIL_AUTODIFF_TESTER_HPP
#define TEST_UNIT_MATH_MIX_MAT_UTIL_AUTODIFF_TESTER_HPP
#include <stan/math/mix/mat.hpp>
#include <test/unit/math/mix/mat/seq_reader.hpp>
#include <test/unit/math/mix/mat/seq_writer.hpp>
#include <gtest/gtest.h>
#include <stdexcept>
namespace stan {
namespace math {
namespace test {
// For an example of how to use this tester, see
/ test/unit/math/mix/core/operator_addition_test.cpp
/**
* Test that scalars x1 and x2 are within the specified
* tolerance, with identity behavior for infinite and NaN
* values.
*/
template <typename T1, typename T2>
void expect_near(const T1& x1, const T2& x2,
double tol = 1e-9) {
if (is_nan(x1) || is_nan(x2))
EXPECT_TRUE(is_nan(x1) && is_nan(x2));
else if (is_inf(x1) || is_inf(x2))
EXPECT_EQ(x1, x2);
else
EXPECT_NEAR(x1, x2, tol);
}
/**
* Tests that matrices (or vectors) x1 and x2 are same size and
* have near values up to specified tolerance.
*/
template <typename T, int R, int C>
void expect_near(const Eigen::Matrix<T, R, C>& x1,
const Eigen::Matrix<T, R, C>& x2,
double tol = 1e-7) {
EXPECT_EQ(x1.rows(), x2.rows());
EXPECT_EQ(x1.cols(), x2.cols());
for (int i = 0; i < x1.size(); ++i)
expect_near(x1(i), x2(i), tol);
}
/**
* Tests that the function f applied to the argument x yields
* the expected value fx (with scalars as double).
*/
template <typename F>
void test_value(const F& f, const Eigen::VectorXd& x, double fx) {
if (is_nan(fx))
EXPECT_TRUE(is_nan(f(x)));
else
expect_near(fx, f(x));
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and the correct first-order derivatives as
* calaculated with the gradient functional using var.
*/
template <typename F>
void test_gradient(const F& f, const Eigen::VectorXd& x, double fx) {
Eigen::VectorXd grad_ad;
double fx_ad;
gradient<F>(f, x, fx_ad, grad_ad);
expect_near(fx, fx_ad);
Eigen::VectorXd grad_fd;
double fx_fd;
finite_diff_gradient(f, x, fx_fd, grad_fd);
expect_near(grad_fd, grad_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first-order derivatives as
* calculated by the gradient functionional using fvar<double>
* scalars.
*/
template <typename F>
void test_gradient_fvar(const F& f, const Eigen::VectorXd& x, double fx) {
Eigen::VectorXd grad_ad;
double fx_ad;
gradient<double, F>(f, x, fx_ad, grad_ad);
expect_near(fx, fx_ad);
Eigen::VectorXd grad_fd;
double fx_fd;
finite_diff_gradient(f, x, fx_fd, grad_fd);
expect_near(grad_fd, grad_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first- and second-order derivatives
* as calculated by the hessian functional using fvar<var>
* scalars.
*/
template <typename F>
void test_hessian_fvar(const F& f, const Eigen::VectorXd& x, double fx) {
double fx_ad;
Eigen::VectorXd grad_ad;
Eigen::MatrixXd H_ad;
hessian<double, F>(f, x, fx_ad, grad_ad, H_ad);
expect_near(fx, fx_ad);
double fx_fd;
Eigen::VectorXd grad_fd;
Eigen::MatrixXd H_fd;
finite_diff_hessian(f, x, fx_fd, grad_fd, H_fd);
expect_near(grad_fd, grad_ad);
expect_near(H_fd, H_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first- and second-order derivatives
* as calculated by the hessian functional using
* fvar<fvar<double>> scalars.
*/
template <typename F>
void test_hessian(const F& f, const Eigen::VectorXd& x, double fx) {
double fx_ad;
Eigen::VectorXd grad_ad;
Eigen::MatrixXd H_ad;
hessian<F>(f, x, fx_ad, grad_ad, H_ad);
expect_near(fx, fx_ad);
double fx_fd;
Eigen::VectorXd grad_fd;
Eigen::MatrixXd H_fd;
finite_diff_hessian(f, x, fx_fd, grad_fd, H_fd);
expect_near(grad_fd, grad_ad);
expect_near(H_fd, H_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first-, second-, and third-order
* derivatives as calculated by the hessian functional using
* fvar<fvar<var>> scalars.
*/
template <typename F>
void test_grad_hessian(const F& f, const Eigen::VectorXd& x, double fx) {
double fx_ad;
Eigen::MatrixXd H_ad;
std::vector<Eigen::MatrixXd> grad_H_ad;
grad_hessian(f, x, fx_ad, H_ad, grad_H_ad);
expect_near(fx, fx_ad);
double fx_fd;
Eigen::MatrixXd H_fd;
std::vector<Eigen::MatrixXd> grad_H_fd;
grad_hessian(f, x, fx_fd, H_fd, grad_H_fd);
expect_near(H_fd, H_ad);
EXPECT_EQ(x.size(), grad_H_fd.size());
for (size_t i = 0; i < grad_H_fd.size(); ++i)
expect_near(grad_H_fd[i], grad_H_ad[i]);
}
// test value and derivative in all functionals vs. finite diffs
template <typename F>
void test_functor(const F& f, const Eigen::VectorXd& x, double fx) {
test_value(f, x, fx);
// finite diffs can't handle infinity
if (is_inf(fx)) return;
for (int i = 0; i < x.size(); ++i)
if (is_inf(x(i)))
return;
test_gradient(f, x, fx);
test_gradient_fvar(f, x, fx);
test_hessian(f, x, fx);
test_hessian_fvar(f, x, fx);
// test_grad_hessian(f, x, fx);
}
/**
* Structure to adapt a two-argument function specified as a
* class with a static apply(,) method that returns a scalar to
* a function that operates on an Eigen vector with templated
* scalar type and returns a scalar of the same type.
*
* <p>It works by adapting the two-argument function to be a
* vector function with zero, one or both arguments being
* instantiated to doubles and the remaining arguments being
* templated on the functor argument scalar type.
*
* @tparam F class with static apply(,) method
* @tparam T1 type of first argument with double scalars
* @tparam T2 type of second argument with double scalars
*/
template <typename F, typename T1, typename T2>
struct binder_binary {
T1 x1_;
T2 x2_;
bool fixed1_;
bool fixed2_;
binder_binary(const T1& x1, const T2& x2)
: x1_(x1), x2_(x2), fixed1_(false), fixed2_(false) { }
template <typename T>
T operator()(const Eigen::Matrix<T, -1, 1>& theta) const {
if (fixed1_ && fixed2_) {
return F::apply(x1_, x2_);
} else if (fixed1_ && !fixed2_) {
seq_reader<T> r(theta);
return F::apply(x1_, r.read(x2_));
} else if (!fixed1_ && fixed2_) {
seq_reader<T> r(theta);
return F::apply(r.read(x1_), x2_);
} else if (!fixed1_ && !fixed2_) {
seq_reader<T> r(theta);
return F::apply(r.read(x1_), r.read(x2_));
}
throw std::logic_error("binder_binary illegal state");
}
};
/**
* Tests whether the binary function specified through the static
* function F::apply with arguments of the specified types
* instantiated with double scalars returns right values and
* first, second, and third derivatives. It tests all possible
* combinations of double, var, fvar<double>,
* fvar<fvar<double>>, fvar<var>, and fvar<fvar<var>>
* instantiations.
*/
// test a single sequence of arguments and result
template <typename F, typename T1, typename T2>
void test_ad(const T1& x1, const T2& x2, double fx) {
// create binder then test all autodiff/double combos
binder_binary<F, T1, T2> f(x1, x2);
// test (double, double) instantiation
f.fixed1_ = true;
f.fixed2_ = true;
seq_writer<double> a;
Eigen::VectorXd aaa(0);
test_functor(f, a.vector(), fx);
// test (double, autodiff) instantiation
f.fixed1_ = true;
f.fixed2_ = false;
seq_writer<double> b;
b.write(x2);
test_functor(f, b.vector(), fx);
// test (autodiff, double) instantiation
f.fixed1_ = false;
f.fixed2_ = true;
seq_writer<double> c;
c.write(x1);
test_functor(f, c.vector(), fx);
// test (autodiff, autodiff) instantiation
f.fixed1_ = false;
f.fixed2_ = false;
seq_writer<double> d;
d.write(x1);
d.write(x2);
test_functor(f, d.vector(), fx);
}
}
}
}
#endif
<commit_msg>ad test framework with operator+ example, typo fix<commit_after>#ifndef TEST_UNIT_MATH_MIX_MAT_UTIL_AUTODIFF_TESTER_HPP
#define TEST_UNIT_MATH_MIX_MAT_UTIL_AUTODIFF_TESTER_HPP
#include <stan/math/mix/mat.hpp>
#include <test/unit/math/mix/mat/seq_reader.hpp>
#include <test/unit/math/mix/mat/seq_writer.hpp>
#include <gtest/gtest.h>
#include <stdexcept>
namespace stan {
namespace math {
namespace test {
// For an example of how to use this tester, see
// test/unit/math/mix/core/operator_addition_test.cpp
/**
* Test that scalars x1 and x2 are within the specified
* tolerance, with identity behavior for infinite and NaN
* values.
*/
template <typename T1, typename T2>
void expect_near(const T1& x1, const T2& x2,
double tol = 1e-9) {
if (is_nan(x1) || is_nan(x2))
EXPECT_TRUE(is_nan(x1) && is_nan(x2));
else if (is_inf(x1) || is_inf(x2))
EXPECT_EQ(x1, x2);
else
EXPECT_NEAR(x1, x2, tol);
}
/**
* Tests that matrices (or vectors) x1 and x2 are same size and
* have near values up to specified tolerance.
*/
template <typename T, int R, int C>
void expect_near(const Eigen::Matrix<T, R, C>& x1,
const Eigen::Matrix<T, R, C>& x2,
double tol = 1e-7) {
EXPECT_EQ(x1.rows(), x2.rows());
EXPECT_EQ(x1.cols(), x2.cols());
for (int i = 0; i < x1.size(); ++i)
expect_near(x1(i), x2(i), tol);
}
/**
* Tests that the function f applied to the argument x yields
* the expected value fx (with scalars as double).
*/
template <typename F>
void test_value(const F& f, const Eigen::VectorXd& x, double fx) {
if (is_nan(fx))
EXPECT_TRUE(is_nan(f(x)));
else
expect_near(fx, f(x));
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and the correct first-order derivatives as
* calaculated with the gradient functional using var.
*/
template <typename F>
void test_gradient(const F& f, const Eigen::VectorXd& x, double fx) {
Eigen::VectorXd grad_ad;
double fx_ad;
gradient<F>(f, x, fx_ad, grad_ad);
expect_near(fx, fx_ad);
Eigen::VectorXd grad_fd;
double fx_fd;
finite_diff_gradient(f, x, fx_fd, grad_fd);
expect_near(grad_fd, grad_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first-order derivatives as
* calculated by the gradient functionional using fvar<double>
* scalars.
*/
template <typename F>
void test_gradient_fvar(const F& f, const Eigen::VectorXd& x, double fx) {
Eigen::VectorXd grad_ad;
double fx_ad;
gradient<double, F>(f, x, fx_ad, grad_ad);
expect_near(fx, fx_ad);
Eigen::VectorXd grad_fd;
double fx_fd;
finite_diff_gradient(f, x, fx_fd, grad_fd);
expect_near(grad_fd, grad_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first- and second-order derivatives
* as calculated by the hessian functional using fvar<var>
* scalars.
*/
template <typename F>
void test_hessian_fvar(const F& f, const Eigen::VectorXd& x, double fx) {
double fx_ad;
Eigen::VectorXd grad_ad;
Eigen::MatrixXd H_ad;
hessian<double, F>(f, x, fx_ad, grad_ad, H_ad);
expect_near(fx, fx_ad);
double fx_fd;
Eigen::VectorXd grad_fd;
Eigen::MatrixXd H_fd;
finite_diff_hessian(f, x, fx_fd, grad_fd, H_fd);
expect_near(grad_fd, grad_ad);
expect_near(H_fd, H_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first- and second-order derivatives
* as calculated by the hessian functional using
* fvar<fvar<double>> scalars.
*/
template <typename F>
void test_hessian(const F& f, const Eigen::VectorXd& x, double fx) {
double fx_ad;
Eigen::VectorXd grad_ad;
Eigen::MatrixXd H_ad;
hessian<F>(f, x, fx_ad, grad_ad, H_ad);
expect_near(fx, fx_ad);
double fx_fd;
Eigen::VectorXd grad_fd;
Eigen::MatrixXd H_fd;
finite_diff_hessian(f, x, fx_fd, grad_fd, H_fd);
expect_near(grad_fd, grad_ad);
expect_near(H_fd, H_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first-, second-, and third-order
* derivatives as calculated by the hessian functional using
* fvar<fvar<var>> scalars.
*/
template <typename F>
void test_grad_hessian(const F& f, const Eigen::VectorXd& x, double fx) {
double fx_ad;
Eigen::MatrixXd H_ad;
std::vector<Eigen::MatrixXd> grad_H_ad;
grad_hessian(f, x, fx_ad, H_ad, grad_H_ad);
expect_near(fx, fx_ad);
double fx_fd;
Eigen::MatrixXd H_fd;
std::vector<Eigen::MatrixXd> grad_H_fd;
grad_hessian(f, x, fx_fd, H_fd, grad_H_fd);
expect_near(H_fd, H_ad);
EXPECT_EQ(x.size(), grad_H_fd.size());
for (size_t i = 0; i < grad_H_fd.size(); ++i)
expect_near(grad_H_fd[i], grad_H_ad[i]);
}
// test value and derivative in all functionals vs. finite diffs
template <typename F>
void test_functor(const F& f, const Eigen::VectorXd& x, double fx) {
test_value(f, x, fx);
// finite diffs can't handle infinity
if (is_inf(fx)) return;
for (int i = 0; i < x.size(); ++i)
if (is_inf(x(i)))
return;
test_gradient(f, x, fx);
test_gradient_fvar(f, x, fx);
test_hessian(f, x, fx);
test_hessian_fvar(f, x, fx);
// test_grad_hessian(f, x, fx);
}
/**
* Structure to adapt a two-argument function specified as a
* class with a static apply(,) method that returns a scalar to
* a function that operates on an Eigen vector with templated
* scalar type and returns a scalar of the same type.
*
* <p>It works by adapting the two-argument function to be a
* vector function with zero, one or both arguments being
* instantiated to doubles and the remaining arguments being
* templated on the functor argument scalar type.
*
* @tparam F class with static apply(,) method
* @tparam T1 type of first argument with double scalars
* @tparam T2 type of second argument with double scalars
*/
template <typename F, typename T1, typename T2>
struct binder_binary {
T1 x1_;
T2 x2_;
bool fixed1_;
bool fixed2_;
binder_binary(const T1& x1, const T2& x2)
: x1_(x1), x2_(x2), fixed1_(false), fixed2_(false) { }
template <typename T>
T operator()(const Eigen::Matrix<T, -1, 1>& theta) const {
if (fixed1_ && fixed2_) {
return F::apply(x1_, x2_);
} else if (fixed1_ && !fixed2_) {
seq_reader<T> r(theta);
return F::apply(x1_, r.read(x2_));
} else if (!fixed1_ && fixed2_) {
seq_reader<T> r(theta);
return F::apply(r.read(x1_), x2_);
} else if (!fixed1_ && !fixed2_) {
seq_reader<T> r(theta);
return F::apply(r.read(x1_), r.read(x2_));
}
throw std::logic_error("binder_binary illegal state");
}
};
/**
* Tests whether the binary function specified through the static
* function F::apply with arguments of the specified types
* instantiated with double scalars returns right values and
* first, second, and third derivatives. It tests all possible
* combinations of double, var, fvar<double>,
* fvar<fvar<double>>, fvar<var>, and fvar<fvar<var>>
* instantiations.
*/
// test a single sequence of arguments and result
template <typename F, typename T1, typename T2>
void test_ad(const T1& x1, const T2& x2, double fx) {
// create binder then test all autodiff/double combos
binder_binary<F, T1, T2> f(x1, x2);
// test (double, double) instantiation
f.fixed1_ = true;
f.fixed2_ = true;
seq_writer<double> a;
Eigen::VectorXd aaa(0);
test_functor(f, a.vector(), fx);
// test (double, autodiff) instantiation
f.fixed1_ = true;
f.fixed2_ = false;
seq_writer<double> b;
b.write(x2);
test_functor(f, b.vector(), fx);
// test (autodiff, double) instantiation
f.fixed1_ = false;
f.fixed2_ = true;
seq_writer<double> c;
c.write(x1);
test_functor(f, c.vector(), fx);
// test (autodiff, autodiff) instantiation
f.fixed1_ = false;
f.fixed2_ = false;
seq_writer<double> d;
d.write(x1);
d.write(x2);
test_functor(f, d.vector(), fx);
}
}
}
}
#endif
<|endoftext|> |
<commit_before>#ifndef TEST_UNIT_MATH_MIX_MAT_UTIL_AUTODIFF_TESTER_HPP
#define TEST_UNIT_MATH_MIX_MAT_UTIL_AUTODIFF_TESTER_HPP
#include <stan/math/mix/mat.hpp>
#include <test/unit/math/mix/mat/seq_reader.hpp>
#include <test/unit/math/mix/mat/seq_writer.hpp>
#include <gtest/gtest.h>
#include <stdexcept>
namespace stan {
namespace math {
namespace test {
// For an example of how to use this tester, see
// test/unit/math/mix/core/operator_addition_test.cpp
/**
* Return true if the specified value is finite.
*
* @param x value to test
* @return true if value is finite
*/
bool is_finite(double x) {
return !is_inf(x) && !is_nan(x);
}
/**
* Return true if all of the elements in the container are finite
*
* @tparam T scalar type
* @tparam R row type
* @tparam C col type
* @param x container to test
* @return true if all container values are finite
*/
template <typename T, int R, int C>
bool is_finite(const Eigen::Matrix<T, R, C>& x) {
for (int i = 0; i < x.size(); ++i)
if (!is_finite(x(i)))
return false;
return true;
}
/**
* Return true if all of the elements in the container are finite
*
* @tparam T contained type
* @param x container to test
* @return true if all container values are finite
*/
template <typename T>
bool is_finite(const std::vector<T>& x) {
for (size_t i = 0; i < x.size(); ++i)
if (!is_finite(x[i]))
return false;
return true;
}
/**
* Test that scalars x1 and x2 are within the specified
* tolerance, with identity behavior for infinite and NaN
* values.
*/
template <typename T1, typename T2>
void expect_near(const std::string& msg, const T1& x1, const T2& x2,
double tol = 1e-9) {
if (is_nan(x1) || is_nan(x2))
EXPECT_TRUE(is_nan(x1) && is_nan(x2))
<< "expect_near(" << x1 << ", " << x2 << ")" << std::endl
<< msg << std::endl;
else if (is_inf(x1) || is_inf(x2))
EXPECT_EQ(x1, x2)
<< "expect_near(" << x1 << ", " << x2 << ")" << std::endl
<< msg << std::endl;
else
EXPECT_NEAR(x1, x2, tol)
<< "expect_near(" << x1 << ", " << x2 << ")" << std::endl
<< msg << std::endl;
}
/**
* Tests that matrices (or vectors) x1 and x2 are same size and
* have near values up to specified tolerance.
*/
template <typename T, int R, int C>
void expect_near(const std::string& msg,
const Eigen::Matrix<T, R, C>& x1,
const Eigen::Matrix<T, R, C>& x2, double tol = 1e-7) {
EXPECT_EQ(x1.rows(), x2.rows())
<< "expect_near rows expect_eq(" << x1.rows()
<< ", " << x2.rows() << ")" << std::endl
<< msg << std::endl;
EXPECT_EQ(x1.cols(), x2.cols())
<< "expect_near cols expect_eq(" << x1.rows()
<< ", " << x2.rows() << ")" << std::endl
<< msg << std::endl;
std::string msg2 = "expect_near elt x1(i) = x2(i)\n" + msg;
for (int i = 0; i < x1.size(); ++i)
expect_near(msg2, x1(i), x2(i), tol);
}
/**
* Tests that the function f applied to the argument x yields
* the expected value fx (with scalars as double).
*/
template <typename F>
void test_value(const F& f, const Eigen::VectorXd& x, double fx) {
if (is_nan(fx))
EXPECT_TRUE(is_nan(f(x)))
<< "test_value is_nan(" << f(x) << std::endl;
else
expect_near("test_value fx == f(x)", fx, f(x));
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and the correct first-order derivatives as
* calaculated with the gradient functional using var.
*/
template <typename F>
void test_gradient(const F& f, const Eigen::VectorXd& x, double fx,
bool test_derivs) {
Eigen::VectorXd grad_ad;
double fx_ad;
gradient<F>(f, x, fx_ad, grad_ad);
expect_near("test_gradient fx = fx_ad", fx, fx_ad);
if (!test_derivs || !is_finite(x) || !is_finite(fx))
return;
Eigen::VectorXd grad_fd;
double fx_fd;
finite_diff_gradient(f, x, fx_fd, grad_fd);
expect_near("test gradient grad_fd == grad_ad", grad_fd, grad_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first-order derivatives as
* calculated by the gradient functionional using fvar<double>
* scalars.
*/
template <typename F>
void test_gradient_fvar(const F& f, const Eigen::VectorXd& x, double fx,
bool test_derivs) {
Eigen::VectorXd grad_ad;
double fx_ad;
gradient<double, F>(f, x, fx_ad, grad_ad);
expect_near("gradient_fvar fx == fx_ad", fx, fx_ad);
if (!test_derivs || !is_finite(x) || !is_finite(fx))
return;
Eigen::VectorXd grad_fd;
double fx_fd;
finite_diff_gradient(f, x, fx_fd, grad_fd);
expect_near("gradeint_fvar gard_fd == grad_ad", grad_fd, grad_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first- and second-order derivatives
* as calculated by the hessian functional using fvar<var>
* scalars.
*/
template <typename F>
void test_hessian_fvar(const F& f, const Eigen::VectorXd& x, double fx,
bool test_derivs) {
double fx_ad;
Eigen::VectorXd grad_ad;
Eigen::MatrixXd H_ad;
hessian<double, F>(f, x, fx_ad, grad_ad, H_ad);
expect_near("hessian_fvar fx == fx_ad", fx, fx_ad);
if (!test_derivs || !is_finite(x) || !is_finite(fx))
return;
double fx_fd;
Eigen::VectorXd grad_fd;
Eigen::MatrixXd H_fd;
finite_diff_hessian(f, x, fx_fd, grad_fd, H_fd);
expect_near("hessian fvar grad_fd == grad_ad", grad_fd, grad_ad);
expect_near("hessian fvar H_fd = H_ad", H_fd, H_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first- and second-order derivatives
* as calculated by the hessian functional using
* fvar<fvar<double>> scalars.
*/
template <typename F>
void test_hessian(const F& f, const Eigen::VectorXd& x, double fx,
bool test_derivs) {
double fx_ad;
Eigen::VectorXd grad_ad;
Eigen::MatrixXd H_ad;
hessian<F>(f, x, fx_ad, grad_ad, H_ad);
expect_near("hessian fx == fx_ad", fx, fx_ad);
if (!test_derivs || !is_finite(x) || !is_finite(fx))
return;
double fx_fd;
Eigen::VectorXd grad_fd;
Eigen::MatrixXd H_fd;
finite_diff_hessian(f, x, fx_fd, grad_fd, H_fd);
expect_near("hessian grad_fd = grad_ad", grad_fd, grad_ad);
expect_near("hessian grad_fd H_fd == H_ad", H_fd, H_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first-, second-, and third-order
* derivatives as calculated by the hessian functional using
* fvar<fvar<var>> scalars.
*/
template <typename F>
void test_grad_hessian(const F& f, const Eigen::VectorXd& x, double fx,
bool test_derivs) {
double fx_ad;
Eigen::MatrixXd H_ad;
std::vector<Eigen::MatrixXd> grad_H_ad;
grad_hessian(f, x, fx_ad, H_ad, grad_H_ad);
expect_near("grad_hessian fx == fx_ad", fx, fx_ad);
if (!test_derivs || !is_finite(x) || !is_finite(fx))
return;
double fx_fd;
Eigen::MatrixXd H_fd;
std::vector<Eigen::MatrixXd> grad_H_fd;
finite_diff_grad_hessian(f, x, fx_fd, H_fd, grad_H_fd);
expect_near("grad hessian H_fd == H_ad", H_fd, H_ad);
EXPECT_EQ(x.size(), grad_H_fd.size());
for (size_t i = 0; i < grad_H_fd.size(); ++i)
expect_near("grad hessian grad_H_fd[i] == grad_H_ad[i]",
grad_H_fd[i], grad_H_ad[i]);
}
// test value and derivative in all functionals vs. finite diffs
template <typename F>
void test_functor(const F& f, const Eigen::VectorXd& x, double fx,
bool test_derivs = true) {
test_value(f, x, fx);
test_gradient(f, x, fx, test_derivs);
test_gradient_fvar(f, x, fx, test_derivs);
test_hessian(f, x, fx, test_derivs);
test_hessian_fvar(f, x, fx, test_derivs);
test_grad_hessian(f, x, fx, test_derivs);
}
/**
* Structure to adapt a two-argument function specified as a
* class with a static apply(,) method that returns a scalar to
* a function that operates on an Eigen vector with templated
* scalar type and returns a scalar of the same type.
*
* <p>It works by adapting the two-argument function to be a
* vector function with zero, one or both arguments being
* instantiated to doubles and the remaining arguments being
* templated on the functor argument scalar type.
*
* @tparam F class with static apply(,) method
* @tparam T1 type of first argument with double scalars
* @tparam T2 type of second argument with double scalars
*/
template <typename F, typename T1, typename T2>
struct binder_binary {
T1 x1_;
T2 x2_;
bool fixed1_;
bool fixed2_;
binder_binary(const T1& x1, const T2& x2)
: x1_(x1), x2_(x2), fixed1_(false), fixed2_(false) { }
template <typename T>
T operator()(const Eigen::Matrix<T, -1, 1>& theta) const {
if (fixed1_ && fixed2_) {
return F::apply(x1_, x2_);
} else if (fixed1_ && !fixed2_) {
seq_reader<T> r(theta);
return F::apply(x1_, r.read(x2_));
} else if (!fixed1_ && fixed2_) {
seq_reader<T> r(theta);
return F::apply(r.read(x1_), x2_);
} else if (!fixed1_ && !fixed2_) {
seq_reader<T> r(theta);
return F::apply(r.read(x1_), r.read(x2_));
}
throw std::logic_error("binder_binary illegal state");
}
};
/**
* Tests whether the binary function specified through the static
* function F::apply with arguments of the specified types
* instantiated with double scalars returns right values and
* first, second, and third derivatives. It tests all possible
* combinations of double, var, fvar<double>,
* fvar<fvar<double>>, fvar<var>, and fvar<fvar<var>>
* instantiations.
*/
template <typename F, typename T1, typename T2>
void test_ad(const T1& x1, const T2& x2, double fx,
bool test_derivs = true) {
// create binder then test all autodiff/double combos
binder_binary<F, T1, T2> f(x1, x2);
// test (double, double) instantiation
f.fixed1_ = true;
f.fixed2_ = true;
seq_writer<double> a;
test_functor(f, a.vector(), fx, test_derivs);
// test (double, autodiff) instantiation
f.fixed1_ = true;
f.fixed2_ = false;
seq_writer<double> b;
b.write(x2);
test_functor(f, b.vector(), fx, test_derivs);
// test (autodiff, double) instantiation
f.fixed1_ = false;
f.fixed2_ = true;
seq_writer<double> c;
c.write(x1);
test_functor(f, c.vector(), fx, test_derivs);
// test (autodiff, autodiff) instantiation
f.fixed1_ = false;
f.fixed2_ = false;
seq_writer<double> d;
d.write(x1);
d.write(x2);
test_functor(f, d.vector(), fx, test_derivs);
}
template <typename F, bool is_comparison>
void test_common_args() {
using stan::math::test::test_ad;
std::vector<double> xs;
xs.push_back(0.5);
xs.push_back(0);
xs.push_back(-1.3);
xs.push_back(stan::math::positive_infinity());
xs.push_back(stan::math::negative_infinity());
xs.push_back(stan::math::not_a_number());
// avoid testing derivatives for comparisons of equal values
// as results will be non-differentiable in one direction
for (size_t i = 0; i < xs.size(); ++i) {
for (size_t j = 0; j < xs.size(); ++j) {
double fx = F::apply(xs[i], xs[j]);
test_ad<F>(xs[i], xs[j], fx,
!(is_comparison && xs[i] == xs[j]));
}
}
}
}
}
}
#endif
<commit_msg>Fix the autodiff testing framework -<commit_after>#ifndef TEST_UNIT_MATH_MIX_MAT_UTIL_AUTODIFF_TESTER_HPP
#define TEST_UNIT_MATH_MIX_MAT_UTIL_AUTODIFF_TESTER_HPP
#include <stan/math/mix/mat.hpp>
#include <test/unit/math/mix/mat/seq_reader.hpp>
#include <test/unit/math/mix/mat/seq_writer.hpp>
#include <gtest/gtest.h>
#include <stdexcept>
namespace stan {
namespace math {
namespace test {
// For an example of how to use this tester, see
// test/unit/math/mix/core/operator_addition_test.cpp
/**
* Return true if the specified value is finite.
*
* @param x value to test
* @return true if value is finite
*/
bool is_finite(double x) {
return !is_inf(x) && !is_nan(x);
}
/**
* Return true if all of the elements in the container are finite
*
* @tparam T scalar type
* @tparam R row type
* @tparam C col type
* @param x container to test
* @return true if all container values are finite
*/
template <typename T, int R, int C>
bool is_finite(const Eigen::Matrix<T, R, C>& x) {
for (int i = 0; i < x.size(); ++i)
if (!is_finite(x(i)))
return false;
return true;
}
/**
* Return true if all of the elements in the container are finite
*
* @tparam T contained type
* @param x container to test
* @return true if all container values are finite
*/
template <typename T>
bool is_finite(const std::vector<T>& x) {
for (size_t i = 0; i < x.size(); ++i)
if (!is_finite(x[i]))
return false;
return true;
}
/**
* Test that scalars x1 and x2 are within the specified
* tolerance, with identity behavior for infinite and NaN
* values.
*/
template <typename T1, typename T2>
void expect_near(const std::string& msg, const T1& x1, const T2& x2,
double tol = 1e-9) {
if (is_nan(x1) || is_nan(x2))
EXPECT_TRUE(is_nan(x1) && is_nan(x2))
<< "expect_near(" << x1 << ", " << x2 << ")" << std::endl
<< msg << std::endl;
else if (is_inf(x1) || is_inf(x2))
EXPECT_EQ(x1, x2)
<< "expect_near(" << x1 << ", " << x2 << ")" << std::endl
<< msg << std::endl;
else
EXPECT_NEAR(x1, x2, tol)
<< "expect_near(" << x1 << ", " << x2 << ")" << std::endl
<< msg << std::endl;
}
/**
* Tests that matrices (or vectors) x1 and x2 are same size and
* have near values up to specified tolerance.
*/
template <typename T, int R, int C>
void expect_near(const std::string& msg,
const Eigen::Matrix<T, R, C>& x1,
const Eigen::Matrix<T, R, C>& x2, double tol = 1e-7) {
EXPECT_EQ(x1.rows(), x2.rows())
<< "expect_near rows expect_eq(" << x1.rows()
<< ", " << x2.rows() << ")" << std::endl
<< msg << std::endl;
EXPECT_EQ(x1.cols(), x2.cols())
<< "expect_near cols expect_eq(" << x1.rows()
<< ", " << x2.rows() << ")" << std::endl
<< msg << std::endl;
std::string msg2 = "expect_near elt x1(i) = x2(i)\n" + msg;
for (int i = 0; i < x1.size(); ++i)
expect_near(msg2, x1(i), x2(i), tol);
}
/**
* Tests that the function f applied to the argument x yields
* the expected value fx (with scalars as double).
*/
template <typename F>
void test_value(const F& f, const Eigen::VectorXd& x, double fx) {
if (is_nan(fx))
EXPECT_TRUE(is_nan(f(x)))
<< "test_value is_nan(" << f(x) << std::endl;
else
expect_near("test_value fx == f(x)", fx, f(x));
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and the correct first-order derivatives as
* calaculated with the gradient functional using var.
*/
template <typename F>
void test_gradient(const F& f, const Eigen::VectorXd& x, double fx,
bool test_derivs) {
Eigen::VectorXd grad_ad;
double fx_ad;
gradient<F>(f, x, fx_ad, grad_ad);
expect_near("test_gradient fx = fx_ad", fx, fx_ad);
if (!test_derivs || !is_finite(x) || !is_finite(fx))
return;
Eigen::VectorXd grad_fd;
double fx_fd;
finite_diff_gradient(f, x, fx_fd, grad_fd);
expect_near("test gradient grad_fd == grad_ad", grad_fd, grad_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first-order derivatives as
* calculated by the gradient functionional using fvar<double>
* scalars.
*/
template <typename F>
void test_gradient_fvar(const F& f, const Eigen::VectorXd& x, double fx,
bool test_derivs) {
Eigen::VectorXd grad_ad;
double fx_ad;
gradient<double, F>(f, x, fx_ad, grad_ad);
expect_near("gradient_fvar fx == fx_ad", fx, fx_ad);
if (!test_derivs || !is_finite(x) || !is_finite(fx))
return;
Eigen::VectorXd grad_fd;
double fx_fd;
finite_diff_gradient(f, x, fx_fd, grad_fd);
expect_near("gradeint_fvar gard_fd == grad_ad", grad_fd, grad_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first- and second-order derivatives
* as calculated by the hessian functional using fvar<var>
* scalars.
*/
template <typename F>
void test_hessian_fvar(const F& f, const Eigen::VectorXd& x, double fx,
bool test_derivs) {
double fx_ad;
Eigen::VectorXd grad_ad;
Eigen::MatrixXd H_ad;
hessian<double, F>(f, x, fx_ad, grad_ad, H_ad);
expect_near("hessian_fvar fx == fx_ad", fx, fx_ad);
if (!test_derivs || !is_finite(x) || !is_finite(fx))
return;
double fx_fd;
Eigen::VectorXd grad_fd;
Eigen::MatrixXd H_fd;
finite_diff_hessian(f, x, fx_fd, grad_fd, H_fd);
expect_near("hessian fvar grad_fd == grad_ad", grad_fd, grad_ad);
expect_near("hessian fvar H_fd = H_ad", H_fd, H_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first- and second-order derivatives
* as calculated by the hessian functional using
* fvar<fvar<double>> scalars.
*/
template <typename F>
void test_hessian(const F& f, const Eigen::VectorXd& x, double fx,
bool test_derivs) {
double fx_ad;
Eigen::VectorXd grad_ad;
Eigen::MatrixXd H_ad;
hessian<F>(f, x, fx_ad, grad_ad, H_ad);
expect_near("hessian fx == fx_ad", fx, fx_ad);
if (!test_derivs || !is_finite(x) || !is_finite(fx))
return;
double fx_fd;
Eigen::VectorXd grad_fd;
Eigen::MatrixXd H_fd;
finite_diff_hessian(f, x, fx_fd, grad_fd, H_fd);
expect_near("hessian grad_fd = grad_ad", grad_fd, grad_ad);
expect_near("hessian grad_fd H_fd == H_ad", H_fd, H_ad);
}
/**
* Tests that the function f applied to the argument x yields
* the value fx and correct first-, second-, and third-order
* derivatives as calculated by the hessian functional using
* fvar<fvar<var>> scalars.
*/
template <typename F>
void test_grad_hessian(const F& f, const Eigen::VectorXd& x, double fx,
bool test_derivs) {
double fx_ad;
Eigen::MatrixXd H_ad;
std::vector<Eigen::MatrixXd> grad_H_ad;
grad_hessian(f, x, fx_ad, H_ad, grad_H_ad);
expect_near("grad_hessian fx == fx_ad", fx, fx_ad);
if (!test_derivs || !is_finite(x) || !is_finite(fx))
return;
double fx_fd;
Eigen::MatrixXd H_fd;
std::vector<Eigen::MatrixXd> grad_H_fd;
finite_diff_grad_hessian(f, x, fx_fd, H_fd, grad_H_fd);
expect_near("grad hessian H_fd == H_ad", H_fd, H_ad);
EXPECT_EQ(x.size(), grad_H_fd.size());
for (size_t i = 0; i < grad_H_fd.size(); ++i)
expect_near("grad hessian grad_H_fd[i] == grad_H_ad[i]",
grad_H_fd[i], grad_H_ad[i]);
}
// test value and derivative in all functionals vs. finite diffs
template <typename F>
void test_functor(const F& f, const Eigen::VectorXd& x, double fx,
bool test_derivs = true) {
test_value(f, x, fx);
test_gradient(f, x, fx, test_derivs);
test_gradient_fvar(f, x, fx, test_derivs);
test_hessian(f, x, fx, test_derivs);
test_hessian_fvar(f, x, fx, test_derivs);
test_grad_hessian(f, x, fx, test_derivs);
}
/**
* Structure to adapt a two-argument function specified as a
* class with a static apply(,) method that returns a scalar to
* a function that operates on an Eigen vector with templated
* scalar type and returns a scalar of the same type.
*
* <p>It works by adapting the two-argument function to be a
* vector function with zero, one or both arguments being
* instantiated to doubles and the remaining arguments being
* templated on the functor argument scalar type.
*
* @tparam F class with static apply(,) method
* @tparam T1 type of first argument with double scalars
* @tparam T2 type of second argument with double scalars
*/
template <typename F, typename T1, typename T2>
struct binder_binary {
T1 x1_;
T2 x2_;
bool fixed1_;
bool fixed2_;
binder_binary(const T1& x1, const T2& x2)
: x1_(x1), x2_(x2), fixed1_(false), fixed2_(false) { }
template <typename T>
T operator()(const Eigen::Matrix<T, -1, 1>& theta) const {
if (fixed1_ && fixed2_) {
return F::apply(x1_, x2_);
} else if (fixed1_ && !fixed2_) {
seq_reader<T> r(theta);
return F::apply(x1_, r.read(x2_));
} else if (!fixed1_ && fixed2_) {
seq_reader<T> r(theta);
return F::apply(r.read(x1_), x2_);
} else if (!fixed1_ && !fixed2_) {
seq_reader<T> r(theta);
T read_x1 = r.read(x1_);
T read_x2 = r.read(x2_);
return F::apply(read_x1, read_x2);
}
throw std::logic_error("binder_binary illegal state");
}
};
/**
* Tests whether the binary function specified through the static
* function F::apply with arguments of the specified types
* instantiated with double scalars returns right values and
* first, second, and third derivatives. It tests all possible
* combinations of double, var, fvar<double>,
* fvar<fvar<double>>, fvar<var>, and fvar<fvar<var>>
* instantiations.
*/
template <typename F, typename T1, typename T2>
void test_ad(const T1& x1, const T2& x2, double fx,
bool test_derivs = true) {
// create binder then test all autodiff/double combos
binder_binary<F, T1, T2> f(x1, x2);
// test (double, double) instantiation
f.fixed1_ = true;
f.fixed2_ = true;
seq_writer<double> a;
test_functor(f, a.vector(), fx, test_derivs);
// test (double, autodiff) instantiation
f.fixed1_ = true;
f.fixed2_ = false;
seq_writer<double> b;
b.write(x2);
test_functor(f, b.vector(), fx, test_derivs);
// test (autodiff, double) instantiation
f.fixed1_ = false;
f.fixed2_ = true;
seq_writer<double> c;
c.write(x1);
test_functor(f, c.vector(), fx, test_derivs);
// test (autodiff, autodiff) instantiation
f.fixed1_ = false;
f.fixed2_ = false;
seq_writer<double> d;
d.write(x1);
d.write(x2);
test_functor(f, d.vector(), fx, test_derivs);
}
template <typename F, bool is_comparison>
void test_common_args() {
using stan::math::test::test_ad;
std::vector<double> xs;
xs.push_back(0.5);
xs.push_back(0);
xs.push_back(-1.3);
xs.push_back(stan::math::positive_infinity());
xs.push_back(stan::math::negative_infinity());
xs.push_back(stan::math::not_a_number());
// avoid testing derivatives for comparisons of equal values
// as results will be non-differentiable in one direction
for (size_t i = 0; i < xs.size(); ++i) {
for (size_t j = 0; j < xs.size(); ++j) {
double fx = F::apply(xs[i], xs[j]);
test_ad<F>(xs[i], xs[j], fx,
!(is_comparison && xs[i] == xs[j]));
}
}
}
}
}
}
#endif
<|endoftext|> |
<commit_before>#include "webcam.hpp"
#include <chrono>
using namespace cv;
using namespace std;
Mat ellipticKernel(int width, int height = -1) {
if (height==-1) {
return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
} else {
return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
}
}
unsigned long long getMilliseconds() {
return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1);
}
int main (int argc, char** argv) {
/*****
begin camera setup
*****/
CvCapture* capture = 0;
int width, height;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream config_file (".config");
if (config_file.is_open()) {
// does not support corrupted .config
string line;
getline(config_file, line);
istringstream(line)>>width;
getline(config_file, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
config_file.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream config_file_out(".config");
config_file_out << width;
config_file_out << "\n";
config_file_out << height;
config_file_out << "\n";
config_file_out.close();
}
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
/*****
end camera setup
*****/
/*****
filter setup
*****/
Mat acbg(256, 256, CV_8UC3, Scalar(0,0,0));
// accumulated background
Mat acbg_m(256, 256, CV_8UC1, Scalar(0));
// accumulated background mask
Mat acfg(256, 256, CV_8UC3, Scalar(0,0,0));
// accumulated foreground
Mat acfg_t(256, 256, CV_8UC3, Scalar(0));
// accumulated foreground threshold
/*****
end filter setup
*****/
/*****
misc
*****/
unsigned long long times[100];
for (int i=0; i<100; i++)
times[i] = 0;
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
unsigned long long timenow = getMilliseconds();
bool keep_going = true;
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
/*****
begin filter loop
*****/
while (keep_going) {
Mat image(cvQueryFrame(capture));
// imshow("webcam", image);
// at some point preprocess by rotating according to OVR roll
// right now really annoying because of state variables
Mat gray, img_256, gray_256;
resize(image, img_256, Size(256, 256));
cvtColor(image, gray, CV_RGB2GRAY);
cvtColor(img_256, gray_256, CV_RGB2GRAY);
// this mask gets anything kind of dark (DK2) and dilates
// should work *great*
Mat gr_m;
// gray mask
equalizeHist(gray_256, gr_m);
threshold(gr_m, gr_m, 100, 1, THRESH_BINARY_INV);
dilate(gr_m, gr_m, ellipticKernel(43));
gr_m = 1 - gr_m;
// change code later so we don't have to do this
imshow("gray mask", gray_256.mul(1-gr_m));
bitwise_or(acbg_m, gr_m, acbg_m);
imshow("accumulated bg mask", gray_256.mul(1-acbg_m));
// this mask watches for flow against accumulated bg
Mat fl_m;
// flow mask
absdiff(img_256, acbg, fl_m);
cvtColor(fl_m, fl_m, CV_BGR2GRAY);
threshold(fl_m, fl_m, 150, 1, THRESH_BINARY);
int t1 = tracker1 + 1 - (tracker1%2);
if (t1<3) t1 = 3;
if (t1>90) t1 = 91;
dilate(fl_m, fl_m, ellipticKernel(35));
erode(fl_m, fl_m, ellipticKernel(51));
imshow("flow mask", gray_256.mul(1-fl_m));
Mat bg_m;
bitwise_and(acbg_m, fl_m, bg_m);
bitwise_or(gr_m, bg_m, bg_m);
// maybe do some morphological operations on bg_m?
// previously combined bg_m with its opening
imshow("bg mask", gray_256.mul(1-bg_m));
/*
// do some stuff with foreground and so on here
Mat haar_m;
// bitwise_and(1 - bg_m, fg_m, haar_m);
haar_m = 1 - bg_m;
// run haar classifier
int scale = width/300;
if (scale < 1)
scale = 1;
// can't use 256x256 since haar isn't stretch invariant
Mat thingy;
resize(gray, thingy, Size(width/scale, height/scale));
equalizeHist(thingy, thingy);
///////////////////
// need to change this after foreground stuff gets written
vector<Rect> mouth_rects;
resize(haar_m, haar_m, Size(width/scale, height/scale));
bitwise_and(haar_m, thingy, thingy);
/////////////////
mouth_cascade.detectMultiScale(thingy, mouth_rects, 1.1, 0, CV_HAAR_SCALE_IMAGE);
Mat rect_image(height, width, CV_8UC1, Scalar(0));
for (size_t i=0; i<mouth_rects.size(); i++) {
Rect scaled(mouth_rects[i].x*scale, mouth_rects[i].y*scale, mouth_rects[i].width*scale,mouth_rects[i].height*scale);
Mat new_rect(height, width, CV_8UC1, Scalar(0));
rectangle(new_rect, scaled, Scalar(1), CV_FILLED);
rect_image += new_rect;
}
double min_val, max_val;
minMaxLoc(rect_image, &min_val, &max_val);
// or maybe equalize? this whole thing needs to be rewritten
// with the new fg and temporal coherence ideas
Mat rect_thresh;
threshold(rect_image, rect_thresh, max_val*0.9, 1, THRESH_BINARY);
imshow("mouth", rect_thresh.mul(gray));
/*
Moments m = moments(rect_thresh, 1);
circle(image, Point(m.m10/m.m00,m.m01/m.m00),20,Scalar(128),30);
imshow("centroid", image);
*/
keep_going = (waitKey(1)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"
#include <chrono>
using namespace cv;
using namespace std;
Mat ellipticKernel(int width, int height = -1) {
if (height==-1) {
return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2));
} else {
return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2));
}
}
unsigned long long getMilliseconds() {
return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1);
}
int main (int argc, char** argv) {
/*****
begin camera setup
*****/
CvCapture* capture = 0;
int width, height;
capture = cvCaptureFromCAM(0);
if (!capture) {
printf("No camera detected!");
return -1;
}
ifstream config_file (".config");
if (config_file.is_open()) {
// does not support corrupted .config
string line;
getline(config_file, line);
istringstream(line)>>width;
getline(config_file, line);
istringstream(line)>>height;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);
config_file.close();
} else {
initResolutions();
for (int i=36; i<150; i++) {
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
}
width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
ofstream config_file_out(".config");
config_file_out << width;
config_file_out << "\n";
config_file_out << height;
config_file_out << "\n";
config_file_out.close();
}
for (int i = 0; i < 30; i++) {
// capture some frames so exposure correction takes place
cvQueryFrame(capture);
}
/*****
end camera setup
*****/
/*****
filter setup
*****/
Mat acbg(256, 256, CV_8UC3, Scalar(0,0,0));
// accumulated background
Mat acbg_m(256, 256, CV_8UC1, Scalar(0));
// accumulated background mask
Mat acfg(256, 256, CV_8UC3, Scalar(0,0,0));
// accumulated foreground
Mat acfg_t(256, 256, CV_8UC3, Scalar(0));
// accumulated foreground threshold
/*****
end filter setup
*****/
/*****
misc
*****/
unsigned long long times[100];
for (int i=0; i<100; i++)
times[i] = 0;
int tracker1, tracker2, tracker3;
namedWindow("s",1);
createTrackbar("1","s",&tracker1,100);
createTrackbar("2","s",&tracker2,100);
createTrackbar("3","s",&tracker3,100);
unsigned long long timenow = getMilliseconds();
bool keep_going = true;
CascadeClassifier mouth_cascade;
mouth_cascade.load("Mouth.xml");
/*****
begin filter loop
*****/
while (keep_going) {
Mat image(cvQueryFrame(capture));
// imshow("webcam", image);
// at some point preprocess by rotating according to OVR roll
// right now really annoying because of state variables
Mat gray, img_256, gray_256;
resize(image, img_256, Size(256, 256));
cvtColor(image, gray, CV_RGB2GRAY);
cvtColor(img_256, gray_256, CV_RGB2GRAY);
// this mask gets anything kind of dark (DK2) and dilates
// should work *great*
Mat gr_m;
// gray mask
equalizeHist(gray_256, gr_m);
threshold(gr_m, gr_m, 100, 1, THRESH_BINARY_INV);
dilate(gr_m, gr_m, ellipticKernel(43));
gr_m = 1 - gr_m;
// change code later so we don't have to do this
// imshow("gray mask", gray_256.mul(1-gr_m));
bitwise_or(acbg_m, gr_m, acbg_m);
// imshow("accumulated bg mask", gray_256.mul(1-acbg_m));
// this mask watches for flow against accumulated bg
Mat fl_m;
// flow mask
absdiff(img_256, acbg, fl_m);
cvtColor(fl_m, fl_m, CV_BGR2GRAY);
threshold(fl_m, fl_m, 150, 1, THRESH_BINARY);
int t1 = tracker1 + 1 - (tracker1%2);
if (t1<3) t1 = 3;
if (t1>90) t1 = 91;
dilate(fl_m, fl_m, ellipticKernel(35));
erode(fl_m, fl_m, ellipticKernel(51));
imshow("flow mask", gray_256.mul(1-fl_m));
Mat bg_m;
bitwise_and(acbg_m, fl_m, bg_m);
// maybe just use fl_m? it's surprisingly good!
bitwise_or(gr_m, bg_m, bg_m);
// maybe do some morphological operations on bg_m?
// previously combined bg_m with its opening
imshow("bg mask", gray_256.mul(1-bg_m));
/*
// do some stuff with foreground and so on here
Mat haar_m;
// bitwise_and(1 - bg_m, fg_m, haar_m);
haar_m = 1 - bg_m;
// run haar classifier
int scale = width/300;
if (scale < 1)
scale = 1;
// can't use 256x256 since haar isn't stretch invariant
Mat thingy;
resize(gray, thingy, Size(width/scale, height/scale));
equalizeHist(thingy, thingy);
///////////////////
// need to change this after foreground stuff gets written
vector<Rect> mouth_rects;
resize(haar_m, haar_m, Size(width/scale, height/scale));
bitwise_and(haar_m, thingy, thingy);
/////////////////
mouth_cascade.detectMultiScale(thingy, mouth_rects, 1.1, 0, CV_HAAR_SCALE_IMAGE);
Mat rect_image(height, width, CV_8UC1, Scalar(0));
for (size_t i=0; i<mouth_rects.size(); i++) {
Rect scaled(mouth_rects[i].x*scale, mouth_rects[i].y*scale, mouth_rects[i].width*scale,mouth_rects[i].height*scale);
Mat new_rect(height, width, CV_8UC1, Scalar(0));
rectangle(new_rect, scaled, Scalar(1), CV_FILLED);
rect_image += new_rect;
}
double min_val, max_val;
minMaxLoc(rect_image, &min_val, &max_val);
// or maybe equalize? this whole thing needs to be rewritten
// with the new fg and temporal coherence ideas
Mat rect_thresh;
threshold(rect_image, rect_thresh, max_val*0.9, 1, THRESH_BINARY);
imshow("mouth", rect_thresh.mul(gray));
/*
Moments m = moments(rect_thresh, 1);
circle(image, Point(m.m10/m.m00,m.m01/m.m00),20,Scalar(128),30);
imshow("centroid", image);
*/
keep_going = (waitKey(1)<0);
}
cvReleaseCapture(&capture);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*/
#include "TestSscCommon.h"
#include <adios2.h>
#include <gtest/gtest.h>
#include <mpi.h>
#include <numeric>
#include <thread>
using namespace adios2;
int mpiRank = 0;
int mpiSize = 1;
MPI_Comm mpiComm;
class SscEngineTest : public ::testing::Test
{
public:
SscEngineTest() = default;
};
void Writer(const Dims &shape, const Dims &start, const Dims &count,
const size_t steps, const adios2::Params &engineParams,
const std::string &name)
{
size_t datasize =
std::accumulate(count.begin(), count.end(), static_cast<size_t>(1),
std::multiplies<size_t>());
adios2::ADIOS adios(mpiComm);
adios2::IO io = adios.DeclareIO("Test");
io.SetEngine("ssc");
io.SetParameters(engineParams);
std::vector<char> myChars(datasize);
std::vector<unsigned char> myUChars(datasize);
std::vector<short> myShorts(datasize);
std::vector<unsigned short> myUShorts(datasize);
std::vector<int> myInts(datasize);
std::vector<unsigned int> myUInts(datasize);
std::vector<float> myFloats(datasize);
std::vector<double> myDoubles(datasize);
std::vector<std::complex<float>> myComplexes(datasize);
std::vector<std::complex<double>> myDComplexes(datasize);
auto bpChars = io.DefineVariable<char>("bpChars", shape, start, count);
auto bpUChars =
io.DefineVariable<unsigned char>("bpUChars", shape, start, count);
auto bpShorts = io.DefineVariable<short>("bpShorts", shape, start, count);
auto bpUShorts =
io.DefineVariable<unsigned short>("bpUShorts", shape, start, count);
auto bpInts = io.DefineVariable<int>("bpInts", shape, start, count);
auto bpUInts =
io.DefineVariable<unsigned int>("bpUInts", shape, start, count);
auto bpFloats = io.DefineVariable<float>("bpFloats", shape, start, count);
auto bpDoubles =
io.DefineVariable<double>("bpDoubles", shape, start, count);
auto bpComplexes = io.DefineVariable<std::complex<float>>(
"bpComplexes", shape, start, count);
auto bpDComplexes = io.DefineVariable<std::complex<double>>(
"bpDComplexes", shape, start, count);
auto scalarInt = io.DefineVariable<int>("scalarInt");
auto stringVar = io.DefineVariable<std::string>("stringVar");
io.DefineAttribute<int>("AttInt", 110);
adios2::Engine engine = io.Open(name, adios2::Mode::Write);
engine.LockWriterDefinitions();
for (size_t i = 0; i < steps; ++i)
{
engine.BeginStep();
GenData(myChars, i, start, count, shape);
GenData(myUChars, i, start, count, shape);
GenData(myShorts, i, start, count, shape);
GenData(myUShorts, i, start, count, shape);
GenData(myInts, i, start, count, shape);
GenData(myUInts, i, start, count, shape);
GenData(myFloats, i, start, count, shape);
GenData(myDoubles, i, start, count, shape);
GenData(myComplexes, i, start, count, shape);
GenData(myDComplexes, i, start, count, shape);
engine.Put(bpChars, myChars.data(), adios2::Mode::Sync);
engine.Put(bpUChars, myUChars.data(), adios2::Mode::Sync);
engine.Put(bpShorts, myShorts.data(), adios2::Mode::Sync);
engine.Put(bpUShorts, myUShorts.data(), adios2::Mode::Sync);
engine.Put(bpInts, myInts.data(), adios2::Mode::Sync);
engine.Put(bpUInts, myUInts.data(), adios2::Mode::Sync);
engine.Put(bpFloats, myFloats.data(), adios2::Mode::Sync);
engine.Put(bpDoubles, myDoubles.data(), adios2::Mode::Sync);
engine.Put(bpComplexes, myComplexes.data(), adios2::Mode::Sync);
engine.Put(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync);
engine.Put(scalarInt, static_cast<int>(i));
std::string s = "sample string sample string sample string";
engine.Put(stringVar, s);
engine.EndStep();
}
engine.Close();
}
void Reader(const Dims &shape, const Dims &start, const Dims &count,
const size_t steps, const adios2::Params &engineParams,
const std::string &name)
{
adios2::ADIOS adios(mpiComm);
adios2::IO io = adios.DeclareIO("Test");
io.SetEngine("ssc");
io.SetParameters(engineParams);
adios2::Engine engine = io.Open(name, adios2::Mode::Read);
size_t datasize =
std::accumulate(count.begin(), count.end(), static_cast<size_t>(1),
std::multiplies<size_t>());
std::vector<char> myChars(datasize);
std::vector<unsigned char> myUChars(datasize);
std::vector<short> myShorts(datasize);
std::vector<unsigned short> myUShorts(datasize);
std::vector<int> myInts(datasize);
std::vector<unsigned int> myUInts(datasize);
std::vector<float> myFloats(datasize);
std::vector<double> myDoubles(datasize);
std::vector<std::complex<float>> myComplexes(datasize);
std::vector<std::complex<double>> myDComplexes(datasize);
engine.LockReaderSelections();
while (true)
{
adios2::StepStatus status = engine.BeginStep(StepMode::Read, 5);
if (status == adios2::StepStatus::OK)
{
auto scalarInt = io.InquireVariable<int>("scalarInt");
auto blocksInfo =
engine.BlocksInfo(scalarInt, engine.CurrentStep());
for (const auto &bi : blocksInfo)
{
ASSERT_EQ(bi.IsValue, true);
ASSERT_EQ(bi.Value, engine.CurrentStep());
ASSERT_EQ(scalarInt.Min(), engine.CurrentStep());
ASSERT_EQ(scalarInt.Max(), engine.CurrentStep());
}
const auto &vars = io.AvailableVariables();
ASSERT_EQ(vars.size(), 12);
size_t currentStep = engine.CurrentStep();
adios2::Variable<char> bpChars =
io.InquireVariable<char>("bpChars");
adios2::Variable<unsigned char> bpUChars =
io.InquireVariable<unsigned char>("bpUChars");
adios2::Variable<short> bpShorts =
io.InquireVariable<short>("bpShorts");
adios2::Variable<unsigned short> bpUShorts =
io.InquireVariable<unsigned short>("bpUShorts");
adios2::Variable<int> bpInts = io.InquireVariable<int>("bpInts");
adios2::Variable<unsigned int> bpUInts =
io.InquireVariable<unsigned int>("bpUInts");
adios2::Variable<float> bpFloats =
io.InquireVariable<float>("bpFloats");
adios2::Variable<double> bpDoubles =
io.InquireVariable<double>("bpDoubles");
adios2::Variable<std::complex<float>> bpComplexes =
io.InquireVariable<std::complex<float>>("bpComplexes");
adios2::Variable<std::complex<double>> bpDComplexes =
io.InquireVariable<std::complex<double>>("bpDComplexes");
adios2::Variable<std::string> stringVar =
io.InquireVariable<std::string>("stringVar");
bpChars.SetSelection({start, count});
bpUChars.SetSelection({start, count});
bpShorts.SetSelection({start, count});
bpUShorts.SetSelection({start, count});
bpInts.SetSelection({start, count});
bpUInts.SetSelection({start, count});
bpFloats.SetSelection({start, count});
bpDoubles.SetSelection({start, count});
bpComplexes.SetSelection({start, count});
bpDComplexes.SetSelection({start, count});
engine.Get(bpChars, myChars.data(), adios2::Mode::Sync);
engine.Get(bpUChars, myUChars.data(), adios2::Mode::Sync);
engine.Get(bpShorts, myShorts.data(), adios2::Mode::Sync);
engine.Get(bpUShorts, myUShorts.data(), adios2::Mode::Sync);
engine.Get(bpInts, myInts.data(), adios2::Mode::Sync);
engine.Get(bpUInts, myUInts.data(), adios2::Mode::Sync);
VerifyData(myChars.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myUChars.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myShorts.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myUShorts.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myInts.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myUInts.data(), currentStep, start, count, shape,
mpiRank);
engine.Get(bpFloats, myFloats.data(), adios2::Mode::Deferred);
engine.Get(bpDoubles, myDoubles.data(), adios2::Mode::Deferred);
engine.Get(bpComplexes, myComplexes.data(), adios2::Mode::Deferred);
engine.Get(bpDComplexes, myDComplexes.data(),
adios2::Mode::Deferred);
engine.PerformGets();
VerifyData(myFloats.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myDoubles.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myComplexes.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myDComplexes.data(), currentStep, start, count, shape,
mpiRank);
std::string s;
engine.Get(stringVar, s);
engine.PerformGets();
ASSERT_EQ(s, "sample string sample string sample string");
ASSERT_EQ(stringVar.Min(),
"sample string sample string sample string");
ASSERT_EQ(stringVar.Max(),
"sample string sample string sample string");
int i;
engine.Get(scalarInt, &i);
engine.PerformGets();
ASSERT_EQ(i, currentStep);
engine.EndStep();
}
else if (status == adios2::StepStatus::EndOfStream)
{
std::cout << "[Rank " + std::to_string(mpiRank) +
"] SscTest reader end of stream!"
<< std::endl;
break;
}
}
auto attInt = io.InquireAttribute<int>("AttInt");
std::cout << "[Rank " + std::to_string(mpiRank) + "] Attribute received "
<< attInt.Data()[0] << ", expected 110" << std::endl;
ASSERT_EQ(110, attInt.Data()[0]);
ASSERT_NE(111, attInt.Data()[0]);
engine.Close();
}
TEST_F(SscEngineTest, TestSscSuperLarge)
{
std::string filename = "TestSscSuperLarge";
adios2::Params engineParams = {{"Verbose", "0"}};
int worldRank, worldSize;
MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
MPI_Comm_size(MPI_COMM_WORLD, &worldSize);
int mpiGroup = worldRank / (worldSize / 2);
MPI_Comm_split(MPI_COMM_WORLD, mpiGroup, worldRank, &mpiComm);
MPI_Comm_rank(mpiComm, &mpiRank);
MPI_Comm_size(mpiComm, &mpiSize);
Dims shape = {500, (size_t)mpiSize * 50};
Dims start = {100, (size_t)mpiRank * 50};
Dims count = {300, 50};
size_t steps = 100;
if (mpiGroup == 0)
{
Writer(shape, start, count, steps, engineParams, filename);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
if (mpiGroup == 1)
{
Reader(shape, start, count, steps, engineParams, filename);
}
MPI_Barrier(MPI_COMM_WORLD);
}
int main(int argc, char **argv)
{
MPI_Init(&argc, &argv);
int worldRank, worldSize;
MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
MPI_Comm_size(MPI_COMM_WORLD, &worldSize);
::testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
MPI_Finalize();
return result;
}
<commit_msg>reduced test size to fit CI<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*/
#include "TestSscCommon.h"
#include <adios2.h>
#include <gtest/gtest.h>
#include <mpi.h>
#include <numeric>
#include <thread>
using namespace adios2;
int mpiRank = 0;
int mpiSize = 1;
MPI_Comm mpiComm;
class SscEngineTest : public ::testing::Test
{
public:
SscEngineTest() = default;
};
void Writer(const Dims &shape, const Dims &start, const Dims &count,
const size_t steps, const adios2::Params &engineParams,
const std::string &name)
{
size_t datasize =
std::accumulate(count.begin(), count.end(), static_cast<size_t>(1),
std::multiplies<size_t>());
adios2::ADIOS adios(mpiComm);
adios2::IO io = adios.DeclareIO("Test");
io.SetEngine("ssc");
io.SetParameters(engineParams);
std::vector<char> myChars(datasize);
std::vector<unsigned char> myUChars(datasize);
std::vector<short> myShorts(datasize);
std::vector<unsigned short> myUShorts(datasize);
std::vector<int> myInts(datasize);
std::vector<unsigned int> myUInts(datasize);
std::vector<float> myFloats(datasize);
std::vector<double> myDoubles(datasize);
std::vector<std::complex<float>> myComplexes(datasize);
std::vector<std::complex<double>> myDComplexes(datasize);
auto bpChars = io.DefineVariable<char>("bpChars", shape, start, count);
auto bpUChars =
io.DefineVariable<unsigned char>("bpUChars", shape, start, count);
auto bpShorts = io.DefineVariable<short>("bpShorts", shape, start, count);
auto bpUShorts =
io.DefineVariable<unsigned short>("bpUShorts", shape, start, count);
auto bpInts = io.DefineVariable<int>("bpInts", shape, start, count);
auto bpUInts =
io.DefineVariable<unsigned int>("bpUInts", shape, start, count);
auto bpFloats = io.DefineVariable<float>("bpFloats", shape, start, count);
auto bpDoubles =
io.DefineVariable<double>("bpDoubles", shape, start, count);
auto bpComplexes = io.DefineVariable<std::complex<float>>(
"bpComplexes", shape, start, count);
auto bpDComplexes = io.DefineVariable<std::complex<double>>(
"bpDComplexes", shape, start, count);
auto scalarInt = io.DefineVariable<int>("scalarInt");
auto stringVar = io.DefineVariable<std::string>("stringVar");
io.DefineAttribute<int>("AttInt", 110);
adios2::Engine engine = io.Open(name, adios2::Mode::Write);
engine.LockWriterDefinitions();
for (size_t i = 0; i < steps; ++i)
{
engine.BeginStep();
GenData(myChars, i, start, count, shape);
GenData(myUChars, i, start, count, shape);
GenData(myShorts, i, start, count, shape);
GenData(myUShorts, i, start, count, shape);
GenData(myInts, i, start, count, shape);
GenData(myUInts, i, start, count, shape);
GenData(myFloats, i, start, count, shape);
GenData(myDoubles, i, start, count, shape);
GenData(myComplexes, i, start, count, shape);
GenData(myDComplexes, i, start, count, shape);
engine.Put(bpChars, myChars.data(), adios2::Mode::Sync);
engine.Put(bpUChars, myUChars.data(), adios2::Mode::Sync);
engine.Put(bpShorts, myShorts.data(), adios2::Mode::Sync);
engine.Put(bpUShorts, myUShorts.data(), adios2::Mode::Sync);
engine.Put(bpInts, myInts.data(), adios2::Mode::Sync);
engine.Put(bpUInts, myUInts.data(), adios2::Mode::Sync);
engine.Put(bpFloats, myFloats.data(), adios2::Mode::Sync);
engine.Put(bpDoubles, myDoubles.data(), adios2::Mode::Sync);
engine.Put(bpComplexes, myComplexes.data(), adios2::Mode::Sync);
engine.Put(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync);
engine.Put(scalarInt, static_cast<int>(i));
std::string s = "sample string sample string sample string";
engine.Put(stringVar, s);
engine.EndStep();
}
engine.Close();
}
void Reader(const Dims &shape, const Dims &start, const Dims &count,
const size_t steps, const adios2::Params &engineParams,
const std::string &name)
{
adios2::ADIOS adios(mpiComm);
adios2::IO io = adios.DeclareIO("Test");
io.SetEngine("ssc");
io.SetParameters(engineParams);
adios2::Engine engine = io.Open(name, adios2::Mode::Read);
size_t datasize =
std::accumulate(count.begin(), count.end(), static_cast<size_t>(1),
std::multiplies<size_t>());
std::vector<char> myChars(datasize);
std::vector<unsigned char> myUChars(datasize);
std::vector<short> myShorts(datasize);
std::vector<unsigned short> myUShorts(datasize);
std::vector<int> myInts(datasize);
std::vector<unsigned int> myUInts(datasize);
std::vector<float> myFloats(datasize);
std::vector<double> myDoubles(datasize);
std::vector<std::complex<float>> myComplexes(datasize);
std::vector<std::complex<double>> myDComplexes(datasize);
engine.LockReaderSelections();
while (true)
{
adios2::StepStatus status = engine.BeginStep(StepMode::Read, 5);
if (status == adios2::StepStatus::OK)
{
auto scalarInt = io.InquireVariable<int>("scalarInt");
auto blocksInfo =
engine.BlocksInfo(scalarInt, engine.CurrentStep());
for (const auto &bi : blocksInfo)
{
ASSERT_EQ(bi.IsValue, true);
ASSERT_EQ(bi.Value, engine.CurrentStep());
ASSERT_EQ(scalarInt.Min(), engine.CurrentStep());
ASSERT_EQ(scalarInt.Max(), engine.CurrentStep());
}
const auto &vars = io.AvailableVariables();
ASSERT_EQ(vars.size(), 12);
size_t currentStep = engine.CurrentStep();
adios2::Variable<char> bpChars =
io.InquireVariable<char>("bpChars");
adios2::Variable<unsigned char> bpUChars =
io.InquireVariable<unsigned char>("bpUChars");
adios2::Variable<short> bpShorts =
io.InquireVariable<short>("bpShorts");
adios2::Variable<unsigned short> bpUShorts =
io.InquireVariable<unsigned short>("bpUShorts");
adios2::Variable<int> bpInts = io.InquireVariable<int>("bpInts");
adios2::Variable<unsigned int> bpUInts =
io.InquireVariable<unsigned int>("bpUInts");
adios2::Variable<float> bpFloats =
io.InquireVariable<float>("bpFloats");
adios2::Variable<double> bpDoubles =
io.InquireVariable<double>("bpDoubles");
adios2::Variable<std::complex<float>> bpComplexes =
io.InquireVariable<std::complex<float>>("bpComplexes");
adios2::Variable<std::complex<double>> bpDComplexes =
io.InquireVariable<std::complex<double>>("bpDComplexes");
adios2::Variable<std::string> stringVar =
io.InquireVariable<std::string>("stringVar");
bpChars.SetSelection({start, count});
bpUChars.SetSelection({start, count});
bpShorts.SetSelection({start, count});
bpUShorts.SetSelection({start, count});
bpInts.SetSelection({start, count});
bpUInts.SetSelection({start, count});
bpFloats.SetSelection({start, count});
bpDoubles.SetSelection({start, count});
bpComplexes.SetSelection({start, count});
bpDComplexes.SetSelection({start, count});
engine.Get(bpChars, myChars.data(), adios2::Mode::Sync);
engine.Get(bpUChars, myUChars.data(), adios2::Mode::Sync);
engine.Get(bpShorts, myShorts.data(), adios2::Mode::Sync);
engine.Get(bpUShorts, myUShorts.data(), adios2::Mode::Sync);
engine.Get(bpInts, myInts.data(), adios2::Mode::Sync);
engine.Get(bpUInts, myUInts.data(), adios2::Mode::Sync);
VerifyData(myChars.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myUChars.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myShorts.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myUShorts.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myInts.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myUInts.data(), currentStep, start, count, shape,
mpiRank);
engine.Get(bpFloats, myFloats.data(), adios2::Mode::Deferred);
engine.Get(bpDoubles, myDoubles.data(), adios2::Mode::Deferred);
engine.Get(bpComplexes, myComplexes.data(), adios2::Mode::Deferred);
engine.Get(bpDComplexes, myDComplexes.data(),
adios2::Mode::Deferred);
engine.PerformGets();
VerifyData(myFloats.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myDoubles.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myComplexes.data(), currentStep, start, count, shape,
mpiRank);
VerifyData(myDComplexes.data(), currentStep, start, count, shape,
mpiRank);
std::string s;
engine.Get(stringVar, s);
engine.PerformGets();
ASSERT_EQ(s, "sample string sample string sample string");
ASSERT_EQ(stringVar.Min(),
"sample string sample string sample string");
ASSERT_EQ(stringVar.Max(),
"sample string sample string sample string");
int i;
engine.Get(scalarInt, &i);
engine.PerformGets();
ASSERT_EQ(i, currentStep);
engine.EndStep();
}
else if (status == adios2::StepStatus::EndOfStream)
{
std::cout << "[Rank " + std::to_string(mpiRank) +
"] SscTest reader end of stream!"
<< std::endl;
break;
}
}
auto attInt = io.InquireAttribute<int>("AttInt");
std::cout << "[Rank " + std::to_string(mpiRank) + "] Attribute received "
<< attInt.Data()[0] << ", expected 110" << std::endl;
ASSERT_EQ(110, attInt.Data()[0]);
ASSERT_NE(111, attInt.Data()[0]);
engine.Close();
}
TEST_F(SscEngineTest, TestSscSuperLarge)
{
std::string filename = "TestSscSuperLarge";
adios2::Params engineParams = {{"Verbose", "0"}};
int worldRank, worldSize;
MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
MPI_Comm_size(MPI_COMM_WORLD, &worldSize);
int mpiGroup = worldRank / (worldSize / 2);
MPI_Comm_split(MPI_COMM_WORLD, mpiGroup, worldRank, &mpiComm);
MPI_Comm_rank(mpiComm, &mpiRank);
MPI_Comm_size(mpiComm, &mpiSize);
Dims shape = {500, (size_t)mpiSize * 20};
Dims start = {100, (size_t)mpiRank * 20};
Dims count = {300, 20};
size_t steps = 100;
if (mpiGroup == 0)
{
Writer(shape, start, count, steps, engineParams, filename);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
if (mpiGroup == 1)
{
Reader(shape, start, count, steps, engineParams, filename);
}
MPI_Barrier(MPI_COMM_WORLD);
}
int main(int argc, char **argv)
{
MPI_Init(&argc, &argv);
int worldRank, worldSize;
MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
MPI_Comm_size(MPI_COMM_WORLD, &worldSize);
::testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
MPI_Finalize();
return result;
}
<|endoftext|> |
<commit_before>
#include <Arduino.h>
#include <inttypes.h>
///////////////////////////
#define NODE_COUNT 8
#define XOD_DEBUG
#define DEBUG_SERIAL Serial
#ifdef XOD_DEBUG
# define XOD_TRACE(x) DEBUG_SERIAL.print(x)
# define XOD_TRACE_LN(x) DEBUG_SERIAL.println(x)
# define XOD_TRACE_F(x) XOD_TRACE(F(x))
# define XOD_TRACE_FLN(x) XOD_TRACE_LN(F(x))
#else
# define XOD_TRACE(x)
# define XOD_TRACE_LN(x)
# define XOD_TRACE_F(x)
# define XOD_TRACE_FLN(x)
#endif
///////////////////////////
typedef double Number;
typedef bool Logic;
// OPTIMIZE: we should choose uint8_t if there are less than 255 nodes in total
// and uint32_t if there are more than 65535
typedef uint16_t NodeId;
// OPTIMIZE: we should choose a proper type with a minimal enough capacity
typedef uint16_t PinKey;
#define PIN_KEY_OFFSET_BITS 13
#define PIN_KEY_MSB_MASK (PinKey(-1) << PIN_KEY_OFFSET_BITS)
#define PIN_KEY_LSB_MASK (~PIN_KEY_MSB_MASK)
// OPTIMIZE: we should choose a proper type with a minimal enough capacity
typedef uint16_t DirtyFlags;
typedef unsigned long TimeMs;
typedef void (*EvalFuncPtr)(NodeId nid, void* state);
#define NO_NODE ((NodeId)-1)
/*=============================================================================
*
*
* Runtime
*
*
=============================================================================*/
namespace xod {
template<typename T>
struct OutputPin {
T value;
// Keep outgoing link list with terminating `NO_NODE`
NodeId* links;
};
struct PinRef {
NodeId nodeId;
PinKey pinKey;
};
extern void* storages[NODE_COUNT];
extern EvalFuncPtr evaluationFuncs[NODE_COUNT];
extern DirtyFlags dirtyFlags[NODE_COUNT];
extern NodeId topology[NODE_COUNT];
// TODO: replace with a compact list
extern TimeMs schedule[NODE_COUNT];
inline void* pinPtr(void* storage, PinKey key) {
const size_t offset = key & PIN_KEY_LSB_MASK;
return (uint8_t*)storage + offset;
}
inline DirtyFlags dirtyPinBit(PinKey key) {
const PinKey nbit = (key >> PIN_KEY_OFFSET_BITS) + 1;
return 1 << nbit;
}
inline bool isOutputDirty(NodeId nid, PinKey key) {
return dirtyFlags[nid] & dirtyPinBit(key);
}
inline bool isInputDirty(NodeId nid, PinKey key) {
PinRef* ref = (PinRef*)pinPtr(storages[nid], key);
if (ref->nodeId == NO_NODE)
return false;
return isOutputDirty(ref->nodeId, ref->pinKey);
}
inline void markPinDirty(NodeId nid, PinKey key) {
dirtyFlags[nid] |= dirtyPinBit(key);
}
inline void markNodeDirty(NodeId nid) {
dirtyFlags[nid] |= 0x1;
}
inline bool isNodeDirty(NodeId nid) {
return dirtyFlags[nid] & 0x1;
}
TimeMs transactionTime() {
return millis();
}
void setTimeout(NodeId nid, TimeMs timeout) {
schedule[nid] = transactionTime() + timeout;
}
void clearTimeout(NodeId nid) {
schedule[nid] = 0;
}
template<typename T>
T getValue(NodeId nid, PinKey key) {
PinRef* ref = (PinRef*)pinPtr(storages[nid], key);
if (ref->nodeId == NO_NODE)
return (T)0;
return *(T*)pinPtr(storages[ref->nodeId], ref->pinKey);
}
Number getNumber(NodeId nid, PinKey key) {
return getValue<Number>(nid, key);
}
Logic getLogic(NodeId nid, PinKey key) {
return getValue<Logic>(nid, key);
}
template<typename T>
void emitValue(NodeId nid, PinKey key, T value) {
OutputPin<T>* outputPin = (OutputPin<T>*)pinPtr(storages[nid], key);
outputPin->value = value;
markPinDirty(nid, key);
NodeId* linkedNode = outputPin->links;
while (*linkedNode != NO_NODE) {
markNodeDirty(*linkedNode++);
}
}
void emitNumber(NodeId nid, PinKey key, Number value) {
emitValue<Number>(nid, key, value);
}
void emitLogic(NodeId nid, PinKey key, Logic value) {
emitValue<Logic>(nid, key, value);
}
template<typename T>
void reemitValue(NodeId nid, PinKey key) {
OutputPin<T>* outputPin = (OutputPin<T>*)pinPtr(storages[nid], key);
emitValue<T>(nid, key, outputPin->value);
}
void reemitNumber(NodeId nid, PinKey key) {
reemitValue<Number>(nid, key);
}
void reemitLogic(NodeId nid, PinKey key) {
reemitValue<Logic>(nid, key);
}
void evaluateNode(NodeId nid) {
XOD_TRACE_F("eval #");
XOD_TRACE_LN(nid);
EvalFuncPtr eval = evaluationFuncs[nid];
eval(nid, storages[nid]);
}
void runTransaction() {
XOD_TRACE_FLN("Transaction started");
for (NodeId nid : topology) {
if (isNodeDirty(nid))
evaluateNode(nid);
}
memset(dirtyFlags, 0, sizeof(dirtyFlags));
XOD_TRACE_FLN("Transaction completed");
}
void idle() {
TimeMs now = millis();
for (NodeId nid = 0; nid < NODE_COUNT; ++nid) {
TimeMs t = schedule[nid];
if (t && t <= now) {
markNodeDirty(nid);
clearTimeout(nid);
return;
}
}
}
}
/*=============================================================================
*
*
* Native node implementations
*
*
=============================================================================*/
namespace xod { namespace core { namespace real_to_logic {
struct State {
};
struct Storage {
State state;
PinRef input_IN;
OutputPin<Logic> output_OUT;
};
enum Inputs : PinKey {
IN = offsetof(Storage, input_IN)
};
enum Outputs : PinKey {
OUT = offsetof(Storage, output_OUT) | (0 << PIN_KEY_OFFSET_BITS)
};
void evaluate(NodeId nid, State* state) {
emitLogic(nid, Outputs::OUT, getNumber(nid, Inputs::IN));
}
}}}
namespace xod { namespace core { namespace logic_to_real {
struct State {
};
struct Storage {
State state;
PinRef input_IN;
OutputPin<Number> output_OUT;
};
enum Inputs : PinKey {
IN = offsetof(Storage, input_IN)
};
enum Outputs : PinKey {
OUT = offsetof(Storage, output_OUT) | (0 << PIN_KEY_OFFSET_BITS)
};
void evaluate(NodeId nid, State* state) {
emitNumber(nid, Outputs::OUT, getLogic(nid, Inputs::IN));
}
}}}
namespace xod { namespace core { namespace digital_output {
struct State {
};
struct Storage {
State state;
PinRef input_VAL;
PinRef input_PIN;
};
enum Inputs : PinKey {
VAL = offsetof(Storage, input_VAL),
PIN = offsetof(Storage, input_PIN)
};
enum Outputs : PinKey {
// no outputs
};
void evaluate(NodeId nid, State* state) {
const int pin = (int)getNumber(nid, Inputs::PIN);
const bool val = getLogic(nid, Inputs::VAL);
if (isInputDirty(nid, Inputs::PIN)) {
::pinMode(pin, OUTPUT);
}
::digitalWrite(pin, val);
}
}}}
namespace xod { namespace core { namespace multiply {
struct State {
};
struct Storage {
State state;
PinRef input_IN1;
PinRef input_IN2;
OutputPin<Number> output_OUT;
};
enum Inputs : PinKey {
IN1 = offsetof(Storage, input_IN1),
IN2 = offsetof(Storage, input_IN2)
};
enum Outputs : PinKey {
OUT = offsetof(Storage, output_OUT) | (0 << PIN_KEY_OFFSET_BITS)
};
void evaluate(NodeId nid, State* state) {
const Number in1 = getNumber(nid, Inputs::IN1);
const Number in2 = getNumber(nid, Inputs::IN2);
emitNumber(nid, Outputs::OUT, in1 * in2);
}
}}}
namespace xod { namespace core { namespace latch {
struct State {
bool value;
};
struct Storage {
State state;
PinRef input_TGL;
PinRef input_SET;
PinRef input_RST;
OutputPin<Logic> output_OUT;
};
enum Inputs : PinKey {
TGL = offsetof(Storage, input_TGL),
SET = offsetof(Storage, input_SET),
RST = offsetof(Storage, input_RST)
};
enum Outputs : PinKey {
OUT = offsetof(Storage, output_OUT)
};
void evaluate(NodeId nid, State* state) {
if (isInputDirty(nid, Inputs::RST)) {
state->value = false;
} else if (isInputDirty(nid, Inputs::SET)) {
state->value = true;
} else {
state->value = !state->value;
}
emitLogic(nid, Outputs::OUT, state->value);
}
}}}
namespace xod { namespace core { namespace clock {
struct State {
TimeMs nextTrig;
};
struct Storage {
State state;
PinRef input_IVAL;
OutputPin<Logic> output_TICK;
};
enum Inputs : PinKey {
IVAL = offsetof(Storage, input_IVAL)
};
enum Outputs : PinKey {
TICK = offsetof(Storage, output_TICK) | (0 << PIN_KEY_OFFSET_BITS)
};
void evaluate(NodeId nid, State* state) {
TimeMs tNow = transactionTime();
TimeMs dt = getNumber(nid, Inputs::IVAL) * 1000;
TimeMs tNext = tNow + dt;
if (isInputDirty(nid, Inputs::IVAL)) {
if (dt == 0) {
state->nextTrig = 0;
clearTimeout(nid);
} else if (state->nextTrig < tNow || state->nextTrig > tNext) {
state->nextTrig = tNext;
setTimeout(nid, dt);
}
} else {
// It was a scheduled tick
emitLogic(nid, Outputs::TICK, 1);
state->nextTrig = tNext;
setTimeout(nid, dt);
}
}
}}}
namespace xod { namespace core { namespace constant_number {
struct State {
};
struct Storage {
State state;
OutputPin<Number> output_VAL;
};
enum Inputs : PinKey {
};
enum Outputs : PinKey {
VAL = offsetof(Storage, output_VAL) | (0 << PIN_KEY_OFFSET_BITS)
};
void evaluate(NodeId nid, State* state) {
reemitNumber(nid, Outputs::VAL);
}
}}}
/*=============================================================================
*
*
* Program graph
*
*
=============================================================================*/
namespace xod {
NodeId links_0_VAL[] = { 1, NO_NODE };
core::constant_number::Storage storage_0 = {
{ }, // state
{ 0.2, links_0_VAL } // output_VAL
};
NodeId links_1_TICK[] = { 2, NO_NODE };
core::clock::Storage storage_1 = {
{ }, // state
{ NodeId(0), core::constant_number::Outputs::VAL }, // input_IVAL
{ 0, links_1_TICK } // output_TICK
};
NodeId links_2_OUT[] = { 3, NO_NODE };
core::latch::Storage storage_2 = {
{ }, // state
{ 1, core::clock::Outputs::TICK }, // input_TGL
{ NO_NODE, 0 }, // input_SET
{ NO_NODE, 0 }, // input_RST
{ 0, links_2_OUT } // output_OUT
};
NodeId links_3_OUT[] = { 4, NO_NODE };
core::logic_to_real::Storage storage_3 = {
{ }, // state
{ NodeId(2), core::latch::Outputs::OUT }, // input_IN
{ 0, links_3_OUT } // output_OUT
};
NodeId links_4_OUT[] = { 5, NO_NODE };
core::multiply::Storage storage_4 = {
{ }, // state
{ NodeId(3), core::logic_to_real::Outputs::OUT }, // input_IN1
{ NodeId(3), core::logic_to_real::Outputs::OUT }, // input_IN2
{ 0, links_4_OUT } // output_OUT
};
NodeId links_5_OUT[] = { 7, NO_NODE };
core::real_to_logic::Storage storage_5 = {
{ }, // state
{ NodeId(4), core::multiply::Outputs::OUT }, // input_IN
{ 0, links_5_OUT } // output_OUT
};
NodeId links_6_VAL[] = { 7, NO_NODE };
core::constant_number::Storage storage_6 = {
{ }, // state
{ 13, links_6_VAL } // output_VAL
};
NodeId links_7_VAL[] = { NO_NODE };
core::digital_output::Storage storage_7 = {
{ }, // state
{ NodeId(5), core::real_to_logic::Outputs::OUT }, // input_VAL
{ NodeId(6), core::constant_number::Outputs::VAL } // input_PIN
};
void* storages[NODE_COUNT] = {
&storage_0,
&storage_1,
&storage_2,
&storage_3,
&storage_4,
&storage_5,
&storage_6,
&storage_7
};
EvalFuncPtr evaluationFuncs[NODE_COUNT] = {
(EvalFuncPtr)&core::constant_number::evaluate,
(EvalFuncPtr)&core::clock::evaluate,
(EvalFuncPtr)&core::latch::evaluate,
(EvalFuncPtr)&core::logic_to_real::evaluate,
(EvalFuncPtr)&core::multiply::evaluate,
(EvalFuncPtr)&core::real_to_logic::evaluate,
(EvalFuncPtr)&core::constant_number::evaluate,
(EvalFuncPtr)&core::digital_output::evaluate
};
DirtyFlags dirtyFlags[NODE_COUNT] = {
0xff, 0, 0, 0, 0, 0, 0xff, 0
};
NodeId topology[NODE_COUNT] = {
0, 1, 2, 3, 4, 5, 6, 7
};
TimeMs schedule[NODE_COUNT] = { 0 };
}
/*=============================================================================
*
*
* Entry point
*
*
=============================================================================*/
void setup() {
// FIXME: looks like there is a rounding bug. Waiting for 1 second fights it
delay(1000);
#ifdef XOD_DEBUG
DEBUG_SERIAL.begin(9600);
#endif
XOD_TRACE_FLN("Program started");
XOD_TRACE_F("NODE_COUNT = ");
XOD_TRACE_LN(NODE_COUNT);
XOD_TRACE_F("sizeof(NodeId) = ");
XOD_TRACE_LN(sizeof(NodeId));
XOD_TRACE_F("sizeof(PinKey) = ");
XOD_TRACE_LN(sizeof(PinKey));
XOD_TRACE_F("sizeof(DirtyFlags) = ");
XOD_TRACE_LN(sizeof(DirtyFlags));
}
void loop() {
xod::idle();
xod::runTransaction();
}
<commit_msg>refactor(arduino): rearrange sample code blocks<commit_after>
/*=============================================================================
*
*
* Configuration
*
*
=============================================================================*/
#define NODE_COUNT 8
#define MAX_OUTPUT_COUNT 3
// Uncomment to trace the program in the Serial Monitor
//#define XOD_DEBUG
/*=============================================================================
*
*
* Runtime
*
*
=============================================================================*/
#include <Arduino.h>
#include <inttypes.h>
//----------------------------------------------------------------------------
// Debug routines
//----------------------------------------------------------------------------
#ifndef DEBUG_SERIAL
# define DEBUG_SERIAL Serial
#endif
#ifdef XOD_DEBUG
# define XOD_TRACE(x) DEBUG_SERIAL.print(x)
# define XOD_TRACE_LN(x) DEBUG_SERIAL.println(x)
# define XOD_TRACE_F(x) XOD_TRACE(F(x))
# define XOD_TRACE_FLN(x) XOD_TRACE_LN(F(x))
#else
# define XOD_TRACE(x)
# define XOD_TRACE_LN(x)
# define XOD_TRACE_F(x)
# define XOD_TRACE_FLN(x)
#endif
//----------------------------------------------------------------------------
// Type definitions
//----------------------------------------------------------------------------
#define PIN_KEY_OFFSET_BITS (16 - MAX_OUTPUT_COUNT)
#define NO_NODE ((NodeId)-1)
namespace xod {
typedef double Number;
typedef bool Logic;
// OPTIMIZE: we should choose uint8_t if there are less than 255 nodes in total
// and uint32_t if there are more than 65535
typedef uint16_t NodeId;
// OPTIMIZE: we should choose a proper type with a minimal enough capacity
typedef uint16_t PinKey;
// OPTIMIZE: we should choose a proper type with a minimal enough capacity
typedef uint16_t DirtyFlags;
typedef unsigned long TimeMs;
typedef void (*EvalFuncPtr)(NodeId nid, void* state);
}
//----------------------------------------------------------------------------
// Engine
//----------------------------------------------------------------------------
namespace xod {
extern void* storages[NODE_COUNT];
extern EvalFuncPtr evaluationFuncs[NODE_COUNT];
extern DirtyFlags dirtyFlags[NODE_COUNT];
extern NodeId topology[NODE_COUNT];
template<typename T>
struct OutputPin {
T value;
// Keep outgoing link list with terminating `NO_NODE`
NodeId* links;
};
struct PinRef {
NodeId nodeId;
PinKey pinKey;
};
// TODO: replace with a compact list
extern TimeMs schedule[NODE_COUNT];
inline void* pinPtr(void* storage, PinKey key) {
const size_t offset = key & ~(PinKey(-1) << PIN_KEY_OFFSET_BITS);
return (uint8_t*)storage + offset;
}
inline DirtyFlags dirtyPinBit(PinKey key) {
const PinKey nbit = (key >> PIN_KEY_OFFSET_BITS) + 1;
return 1 << nbit;
}
inline bool isOutputDirty(NodeId nid, PinKey key) {
return dirtyFlags[nid] & dirtyPinBit(key);
}
inline bool isInputDirty(NodeId nid, PinKey key) {
PinRef* ref = (PinRef*)pinPtr(storages[nid], key);
if (ref->nodeId == NO_NODE)
return false;
return isOutputDirty(ref->nodeId, ref->pinKey);
}
inline void markPinDirty(NodeId nid, PinKey key) {
dirtyFlags[nid] |= dirtyPinBit(key);
}
inline void markNodeDirty(NodeId nid) {
dirtyFlags[nid] |= 0x1;
}
inline bool isNodeDirty(NodeId nid) {
return dirtyFlags[nid] & 0x1;
}
TimeMs transactionTime() {
return millis();
}
void setTimeout(NodeId nid, TimeMs timeout) {
schedule[nid] = transactionTime() + timeout;
}
void clearTimeout(NodeId nid) {
schedule[nid] = 0;
}
template<typename T>
T getValue(NodeId nid, PinKey key) {
PinRef* ref = (PinRef*)pinPtr(storages[nid], key);
if (ref->nodeId == NO_NODE)
return (T)0;
return *(T*)pinPtr(storages[ref->nodeId], ref->pinKey);
}
Number getNumber(NodeId nid, PinKey key) {
return getValue<Number>(nid, key);
}
Logic getLogic(NodeId nid, PinKey key) {
return getValue<Logic>(nid, key);
}
template<typename T>
void emitValue(NodeId nid, PinKey key, T value) {
OutputPin<T>* outputPin = (OutputPin<T>*)pinPtr(storages[nid], key);
outputPin->value = value;
markPinDirty(nid, key);
NodeId* linkedNode = outputPin->links;
while (*linkedNode != NO_NODE) {
markNodeDirty(*linkedNode++);
}
}
void emitNumber(NodeId nid, PinKey key, Number value) {
emitValue<Number>(nid, key, value);
}
void emitLogic(NodeId nid, PinKey key, Logic value) {
emitValue<Logic>(nid, key, value);
}
template<typename T>
void reemitValue(NodeId nid, PinKey key) {
OutputPin<T>* outputPin = (OutputPin<T>*)pinPtr(storages[nid], key);
emitValue<T>(nid, key, outputPin->value);
}
void reemitNumber(NodeId nid, PinKey key) {
reemitValue<Number>(nid, key);
}
void reemitLogic(NodeId nid, PinKey key) {
reemitValue<Logic>(nid, key);
}
void evaluateNode(NodeId nid) {
XOD_TRACE_F("eval #");
XOD_TRACE_LN(nid);
EvalFuncPtr eval = evaluationFuncs[nid];
eval(nid, storages[nid]);
}
void runTransaction() {
XOD_TRACE_FLN("Transaction started");
for (NodeId nid : topology) {
if (isNodeDirty(nid))
evaluateNode(nid);
}
memset(dirtyFlags, 0, sizeof(dirtyFlags));
XOD_TRACE_FLN("Transaction completed");
}
void idle() {
TimeMs now = millis();
for (NodeId nid = 0; nid < NODE_COUNT; ++nid) {
TimeMs t = schedule[nid];
if (t && t <= now) {
markNodeDirty(nid);
clearTimeout(nid);
return;
}
}
}
}
//----------------------------------------------------------------------------
// Entry point
//----------------------------------------------------------------------------
void setup() {
// FIXME: looks like there is a rounding bug. Waiting for 1 second fights it
delay(1000);
#ifdef XOD_DEBUG
DEBUG_SERIAL.begin(9600);
#endif
XOD_TRACE_FLN("Program started");
XOD_TRACE_F("NODE_COUNT = ");
XOD_TRACE_LN(NODE_COUNT);
XOD_TRACE_F("sizeof(NodeId) = ");
XOD_TRACE_LN(sizeof(NodeId));
XOD_TRACE_F("sizeof(PinKey) = ");
XOD_TRACE_LN(sizeof(PinKey));
XOD_TRACE_F("sizeof(DirtyFlags) = ");
XOD_TRACE_LN(sizeof(DirtyFlags));
}
void loop() {
xod::idle();
xod::runTransaction();
}
/*=============================================================================
*
*
* Native node implementations
*
*
=============================================================================*/
namespace xod { namespace core { namespace real_to_logic {
struct State {
};
struct Storage {
State state;
PinRef input_IN;
OutputPin<Logic> output_OUT;
};
enum Inputs : PinKey {
IN = offsetof(Storage, input_IN)
};
enum Outputs : PinKey {
OUT = offsetof(Storage, output_OUT) | (0 << PIN_KEY_OFFSET_BITS)
};
void evaluate(NodeId nid, State* state) {
emitLogic(nid, Outputs::OUT, getNumber(nid, Inputs::IN));
}
}}}
namespace xod { namespace core { namespace logic_to_real {
struct State {
};
struct Storage {
State state;
PinRef input_IN;
OutputPin<Number> output_OUT;
};
enum Inputs : PinKey {
IN = offsetof(Storage, input_IN)
};
enum Outputs : PinKey {
OUT = offsetof(Storage, output_OUT) | (0 << PIN_KEY_OFFSET_BITS)
};
void evaluate(NodeId nid, State* state) {
emitNumber(nid, Outputs::OUT, getLogic(nid, Inputs::IN));
}
}}}
namespace xod { namespace core { namespace digital_output {
struct State {
};
struct Storage {
State state;
PinRef input_VAL;
PinRef input_PIN;
};
enum Inputs : PinKey {
VAL = offsetof(Storage, input_VAL),
PIN = offsetof(Storage, input_PIN)
};
enum Outputs : PinKey {
// no outputs
};
void evaluate(NodeId nid, State* state) {
const int pin = (int)getNumber(nid, Inputs::PIN);
const bool val = getLogic(nid, Inputs::VAL);
if (isInputDirty(nid, Inputs::PIN)) {
::pinMode(pin, OUTPUT);
}
::digitalWrite(pin, val);
}
}}}
namespace xod { namespace core { namespace multiply {
struct State {
};
struct Storage {
State state;
PinRef input_IN1;
PinRef input_IN2;
OutputPin<Number> output_OUT;
};
enum Inputs : PinKey {
IN1 = offsetof(Storage, input_IN1),
IN2 = offsetof(Storage, input_IN2)
};
enum Outputs : PinKey {
OUT = offsetof(Storage, output_OUT) | (0 << PIN_KEY_OFFSET_BITS)
};
void evaluate(NodeId nid, State* state) {
const Number in1 = getNumber(nid, Inputs::IN1);
const Number in2 = getNumber(nid, Inputs::IN2);
emitNumber(nid, Outputs::OUT, in1 * in2);
}
}}}
namespace xod { namespace core { namespace latch {
struct State {
bool value;
};
struct Storage {
State state;
PinRef input_TGL;
PinRef input_SET;
PinRef input_RST;
OutputPin<Logic> output_OUT;
};
enum Inputs : PinKey {
TGL = offsetof(Storage, input_TGL),
SET = offsetof(Storage, input_SET),
RST = offsetof(Storage, input_RST)
};
enum Outputs : PinKey {
OUT = offsetof(Storage, output_OUT)
};
void evaluate(NodeId nid, State* state) {
if (isInputDirty(nid, Inputs::RST)) {
state->value = false;
} else if (isInputDirty(nid, Inputs::SET)) {
state->value = true;
} else {
state->value = !state->value;
}
emitLogic(nid, Outputs::OUT, state->value);
}
}}}
namespace xod { namespace core { namespace clock {
struct State {
TimeMs nextTrig;
};
struct Storage {
State state;
PinRef input_IVAL;
OutputPin<Logic> output_TICK;
};
enum Inputs : PinKey {
IVAL = offsetof(Storage, input_IVAL)
};
enum Outputs : PinKey {
TICK = offsetof(Storage, output_TICK) | (0 << PIN_KEY_OFFSET_BITS)
};
void evaluate(NodeId nid, State* state) {
TimeMs tNow = transactionTime();
TimeMs dt = getNumber(nid, Inputs::IVAL) * 1000;
TimeMs tNext = tNow + dt;
if (isInputDirty(nid, Inputs::IVAL)) {
if (dt == 0) {
state->nextTrig = 0;
clearTimeout(nid);
} else if (state->nextTrig < tNow || state->nextTrig > tNext) {
state->nextTrig = tNext;
setTimeout(nid, dt);
}
} else {
// It was a scheduled tick
emitLogic(nid, Outputs::TICK, 1);
state->nextTrig = tNext;
setTimeout(nid, dt);
}
}
}}}
namespace xod { namespace core { namespace constant_number {
struct State {
};
struct Storage {
State state;
OutputPin<Number> output_VAL;
};
enum Inputs : PinKey {
};
enum Outputs : PinKey {
VAL = offsetof(Storage, output_VAL) | (0 << PIN_KEY_OFFSET_BITS)
};
void evaluate(NodeId nid, State* state) {
reemitNumber(nid, Outputs::VAL);
}
}}}
/*=============================================================================
*
*
* Program graph
*
*
=============================================================================*/
namespace xod {
NodeId links_0_VAL[] = { 1, NO_NODE };
core::constant_number::Storage storage_0 = {
{ }, // state
{ 0.2, links_0_VAL } // output_VAL
};
NodeId links_1_TICK[] = { 2, NO_NODE };
core::clock::Storage storage_1 = {
{ }, // state
{ NodeId(0), core::constant_number::Outputs::VAL }, // input_IVAL
{ 0, links_1_TICK } // output_TICK
};
NodeId links_2_OUT[] = { 3, NO_NODE };
core::latch::Storage storage_2 = {
{ }, // state
{ 1, core::clock::Outputs::TICK }, // input_TGL
{ NO_NODE, 0 }, // input_SET
{ NO_NODE, 0 }, // input_RST
{ 0, links_2_OUT } // output_OUT
};
NodeId links_3_OUT[] = { 4, NO_NODE };
core::logic_to_real::Storage storage_3 = {
{ }, // state
{ NodeId(2), core::latch::Outputs::OUT }, // input_IN
{ 0, links_3_OUT } // output_OUT
};
NodeId links_4_OUT[] = { 5, NO_NODE };
core::multiply::Storage storage_4 = {
{ }, // state
{ NodeId(3), core::logic_to_real::Outputs::OUT }, // input_IN1
{ NodeId(3), core::logic_to_real::Outputs::OUT }, // input_IN2
{ 0, links_4_OUT } // output_OUT
};
NodeId links_5_OUT[] = { 7, NO_NODE };
core::real_to_logic::Storage storage_5 = {
{ }, // state
{ NodeId(4), core::multiply::Outputs::OUT }, // input_IN
{ 0, links_5_OUT } // output_OUT
};
NodeId links_6_VAL[] = { 7, NO_NODE };
core::constant_number::Storage storage_6 = {
{ }, // state
{ 13, links_6_VAL } // output_VAL
};
NodeId links_7_VAL[] = { NO_NODE };
core::digital_output::Storage storage_7 = {
{ }, // state
{ NodeId(5), core::real_to_logic::Outputs::OUT }, // input_VAL
{ NodeId(6), core::constant_number::Outputs::VAL } // input_PIN
};
void* storages[NODE_COUNT] = {
&storage_0,
&storage_1,
&storage_2,
&storage_3,
&storage_4,
&storage_5,
&storage_6,
&storage_7
};
EvalFuncPtr evaluationFuncs[NODE_COUNT] = {
(EvalFuncPtr)&core::constant_number::evaluate,
(EvalFuncPtr)&core::clock::evaluate,
(EvalFuncPtr)&core::latch::evaluate,
(EvalFuncPtr)&core::logic_to_real::evaluate,
(EvalFuncPtr)&core::multiply::evaluate,
(EvalFuncPtr)&core::real_to_logic::evaluate,
(EvalFuncPtr)&core::constant_number::evaluate,
(EvalFuncPtr)&core::digital_output::evaluate
};
DirtyFlags dirtyFlags[NODE_COUNT] = {
0xff, 0, 0, 0, 0, 0, 0xff, 0
};
NodeId topology[NODE_COUNT] = {
0, 1, 2, 3, 4, 5, 6, 7
};
TimeMs schedule[NODE_COUNT] = { 0 };
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2019 PaddlePaddle 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 "paddle/fluid/operators/batch_norm_op.h"
namespace paddle {
namespace operators {
template <typename T>
class BatchNormGradMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
protected:
std::unique_ptr<T> Apply() const override {
auto *op = new T();
op->SetType(this->ForwardOpType() + "_grad");
op->SetInput("X", this->Input("X"));
op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y"));
op->SetInput("Scale", this->Input("Scale"));
op->SetInput("Bias", this->Input("Bias"));
op->SetInput("SavedMean", this->Output("SavedMean"));
op->SetInput("SavedVariance", this->Output("SavedVariance"));
// used when setting use_global_stats True during training
if (boost::get<bool>(this->GetAttr("use_global_stats"))) {
op->SetInput("Mean", this->Output("MeanOut"));
op->SetInput("Variance", this->Output("VarianceOut"));
}
op->SetAttrMap(this->Attrs());
op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
op->SetOutput(framework::GradVarName("Scale"), this->InputGrad("Scale"));
op->SetOutput(framework::GradVarName("Bias"), this->InputGrad("Bias"));
return std::unique_ptr<T>(op);
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(sync_batch_norm, ops::BatchNormOp, ops::BatchNormOpMaker,
ops::BatchNormOpInferVarType,
ops::BatchNormGradMaker<paddle::framework::OpDesc>,
ops::BatchNormGradMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(sync_batch_norm_grad, ops::BatchNormGradOp);
<commit_msg>fix syn bn grad maker, test=develop, test=document_fix (#21317)<commit_after>/* Copyright (c) 2019 PaddlePaddle 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 "paddle/fluid/operators/batch_norm_op.h"
namespace paddle {
namespace operators {
template <typename T>
class SyncBatchNormGradMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
protected:
std::unique_ptr<T> Apply() const override {
auto *op = new T();
op->SetType(this->ForwardOpType() + "_grad");
op->SetInput("X", this->Input("X"));
op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y"));
op->SetInput("Scale", this->Input("Scale"));
op->SetInput("Bias", this->Input("Bias"));
op->SetInput("SavedMean", this->Output("SavedMean"));
op->SetInput("SavedVariance", this->Output("SavedVariance"));
// used when setting use_global_stats True during training
if (boost::get<bool>(this->GetAttr("use_global_stats"))) {
op->SetInput("Mean", this->Output("MeanOut"));
op->SetInput("Variance", this->Output("VarianceOut"));
}
op->SetAttrMap(this->Attrs());
op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
op->SetOutput(framework::GradVarName("Scale"), this->InputGrad("Scale"));
op->SetOutput(framework::GradVarName("Bias"), this->InputGrad("Bias"));
return std::unique_ptr<T>(op);
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(sync_batch_norm, ops::BatchNormOp, ops::BatchNormOpMaker,
ops::BatchNormOpInferVarType,
ops::SyncBatchNormGradMaker<paddle::framework::OpDesc>,
ops::SyncBatchNormGradMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(sync_batch_norm_grad, ops::BatchNormGradOp);
<|endoftext|> |
<commit_before>// Pass -DGHEAP_CPP11 to compiler for gheap_cpp11.hpp tests,
// otherwise gheap_cpp03.hpp will be tested.
#include "gheap.hpp"
#include "gpriority_queue.hpp"
#include <algorithm> // for *_heap(), copy(), move()
#include <cstdlib> // for rand(), srand()
#include <ctime> // for clock()
#include <iostream>
#include <memory> // for *_temporary_buffer(), raw_storage_iterator()
#include <queue> // for priority_queue
#include <utility> // for pair
#include <vector> // for vector
using namespace std;
namespace {
double get_time()
{
return (double)clock() / CLOCKS_PER_SEC;
}
void print_performance(const double t, const size_t m)
{
cout << ": " << (m / t / 1000) << " Kops/s" << endl;
}
template <class T>
void init_array(T *const a, const size_t n)
{
for (size_t i = 0; i < n; ++i) {
a[i] = rand();
}
}
// Dummy wrapper for STL heap.
struct stl_heap
{
template <class RandomAccessIterator>
static void make_heap(const RandomAccessIterator &first,
const RandomAccessIterator &last)
{
std::make_heap(first, last);
}
template <class RandomAccessIterator>
static void sort_heap(const RandomAccessIterator &first,
const RandomAccessIterator &last)
{
std::sort_heap(first, last);
}
};
template <class T, class Heap>
void heapsort(T *const a, const size_t n)
{
Heap::make_heap(a, a + n);
Heap::sort_heap(a, a + n);
}
template <class T, class Heap>
void perftest_heapsort(T *const a, const size_t n, const size_t m)
{
cout << "perftest_heapsort(n=" << n << ", m=" << m << ")";
double total_time = 0;
for (size_t i = 0; i < m / n; ++i) {
init_array(a, n);
double start = get_time();
heapsort<T, Heap>(a, n);
double end = get_time();
total_time += end - start;
}
print_performance(total_time, m);
}
template <class T>
void move_items(T *const src, const size_t n, T *const dst)
{
#ifdef GHEAP_CPP11
move(src, src + n, dst);
#else
copy(src, src + n, dst);
for (size_t i = 0; i < n; ++i) {
src[i].~T();
}
#endif
}
template <class T, class Heap>
void nway_mergesort(T *const a, const size_t n, T *const tmp_buf,
const size_t input_ranges_count)
{
assert(input_ranges_count > 0);
const size_t critical_range_size = (1 << 18) - 1;
if (n <= critical_range_size) {
heapsort<T, Heap>(a, n);
return;
}
const size_t range_size = n / input_ranges_count;
const size_t last_full_range = n - n % range_size;
vector<pair<T *, T *> > input_ranges;
for (size_t i = 0; i < last_full_range; i += range_size) {
nway_mergesort<T, Heap>(a + i, range_size, tmp_buf, input_ranges_count);
input_ranges.push_back(pair<T *, T *>(a + i, a + (i + range_size)));
}
if (n > last_full_range) {
nway_mergesort<T, Heap>(a + last_full_range, n - last_full_range, tmp_buf,
input_ranges_count);
input_ranges.push_back(pair<T *, T *>(a + last_full_range, a + n));
}
Heap::nway_merge(input_ranges.begin(), input_ranges.end(),
raw_storage_iterator<T *, T>(tmp_buf));
move_items(tmp_buf, n, a);
}
template <class T, class Heap>
void perftest_nway_mergesort(T *const a, const size_t n, const size_t m)
{
const size_t input_ranges_count = 15;
cout << "perftest_nway_mergesort(n=" << n << ", m=" << m <<
", input_ranges_count=" << input_ranges_count << ")";
double total_time = 0;
for (size_t i = 0; i < m / n; ++i) {
init_array(a, n);
double start = get_time();
const pair<T *, ptrdiff_t> tmp_buf = get_temporary_buffer<T>(n);
nway_mergesort<T, Heap>(a, n, tmp_buf.first, input_ranges_count);
return_temporary_buffer(tmp_buf.first);
double end = get_time();
total_time += end - start;
}
print_performance(total_time, m);
}
template <class T, class PriorityQueue>
void perftest_priority_queue(T *const a, const size_t n, const size_t m)
{
cout << "perftest_priority_queue(n=" << n << ", m=" << m << ")";
init_array(a, n);
PriorityQueue q(a, a + n);
double start = get_time();
for (size_t i = 0; i < m; ++i) {
q.pop();
q.push(rand());
}
double end = get_time();
print_performance(end - start, m);
}
template <class T, class Heap, class PriorityQueue>
void perftest_gheap(T *const a, const size_t max_n)
{
size_t n = max_n;
while (n > 0) {
perftest_heapsort<T, Heap>(a, n, max_n);
perftest_nway_mergesort<T, Heap>(a, n, max_n);
perftest_priority_queue<T, PriorityQueue>(a, n, max_n);
n >>= 1;
}
}
template <class T>
void perftest_stl_heap(T *const a, const size_t max_n)
{
size_t n = max_n;
while (n > 0) {
perftest_heapsort<T, stl_heap>(a, n, max_n);
// stl heap doesn't provide nway_merge(),
// so skipping perftest_nway_mergesort().
perftest_priority_queue<T, priority_queue<T> >(a, n, max_n);
n >>= 1;
}
}
} // end of anonymous namespace.
int main(void)
{
static const size_t MAX_N = 32 * 1024 * 1024;
static const size_t FANOUT = 2;
static const size_t PAGE_CHUNKS = 1;
typedef size_t T;
cout << "fanout=" << FANOUT << ", page_chunks=" << PAGE_CHUNKS <<
", max_n=" << MAX_N << endl;
srand(0);
T *const a = new T[MAX_N];
cout << "* STL heap" << endl;
// perftest_stl_heap(a, MAX_N);
cout << "* gheap" << endl;
perftest_gheap<T, gheap<FANOUT, PAGE_CHUNKS>,
gpriority_queue<FANOUT, PAGE_CHUNKS, T> >(a, MAX_N);
delete[] a;
}
<commit_msg>uncommented perftest for stl heap<commit_after>// Pass -DGHEAP_CPP11 to compiler for gheap_cpp11.hpp tests,
// otherwise gheap_cpp03.hpp will be tested.
#include "gheap.hpp"
#include "gpriority_queue.hpp"
#include <algorithm> // for *_heap(), copy(), move()
#include <cstdlib> // for rand(), srand()
#include <ctime> // for clock()
#include <iostream>
#include <memory> // for *_temporary_buffer(), raw_storage_iterator()
#include <queue> // for priority_queue
#include <utility> // for pair
#include <vector> // for vector
using namespace std;
namespace {
double get_time()
{
return (double)clock() / CLOCKS_PER_SEC;
}
void print_performance(const double t, const size_t m)
{
cout << ": " << (m / t / 1000) << " Kops/s" << endl;
}
template <class T>
void init_array(T *const a, const size_t n)
{
for (size_t i = 0; i < n; ++i) {
a[i] = rand();
}
}
// Dummy wrapper for STL heap.
struct stl_heap
{
template <class RandomAccessIterator>
static void make_heap(const RandomAccessIterator &first,
const RandomAccessIterator &last)
{
std::make_heap(first, last);
}
template <class RandomAccessIterator>
static void sort_heap(const RandomAccessIterator &first,
const RandomAccessIterator &last)
{
std::sort_heap(first, last);
}
};
template <class T, class Heap>
void heapsort(T *const a, const size_t n)
{
Heap::make_heap(a, a + n);
Heap::sort_heap(a, a + n);
}
template <class T, class Heap>
void perftest_heapsort(T *const a, const size_t n, const size_t m)
{
cout << "perftest_heapsort(n=" << n << ", m=" << m << ")";
double total_time = 0;
for (size_t i = 0; i < m / n; ++i) {
init_array(a, n);
double start = get_time();
heapsort<T, Heap>(a, n);
double end = get_time();
total_time += end - start;
}
print_performance(total_time, m);
}
template <class T>
void move_items(T *const src, const size_t n, T *const dst)
{
#ifdef GHEAP_CPP11
move(src, src + n, dst);
#else
copy(src, src + n, dst);
for (size_t i = 0; i < n; ++i) {
src[i].~T();
}
#endif
}
template <class T, class Heap>
void nway_mergesort(T *const a, const size_t n, T *const tmp_buf,
const size_t input_ranges_count)
{
assert(input_ranges_count > 0);
const size_t critical_range_size = (1 << 18) - 1;
if (n <= critical_range_size) {
heapsort<T, Heap>(a, n);
return;
}
const size_t range_size = n / input_ranges_count;
const size_t last_full_range = n - n % range_size;
vector<pair<T *, T *> > input_ranges;
for (size_t i = 0; i < last_full_range; i += range_size) {
nway_mergesort<T, Heap>(a + i, range_size, tmp_buf, input_ranges_count);
input_ranges.push_back(pair<T *, T *>(a + i, a + (i + range_size)));
}
if (n > last_full_range) {
nway_mergesort<T, Heap>(a + last_full_range, n - last_full_range, tmp_buf,
input_ranges_count);
input_ranges.push_back(pair<T *, T *>(a + last_full_range, a + n));
}
Heap::nway_merge(input_ranges.begin(), input_ranges.end(),
raw_storage_iterator<T *, T>(tmp_buf));
move_items(tmp_buf, n, a);
}
template <class T, class Heap>
void perftest_nway_mergesort(T *const a, const size_t n, const size_t m)
{
const size_t input_ranges_count = 15;
cout << "perftest_nway_mergesort(n=" << n << ", m=" << m <<
", input_ranges_count=" << input_ranges_count << ")";
double total_time = 0;
for (size_t i = 0; i < m / n; ++i) {
init_array(a, n);
double start = get_time();
const pair<T *, ptrdiff_t> tmp_buf = get_temporary_buffer<T>(n);
nway_mergesort<T, Heap>(a, n, tmp_buf.first, input_ranges_count);
return_temporary_buffer(tmp_buf.first);
double end = get_time();
total_time += end - start;
}
print_performance(total_time, m);
}
template <class T, class PriorityQueue>
void perftest_priority_queue(T *const a, const size_t n, const size_t m)
{
cout << "perftest_priority_queue(n=" << n << ", m=" << m << ")";
init_array(a, n);
PriorityQueue q(a, a + n);
double start = get_time();
for (size_t i = 0; i < m; ++i) {
q.pop();
q.push(rand());
}
double end = get_time();
print_performance(end - start, m);
}
template <class T, class Heap, class PriorityQueue>
void perftest_gheap(T *const a, const size_t max_n)
{
size_t n = max_n;
while (n > 0) {
perftest_heapsort<T, Heap>(a, n, max_n);
perftest_nway_mergesort<T, Heap>(a, n, max_n);
perftest_priority_queue<T, PriorityQueue>(a, n, max_n);
n >>= 1;
}
}
template <class T>
void perftest_stl_heap(T *const a, const size_t max_n)
{
size_t n = max_n;
while (n > 0) {
perftest_heapsort<T, stl_heap>(a, n, max_n);
// stl heap doesn't provide nway_merge(),
// so skipping perftest_nway_mergesort().
perftest_priority_queue<T, priority_queue<T> >(a, n, max_n);
n >>= 1;
}
}
} // end of anonymous namespace.
int main(void)
{
static const size_t MAX_N = 32 * 1024 * 1024;
static const size_t FANOUT = 2;
static const size_t PAGE_CHUNKS = 1;
typedef size_t T;
cout << "fanout=" << FANOUT << ", page_chunks=" << PAGE_CHUNKS <<
", max_n=" << MAX_N << endl;
srand(0);
T *const a = new T[MAX_N];
cout << "* STL heap" << endl;
perftest_stl_heap(a, MAX_N);
cout << "* gheap" << endl;
perftest_gheap<T, gheap<FANOUT, PAGE_CHUNKS>,
gpriority_queue<FANOUT, PAGE_CHUNKS, T> >(a, MAX_N);
delete[] a;
}
<|endoftext|> |
<commit_before>/*
For secp384r1
define this macro if using secp384r1
*/
// #define MCLBN_FP_UNIT_SIZE 6
/*
For secp521r1
1. rebuild libmcl.a
make clean && make lib/libmcl.a MCL_MAX_BIT_SIZE=576
2. define this macro if using secp521r1
*/
// #define MCLBN_FP_UNIT_SIZE 9
#include <mcl/she.hpp>
#include <cybozu/option.hpp>
#include <cybozu/benchmark.hpp>
#include <sstream>
#include <vector>
#include <omp.h>
using namespace mcl::she;
const int maxMsg = 10000;
typedef std::vector<CipherTextG1> CipherTextG1Vec;
template<class T>
void loadSaveTest(const char *msg, const T& x, bool compress)
{
std::string s;
// save
{
std::ostringstream oss; // you can use std::fstream
if (compress) {
cybozu::save(oss, x);
} else {
oss.write((const char*)&x, sizeof(x));
}
s = oss.str();
printf("size=%zd\n", s.size());
}
// load
{
std::istringstream iss(s);
T y;
if (compress) {
cybozu::load(y, iss);
} else {
iss.read((char*)&y, sizeof(y));
}
printf("save and load %s %s\n", msg, (x == y) ? "ok" : "err");
}
}
void loadSave(const SecretKey& sec, const PublicKey& pub, bool compress)
{
printf("loadSave compress=%d\n", compress);
int m = 123;
CipherTextG1 c;
pub.enc(c, m);
loadSaveTest("sec", sec, compress);
loadSaveTest("pub", pub, compress);
loadSaveTest("ciphertext", c, compress);
}
void benchEnc(const PrecomputedPublicKey& ppub, int vecN)
{
cybozu::CpuClock clk;
CipherTextG1Vec cv;
cv.resize(vecN);
const int C = 10;
for (int k = 0; k < C; k++) {
clk.begin();
#pragma omp parallel for
for (int i = 0; i < vecN; i++) {
ppub.enc(cv[i], i);
}
clk.end();
}
clk.put("enc");
}
void benchAdd(const PrecomputedPublicKey& ppub, int addN, int vecN)
{
cybozu::CpuClock clk;
CipherTextG1Vec sumv, cv;
sumv.resize(vecN);
cv.resize(addN);
for (int i = 0; i < addN; i++) {
ppub.enc(cv[i], i);
}
const int C = 10;
for (int k = 0; k < C; k++) {
clk.begin();
#pragma omp parallel for
for (int j = 0; j < vecN; j++) {
sumv[j] = cv[0];
for (int i = 1; i < addN; i++) {
sumv[j].add(cv[i]);
}
}
clk.end();
}
clk.put("add");
}
void benchDec(const PrecomputedPublicKey& ppub, const SecretKey& sec, int vecN)
{
cybozu::CpuClock clk;
CipherTextG1Vec cv;
cv.resize(vecN);
for (int i = 0; i < vecN; i++) {
ppub.enc(cv[i], i % maxMsg);
}
const int C = 10;
for (int k = 0; k < C; k++) {
clk.begin();
#pragma omp parallel for
for (int i = 0; i < vecN; i++) {
sec.dec(cv[i]);
}
clk.end();
}
clk.put("dec");
}
void exec(const std::string& mode, int addN, int vecN)
{
SecretKey sec;
sec.setByCSPRNG();
PublicKey pub;
sec.getPublicKey(pub);
PrecomputedPublicKey ppub;
ppub.init(pub);
if (mode == "enc") {
benchEnc(ppub, vecN);
return;
}
if (mode == "add") {
benchAdd(ppub, addN, vecN);
return;
}
if (mode == "dec") {
benchDec(ppub, sec, vecN);
return;
}
if (mode == "loadsave") {
loadSave(sec, pub, false);
loadSave(sec, pub, true);
return;
}
printf("not supported mode=%s\n", mode.c_str());
}
int main(int argc, char *argv[])
try
{
cybozu::Option opt;
int cpuN;
int addN;
int vecN;
std::string mode;
opt.appendOpt(&cpuN, 1, "cpu", "# of cpus");
opt.appendOpt(&addN, 128, "add", "# of add");
opt.appendOpt(&vecN, 1024, "n", "# of elements");
opt.appendParam(&mode, "mode", "enc|add|dec|loadsave");
opt.appendHelp("h");
if (opt.parse(argc, argv)) {
opt.put();
} else {
opt.usage();
return 1;
}
omp_set_num_threads(cpuN);
// initialize system
const size_t hashSize = maxMsg;
printf("MCL_MAX_BIT_SIZE=%d\n", MCL_MAX_BIT_SIZE);
#if 1
#if MCLBN_FP_UNIT_SIZE == 4
const mcl::EcParam& param = mcl::ecparam::secp256k1;
puts("secp256k1");
#elif MCLBN_FP_UNIT_SIZE == 6
const mcl::EcParam& param = mcl::ecparam::secp384r1;
puts("secp384r1");
#elif MCLBN_FP_UNIT_SIZE == 9
const mcl::EcParam& param = mcl::ecparam::secp521r1;
puts("secp521r1");
#else
#error "bad MCLBN_FP_UNIT_SIZE"
#endif
initG1only(param, hashSize);
#else
init();
setRangeForDLP(hashSize);
#endif
exec(mode, addN, vecN);
} catch (std::exception& e) {
printf("ERR %s\n", e.what());
return 1;
}
<commit_msg>[she] use load/save method<commit_after>/*
For secp384r1
define this macro if using secp384r1
*/
// #define MCLBN_FP_UNIT_SIZE 6
/*
For secp521r1
1. rebuild libmcl.a
make clean && make lib/libmcl.a MCL_MAX_BIT_SIZE=576
2. define this macro if using secp521r1
*/
// #define MCLBN_FP_UNIT_SIZE 9
#include <mcl/she.hpp>
#include <cybozu/option.hpp>
#include <cybozu/benchmark.hpp>
#include <sstream>
#include <vector>
#include <omp.h>
using namespace mcl::she;
const int maxMsg = 10000;
typedef std::vector<CipherTextG1> CipherTextG1Vec;
template<class T>
void loadSaveTest(const char *msg, const T& x, bool compress)
{
std::string s;
// save
{
std::ostringstream oss; // you can use std::fstream
if (compress) {
// cybozu::save(oss, x);
x.save(oss);
} else {
oss.write((const char*)&x, sizeof(x));
}
s = oss.str();
printf("size=%zd\n", s.size());
}
// load
{
std::istringstream iss(s);
T y;
if (compress) {
// cybozu::load(y, iss);
y.load(iss);
} else {
iss.read((char*)&y, sizeof(y));
}
printf("save and load %s %s\n", msg, (x == y) ? "ok" : "err");
}
}
void loadSave(const SecretKey& sec, const PublicKey& pub, bool compress)
{
printf("loadSave compress=%d\n", compress);
int m = 123;
CipherTextG1 c;
pub.enc(c, m);
loadSaveTest("sec", sec, compress);
loadSaveTest("pub", pub, compress);
loadSaveTest("ciphertext", c, compress);
}
void benchEnc(const PrecomputedPublicKey& ppub, int vecN)
{
cybozu::CpuClock clk;
CipherTextG1Vec cv;
cv.resize(vecN);
const int C = 10;
for (int k = 0; k < C; k++) {
clk.begin();
#pragma omp parallel for
for (int i = 0; i < vecN; i++) {
ppub.enc(cv[i], i);
}
clk.end();
}
clk.put("enc");
}
void benchAdd(const PrecomputedPublicKey& ppub, int addN, int vecN)
{
cybozu::CpuClock clk;
CipherTextG1Vec sumv, cv;
sumv.resize(vecN);
cv.resize(addN);
for (int i = 0; i < addN; i++) {
ppub.enc(cv[i], i);
}
const int C = 10;
for (int k = 0; k < C; k++) {
clk.begin();
#pragma omp parallel for
for (int j = 0; j < vecN; j++) {
sumv[j] = cv[0];
for (int i = 1; i < addN; i++) {
sumv[j].add(cv[i]);
}
}
clk.end();
}
clk.put("add");
}
void benchDec(const PrecomputedPublicKey& ppub, const SecretKey& sec, int vecN)
{
cybozu::CpuClock clk;
CipherTextG1Vec cv;
cv.resize(vecN);
for (int i = 0; i < vecN; i++) {
ppub.enc(cv[i], i % maxMsg);
}
const int C = 10;
for (int k = 0; k < C; k++) {
clk.begin();
#pragma omp parallel for
for (int i = 0; i < vecN; i++) {
sec.dec(cv[i]);
}
clk.end();
}
clk.put("dec");
}
void exec(const std::string& mode, int addN, int vecN)
{
SecretKey sec;
sec.setByCSPRNG();
PublicKey pub;
sec.getPublicKey(pub);
PrecomputedPublicKey ppub;
ppub.init(pub);
if (mode == "enc") {
benchEnc(ppub, vecN);
return;
}
if (mode == "add") {
benchAdd(ppub, addN, vecN);
return;
}
if (mode == "dec") {
benchDec(ppub, sec, vecN);
return;
}
if (mode == "loadsave") {
loadSave(sec, pub, false);
loadSave(sec, pub, true);
return;
}
printf("not supported mode=%s\n", mode.c_str());
}
int main(int argc, char *argv[])
try
{
cybozu::Option opt;
int cpuN;
int addN;
int vecN;
std::string mode;
opt.appendOpt(&cpuN, 1, "cpu", "# of cpus");
opt.appendOpt(&addN, 128, "add", "# of add");
opt.appendOpt(&vecN, 1024, "n", "# of elements");
opt.appendParam(&mode, "mode", "enc|add|dec|loadsave");
opt.appendHelp("h");
if (opt.parse(argc, argv)) {
opt.put();
} else {
opt.usage();
return 1;
}
omp_set_num_threads(cpuN);
// initialize system
const size_t hashSize = maxMsg;
printf("MCL_MAX_BIT_SIZE=%d\n", MCL_MAX_BIT_SIZE);
#if 1
#if MCLBN_FP_UNIT_SIZE == 4
const mcl::EcParam& param = mcl::ecparam::secp256k1;
puts("secp256k1");
#elif MCLBN_FP_UNIT_SIZE == 6
const mcl::EcParam& param = mcl::ecparam::secp384r1;
puts("secp384r1");
#elif MCLBN_FP_UNIT_SIZE == 9
const mcl::EcParam& param = mcl::ecparam::secp521r1;
puts("secp521r1");
#else
#error "bad MCLBN_FP_UNIT_SIZE"
#endif
initG1only(param, hashSize);
#else
init();
setRangeForDLP(hashSize);
#endif
exec(mode, addN, vecN);
} catch (std::exception& e) {
printf("ERR %s\n", e.what());
return 1;
}
<|endoftext|> |
<commit_before>#include <catch.hpp>
#include "../src/base.hpp"
TEST_CASE("TranslationException") {
REQUIRE_THROWS_AS(throw ctf::TranslationException("m"),
ctf::TranslationException &);
REQUIRE_THROWS_WITH(throw ctf::TranslationException("m"), "m");
}
TEST_CASE("Symbol Construction", "[Symbol]") {
using ctf::Symbol;
Symbol s(Symbol::Type::UNKNOWN, "name", "a");
REQUIRE(s.type() == Symbol::Type::UNKNOWN);
REQUIRE(s.name() == "name");
REQUIRE(s.attribute() == "a");
REQUIRE_THROWS_AS(s = Symbol(""), std::invalid_argument &);
using namespace ctf::literals;
s = "ter"_t;
REQUIRE(s.type() == Symbol::Type::TERMINAL);
REQUIRE(s.name() == "ter");
REQUIRE(s.attribute() == "");
s = "nter"_nt;
REQUIRE(s.type() == Symbol::Type::NONTERMINAL);
REQUIRE(s.name() == "nter");
REQUIRE(s.attribute() == "");
s = "spec"_s;
REQUIRE(s.type() == Symbol::Type::SPECIAL);
REQUIRE(s.name() == "spec");
REQUIRE(s.attribute() == "");
s = Symbol::eof();
REQUIRE(s.type() == Symbol::Type::EOI);
REQUIRE(s.name() == "");
}
TEST_CASE("operators", "[Symbol]") {
using namespace ctf::literals;
using ctf::Symbol;
Symbol s1 = "0"_t;
Symbol s2 = "5"_t;
Symbol s3 = "5"_nt;
Symbol s4 = "7"_t;
REQUIRE(s1 < s2);
REQUIRE_FALSE(s2 < s1);
REQUIRE_FALSE(s3 == s2);
REQUIRE_FALSE(s1 == s4);
REQUIRE(s1 != s2);
REQUIRE_FALSE(s2 != s2);
REQUIRE(s4 > s2);
REQUIRE(s4 >= s2);
REQUIRE(s3 >= s2);
REQUIRE_FALSE(s2 >= s4);
REQUIRE(s2 <= s4);
}<commit_msg>fixed bad test<commit_after>#include <catch.hpp>
#include "../src/base.hpp"
TEST_CASE("TranslationException") {
REQUIRE_THROWS_AS(throw ctf::TranslationException("m"),
ctf::TranslationException &);
REQUIRE_THROWS_WITH(throw ctf::TranslationException("m"), "m");
}
TEST_CASE("Symbol Construction", "[Symbol]") {
using ctf::Symbol;
Symbol s(Symbol::Type::UNKNOWN, "name", "a");
REQUIRE(s.type() == Symbol::Type::UNKNOWN);
REQUIRE(s.name() == "name");
REQUIRE(s.attribute() == "a");
REQUIRE_THROWS_AS(s = Symbol(""), std::invalid_argument &);
using namespace ctf::literals;
s = "ter"_t;
REQUIRE(s.type() == Symbol::Type::TERMINAL);
REQUIRE(s.name() == "ter");
REQUIRE(s.attribute() == "");
s = "nter"_nt;
REQUIRE(s.type() == Symbol::Type::NONTERMINAL);
REQUIRE(s.name() == "nter");
REQUIRE(s.attribute() == "");
s = "spec"_s;
REQUIRE(s.type() == Symbol::Type::SPECIAL);
REQUIRE(s.name() == "spec");
REQUIRE(s.attribute() == "");
s = Symbol::eof();
REQUIRE(s.type() == Symbol::Type::EOI);
REQUIRE(s.name() == "");
}
TEST_CASE("operators", "[Symbol]") {
using namespace ctf::literals;
using ctf::Symbol;
Symbol s1 = "0"_t;
Symbol s2 = "5"_t;
Symbol s3 = "5"_nt;
Symbol s4 = "7"_t;
REQUIRE(s1 < s2);
REQUIRE_FALSE(s2 < s1);
REQUIRE_FALSE(s3 == s2);
REQUIRE_FALSE(s1 == s4);
REQUIRE(s1 != s2);
REQUIRE_FALSE(s2 != s2);
REQUIRE(s4 > s2);
REQUIRE(s4 >= s2);
REQUIRE_FALSE(s3 >= s2);
REQUIRE_FALSE(s2 >= s4);
REQUIRE(s2 <= s4);
}<|endoftext|> |
<commit_before>#include <cstddef>
#include <cstdint>
#include <type_traits>
#include <utility>
#include <tuple>
using size_type = std::size_t;
template <size_type N>
using Number = std::integral_constant<size_type, N>;
namespace detail {
using ByteSize = std::integral_constant<size_type, 8>;
template <size_type Size>
struct GetStorage {
static_assert(Size <= ByteSize::value * sizeof(std::uint64_t),
"Max possible size exceeded");
using type = typename std::conditional<
(Size > ByteSize::value * sizeof(std::uint8_t)),
typename std::conditional<
(Size > ByteSize::value * sizeof(std::uint16_t)),
typename std::conditional<
(Size > ByteSize::value * sizeof(std::uint32_t)), std::uint64_t,
std::uint32_t>::type,
std::uint16_t>::type,
std::uint8_t>::type;
};
template <size_type Size>
using storage = typename GetStorage<Size>::type;
template <typename...>
struct Sum;
template <typename Head, typename... Args>
struct Sum<Head, Args...> {
using tail = typename Sum<Args...>::type;
using type = Number<Head::value + tail::value>;
};
template <typename Head>
struct Sum<Head> {
using type = Number<Head::value>;
};
template <size_type Index, typename... Args>
struct At {
static_assert(Index < sizeof...(Args), "Index out of bounds");
using type = std::remove_reference_t<
decltype(std::get<Index>(std::declval<std::tuple<Args...>>()))>;
};
template <size_type...>
struct Subset;
template <size_type Head, size_type... Indexes>
struct Subset<Head, Indexes...> {
template <typename... Args>
using tail = typename Subset<Indexes...>::template type<Args...>;
template <typename... Args>
using type = Number<At<Head, Args...>::type::value + tail<Args...>::value>;
};
template <size_type Head>
struct Subset<Head> {
template <typename... Args>
using type = Number<At<Head, Args...>::type::value>;
};
}
template <typename... Args>
struct Sum : public detail::Sum<Args...>::type {};
template <size_type Index, typename... Args>
struct At : public detail::At<Index, Args...>::type {};
template <size_type... Indexes>
struct Subset {
template <typename... Args>
struct type : public detail::Subset<Indexes...>::template type<Args...> {};
};
template <typename... Sizes>
struct Bitfields {
using length = Sum<Sizes...>;
using fields = std::tuple<Sizes...>;
detail::storage<length::value> storage;
};
#include <gtest/gtest.h>
struct bitfields_test : public ::testing::Test {};
TEST_F(bitfields_test, nothing) {
static_assert(sizeof(Bitfields<Number<1>>) <= sizeof(std::uint8_t), "");
static_assert(sizeof(Bitfields<Number<8>>) <= sizeof(std::uint8_t), "");
static_assert(Sum<Number<1>, Number<2>, Number<3>>::value == 6, "");
static_assert(At<2, Number<1>, Number<2>, Number<3>>::value == 3, "");
static_assert(
Subset<0, 2>::type<Number<1>, Number<2>, Number<3>, Number<4>>::value ==
4,
"");
}
<commit_msg>new impl<commit_after>#include <cstddef>
#include <cstdint>
#include <type_traits>
#include <utility>
#include <tuple>
namespace archie {
namespace utils {
using size_type = std::uint8_t;
template <size_type N>
using Number = std::integral_constant<size_type, N>;
using ByteSize = std::integral_constant<size_type, 8>;
template <size_type Size>
struct GetStorage {
static_assert(Size <= ByteSize::value * sizeof(std::uint64_t),
"Max possible size exceeded");
using type = typename std::conditional<
(Size > ByteSize::value * sizeof(std::uint8_t)),
typename std::conditional<
(Size > ByteSize::value * sizeof(std::uint16_t)),
typename std::conditional<
(Size > ByteSize::value * sizeof(std::uint32_t)), std::uint64_t,
std::uint32_t>::type,
std::uint16_t>::type,
std::uint8_t>::type;
};
template <size_type Size>
using Storage = typename GetStorage<Size>::type;
template <size_type I, size_type O, size_type S>
struct PackElement {
using Index = Number<I>;
using Offset = Number<O>;
using Size = Number<S>;
};
template <size_type I, size_type O, size_type S>
constexpr size_type offset_of(PackElement<I, O, S>) {
return O;
}
namespace detail {
template <size_type...>
struct PackImpl;
template <size_type I, size_type O, size_type S>
struct PackImpl<I, O, S> : PackElement<I, O, S> {};
template <size_type I, size_type O, size_type S, size_type... T>
struct PackImpl<I, O, S, T...> : PackElement<I, O, S>,
PackImpl<I + 1, O + S, T...> {};
}
template <size_type... S>
struct Pack : detail::PackImpl<0, 0, S...> {
constexpr Pack() = default;
};
}
}
#include <gtest/gtest.h>
namespace {
namespace au = archie::utils;
struct bitfields_test : public ::testing::Test {};
TEST_F(bitfields_test, storage) {
static_assert(sizeof(au::Storage<0>) <= sizeof(std::uint8_t), "");
static_assert(sizeof(au::Storage<8>) <= sizeof(std::uint8_t), "");
static_assert(sizeof(au::Storage<9>) <= sizeof(std::uint16_t), "");
static_assert(sizeof(au::Storage<16>) <= sizeof(std::uint16_t), "");
static_assert(sizeof(au::Storage<17>) <= sizeof(std::uint32_t), "");
static_assert(sizeof(au::Storage<32>) <= sizeof(std::uint32_t), "");
static_assert(sizeof(au::Storage<33>) <= sizeof(std::uint64_t), "");
static_assert(sizeof(au::Storage<64>) <= sizeof(std::uint64_t), "");
}
TEST_F(bitfields_test, pack_element_offset) {
constexpr au::Pack<1, 2, 3> pack;
static_assert(au::offset_of<0>(pack) == 0, "");
static_assert(au::offset_of<1>(pack) == 1, "");
static_assert(au::offset_of<2>(pack) == 3, "");
}
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cstring>
#include <ctime>
#include "frame/test_macros.h"
#include "time/time_utility.h"
CASE_TEST(time_test, zone_offset) {
util::time::time_utility::update();
time_t offset = util::time::time_utility::get_sys_zone_offset() - 5 * util::time::time_utility::HOUR_SECONDS;
util::time::time_utility::set_zone_offset(offset);
CASE_EXPECT_EQ(offset, util::time::time_utility::get_zone_offset());
CASE_EXPECT_NE(offset, util::time::time_utility::get_sys_zone_offset());
// 恢复时区设置
util::time::time_utility::set_zone_offset(util::time::time_utility::get_sys_zone_offset());
}
CASE_TEST(time_test, today_offset) {
using std::abs;
struct tm tobj;
time_t tnow, loffset, cnow;
util::time::time_utility::update();
tnow = util::time::time_utility::get_now();
UTIL_STRFUNC_LOCALTIME_S(&tnow, &tobj);
loffset = tobj.tm_hour * util::time::time_utility::HOUR_SECONDS + tobj.tm_min * util::time::time_utility::MINITE_SECONDS + tobj.tm_sec;
cnow = util::time::time_utility::get_today_offset(loffset);
// 只有闰秒误差,肯定在5秒以内
CASE_EXPECT_TRUE(abs(cnow - tnow) <= 5);
}
CASE_TEST(time_test, is_same_day) {
struct tm tobj;
time_t lt, rt;
util::time::time_utility::update();
lt = util::time::time_utility::get_now();
UTIL_STRFUNC_LOCALTIME_S(<, &tobj);
tobj.tm_hour = 0;
tobj.tm_min = 0;
tobj.tm_sec = 5;
lt = mktime(&tobj);
rt = lt + 5;
CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt));
tobj.tm_hour = 23;
tobj.tm_min = 59;
tobj.tm_sec = 55;
rt = mktime(&tobj);
CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt));
lt = rt - 5;
CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt));
lt = rt + 10;
CASE_EXPECT_FALSE(util::time::time_utility::is_same_day(lt, rt));
}
CASE_TEST(time_test, is_same_day_with_offset) {
struct tm tobj;
time_t lt, rt;
int zero_hore = 5;
time_t day_offset = zero_hore * util::time::time_utility::DAY_SECONDS;
util::time::time_utility::update();
lt = util::time::time_utility::get_now();
UTIL_STRFUNC_LOCALTIME_S(<, &tobj);
tobj.tm_hour = zero_hore;
tobj.tm_min = 0;
tobj.tm_sec = 5;
lt = mktime(&tobj);
rt = lt + 5;
CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt, day_offset));
tobj.tm_hour = zero_hore - 1;
tobj.tm_min = 59;
tobj.tm_sec = 55;
rt = mktime(&tobj);
CASE_EXPECT_FALSE(util::time::time_utility::is_same_day(lt, rt, day_offset));
}
CASE_TEST(time_test, is_same_week) {
struct tm tobj;
time_t lt, rt, tnow;
util::time::time_utility::update();
tnow = util::time::time_utility::get_now();
UTIL_STRFUNC_LOCALTIME_S(&tnow, &tobj);
tobj.tm_hour = 0;
tobj.tm_min = 0;
tobj.tm_sec = 5;
lt = mktime(&tobj);
lt -= util::time::time_utility::DAY_SECONDS * tobj.tm_wday;
rt = lt + util::time::time_utility::WEEK_SECONDS;
CASE_EXPECT_FALSE(util::time::time_utility::is_same_week(lt, rt));
rt -= 10;
CASE_EXPECT_TRUE(util::time::time_utility::is_same_week(lt, rt));
CASE_EXPECT_TRUE(util::time::time_utility::is_same_week(lt, tnow));
}
CASE_TEST(time_test, get_week_day) {
struct tm tobj;
time_t lt, rt, tnow;
util::time::time_utility::update();
tnow = util::time::time_utility::get_now();
UTIL_STRFUNC_LOCALTIME_S(&tnow, &tobj);
tobj.tm_hour = 0;
tobj.tm_min = 0;
tobj.tm_sec = 5;
lt = mktime(&tobj);
tobj.tm_hour = 23;
tobj.tm_min = 59;
tobj.tm_sec = 55;
rt = mktime(&tobj);
CASE_EXPECT_EQ(util::time::time_utility::get_week_day(lt), util::time::time_utility::get_week_day(tnow));
CASE_EXPECT_EQ(util::time::time_utility::get_week_day(lt), util::time::time_utility::get_week_day(rt));
}
CASE_TEST(time_test, is_same_month) {
// nothing todo use libc now
}
<commit_msg>修正一处单元测试错误<commit_after>#include <algorithm>
#include <cstring>
#include <ctime>
#include "frame/test_macros.h"
#include "time/time_utility.h"
CASE_TEST(time_test, zone_offset) {
util::time::time_utility::update();
time_t offset = util::time::time_utility::get_sys_zone_offset() - 5 * util::time::time_utility::HOUR_SECONDS;
util::time::time_utility::set_zone_offset(offset);
CASE_EXPECT_EQ(offset, util::time::time_utility::get_zone_offset());
CASE_EXPECT_NE(offset, util::time::time_utility::get_sys_zone_offset());
// 恢复时区设置
util::time::time_utility::set_zone_offset(util::time::time_utility::get_sys_zone_offset());
}
CASE_TEST(time_test, today_offset) {
using std::abs;
struct tm tobj;
time_t tnow, loffset, cnow;
util::time::time_utility::update();
tnow = util::time::time_utility::get_now();
UTIL_STRFUNC_LOCALTIME_S(&tnow, &tobj);
loffset = tobj.tm_hour * util::time::time_utility::HOUR_SECONDS + tobj.tm_min * util::time::time_utility::MINITE_SECONDS + tobj.tm_sec;
cnow = util::time::time_utility::get_today_offset(loffset);
// 只有闰秒误差,肯定在5秒以内
CASE_EXPECT_TRUE(abs(cnow - tnow) <= 5);
}
CASE_TEST(time_test, is_same_day) {
struct tm tobj;
time_t lt, rt;
util::time::time_utility::update();
lt = util::time::time_utility::get_now();
UTIL_STRFUNC_LOCALTIME_S(<, &tobj);
tobj.tm_hour = 0;
tobj.tm_min = 0;
tobj.tm_sec = 5;
lt = mktime(&tobj);
rt = lt + 5;
CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt));
tobj.tm_hour = 23;
tobj.tm_min = 59;
tobj.tm_sec = 55;
rt = mktime(&tobj);
CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt));
lt = rt - 5;
CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt));
lt = rt + 10;
CASE_EXPECT_FALSE(util::time::time_utility::is_same_day(lt, rt));
}
CASE_TEST(time_test, is_same_day_with_offset) {
struct tm tobj;
time_t lt, rt;
int zero_hore = 5;
time_t day_offset = zero_hore * util::time::time_utility::HOUR_SECONDS;
util::time::time_utility::update();
lt = util::time::time_utility::get_now();
UTIL_STRFUNC_LOCALTIME_S(<, &tobj);
tobj.tm_hour = zero_hore;
tobj.tm_min = 0;
tobj.tm_sec = 5;
lt = mktime(&tobj);
rt = lt + 5;
CASE_EXPECT_TRUE(util::time::time_utility::is_same_day(lt, rt, day_offset));
tobj.tm_hour = zero_hore - 1;
tobj.tm_min = 59;
tobj.tm_sec = 55;
rt = mktime(&tobj);
CASE_EXPECT_FALSE(util::time::time_utility::is_same_day(lt, rt, day_offset));
}
CASE_TEST(time_test, is_same_week) {
struct tm tobj;
time_t lt, rt, tnow;
util::time::time_utility::update();
tnow = util::time::time_utility::get_now();
UTIL_STRFUNC_LOCALTIME_S(&tnow, &tobj);
tobj.tm_hour = 0;
tobj.tm_min = 0;
tobj.tm_sec = 5;
lt = mktime(&tobj);
lt -= util::time::time_utility::DAY_SECONDS * tobj.tm_wday;
rt = lt + util::time::time_utility::WEEK_SECONDS;
CASE_EXPECT_FALSE(util::time::time_utility::is_same_week(lt, rt));
rt -= 10;
CASE_EXPECT_TRUE(util::time::time_utility::is_same_week(lt, rt));
CASE_EXPECT_TRUE(util::time::time_utility::is_same_week(lt, tnow));
}
CASE_TEST(time_test, get_week_day) {
struct tm tobj;
time_t lt, rt, tnow;
util::time::time_utility::update();
tnow = util::time::time_utility::get_now();
UTIL_STRFUNC_LOCALTIME_S(&tnow, &tobj);
tobj.tm_hour = 0;
tobj.tm_min = 0;
tobj.tm_sec = 5;
lt = mktime(&tobj);
tobj.tm_hour = 23;
tobj.tm_min = 59;
tobj.tm_sec = 55;
rt = mktime(&tobj);
CASE_EXPECT_EQ(util::time::time_utility::get_week_day(lt), util::time::time_utility::get_week_day(tnow));
CASE_EXPECT_EQ(util::time::time_utility::get_week_day(lt), util::time::time_utility::get_week_day(rt));
}
CASE_TEST(time_test, is_same_month) {
// nothing todo use libc now
}
<|endoftext|> |
<commit_before>#include "FImage.h"
using namespace FImage;
int main(int argc, char **argv) {
Var x, y;
Func f, g;
printf("Defining function...\n");
f(x, y) = 2.0;
g(x, y) = f(x+1, y) + f(x-1, y);
Var xo, xi, yo, yi;
g.split(x, xo, xi, 4);
g.split(y, yo, yi, 4);
g.transpose(xo, yi);
f.chunk(xo);
printf("Realizing function...\n");
assert(f.returnType() == Float(64));
assert(g.returnType() == Float(64));
Image<double> im = g.realize(32, 32);
for (size_t i = 0; i < 32; i++) {
if (im(i) != 4.0) {
for (size_t j = 0; j < 32; j++) {
printf("im[%d] = %f\n", j, im(j));
}
return -1;
}
}
printf("Success!\n");
return 0;
}
<commit_msg>Chunk test works on PTX<commit_after>#include "FImage.h"
using namespace FImage;
int main(int argc, char **argv) {
Var x("x"), y("y");
Var xo("blockidx"), xi("threadidx"), yo("blockidy"), yi("threadidy");
Func f("f"), g("g");
printf("Defining function...\n");
// This is kind of ugly -- trying to force g.f to be over threadid{x,y} when chunked
// Also: CUDA on older machines is unhappy with doubles, so now use floats
f(xi, yi) = 2.0f;
g(x, y) = f(x+1, y) + f(x-1, y);
g.split(x, xo, xi, 8);
g.split(y, yo, yi, 8);
g.transpose(xo, yi);
f.chunk(xo);
if (use_gpu()) {
g.parallel(xo).parallel(xi).parallel(yo).parallel(yi);
f.parallel(xi).parallel(yi);
}
printf("Realizing function...\n");
Image<float> im = g.realize(32, 32);
for (size_t i = 0; i < 32; i++) {
for (size_t j = 0; j < 32; j++) {
if (im(i,j) != 4.0) {
printf("im[%d, %d] = %f\n", (int)i, (int)j, im(i,j));
return -1;
}
}
}
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <sal/config.h>
#include <stdio.h>
#include <sfx2/docfile.hxx>
#include "qproform.hxx"
#include "qpro.hxx"
#include "qprostyle.hxx"
#include "global.hxx"
#include "scerrors.hxx"
#include "docpool.hxx"
#include "patattr.hxx"
#include "filter.hxx"
#include "document.hxx"
#include "formulacell.hxx"
#include "biff.hxx"
#include <tools/stream.hxx>
FltError ScQProReader::readSheet( SCTAB nTab, ScDocument* pDoc, ScQProStyle *pStyle )
{
FltError eRet = eERR_OK;
sal_uInt8 nCol, nDummy;
sal_uInt16 nRow;
sal_uInt16 nStyle;
bool bEndOfSheet = false;
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "Read sheet (%d)\n", nTab );
#endif
while( eERR_OK == eRet && !bEndOfSheet && nextRecord() )
{
switch( getId() )
{
case 0x000f:{ // Label cell
OUString aLabel;
mpStream->ReadUChar( nCol ).ReadUChar( nDummy ).ReadUInt16( nRow ).ReadUInt16( nStyle ).ReadUChar( nDummy );
sal_uInt16 nLen = getLength();
if (nLen >= 7)
{
readString( aLabel, nLen - 7 );
nStyle = nStyle >> 3;
pStyle->SetFormat( pDoc, nCol, nRow, nTab, nStyle );
pDoc->EnsureTable(nTab);
pDoc->SetTextCell(ScAddress(nCol,nRow,nTab), aLabel);
}
else
eRet = eERR_FORMAT;
}
break;
case 0x00cb: // End of sheet
bEndOfSheet = true;
break;
case 0x000c: // Blank cell
mpStream->ReadUChar( nCol ).ReadUChar( nDummy ).ReadUInt16( nRow ).ReadUInt16( nStyle );
nStyle = nStyle >> 3;
pStyle->SetFormat( pDoc, nCol, nRow, nTab, nStyle );
break;
case 0x000d:{ // Integer cell
sal_Int16 nValue;
mpStream->ReadUChar( nCol ).ReadUChar( nDummy ).ReadUInt16( nRow ).ReadUInt16( nStyle ).ReadInt16( nValue );
nStyle = nStyle >> 3;
pStyle->SetFormat( pDoc, nCol, nRow, nTab, nStyle );
pDoc->EnsureTable(nTab);
pDoc->SetValue(ScAddress(nCol,nRow,nTab), static_cast<double>(nValue));
}
break;
case 0x000e:{ // Floating point cell
double nValue;
mpStream->ReadUChar( nCol ).ReadUChar( nDummy ).ReadUInt16( nRow ).ReadUInt16( nStyle ).ReadDouble( nValue );
nStyle = nStyle >> 3;
pStyle->SetFormat( pDoc, nCol, nRow, nTab, nStyle );
pDoc->EnsureTable(nTab);
pDoc->SetValue(ScAddress(nCol,nRow,nTab), nValue);
}
break;
case 0x0010:{ // Formula cell
double nValue;
sal_uInt16 nState, nLen;
mpStream->ReadUChar( nCol ).ReadUChar( nDummy ).ReadUInt16( nRow ).ReadUInt16( nStyle ).ReadDouble( nValue ).ReadUInt16( nState ).ReadUInt16( nLen );
ScAddress aAddr( nCol, nRow, nTab );
const ScTokenArray *pArray;
QProToSc aConv( *mpStream, aAddr );
if (ConvOK != aConv.Convert( pArray, nLen ))
eRet = eERR_FORMAT;
else
{
ScFormulaCell* pFormula = new ScFormulaCell(pDoc, aAddr, *pArray);
nStyle = nStyle >> 3;
pFormula->AddRecalcMode( RECALCMODE_ONLOAD_ONCE );
pStyle->SetFormat( pDoc, nCol, nRow, nTab, nStyle );
pDoc->EnsureTable(nTab);
pDoc->SetFormulaCell(ScAddress(nCol,nRow,nTab), pFormula);
}
}
break;
}
}
return eRet;
}
FltError ScFormatFilterPluginImpl::ScImportQuattroPro( SfxMedium &rMedium, ScDocument *pDoc )
{
ScQProReader aReader( rMedium );
FltError eRet = aReader.import( pDoc );
return eRet;
}
ScQProReader::ScQProReader( SfxMedium &rMedium ):
ScBiffReader( rMedium )
{
}
FltError ScQProReader::import( ScDocument *pDoc )
{
FltError eRet = eERR_OK;
sal_uInt16 nVersion;
sal_uInt16 i = 1, j = 1;
SCTAB nTab = 0;
SetEof( false );
if( !recordsLeft() )
return eERR_OPEN;
ScQProStyle *pStyleElement = new ScQProStyle;
while( nextRecord() && eRet == eERR_OK)
{
switch( getId() )
{
case 0x0000: // Begginning of file
mpStream->ReadUInt16( nVersion );
break;
case 0x00ca: // Beginning of sheet
if( nTab <= MAXTAB )
{
if( nTab < 26 )
{
OUString aName;
aName += OUString( sal_Unicode( 'A' + nTab ) );
if (!nTab)
pDoc->RenameTab( nTab, aName, false, false);
else
pDoc->InsertTab( nTab, aName );
}
eRet = readSheet( nTab, pDoc, pStyleElement );
nTab++;
}
break;
case 0x0001: // End of file
SetEof( true );
break;
case 0x00ce:{ // Attribute cell
sal_uInt8 nFormat, nAlign, nFont;
sal_Int16 nColor;
mpStream->ReadUChar( nFormat ).ReadUChar( nAlign ).ReadInt16( nColor ).ReadUChar( nFont );
pStyleElement->setAlign( i, nAlign );
pStyleElement->setFont( i, nFont );
i++;
}
break;
case 0x00cf:{ // Font description
sal_uInt16 nPtSize, nFontAttr;
OUString aLabel;
mpStream->ReadUInt16( nPtSize ).ReadUInt16( nFontAttr );
pStyleElement->setFontRecord( j, nFontAttr, nPtSize );
sal_uInt16 nLen = getLength();
if (nLen >= 4)
readString( aLabel, nLen - 4 );
else
eRet = eERR_FORMAT;
pStyleElement->setFontType( j, aLabel );
j++;
}
break;
}
}
pDoc->CalcAfterLoad();
delete pStyleElement;
return eRet;
}
bool ScQProReader::recordsLeft()
{
bool bValue = ScBiffReader::recordsLeft();
return bValue;
}
bool ScQProReader::nextRecord()
{
bool bValue = ScBiffReader::nextRecord();
return bValue;
}
void ScQProReader::readString( OUString &rString, sal_uInt16 nLength )
{
sal_Char* pText = new sal_Char[ nLength + 1 ];
mpStream->Read( pText, nLength );
pText[ nLength ] = 0;
rString = OUString( pText, std::strlen(pText), mpStream->GetStreamCharSet() );
delete [] pText;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>belt-and-braces, check for short read<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <sal/config.h>
#include <stdio.h>
#include <sfx2/docfile.hxx>
#include "qproform.hxx"
#include "qpro.hxx"
#include "qprostyle.hxx"
#include "global.hxx"
#include "scerrors.hxx"
#include "docpool.hxx"
#include "patattr.hxx"
#include "filter.hxx"
#include "document.hxx"
#include "formulacell.hxx"
#include "biff.hxx"
#include <tools/stream.hxx>
FltError ScQProReader::readSheet( SCTAB nTab, ScDocument* pDoc, ScQProStyle *pStyle )
{
FltError eRet = eERR_OK;
sal_uInt8 nCol, nDummy;
sal_uInt16 nRow;
sal_uInt16 nStyle;
bool bEndOfSheet = false;
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "Read sheet (%d)\n", nTab );
#endif
while( eERR_OK == eRet && !bEndOfSheet && nextRecord() )
{
switch( getId() )
{
case 0x000f:{ // Label cell
OUString aLabel;
mpStream->ReadUChar( nCol ).ReadUChar( nDummy ).ReadUInt16( nRow ).ReadUInt16( nStyle ).ReadUChar( nDummy );
sal_uInt16 nLen = getLength();
if (nLen >= 7)
{
readString( aLabel, nLen - 7 );
nStyle = nStyle >> 3;
pStyle->SetFormat( pDoc, nCol, nRow, nTab, nStyle );
pDoc->EnsureTable(nTab);
pDoc->SetTextCell(ScAddress(nCol,nRow,nTab), aLabel);
}
else
eRet = eERR_FORMAT;
}
break;
case 0x00cb: // End of sheet
bEndOfSheet = true;
break;
case 0x000c: // Blank cell
mpStream->ReadUChar( nCol ).ReadUChar( nDummy ).ReadUInt16( nRow ).ReadUInt16( nStyle );
nStyle = nStyle >> 3;
pStyle->SetFormat( pDoc, nCol, nRow, nTab, nStyle );
break;
case 0x000d:{ // Integer cell
sal_Int16 nValue;
mpStream->ReadUChar( nCol ).ReadUChar( nDummy ).ReadUInt16( nRow ).ReadUInt16( nStyle ).ReadInt16( nValue );
nStyle = nStyle >> 3;
pStyle->SetFormat( pDoc, nCol, nRow, nTab, nStyle );
pDoc->EnsureTable(nTab);
pDoc->SetValue(ScAddress(nCol,nRow,nTab), static_cast<double>(nValue));
}
break;
case 0x000e:{ // Floating point cell
double nValue;
mpStream->ReadUChar( nCol ).ReadUChar( nDummy ).ReadUInt16( nRow ).ReadUInt16( nStyle ).ReadDouble( nValue );
nStyle = nStyle >> 3;
pStyle->SetFormat( pDoc, nCol, nRow, nTab, nStyle );
pDoc->EnsureTable(nTab);
pDoc->SetValue(ScAddress(nCol,nRow,nTab), nValue);
}
break;
case 0x0010:{ // Formula cell
double nValue;
sal_uInt16 nState, nLen;
mpStream->ReadUChar( nCol ).ReadUChar( nDummy ).ReadUInt16( nRow ).ReadUInt16( nStyle ).ReadDouble( nValue ).ReadUInt16( nState ).ReadUInt16( nLen );
ScAddress aAddr( nCol, nRow, nTab );
const ScTokenArray *pArray;
QProToSc aConv( *mpStream, aAddr );
if (ConvOK != aConv.Convert( pArray, nLen ))
eRet = eERR_FORMAT;
else
{
ScFormulaCell* pFormula = new ScFormulaCell(pDoc, aAddr, *pArray);
nStyle = nStyle >> 3;
pFormula->AddRecalcMode( RECALCMODE_ONLOAD_ONCE );
pStyle->SetFormat( pDoc, nCol, nRow, nTab, nStyle );
pDoc->EnsureTable(nTab);
pDoc->SetFormulaCell(ScAddress(nCol,nRow,nTab), pFormula);
}
}
break;
}
}
return eRet;
}
FltError ScFormatFilterPluginImpl::ScImportQuattroPro( SfxMedium &rMedium, ScDocument *pDoc )
{
ScQProReader aReader( rMedium );
FltError eRet = aReader.import( pDoc );
return eRet;
}
ScQProReader::ScQProReader( SfxMedium &rMedium ):
ScBiffReader( rMedium )
{
}
FltError ScQProReader::import( ScDocument *pDoc )
{
FltError eRet = eERR_OK;
sal_uInt16 nVersion;
sal_uInt16 i = 1, j = 1;
SCTAB nTab = 0;
SetEof( false );
if( !recordsLeft() )
return eERR_OPEN;
ScQProStyle *pStyleElement = new ScQProStyle;
while( nextRecord() && eRet == eERR_OK)
{
switch( getId() )
{
case 0x0000: // Begginning of file
mpStream->ReadUInt16( nVersion );
break;
case 0x00ca: // Beginning of sheet
if( nTab <= MAXTAB )
{
if( nTab < 26 )
{
OUString aName;
aName += OUString( sal_Unicode( 'A' + nTab ) );
if (!nTab)
pDoc->RenameTab( nTab, aName, false, false);
else
pDoc->InsertTab( nTab, aName );
}
eRet = readSheet( nTab, pDoc, pStyleElement );
nTab++;
}
break;
case 0x0001: // End of file
SetEof( true );
break;
case 0x00ce:{ // Attribute cell
sal_uInt8 nFormat, nAlign, nFont;
sal_Int16 nColor;
mpStream->ReadUChar( nFormat ).ReadUChar( nAlign ).ReadInt16( nColor ).ReadUChar( nFont );
pStyleElement->setAlign( i, nAlign );
pStyleElement->setFont( i, nFont );
i++;
}
break;
case 0x00cf:{ // Font description
sal_uInt16 nPtSize, nFontAttr;
OUString aLabel;
mpStream->ReadUInt16( nPtSize ).ReadUInt16( nFontAttr );
pStyleElement->setFontRecord( j, nFontAttr, nPtSize );
sal_uInt16 nLen = getLength();
if (nLen >= 4)
readString( aLabel, nLen - 4 );
else
eRet = eERR_FORMAT;
pStyleElement->setFontType( j, aLabel );
j++;
}
break;
}
}
pDoc->CalcAfterLoad();
delete pStyleElement;
return eRet;
}
bool ScQProReader::recordsLeft()
{
bool bValue = ScBiffReader::recordsLeft();
return bValue;
}
bool ScQProReader::nextRecord()
{
bool bValue = ScBiffReader::nextRecord();
return bValue;
}
void ScQProReader::readString( OUString &rString, sal_uInt16 nLength )
{
sal_Char* pText = new sal_Char[ nLength + 1 ];
nLength = mpStream->Read(pText, nLength);
pText[ nLength ] = 0;
rString = OUString( pText, std::strlen(pText), mpStream->GetStreamCharSet() );
delete [] pText;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: foptmgr.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2006-07-21 13:24:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// System - Includes ---------------------------------------------------------
// INCLUDE -------------------------------------------------------------------
#include <vcl/morebtn.hxx>
#include <svtools/stdctrl.hxx>
#include "anyrefdg.hxx"
#include "rangeutl.hxx"
#include "dbcolect.hxx"
#include "viewdata.hxx"
#include "document.hxx"
#define _FOPTMGR_CXX
#include "foptmgr.hxx"
#undef _FOPTMGR_CXX
//----------------------------------------------------------------------------
ScFilterOptionsMgr::ScFilterOptionsMgr(
Dialog* ptrDlg,
ScViewData* ptrViewData,
const ScQueryParam& refQueryData,
MoreButton& refBtnMore,
CheckBox& refBtnCase,
CheckBox& refBtnRegExp,
CheckBox& refBtnHeader,
CheckBox& refBtnUnique,
CheckBox& refBtnCopyResult,
CheckBox& refBtnDestPers,
ListBox& refLbCopyArea,
Edit& refEdCopyArea,
ScRefButton& refRbCopyArea,
FixedText& refFtDbAreaLabel,
FixedInfo& refFtDbArea,
FixedLine& refFlOptions,
const String& refStrNoName,
const String& refStrUndefined )
: pDlg ( ptrDlg ),
pViewData ( ptrViewData ),
pDoc ( ptrViewData ? ptrViewData->GetDocument() : NULL ),
rQueryData ( refQueryData ),
rBtnMore ( refBtnMore ),
rBtnCase ( refBtnCase ),
rBtnRegExp ( refBtnRegExp ),
rBtnHeader ( refBtnHeader ),
rBtnUnique ( refBtnUnique ),
rBtnCopyResult ( refBtnCopyResult ),
rBtnDestPers ( refBtnDestPers ),
rLbCopyPos ( refLbCopyArea ),
rEdCopyPos ( refEdCopyArea ),
rRbCopyPos ( refRbCopyArea ),
rFtDbAreaLabel ( refFtDbAreaLabel ),
rFtDbArea ( refFtDbArea ),
rFlOptions ( refFlOptions ),
rStrNoName ( refStrNoName ),
rStrUndefined ( refStrUndefined )
{
Init();
}
//----------------------------------------------------------------------------
ScFilterOptionsMgr::~ScFilterOptionsMgr()
{
USHORT nEntries = rLbCopyPos.GetEntryCount();
USHORT i;
for ( i=2; i<nEntries; i++ )
delete (String*)rLbCopyPos.GetEntryData( i );
}
//----------------------------------------------------------------------------
void ScFilterOptionsMgr::Init()
{
DBG_ASSERT( pViewData && pDoc, "Init failed :-/" );
rLbCopyPos.SetSelectHdl ( LINK( this, ScFilterOptionsMgr, LbPosSelHdl ) );
rEdCopyPos.SetModifyHdl ( LINK( this, ScFilterOptionsMgr, EdPosModifyHdl ) );
rBtnCopyResult.SetClickHdl( LINK( this, ScFilterOptionsMgr, BtnCopyResultHdl ) );
rBtnMore.AddWindow( &rBtnCase );
rBtnMore.AddWindow( &rBtnRegExp );
rBtnMore.AddWindow( &rBtnHeader );
rBtnMore.AddWindow( &rBtnUnique );
rBtnMore.AddWindow( &rBtnCopyResult );
rBtnMore.AddWindow( &rBtnDestPers );
rBtnMore.AddWindow( &rLbCopyPos );
rBtnMore.AddWindow( &rEdCopyPos );
rBtnMore.AddWindow( &rRbCopyPos );
rBtnMore.AddWindow( &rFtDbAreaLabel );
rBtnMore.AddWindow( &rFtDbArea );
rBtnMore.AddWindow( &rFlOptions );
rBtnCase .Check( rQueryData.bCaseSens );
rBtnHeader .Check( rQueryData.bHasHeader );
rBtnRegExp .Check( rQueryData.bRegExp );
rBtnUnique .Check( !rQueryData.bDuplicate );
if ( pViewData && pDoc )
{
String theAreaStr;
ScRange theCurArea ( ScAddress( rQueryData.nCol1,
rQueryData.nRow1,
pViewData->GetTabNo() ),
ScAddress( rQueryData.nCol2,
rQueryData.nRow2,
pViewData->GetTabNo() ) );
ScDBCollection* pDBColl = pDoc->GetDBCollection();
String theDbArea;
String theDbName = rStrNoName;
theCurArea.Format( theAreaStr, SCR_ABS_3D, pDoc );
// Zielbereichsliste fuellen
rLbCopyPos.Clear();
rLbCopyPos.InsertEntry( rStrUndefined, 0 );
ScAreaNameIterator aIter( pDoc );
String aName;
ScRange aRange;
String aRefStr;
while ( aIter.Next( aName, aRange ) )
{
USHORT nInsert = rLbCopyPos.InsertEntry( aName );
aRange.aStart.Format( aRefStr, SCA_ABS_3D, pDoc );
rLbCopyPos.SetEntryData( nInsert, new String( aRefStr ) );
}
rBtnDestPers.Check( TRUE ); // beim Aufruf immer an
rLbCopyPos.SelectEntryPos( 0 );
rEdCopyPos.SetText( EMPTY_STRING );
/*
* Ueberpruefen, ob es sich bei dem uebergebenen
* Bereich um einen Datenbankbereich handelt:
*/
theDbArea = theAreaStr;
if ( pDBColl )
{
ScAddress& rStart = theCurArea.aStart;
ScAddress& rEnd = theCurArea.aEnd;
ScDBData* pDBData = pDBColl->GetDBAtArea( rStart.Tab(),
rStart.Col(), rStart.Row(),
rEnd.Col(), rEnd.Row() );
if ( pDBData )
{
rBtnHeader.Check( pDBData->HasHeader() );
pDBData->GetName( theDbName );
if ( theDbName != rStrNoName )
{
rBtnHeader.Disable();
}
}
}
theDbArea.AppendAscii(RTL_CONSTASCII_STRINGPARAM(" ("));
theDbArea += theDbName;
theDbArea += ')';
rFtDbArea.SetText( theDbArea );
//------------------------------------------------------
// Kopierposition:
if ( !rQueryData.bInplace )
{
String aString;
ScAddress( rQueryData.nDestCol,
rQueryData.nDestRow,
rQueryData.nDestTab
).Format( aString, SCA_ABS_3D, pDoc );
rBtnCopyResult.Check( TRUE );
rEdCopyPos.SetText( aString );
EdPosModifyHdl( &rEdCopyPos );
rLbCopyPos.Enable();
rEdCopyPos.Enable();
rRbCopyPos.Enable();
rBtnDestPers.Enable();
}
else
{
rBtnCopyResult.Check( FALSE );
rEdCopyPos.SetText( EMPTY_STRING );
rLbCopyPos.Disable();
rEdCopyPos.Disable();
rRbCopyPos.Disable();
rBtnDestPers.Disable();
}
}
else
rEdCopyPos.SetText( EMPTY_STRING );
}
//----------------------------------------------------------------------------
BOOL ScFilterOptionsMgr::VerifyPosStr( const String& rPosStr ) const
{
String aPosStr( rPosStr );
xub_StrLen nColonPos = aPosStr.Search( ':' );
if ( STRING_NOTFOUND != nColonPos )
aPosStr.Erase( nColonPos );
USHORT nResult = ScAddress().Parse( aPosStr, pDoc );
return ( SCA_VALID == (nResult & SCA_VALID) );
}
//----------------------------------------------------------------------------
// Handler:
//----------------------------------------------------------------------------
IMPL_LINK( ScFilterOptionsMgr, LbPosSelHdl, ListBox*, pLb )
{
if ( pLb == &rLbCopyPos )
{
String aString;
USHORT nSelPos = rLbCopyPos.GetSelectEntryPos();
if ( nSelPos > 0 )
aString = *(String*)rLbCopyPos.GetEntryData( nSelPos );
rEdCopyPos.SetText( aString );
}
return 0;
}
//----------------------------------------------------------------------------
IMPL_LINK( ScFilterOptionsMgr, EdPosModifyHdl, Edit*, pEd )
{
if ( pEd == &rEdCopyPos )
{
String theCurPosStr = pEd->GetText();
USHORT nResult = ScAddress().Parse( theCurPosStr, pDoc );
if ( SCA_VALID == (nResult & SCA_VALID) )
{
String* pStr = NULL;
BOOL bFound = FALSE;
USHORT i = 0;
USHORT nCount = rLbCopyPos.GetEntryCount();
for ( i=2; i<nCount && !bFound; i++ )
{
pStr = (String*)rLbCopyPos.GetEntryData( i );
bFound = (theCurPosStr == *pStr);
}
if ( bFound )
rLbCopyPos.SelectEntryPos( --i );
else
rLbCopyPos.SelectEntryPos( 0 );
}
else
rLbCopyPos.SelectEntryPos( 0 );
}
return 0;
}
//----------------------------------------------------------------------------
IMPL_LINK( ScFilterOptionsMgr, BtnCopyResultHdl, CheckBox*, pBox )
{
if ( pBox == &rBtnCopyResult )
{
if ( pBox->IsChecked() )
{
rBtnDestPers.Enable();
rLbCopyPos.Enable();
rEdCopyPos.Enable();
rRbCopyPos.Enable();
rEdCopyPos.GrabFocus();
}
else
{
rBtnDestPers.Disable();
rLbCopyPos.Disable();
rEdCopyPos.Disable();
rRbCopyPos.Disable();
}
}
return 0;
}
<commit_msg>INTEGRATION: CWS calcwarnings (1.5.110); FILE MERGED 2006/12/12 17:03:09 nn 1.5.110.1: #i69284# warning-free: ui, unxlngi6<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: foptmgr.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2007-02-27 13:03:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// System - Includes ---------------------------------------------------------
// INCLUDE -------------------------------------------------------------------
#include <vcl/morebtn.hxx>
#include <svtools/stdctrl.hxx>
#include "anyrefdg.hxx"
#include "rangeutl.hxx"
#include "dbcolect.hxx"
#include "viewdata.hxx"
#include "document.hxx"
#define _FOPTMGR_CXX
#include "foptmgr.hxx"
#undef _FOPTMGR_CXX
//----------------------------------------------------------------------------
ScFilterOptionsMgr::ScFilterOptionsMgr(
Dialog* ptrDlg,
ScViewData* ptrViewData,
const ScQueryParam& refQueryData,
MoreButton& refBtnMore,
CheckBox& refBtnCase,
CheckBox& refBtnRegExp,
CheckBox& refBtnHeader,
CheckBox& refBtnUnique,
CheckBox& refBtnCopyResult,
CheckBox& refBtnDestPers,
ListBox& refLbCopyArea,
Edit& refEdCopyArea,
ScRefButton& refRbCopyArea,
FixedText& refFtDbAreaLabel,
FixedInfo& refFtDbArea,
FixedLine& refFlOptions,
const String& refStrNoName,
const String& refStrUndefined )
: pDlg ( ptrDlg ),
pViewData ( ptrViewData ),
pDoc ( ptrViewData ? ptrViewData->GetDocument() : NULL ),
rBtnMore ( refBtnMore ),
rBtnCase ( refBtnCase ),
rBtnRegExp ( refBtnRegExp ),
rBtnHeader ( refBtnHeader ),
rBtnUnique ( refBtnUnique ),
rBtnCopyResult ( refBtnCopyResult ),
rBtnDestPers ( refBtnDestPers ),
rLbCopyPos ( refLbCopyArea ),
rEdCopyPos ( refEdCopyArea ),
rRbCopyPos ( refRbCopyArea ),
rFtDbAreaLabel ( refFtDbAreaLabel ),
rFtDbArea ( refFtDbArea ),
rFlOptions ( refFlOptions ),
rStrNoName ( refStrNoName ),
rStrUndefined ( refStrUndefined ),
rQueryData ( refQueryData )
{
Init();
}
//----------------------------------------------------------------------------
ScFilterOptionsMgr::~ScFilterOptionsMgr()
{
USHORT nEntries = rLbCopyPos.GetEntryCount();
USHORT i;
for ( i=2; i<nEntries; i++ )
delete (String*)rLbCopyPos.GetEntryData( i );
}
//----------------------------------------------------------------------------
void ScFilterOptionsMgr::Init()
{
DBG_ASSERT( pViewData && pDoc, "Init failed :-/" );
rLbCopyPos.SetSelectHdl ( LINK( this, ScFilterOptionsMgr, LbPosSelHdl ) );
rEdCopyPos.SetModifyHdl ( LINK( this, ScFilterOptionsMgr, EdPosModifyHdl ) );
rBtnCopyResult.SetClickHdl( LINK( this, ScFilterOptionsMgr, BtnCopyResultHdl ) );
rBtnMore.AddWindow( &rBtnCase );
rBtnMore.AddWindow( &rBtnRegExp );
rBtnMore.AddWindow( &rBtnHeader );
rBtnMore.AddWindow( &rBtnUnique );
rBtnMore.AddWindow( &rBtnCopyResult );
rBtnMore.AddWindow( &rBtnDestPers );
rBtnMore.AddWindow( &rLbCopyPos );
rBtnMore.AddWindow( &rEdCopyPos );
rBtnMore.AddWindow( &rRbCopyPos );
rBtnMore.AddWindow( &rFtDbAreaLabel );
rBtnMore.AddWindow( &rFtDbArea );
rBtnMore.AddWindow( &rFlOptions );
rBtnCase .Check( rQueryData.bCaseSens );
rBtnHeader .Check( rQueryData.bHasHeader );
rBtnRegExp .Check( rQueryData.bRegExp );
rBtnUnique .Check( !rQueryData.bDuplicate );
if ( pViewData && pDoc )
{
String theAreaStr;
ScRange theCurArea ( ScAddress( rQueryData.nCol1,
rQueryData.nRow1,
pViewData->GetTabNo() ),
ScAddress( rQueryData.nCol2,
rQueryData.nRow2,
pViewData->GetTabNo() ) );
ScDBCollection* pDBColl = pDoc->GetDBCollection();
String theDbArea;
String theDbName = rStrNoName;
theCurArea.Format( theAreaStr, SCR_ABS_3D, pDoc );
// Zielbereichsliste fuellen
rLbCopyPos.Clear();
rLbCopyPos.InsertEntry( rStrUndefined, 0 );
ScAreaNameIterator aIter( pDoc );
String aName;
ScRange aRange;
String aRefStr;
while ( aIter.Next( aName, aRange ) )
{
USHORT nInsert = rLbCopyPos.InsertEntry( aName );
aRange.aStart.Format( aRefStr, SCA_ABS_3D, pDoc );
rLbCopyPos.SetEntryData( nInsert, new String( aRefStr ) );
}
rBtnDestPers.Check( TRUE ); // beim Aufruf immer an
rLbCopyPos.SelectEntryPos( 0 );
rEdCopyPos.SetText( EMPTY_STRING );
/*
* Ueberpruefen, ob es sich bei dem uebergebenen
* Bereich um einen Datenbankbereich handelt:
*/
theDbArea = theAreaStr;
if ( pDBColl )
{
ScAddress& rStart = theCurArea.aStart;
ScAddress& rEnd = theCurArea.aEnd;
ScDBData* pDBData = pDBColl->GetDBAtArea( rStart.Tab(),
rStart.Col(), rStart.Row(),
rEnd.Col(), rEnd.Row() );
if ( pDBData )
{
rBtnHeader.Check( pDBData->HasHeader() );
pDBData->GetName( theDbName );
if ( theDbName != rStrNoName )
{
rBtnHeader.Disable();
}
}
}
theDbArea.AppendAscii(RTL_CONSTASCII_STRINGPARAM(" ("));
theDbArea += theDbName;
theDbArea += ')';
rFtDbArea.SetText( theDbArea );
//------------------------------------------------------
// Kopierposition:
if ( !rQueryData.bInplace )
{
String aString;
ScAddress( rQueryData.nDestCol,
rQueryData.nDestRow,
rQueryData.nDestTab
).Format( aString, SCA_ABS_3D, pDoc );
rBtnCopyResult.Check( TRUE );
rEdCopyPos.SetText( aString );
EdPosModifyHdl( &rEdCopyPos );
rLbCopyPos.Enable();
rEdCopyPos.Enable();
rRbCopyPos.Enable();
rBtnDestPers.Enable();
}
else
{
rBtnCopyResult.Check( FALSE );
rEdCopyPos.SetText( EMPTY_STRING );
rLbCopyPos.Disable();
rEdCopyPos.Disable();
rRbCopyPos.Disable();
rBtnDestPers.Disable();
}
}
else
rEdCopyPos.SetText( EMPTY_STRING );
}
//----------------------------------------------------------------------------
BOOL ScFilterOptionsMgr::VerifyPosStr( const String& rPosStr ) const
{
String aPosStr( rPosStr );
xub_StrLen nColonPos = aPosStr.Search( ':' );
if ( STRING_NOTFOUND != nColonPos )
aPosStr.Erase( nColonPos );
USHORT nResult = ScAddress().Parse( aPosStr, pDoc );
return ( SCA_VALID == (nResult & SCA_VALID) );
}
//----------------------------------------------------------------------------
// Handler:
//----------------------------------------------------------------------------
IMPL_LINK( ScFilterOptionsMgr, LbPosSelHdl, ListBox*, pLb )
{
if ( pLb == &rLbCopyPos )
{
String aString;
USHORT nSelPos = rLbCopyPos.GetSelectEntryPos();
if ( nSelPos > 0 )
aString = *(String*)rLbCopyPos.GetEntryData( nSelPos );
rEdCopyPos.SetText( aString );
}
return 0;
}
//----------------------------------------------------------------------------
IMPL_LINK( ScFilterOptionsMgr, EdPosModifyHdl, Edit*, pEd )
{
if ( pEd == &rEdCopyPos )
{
String theCurPosStr = pEd->GetText();
USHORT nResult = ScAddress().Parse( theCurPosStr, pDoc );
if ( SCA_VALID == (nResult & SCA_VALID) )
{
String* pStr = NULL;
BOOL bFound = FALSE;
USHORT i = 0;
USHORT nCount = rLbCopyPos.GetEntryCount();
for ( i=2; i<nCount && !bFound; i++ )
{
pStr = (String*)rLbCopyPos.GetEntryData( i );
bFound = (theCurPosStr == *pStr);
}
if ( bFound )
rLbCopyPos.SelectEntryPos( --i );
else
rLbCopyPos.SelectEntryPos( 0 );
}
else
rLbCopyPos.SelectEntryPos( 0 );
}
return 0;
}
//----------------------------------------------------------------------------
IMPL_LINK( ScFilterOptionsMgr, BtnCopyResultHdl, CheckBox*, pBox )
{
if ( pBox == &rBtnCopyResult )
{
if ( pBox->IsChecked() )
{
rBtnDestPers.Enable();
rLbCopyPos.Enable();
rEdCopyPos.Enable();
rRbCopyPos.Enable();
rEdCopyPos.GrabFocus();
}
else
{
rBtnDestPers.Disable();
rLbCopyPos.Disable();
rEdCopyPos.Disable();
rRbCopyPos.Disable();
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabvwshd.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2006-07-21 15:17:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
//------------------------------------------------------------------
#ifdef WNT
#pragma optimize ("", off)
#endif
// INCLUDE ---------------------------------------------------------------
#include <sfx2/childwin.hxx>
#include <sfx2/request.hxx>
#include <sfx2/topfrm.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include "tabvwsh.hxx"
#include "global.hxx"
#include "scmod.hxx"
#include "docsh.hxx"
#include "sc.hrc"
// STATIC DATA -----------------------------------------------------------
//------------------------------------------------------------------
#define IS_AVAILABLE(WhichId,ppItem) \
(pReqArgs->GetItemState((WhichId), TRUE, ppItem ) == SFX_ITEM_SET)
//! Parent-Window fuer Dialoge
//! Problem: OLE Server!
Window* ScTabViewShell::GetDialogParent()
{
// #95513# if a ref-input dialog is open, use it as parent
// (necessary when a slot is executed from the dialog's OK handler)
if ( nCurRefDlgId && nCurRefDlgId == SC_MOD()->GetCurRefDlgId() )
{
SfxViewFrame* pViewFrm = GetViewFrame();
if ( pViewFrm->HasChildWindow(nCurRefDlgId) )
{
SfxChildWindow* pChild = pViewFrm->GetChildWindow(nCurRefDlgId);
if (pChild)
{
Window* pWin = pChild->GetWindow();
if (pWin && pWin->IsVisible())
return pWin;
}
}
}
ScDocShell* pDocSh = GetViewData()->GetDocShell();
if ( pDocSh->IsOle() )
{
//TODO/LATER: how to GetEditWindow in embedded document?!
//It should be OK to return the VieShell Window!
return GetWindow();
//SvInPlaceEnvironment* pEnv = pDocSh->GetIPEnv();
//if (pEnv)
// return pEnv->GetEditWin();
}
return GetActiveWin(); // for normal views, too
}
<commit_msg>INTEGRATION: CWS mingwport06 (1.5.314); FILE MERGED 2007/08/24 13:08:31 vg 1.5.314.1: #i75499# pragma is for MSVC<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: tabvwshd.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2007-09-06 14:22:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
//------------------------------------------------------------------
#ifdef _MSC_VER
#pragma optimize ("", off)
#endif
// INCLUDE ---------------------------------------------------------------
#include <sfx2/childwin.hxx>
#include <sfx2/request.hxx>
#include <sfx2/topfrm.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include "tabvwsh.hxx"
#include "global.hxx"
#include "scmod.hxx"
#include "docsh.hxx"
#include "sc.hrc"
// STATIC DATA -----------------------------------------------------------
//------------------------------------------------------------------
#define IS_AVAILABLE(WhichId,ppItem) \
(pReqArgs->GetItemState((WhichId), TRUE, ppItem ) == SFX_ITEM_SET)
//! Parent-Window fuer Dialoge
//! Problem: OLE Server!
Window* ScTabViewShell::GetDialogParent()
{
// #95513# if a ref-input dialog is open, use it as parent
// (necessary when a slot is executed from the dialog's OK handler)
if ( nCurRefDlgId && nCurRefDlgId == SC_MOD()->GetCurRefDlgId() )
{
SfxViewFrame* pViewFrm = GetViewFrame();
if ( pViewFrm->HasChildWindow(nCurRefDlgId) )
{
SfxChildWindow* pChild = pViewFrm->GetChildWindow(nCurRefDlgId);
if (pChild)
{
Window* pWin = pChild->GetWindow();
if (pWin && pWin->IsVisible())
return pWin;
}
}
}
ScDocShell* pDocSh = GetViewData()->GetDocShell();
if ( pDocSh->IsOle() )
{
//TODO/LATER: how to GetEditWindow in embedded document?!
//It should be OK to return the VieShell Window!
return GetWindow();
//SvInPlaceEnvironment* pEnv = pDocSh->GetIPEnv();
//if (pEnv)
// return pEnv->GetEditWin();
}
return GetActiveWin(); // for normal views, too
}
<|endoftext|> |
<commit_before>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
* Copyright (C) 2005 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: operation/buffer/SubgraphDepthLocater.java rev. 1.5 (JTS-1.7)
*
**********************************************************************/
#include <geos/opBuffer.h>
#ifndef DEBUG
#define DEBUG 0
#endif
using namespace geos::geomgraph;
using namespace geos::noding;
using namespace geos::algorithm;
using namespace geos::operation::overlay;
namespace geos {
namespace operation { // geos.operation
namespace buffer { // geos.operation.buffer
/*public*/
int
SubgraphDepthLocater::getDepth(Coordinate &p)
{
vector<DepthSegment*> stabbedSegments;
findStabbedSegments(p, stabbedSegments);
// if no segments on stabbing line subgraph must be outside all others->
if (stabbedSegments.size()==0) return 0;
sort(stabbedSegments.begin(), stabbedSegments.end(), DepthSegmentLT);
DepthSegment *ds=stabbedSegments[0];
int ret = ds->leftDepth;
#if DEBUG
cerr<<"SubgraphDepthLocater::getDepth("<<p.toString()<<"): "<<ret<<endl;
#endif
for (vector<DepthSegment *>::iterator
it=stabbedSegments.begin(), itEnd=stabbedSegments.end();
it != itEnd;
++it)
{
delete *it;
}
return ret;
}
/*private*/
void
SubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt,
std::vector<DepthSegment*>& stabbedSegments)
{
unsigned int size = subgraphs->size();
for (unsigned int i=0; i<size; ++i)
{
BufferSubgraph *bsg=(*subgraphs)[i];
// optimization - don't bother checking subgraphs
// which the ray does not intersect
Envelope *env = bsg->getEnvelope();
if ( stabbingRayLeftPt.y < env->getMinY()
|| stabbingRayLeftPt.y > env->getMaxY() )
continue;
findStabbedSegments(stabbingRayLeftPt, bsg->getDirectedEdges(),
stabbedSegments);
}
//return stabbedSegments;
}
/*private*/
void
SubgraphDepthLocater::findStabbedSegments( Coordinate &stabbingRayLeftPt,
vector<DirectedEdge*>* dirEdges,
vector<DepthSegment*>& stabbedSegments)
{
/**
* Check all forward DirectedEdges only. This is still general,
* because each Edge has a forward DirectedEdge.
*/
for (unsigned int i=0; i<dirEdges->size(); ++i)
{
DirectedEdge *de=(*dirEdges)[i];
if (!de->isForward())
continue;
findStabbedSegments(stabbingRayLeftPt, de, stabbedSegments);
}
}
/*private*/
void
SubgraphDepthLocater::findStabbedSegments( Coordinate &stabbingRayLeftPt,
DirectedEdge *dirEdge,
vector<DepthSegment*>& stabbedSegments)
{
const CoordinateSequence *pts=dirEdge->getEdge()->getCoordinates();
// It seems that LineSegment is *very* slow... undef this
// to see yourself
#define SKIP_LS 1
int n = pts->getSize()-1;
for (int i=0; i<n; ++i) {
#ifndef SKIP_LS
seg.p0=pts->getAt(i);
seg.p1=pts->getAt(i + 1);
#else
const Coordinate *low=&(pts->getAt(i));
const Coordinate *high=&(pts->getAt(i+1));
const Coordinate *swap=NULL;
#endif
#if DEBUG
cerr<<" SubgraphDepthLocater::findStabbedSegments: segment "<<i<<" ("<<seg.toString()<<") ";
#endif
#ifndef SKIP_LS
// ensure segment always points upwards
//if (seg.p0.y > seg.p1.y)
{
seg.reverse();
#if DEBUG
cerr<<" reverse ("<<seg.toString()<<") ";
#endif
}
#else
if (low->y > high->y)
{
swap=low;
low=high;
high=swap;
}
#endif
// skip segment if it is left of the stabbing line
// skip if segment is above or below stabbing line
#ifndef SKIP_LS
double maxx=max(seg.p0.x, seg.p1.x);
#else
double maxx=max(low->x, high->x);
#endif
if (maxx < stabbingRayLeftPt.x)
{
#if DEBUG
cerr<<" segment is left to stabbing line, skipping "<<endl;
#endif
continue;
}
// skip horizontal segments (there will be a non-horizontal
// one carrying the same depth info
#ifndef SKIP_LS
if (seg.isHorizontal())
#else
if (low->y == high->y)
#endif
{
#if DEBUG
cerr<<" segment is horizontal, skipping "<<endl;
#endif
continue;
}
// skip if segment is above or below stabbing line
#ifndef SKIP_LS
if (stabbingRayLeftPt.y < seg.p0.y ||
stabbingRayLeftPt.y > seg.p1.y)
#else
if (stabbingRayLeftPt.y < low->y ||
stabbingRayLeftPt.y > high->y)
#endif
{
#if DEBUG
cerr<<" segment above or below stabbing line, skipping "<<endl;
#endif
continue;
}
// skip if stabbing ray is right of the segment
#ifndef SKIP_LS
if (CGAlgorithms::computeOrientation(seg.p0, seg.p1,
#else
if (CGAlgorithms::computeOrientation(*low, *high,
#endif
stabbingRayLeftPt)==CGAlgorithms::RIGHT)
{
#if DEBUG
cerr<<" stabbing ray right of segment, skipping"<<endl;
#endif
continue;
}
#ifndef SKIP_LS
// stabbing line cuts this segment, so record it
int depth=dirEdge->getDepth(Position::LEFT);
// if segment direction was flipped, use RHS depth instead
if (! (seg.p0==pts->getAt(i)))
depth=dirEdge->getDepth(Position::RIGHT);
#else
int depth = swap ?
dirEdge->getDepth(Position::RIGHT)
:
dirEdge->getDepth(Position::LEFT);
#endif
#if DEBUG
cerr<<" depth: "<<depth<<endl;
#endif
#ifdef SKIP_LS
seg.p0 = *low;
seg.p1 = *high;
#endif
DepthSegment *ds=new DepthSegment(seg, depth);
stabbedSegments.push_back(ds);
}
}
} // namespace geos.operation.buffer
} // namespace geos.operation
} // namespace geos
/**********************************************************************
* $Log$
* Revision 1.18 2006/03/01 17:16:39 strk
* LineSegment class made final and optionally (compile-time) inlined.
* Reduced heap allocations in Centroid{Area,Line,Point} and InteriorPoint{Area,Line,Point}.
*
* Revision 1.17 2006/02/19 19:46:49 strk
* Packages <-> namespaces mapping for most GEOS internal code (uncomplete, but working). Dir-level libs for index/ subdirs.
*
* Revision 1.16 2006/01/31 19:07:34 strk
* - Renamed DefaultCoordinateSequence to CoordinateArraySequence.
* - Moved GetNumGeometries() and GetGeometryN() interfaces
* from GeometryCollection to Geometry class.
* - Added getAt(int pos, Coordinate &to) funtion to CoordinateSequence class.
* - Reworked automake scripts to produce a static lib for each subdir and
* then link all subsystem's libs togheter
* - Moved C-API in it's own top-level dir capi/
* - Moved source/bigtest and source/test to tests/bigtest and test/xmltester
* - Fixed PointLocator handling of LinearRings
* - Changed CoordinateArrayFilter to reduce memory copies
* - Changed UniqueCoordinateArrayFilter to reduce memory copies
* - Added CGAlgorithms::isPointInRing() version working with
* Coordinate::ConstVect type (faster!)
* - Ported JTS-1.7 version of ConvexHull with big attention to
* memory usage optimizations.
* - Improved XMLTester output and user interface
* - geos::geom::util namespace used for geom/util stuff
* - Improved memory use in geos::geom::util::PolygonExtractor
* - New ShortCircuitedGeometryVisitor class
* - New operation/predicate package
*
* Revision 1.15 2005/11/08 20:12:44 strk
* Memory overhead reductions in buffer operations.
*
* Revision 1.14 2005/07/11 10:27:14 strk
* Fixed initializzazion lists
*
* Revision 1.13 2005/06/30 18:31:48 strk
* Ported SubgraphDepthLocator optimizations from JTS code
*
* Revision 1.12 2005/06/28 21:13:43 strk
* Fixed a bug introduced by LineSegment skip - made LineSegment skip a compile-time optione
*
* Revision 1.11 2005/06/27 21:58:31 strk
* Bugfix in DepthSegmentLT as suggested by Graeme Hiebert
*
* Revision 1.10 2005/06/27 21:24:54 strk
* Fixed bug just-introduced with optimization.
*
* Revision 1.9 2005/06/27 21:21:21 strk
* Reduced Coordinate copies due to LineSegment overuse
*
* Revision 1.8 2005/05/23 15:13:00 strk
* Added debugging output
*
* Revision 1.7 2005/05/20 16:15:41 strk
* Code cleanups
*
* Revision 1.6 2005/05/19 10:29:28 strk
* Removed some CGAlgorithms instances substituting them with direct calls
* to the static functions. Interfaces accepting CGAlgorithms pointers kept
* for backward compatibility but modified to make the argument optional.
* Fixed a small memory leak in OffsetCurveBuilder::getRingCurve.
* Inlined some smaller functions encountered during bug hunting.
* Updated Copyright notices in the touched files.
*
* Revision 1.5 2004/07/08 19:34:49 strk
* Mirrored JTS interface of CoordinateSequence, factory and
* default implementations.
* Added CoordinateArraySequenceFactory::instance() function.
*
* Revision 1.4 2004/07/02 13:28:28 strk
* Fixed all #include lines to reflect headers layout change.
* Added client application build tips in README.
*
* Revision 1.3 2004/05/05 12:29:44 strk
* memleak fixed in ::getDepth
*
* Revision 1.2 2004/05/03 22:56:44 strk
* leaks fixed, exception specification omitted.
*
* Revision 1.1 2004/04/10 08:40:01 ybychkov
* "operation/buffer" upgraded to JTS 1.4
*
*
**********************************************************************/
<commit_msg>cleaned up debugging lines<commit_after>/**********************************************************************
* $Id$
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2001-2002 Vivid Solutions Inc.
* Copyright (C) 2005 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: operation/buffer/SubgraphDepthLocater.java rev. 1.5 (JTS-1.7)
*
**********************************************************************/
#include <geos/opBuffer.h>
#ifndef DEBUG
#define DEBUG 0
#endif
using namespace geos::geomgraph;
using namespace geos::noding;
using namespace geos::algorithm;
using namespace geos::operation::overlay;
namespace geos {
namespace operation { // geos.operation
namespace buffer { // geos.operation.buffer
/*public*/
int
SubgraphDepthLocater::getDepth(Coordinate &p)
{
vector<DepthSegment*> stabbedSegments;
findStabbedSegments(p, stabbedSegments);
// if no segments on stabbing line subgraph must be outside all others->
if (stabbedSegments.size()==0) return 0;
sort(stabbedSegments.begin(), stabbedSegments.end(), DepthSegmentLT);
DepthSegment *ds=stabbedSegments[0];
int ret = ds->leftDepth;
#if DEBUG
cerr<<"SubgraphDepthLocater::getDepth("<<p.toString()<<"): "<<ret<<endl;
#endif
for (vector<DepthSegment *>::iterator
it=stabbedSegments.begin(), itEnd=stabbedSegments.end();
it != itEnd;
++it)
{
delete *it;
}
return ret;
}
/*private*/
void
SubgraphDepthLocater::findStabbedSegments(Coordinate &stabbingRayLeftPt,
std::vector<DepthSegment*>& stabbedSegments)
{
unsigned int size = subgraphs->size();
for (unsigned int i=0; i<size; ++i)
{
BufferSubgraph *bsg=(*subgraphs)[i];
// optimization - don't bother checking subgraphs
// which the ray does not intersect
Envelope *env = bsg->getEnvelope();
if ( stabbingRayLeftPt.y < env->getMinY()
|| stabbingRayLeftPt.y > env->getMaxY() )
continue;
findStabbedSegments(stabbingRayLeftPt, bsg->getDirectedEdges(),
stabbedSegments);
}
//return stabbedSegments;
}
/*private*/
void
SubgraphDepthLocater::findStabbedSegments( Coordinate &stabbingRayLeftPt,
vector<DirectedEdge*>* dirEdges,
vector<DepthSegment*>& stabbedSegments)
{
/**
* Check all forward DirectedEdges only. This is still general,
* because each Edge has a forward DirectedEdge.
*/
for (unsigned int i=0; i<dirEdges->size(); ++i)
{
DirectedEdge *de=(*dirEdges)[i];
if (!de->isForward())
continue;
findStabbedSegments(stabbingRayLeftPt, de, stabbedSegments);
}
}
/*private*/
void
SubgraphDepthLocater::findStabbedSegments( Coordinate &stabbingRayLeftPt,
DirectedEdge *dirEdge,
vector<DepthSegment*>& stabbedSegments)
{
const CoordinateSequence *pts=dirEdge->getEdge()->getCoordinates();
// It seems that LineSegment is *very* slow... undef this
// to see yourself
// LineSegment has been refactored to be mostly inline, still
// it makes copies of the given coordinates, while the 'non-LineSemgent'
// based code below uses pointers instead. I'll kip the SKIP_LS
// defined until LineSegment switches to Coordinate pointers instead.
//
#define SKIP_LS 1
int n = pts->getSize()-1;
for (int i=0; i<n; ++i) {
#ifndef SKIP_LS
seg.p0=pts->getAt(i);
seg.p1=pts->getAt(i + 1);
#if DEBUG
cerr << " SubgraphDepthLocater::findStabbedSegments: segment " << i
<< " (" << seg << ") ";
#endif
#else
const Coordinate *low=&(pts->getAt(i));
const Coordinate *high=&(pts->getAt(i+1));
const Coordinate *swap=NULL;
#endif
#ifndef SKIP_LS
// ensure segment always points upwards
//if (seg.p0.y > seg.p1.y)
{
seg.reverse();
#if DEBUG
cerr << " reverse (" << seg << ") ";
#endif
}
#else
if (low->y > high->y)
{
swap=low;
low=high;
high=swap;
}
#endif
// skip segment if it is left of the stabbing line
// skip if segment is above or below stabbing line
#ifndef SKIP_LS
double maxx=max(seg.p0.x, seg.p1.x);
#else
double maxx=max(low->x, high->x);
#endif
if (maxx < stabbingRayLeftPt.x)
{
#if DEBUG
cerr<<" segment is left to stabbing line, skipping "<<endl;
#endif
continue;
}
// skip horizontal segments (there will be a non-horizontal
// one carrying the same depth info
#ifndef SKIP_LS
if (seg.isHorizontal())
#else
if (low->y == high->y)
#endif
{
#if DEBUG
cerr<<" segment is horizontal, skipping "<<endl;
#endif
continue;
}
// skip if segment is above or below stabbing line
#ifndef SKIP_LS
if (stabbingRayLeftPt.y < seg.p0.y ||
stabbingRayLeftPt.y > seg.p1.y)
#else
if (stabbingRayLeftPt.y < low->y ||
stabbingRayLeftPt.y > high->y)
#endif
{
#if DEBUG
cerr<<" segment above or below stabbing line, skipping "<<endl;
#endif
continue;
}
// skip if stabbing ray is right of the segment
#ifndef SKIP_LS
if (CGAlgorithms::computeOrientation(seg.p0, seg.p1,
#else
if (CGAlgorithms::computeOrientation(*low, *high,
#endif
stabbingRayLeftPt)==CGAlgorithms::RIGHT)
{
#if DEBUG
cerr<<" stabbing ray right of segment, skipping"<<endl;
#endif
continue;
}
#ifndef SKIP_LS
// stabbing line cuts this segment, so record it
int depth=dirEdge->getDepth(Position::LEFT);
// if segment direction was flipped, use RHS depth instead
if (! (seg.p0==pts->getAt(i)))
depth=dirEdge->getDepth(Position::RIGHT);
#else
int depth = swap ?
dirEdge->getDepth(Position::RIGHT)
:
dirEdge->getDepth(Position::LEFT);
#endif
#if DEBUG
cerr<<" depth: "<<depth<<endl;
#endif
#ifdef SKIP_LS
seg.p0 = *low;
seg.p1 = *high;
#endif
DepthSegment *ds=new DepthSegment(seg, depth);
stabbedSegments.push_back(ds);
}
}
} // namespace geos.operation.buffer
} // namespace geos.operation
} // namespace geos
/**********************************************************************
* $Log$
* Revision 1.19 2006/03/02 09:46:04 strk
* cleaned up debugging lines
*
* Revision 1.18 2006/03/01 17:16:39 strk
* LineSegment class made final and optionally (compile-time) inlined.
* Reduced heap allocations in Centroid{Area,Line,Point} and InteriorPoint{Area,Line,Point}.
*
* Revision 1.17 2006/02/19 19:46:49 strk
* Packages <-> namespaces mapping for most GEOS internal code (uncomplete, but working). Dir-level libs for index/ subdirs.
*
* Revision 1.16 2006/01/31 19:07:34 strk
* - Renamed DefaultCoordinateSequence to CoordinateArraySequence.
* - Moved GetNumGeometries() and GetGeometryN() interfaces
* from GeometryCollection to Geometry class.
* - Added getAt(int pos, Coordinate &to) funtion to CoordinateSequence class.
* - Reworked automake scripts to produce a static lib for each subdir and
* then link all subsystem's libs togheter
* - Moved C-API in it's own top-level dir capi/
* - Moved source/bigtest and source/test to tests/bigtest and test/xmltester
* - Fixed PointLocator handling of LinearRings
* - Changed CoordinateArrayFilter to reduce memory copies
* - Changed UniqueCoordinateArrayFilter to reduce memory copies
* - Added CGAlgorithms::isPointInRing() version working with
* Coordinate::ConstVect type (faster!)
* - Ported JTS-1.7 version of ConvexHull with big attention to
* memory usage optimizations.
* - Improved XMLTester output and user interface
* - geos::geom::util namespace used for geom/util stuff
* - Improved memory use in geos::geom::util::PolygonExtractor
* - New ShortCircuitedGeometryVisitor class
* - New operation/predicate package
*
* Revision 1.15 2005/11/08 20:12:44 strk
* Memory overhead reductions in buffer operations.
*
* Revision 1.14 2005/07/11 10:27:14 strk
* Fixed initializzazion lists
*
* Revision 1.13 2005/06/30 18:31:48 strk
* Ported SubgraphDepthLocator optimizations from JTS code
*
* Revision 1.12 2005/06/28 21:13:43 strk
* Fixed a bug introduced by LineSegment skip - made LineSegment skip a compile-time optione
*
* Revision 1.11 2005/06/27 21:58:31 strk
* Bugfix in DepthSegmentLT as suggested by Graeme Hiebert
*
* Revision 1.10 2005/06/27 21:24:54 strk
* Fixed bug just-introduced with optimization.
*
* Revision 1.9 2005/06/27 21:21:21 strk
* Reduced Coordinate copies due to LineSegment overuse
*
* Revision 1.8 2005/05/23 15:13:00 strk
* Added debugging output
*
* Revision 1.7 2005/05/20 16:15:41 strk
* Code cleanups
*
* Revision 1.6 2005/05/19 10:29:28 strk
* Removed some CGAlgorithms instances substituting them with direct calls
* to the static functions. Interfaces accepting CGAlgorithms pointers kept
* for backward compatibility but modified to make the argument optional.
* Fixed a small memory leak in OffsetCurveBuilder::getRingCurve.
* Inlined some smaller functions encountered during bug hunting.
* Updated Copyright notices in the touched files.
*
* Revision 1.5 2004/07/08 19:34:49 strk
* Mirrored JTS interface of CoordinateSequence, factory and
* default implementations.
* Added CoordinateArraySequenceFactory::instance() function.
*
* Revision 1.4 2004/07/02 13:28:28 strk
* Fixed all #include lines to reflect headers layout change.
* Added client application build tips in README.
*
* Revision 1.3 2004/05/05 12:29:44 strk
* memleak fixed in ::getDepth
*
* Revision 1.2 2004/05/03 22:56:44 strk
* leaks fixed, exception specification omitted.
*
* Revision 1.1 2004/04/10 08:40:01 ybychkov
* "operation/buffer" upgraded to JTS 1.4
*
*
**********************************************************************/
<|endoftext|> |
<commit_before>/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <ndb_global.h>
#include <NDBT_Thread.hpp>
#include <NdbApi.hpp>
NDBT_Thread::NDBT_Thread()
{
create(0, -1);
}
NDBT_Thread::NDBT_Thread(NDBT_ThreadSet* thread_set, int thread_no)
{
create(thread_set, thread_no);
}
void
NDBT_Thread::create(NDBT_ThreadSet* thread_set, int thread_no)
{
m_magic = NDBT_Thread::Magic;
m_state = Wait;
m_thread_set = thread_set;
m_thread_no = thread_no;
m_func = 0;
m_input = 0;
m_output = 0;
m_ndb = 0;
m_err = 0;
m_mutex = NdbMutex_Create();
assert(m_mutex != 0);
m_cond = NdbCondition_Create();
assert(m_cond != 0);
char buf[20];
sprintf(buf, "NDBT_%04u");
const char* name = strdup(buf);
assert(name != 0);
unsigned stacksize = 512 * 1024;
NDB_THREAD_PRIO prio = NDB_THREAD_PRIO_LOW;
m_thread = NdbThread_Create(NDBT_Thread_run,
(void**)this, stacksize, name, prio);
assert(m_thread != 0);
}
NDBT_Thread::~NDBT_Thread()
{
if (m_thread != 0) {
NdbThread_Destroy(&m_thread);
m_thread = 0;
}
if (m_cond != 0) {
NdbCondition_Destroy(m_cond);
m_cond = 0;
}
if (m_mutex != 0) {
NdbMutex_Destroy(m_mutex);
m_mutex = 0;
}
}
static void*
NDBT_Thread_run(void* arg)
{
assert(arg != 0);
NDBT_Thread& thr = *(NDBT_Thread*)arg;
assert(thr.m_magic == NDBT_Thread::Magic);
thr.run();
return 0;
}
void
NDBT_Thread::run()
{
while (1) {
lock();
while (m_state != Start && m_state != Exit) {
wait();
}
if (m_state == Exit) {
unlock();
break;
}
(*m_func)(*this);
m_state = Stop;
signal();
unlock();
}
}
// methods for main process
void
NDBT_Thread::start()
{
lock();
m_state = Start;
signal();
unlock();
}
void
NDBT_Thread::stop()
{
lock();
while (m_state != Stop)
wait();
m_state = Wait;
unlock();
}
void
NDBT_Thread::exit()
{
lock();
m_state = Exit;
signal();
unlock();
};
void
NDBT_Thread::join()
{
NdbThread_WaitFor(m_thread, &m_status);
m_thread = 0;
}
int
NDBT_Thread::connect(class Ndb_cluster_connection* ncc, const char* db)
{
m_ndb = new Ndb(ncc, db);
if (m_ndb->init() == -1 ||
m_ndb->waitUntilReady() == -1) {
m_err = m_ndb->getNdbError().code;
return -1;
}
return 0;
}
void
NDBT_Thread::disconnect()
{
delete m_ndb;
m_ndb = 0;
}
// set of threads
NDBT_ThreadSet::NDBT_ThreadSet(int count)
{
m_count = count;
m_thread = new NDBT_Thread* [count];
for (int n = 0; n < count; n++) {
m_thread[n] = new NDBT_Thread(this, n);
}
}
NDBT_ThreadSet::~NDBT_ThreadSet()
{
delete_output();
for (int n = 0; n < m_count; n++) {
delete m_thread[n];
m_thread[n] = 0;
}
delete [] m_thread;
}
void
NDBT_ThreadSet::start()
{
for (int n = 0; n < m_count; n++) {
NDBT_Thread& thr = *m_thread[n];
thr.start();
}
}
void
NDBT_ThreadSet::stop()
{
for (int n = 0; n < m_count; n++) {
NDBT_Thread& thr = *m_thread[n];
thr.stop();
}
}
void
NDBT_ThreadSet::exit()
{
for (int n = 0; n < m_count; n++) {
NDBT_Thread& thr = *m_thread[n];
thr.exit();
}
}
void
NDBT_ThreadSet::join()
{
for (int n = 0; n < m_count; n++) {
NDBT_Thread& thr = *m_thread[n];
thr.join();
}
}
void
NDBT_ThreadSet::set_func(NDBT_ThreadFunc* func)
{
for (int n = 0; n < m_count; n++) {
NDBT_Thread& thr = *m_thread[n];
thr.set_func(func);
}
}
void
NDBT_ThreadSet::set_input(const void* input)
{
for (int n = 0; n < m_count; n++) {
NDBT_Thread& thr = *m_thread[n];
thr.set_input(input);
}
}
void
NDBT_ThreadSet::delete_output()
{
for (int n = 0; n < m_count; n++) {
if (m_thread[n] != 0) {
NDBT_Thread& thr = *m_thread[n];
thr.delete_output();
}
}
}
int
NDBT_ThreadSet::connect(class Ndb_cluster_connection* ncc, const char* db)
{
for (int n = 0; n < m_count; n++) {
assert(m_thread[n] != 0);
NDBT_Thread& thr = *m_thread[n];
if (thr.connect(ncc, db) == -1)
return -1;
}
return 0;
}
void
NDBT_ThreadSet::disconnect()
{
for (int n = 0; n < m_count; n++) {
if (m_thread[n] != 0) {
NDBT_Thread& thr = *m_thread[n];
thr.disconnect();
}
}
}
int
NDBT_ThreadSet::get_err() const
{
for (int n = 0; n < m_count; n++) {
if (m_thread[n] != 0) {
NDBT_Thread& thr = *m_thread[n];
int err = thr.get_err();
if (err != 0)
return err;
}
}
return 0;
}
<commit_msg>ndb - remove extra ; (in test framework)<commit_after>/* Copyright (C) 2003 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include <ndb_global.h>
#include <NDBT_Thread.hpp>
#include <NdbApi.hpp>
NDBT_Thread::NDBT_Thread()
{
create(0, -1);
}
NDBT_Thread::NDBT_Thread(NDBT_ThreadSet* thread_set, int thread_no)
{
create(thread_set, thread_no);
}
void
NDBT_Thread::create(NDBT_ThreadSet* thread_set, int thread_no)
{
m_magic = NDBT_Thread::Magic;
m_state = Wait;
m_thread_set = thread_set;
m_thread_no = thread_no;
m_func = 0;
m_input = 0;
m_output = 0;
m_ndb = 0;
m_err = 0;
m_mutex = NdbMutex_Create();
assert(m_mutex != 0);
m_cond = NdbCondition_Create();
assert(m_cond != 0);
char buf[20];
sprintf(buf, "NDBT_%04u");
const char* name = strdup(buf);
assert(name != 0);
unsigned stacksize = 512 * 1024;
NDB_THREAD_PRIO prio = NDB_THREAD_PRIO_LOW;
m_thread = NdbThread_Create(NDBT_Thread_run,
(void**)this, stacksize, name, prio);
assert(m_thread != 0);
}
NDBT_Thread::~NDBT_Thread()
{
if (m_thread != 0) {
NdbThread_Destroy(&m_thread);
m_thread = 0;
}
if (m_cond != 0) {
NdbCondition_Destroy(m_cond);
m_cond = 0;
}
if (m_mutex != 0) {
NdbMutex_Destroy(m_mutex);
m_mutex = 0;
}
}
static void*
NDBT_Thread_run(void* arg)
{
assert(arg != 0);
NDBT_Thread& thr = *(NDBT_Thread*)arg;
assert(thr.m_magic == NDBT_Thread::Magic);
thr.run();
return 0;
}
void
NDBT_Thread::run()
{
while (1) {
lock();
while (m_state != Start && m_state != Exit) {
wait();
}
if (m_state == Exit) {
unlock();
break;
}
(*m_func)(*this);
m_state = Stop;
signal();
unlock();
}
}
// methods for main process
void
NDBT_Thread::start()
{
lock();
m_state = Start;
signal();
unlock();
}
void
NDBT_Thread::stop()
{
lock();
while (m_state != Stop)
wait();
m_state = Wait;
unlock();
}
void
NDBT_Thread::exit()
{
lock();
m_state = Exit;
signal();
unlock();
}
void
NDBT_Thread::join()
{
NdbThread_WaitFor(m_thread, &m_status);
m_thread = 0;
}
int
NDBT_Thread::connect(class Ndb_cluster_connection* ncc, const char* db)
{
m_ndb = new Ndb(ncc, db);
if (m_ndb->init() == -1 ||
m_ndb->waitUntilReady() == -1) {
m_err = m_ndb->getNdbError().code;
return -1;
}
return 0;
}
void
NDBT_Thread::disconnect()
{
delete m_ndb;
m_ndb = 0;
}
// set of threads
NDBT_ThreadSet::NDBT_ThreadSet(int count)
{
m_count = count;
m_thread = new NDBT_Thread* [count];
for (int n = 0; n < count; n++) {
m_thread[n] = new NDBT_Thread(this, n);
}
}
NDBT_ThreadSet::~NDBT_ThreadSet()
{
delete_output();
for (int n = 0; n < m_count; n++) {
delete m_thread[n];
m_thread[n] = 0;
}
delete [] m_thread;
}
void
NDBT_ThreadSet::start()
{
for (int n = 0; n < m_count; n++) {
NDBT_Thread& thr = *m_thread[n];
thr.start();
}
}
void
NDBT_ThreadSet::stop()
{
for (int n = 0; n < m_count; n++) {
NDBT_Thread& thr = *m_thread[n];
thr.stop();
}
}
void
NDBT_ThreadSet::exit()
{
for (int n = 0; n < m_count; n++) {
NDBT_Thread& thr = *m_thread[n];
thr.exit();
}
}
void
NDBT_ThreadSet::join()
{
for (int n = 0; n < m_count; n++) {
NDBT_Thread& thr = *m_thread[n];
thr.join();
}
}
void
NDBT_ThreadSet::set_func(NDBT_ThreadFunc* func)
{
for (int n = 0; n < m_count; n++) {
NDBT_Thread& thr = *m_thread[n];
thr.set_func(func);
}
}
void
NDBT_ThreadSet::set_input(const void* input)
{
for (int n = 0; n < m_count; n++) {
NDBT_Thread& thr = *m_thread[n];
thr.set_input(input);
}
}
void
NDBT_ThreadSet::delete_output()
{
for (int n = 0; n < m_count; n++) {
if (m_thread[n] != 0) {
NDBT_Thread& thr = *m_thread[n];
thr.delete_output();
}
}
}
int
NDBT_ThreadSet::connect(class Ndb_cluster_connection* ncc, const char* db)
{
for (int n = 0; n < m_count; n++) {
assert(m_thread[n] != 0);
NDBT_Thread& thr = *m_thread[n];
if (thr.connect(ncc, db) == -1)
return -1;
}
return 0;
}
void
NDBT_ThreadSet::disconnect()
{
for (int n = 0; n < m_count; n++) {
if (m_thread[n] != 0) {
NDBT_Thread& thr = *m_thread[n];
thr.disconnect();
}
}
}
int
NDBT_ThreadSet::get_err() const
{
for (int n = 0; n < m_count; n++) {
if (m_thread[n] != 0) {
NDBT_Thread& thr = *m_thread[n];
int err = thr.get_err();
if (err != 0)
return err;
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef _WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
#include <map>
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/md5.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "net/server/http_listen_socket.h"
#include "net/server/http_server_request_info.h"
// must run in the IO thread
HttpListenSocket::HttpListenSocket(SOCKET s,
HttpListenSocket::Delegate* delegate)
: ALLOW_THIS_IN_INITIALIZER_LIST(ListenSocket(s, this)),
delegate_(delegate),
is_web_socket_(false) {
}
// must run in the IO thread
HttpListenSocket::~HttpListenSocket() {
}
void HttpListenSocket::Accept() {
SOCKET conn = ListenSocket::Accept(socket_);
DCHECK_NE(conn, ListenSocket::kInvalidSocket);
if (conn == ListenSocket::kInvalidSocket) {
// TODO
} else {
scoped_refptr<HttpListenSocket> sock(
new HttpListenSocket(conn, delegate_));
#if defined(OS_POSIX)
sock->WatchSocket(WAITING_READ);
#endif
// it's up to the delegate to AddRef if it wants to keep it around
DidAccept(this, sock);
}
}
HttpListenSocket* HttpListenSocket::Listen(
const std::string& ip,
int port,
HttpListenSocket::Delegate* delegate) {
SOCKET s = ListenSocket::Listen(ip, port);
if (s == ListenSocket::kInvalidSocket) {
// TODO (ibrar): error handling
} else {
HttpListenSocket *serv = new HttpListenSocket(s, delegate);
serv->Listen();
return serv;
}
return NULL;
}
std::string GetHeaderValue(
const HttpServerRequestInfo& request,
const std::string& header_name) {
HttpServerRequestInfo::HeadersMap::iterator it =
request.headers.find(header_name);
if (it != request.headers.end())
return it->second;
return "";
}
uint32 WebSocketKeyFingerprint(const std::string& str) {
std::string result;
const char* pChar = str.c_str();
int length = str.length();
int spaces = 0;
for (int i = 0; i < length; ++i) {
if (pChar[i] >= '0' && pChar[i] <= '9')
result.append(&pChar[i], 1);
else if (pChar[i] == ' ')
spaces++;
}
if (spaces == 0)
return 0;
int64 number = 0;
if (!base::StringToInt64(result, &number))
return 0;
return htonl(static_cast<uint32>(number / spaces));
}
void HttpListenSocket::AcceptWebSocket(const HttpServerRequestInfo& request) {
std::string key1 = GetHeaderValue(request, "Sec-WebSocket-Key1");
std::string key2 = GetHeaderValue(request, "Sec-WebSocket-Key2");
uint32 fp1 = WebSocketKeyFingerprint(key1);
uint32 fp2 = WebSocketKeyFingerprint(key2);
char data[16];
memcpy(data, &fp1, 4);
memcpy(data + 4, &fp2, 4);
memcpy(data + 8, &request.data[0], 8);
MD5Digest digest;
MD5Sum(data, 16, &digest);
std::string origin = GetHeaderValue(request, "Origin");
std::string host = GetHeaderValue(request, "Host");
std::string location = "ws://" + host + request.path;
is_web_socket_ = true;
Send(base::StringPrintf("HTTP/1.1 101 WebSocket Protocol Handshake\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Origin: %s\r\n"
"Sec-WebSocket-Location: %s\r\n"
"\r\n",
origin.c_str(),
location.c_str()));
Send(reinterpret_cast<char*>(digest.a), 16);
}
void HttpListenSocket::SendOverWebSocket(const std::string& data) {
DCHECK(is_web_socket_);
char message_start = 0;
char message_end = -1;
Send(&message_start, 1);
Send(data);
Send(&message_end, 1);
}
void HttpListenSocket::Send200(const std::string& data,
const std::string& content_type) {
Send(base::StringPrintf("HTTP/1.1 200 OK\r\n"
"Content-Type:%s\r\n"
"Content-Length:%d\r\n"
"\r\n",
content_type.c_str(),
static_cast<int>(data.length())));
Send(data);
}
void HttpListenSocket::Send404() {
Send("HTTP/1.1 404 Not Found\r\n"
"Content-Length: 0\r\n"
"\r\n");
}
void HttpListenSocket::Send500(const std::string& message) {
Send(base::StringPrintf("HTTP/1.1 500 Internal Error\r\n"
"Content-Type:text/html\r\n"
"Content-Length:%d\r\n"
"\r\n"
"%s",
static_cast<int>(message.length()),
message.c_str()));
}
//
// HTTP Request Parser
// This HTTP request parser uses a simple state machine to quickly parse
// through the headers. The parser is not 100% complete, as it is designed
// for use in this simple test driver.
//
// Known issues:
// - does not handle whitespace on first HTTP line correctly. Expects
// a single space between the method/url and url/protocol.
// Input character types.
enum header_parse_inputs {
INPUT_SPACE,
INPUT_CR,
INPUT_LF,
INPUT_COLON,
INPUT_00,
INPUT_FF,
INPUT_DEFAULT,
MAX_INPUTS,
};
// Parser states.
enum header_parse_states {
ST_METHOD, // Receiving the method
ST_URL, // Receiving the URL
ST_PROTO, // Receiving the protocol
ST_HEADER, // Starting a Request Header
ST_NAME, // Receiving a request header name
ST_SEPARATOR, // Receiving the separator between header name and value
ST_VALUE, // Receiving a request header value
ST_WS_READY, // Ready to receive web socket frame
ST_WS_FRAME, // Receiving WebSocket frame
ST_WS_CLOSE, // Closing the connection WebSocket connection
ST_DONE, // Parsing is complete and successful
ST_ERR, // Parsing encountered invalid syntax.
MAX_STATES
};
// State transition table
int parser_state[MAX_STATES][MAX_INPUTS] = {
/* METHOD */ { ST_URL, ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_METHOD },
/* URL */ { ST_PROTO, ST_ERR, ST_ERR, ST_URL, ST_ERR, ST_ERR, ST_URL },
/* PROTOCOL */ { ST_ERR, ST_HEADER, ST_NAME, ST_ERR, ST_ERR, ST_ERR, ST_PROTO },
/* HEADER */ { ST_ERR, ST_ERR, ST_NAME, ST_ERR, ST_ERR, ST_ERR, ST_ERR },
/* NAME */ { ST_SEPARATOR, ST_DONE, ST_ERR, ST_SEPARATOR, ST_ERR, ST_ERR, ST_NAME },
/* SEPARATOR */ { ST_SEPARATOR, ST_ERR, ST_ERR, ST_SEPARATOR, ST_ERR, ST_ERR, ST_VALUE },
/* VALUE */ { ST_VALUE, ST_HEADER, ST_NAME, ST_VALUE, ST_ERR, ST_ERR, ST_VALUE },
/* WS_READY */ { ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_WS_FRAME, ST_WS_CLOSE, ST_ERR},
/* WS_FRAME */ { ST_WS_FRAME, ST_WS_FRAME, ST_WS_FRAME, ST_WS_FRAME, ST_ERR, ST_WS_READY, ST_WS_FRAME },
/* WS_CLOSE */ { ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_WS_CLOSE, ST_ERR, ST_ERR },
/* DONE */ { ST_DONE, ST_DONE, ST_DONE, ST_DONE, ST_DONE, ST_DONE, ST_DONE },
/* ERR */ { ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_ERR }
};
// Convert an input character to the parser's input token.
int charToInput(char ch) {
switch(ch) {
case ' ':
return INPUT_SPACE;
case '\r':
return INPUT_CR;
case '\n':
return INPUT_LF;
case ':':
return INPUT_COLON;
case 0x0:
return INPUT_00;
case static_cast<char>(-1):
return INPUT_FF;
}
return INPUT_DEFAULT;
}
bool HttpListenSocket::ParseHeaders(HttpServerRequestInfo* info) {
int pos = 0;
int data_len = recv_data_.length();
int state = is_web_socket_ ? ST_WS_READY : ST_METHOD;
std::string buffer;
std::string header_name;
std::string header_value;
while (pos < data_len) {
char ch = recv_data_[pos++];
int input = charToInput(ch);
int next_state = parser_state[state][input];
bool transition = (next_state != state);
if (transition) {
// Do any actions based on state transitions.
switch (state) {
case ST_METHOD:
info->method = buffer;
buffer.clear();
break;
case ST_URL:
info->path = buffer;
buffer.clear();
break;
case ST_PROTO:
// TODO(mbelshe): Deal better with parsing protocol.
DCHECK(buffer == "HTTP/1.1");
buffer.clear();
break;
case ST_NAME:
header_name = buffer;
buffer.clear();
break;
case ST_VALUE:
header_value = buffer;
// TODO(mbelshe): Deal better with duplicate headers
DCHECK(info->headers.find(header_name) == info->headers.end());
info->headers[header_name] = header_value;
buffer.clear();
break;
case ST_SEPARATOR:
buffer.append(&ch, 1);
break;
case ST_WS_FRAME:
recv_data_ = recv_data_.substr(pos);
info->data = buffer;
buffer.clear();
return true;
break;
}
state = next_state;
} else {
// Do any actions based on current state
switch (state) {
case ST_METHOD:
case ST_URL:
case ST_PROTO:
case ST_VALUE:
case ST_NAME:
case ST_WS_FRAME:
buffer.append(&ch, 1);
break;
case ST_DONE:
recv_data_ = recv_data_.substr(pos);
info->data = recv_data_;
recv_data_.clear();
return true;
case ST_WS_CLOSE:
is_web_socket_ = false;
return false;
case ST_ERR:
return false;
}
}
}
// No more characters, but we haven't finished parsing yet.
return false;
}
void HttpListenSocket::Close() {
ListenSocket::Close();
}
void HttpListenSocket::Listen() {
ListenSocket::Listen();
}
void HttpListenSocket::DidAccept(ListenSocket* server,
ListenSocket* connection) {
connection->AddRef();
}
void HttpListenSocket::DidRead(ListenSocket*,
const char* data,
int len) {
recv_data_.append(data, len);
while (recv_data_.length()) {
HttpServerRequestInfo request;
if (!ParseHeaders(&request))
break;
if (is_web_socket_) {
delegate_->OnWebSocketMessage(this, request.data);
continue;
}
std::string connection = GetHeaderValue(request, "Connection");
if (connection == "Upgrade") {
// Is this WebSocket and if yes, upgrade the connection.
std::string key1 = GetHeaderValue(request, "Sec-WebSocket-Key1");
std::string key2 = GetHeaderValue(request, "Sec-WebSocket-Key2");
if (!key1.empty() && !key2.empty()) {
delegate_->OnWebSocketRequest(this, request);
continue;
}
}
delegate_->OnHttpRequest(this, request);
}
}
void HttpListenSocket::DidClose(ListenSocket* sock) {
sock->Release();
delegate_->OnClose(this);
}
<commit_msg>Fix HttpListenSocket.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef _WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
#include <map>
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/md5.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "net/server/http_listen_socket.h"
#include "net/server/http_server_request_info.h"
// must run in the IO thread
HttpListenSocket::HttpListenSocket(SOCKET s,
HttpListenSocket::Delegate* delegate)
: ALLOW_THIS_IN_INITIALIZER_LIST(ListenSocket(s, this)),
delegate_(delegate),
is_web_socket_(false) {
}
// must run in the IO thread
HttpListenSocket::~HttpListenSocket() {
}
void HttpListenSocket::Accept() {
SOCKET conn = ListenSocket::Accept(socket_);
DCHECK_NE(conn, ListenSocket::kInvalidSocket);
if (conn == ListenSocket::kInvalidSocket) {
// TODO
} else {
scoped_refptr<HttpListenSocket> sock(
new HttpListenSocket(conn, delegate_));
#if defined(OS_POSIX)
sock->WatchSocket(WAITING_READ);
#endif
// it's up to the delegate to AddRef if it wants to keep it around
DidAccept(this, sock);
}
}
HttpListenSocket* HttpListenSocket::Listen(
const std::string& ip,
int port,
HttpListenSocket::Delegate* delegate) {
SOCKET s = ListenSocket::Listen(ip, port);
if (s == ListenSocket::kInvalidSocket) {
// TODO (ibrar): error handling
} else {
HttpListenSocket *serv = new HttpListenSocket(s, delegate);
serv->Listen();
return serv;
}
return NULL;
}
std::string GetHeaderValue(
const HttpServerRequestInfo& request,
const std::string& header_name) {
HttpServerRequestInfo::HeadersMap::iterator it =
request.headers.find(header_name);
if (it != request.headers.end())
return it->second;
return "";
}
uint32 WebSocketKeyFingerprint(const std::string& str) {
std::string result;
const char* pChar = str.c_str();
int length = str.length();
int spaces = 0;
for (int i = 0; i < length; ++i) {
if (pChar[i] >= '0' && pChar[i] <= '9')
result.append(&pChar[i], 1);
else if (pChar[i] == ' ')
spaces++;
}
if (spaces == 0)
return 0;
int64 number = 0;
if (!base::StringToInt64(result, &number))
return 0;
return htonl(static_cast<uint32>(number / spaces));
}
void HttpListenSocket::AcceptWebSocket(const HttpServerRequestInfo& request) {
std::string key1 = GetHeaderValue(request, "Sec-WebSocket-Key1");
std::string key2 = GetHeaderValue(request, "Sec-WebSocket-Key2");
uint32 fp1 = WebSocketKeyFingerprint(key1);
uint32 fp2 = WebSocketKeyFingerprint(key2);
char data[16];
memcpy(data, &fp1, 4);
memcpy(data + 4, &fp2, 4);
memcpy(data + 8, &request.data[0], 8);
MD5Digest digest;
MD5Sum(data, 16, &digest);
std::string origin = GetHeaderValue(request, "Origin");
std::string host = GetHeaderValue(request, "Host");
std::string location = "ws://" + host + request.path;
is_web_socket_ = true;
Send(base::StringPrintf("HTTP/1.1 101 WebSocket Protocol Handshake\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Origin: %s\r\n"
"Sec-WebSocket-Location: %s\r\n"
"\r\n",
origin.c_str(),
location.c_str()));
Send(reinterpret_cast<char*>(digest.a), 16);
}
void HttpListenSocket::SendOverWebSocket(const std::string& data) {
DCHECK(is_web_socket_);
char message_start = 0;
char message_end = -1;
Send(&message_start, 1);
Send(data);
Send(&message_end, 1);
}
void HttpListenSocket::Send200(const std::string& data,
const std::string& content_type) {
Send(base::StringPrintf("HTTP/1.1 200 OK\r\n"
"Content-Type:%s\r\n"
"Content-Length:%d\r\n"
"\r\n",
content_type.c_str(),
static_cast<int>(data.length())));
Send(data);
}
void HttpListenSocket::Send404() {
Send("HTTP/1.1 404 Not Found\r\n"
"Content-Length: 0\r\n"
"\r\n");
}
void HttpListenSocket::Send500(const std::string& message) {
Send(base::StringPrintf("HTTP/1.1 500 Internal Error\r\n"
"Content-Type:text/html\r\n"
"Content-Length:%d\r\n"
"\r\n"
"%s",
static_cast<int>(message.length()),
message.c_str()));
}
//
// HTTP Request Parser
// This HTTP request parser uses a simple state machine to quickly parse
// through the headers. The parser is not 100% complete, as it is designed
// for use in this simple test driver.
//
// Known issues:
// - does not handle whitespace on first HTTP line correctly. Expects
// a single space between the method/url and url/protocol.
// Input character types.
enum header_parse_inputs {
INPUT_SPACE,
INPUT_CR,
INPUT_LF,
INPUT_COLON,
INPUT_00,
INPUT_FF,
INPUT_DEFAULT,
MAX_INPUTS,
};
// Parser states.
enum header_parse_states {
ST_METHOD, // Receiving the method
ST_URL, // Receiving the URL
ST_PROTO, // Receiving the protocol
ST_HEADER, // Starting a Request Header
ST_NAME, // Receiving a request header name
ST_SEPARATOR, // Receiving the separator between header name and value
ST_VALUE, // Receiving a request header value
ST_WS_READY, // Ready to receive web socket frame
ST_WS_FRAME, // Receiving WebSocket frame
ST_WS_CLOSE, // Closing the connection WebSocket connection
ST_DONE, // Parsing is complete and successful
ST_ERR, // Parsing encountered invalid syntax.
MAX_STATES
};
// State transition table
int parser_state[MAX_STATES][MAX_INPUTS] = {
/* METHOD */ { ST_URL, ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_METHOD },
/* URL */ { ST_PROTO, ST_ERR, ST_ERR, ST_URL, ST_ERR, ST_ERR, ST_URL },
/* PROTOCOL */ { ST_ERR, ST_HEADER, ST_NAME, ST_ERR, ST_ERR, ST_ERR, ST_PROTO },
/* HEADER */ { ST_ERR, ST_ERR, ST_NAME, ST_ERR, ST_ERR, ST_ERR, ST_ERR },
/* NAME */ { ST_SEPARATOR, ST_DONE, ST_ERR, ST_SEPARATOR, ST_ERR, ST_ERR, ST_NAME },
/* SEPARATOR */ { ST_SEPARATOR, ST_ERR, ST_ERR, ST_SEPARATOR, ST_ERR, ST_ERR, ST_VALUE },
/* VALUE */ { ST_VALUE, ST_HEADER, ST_NAME, ST_VALUE, ST_ERR, ST_ERR, ST_VALUE },
/* WS_READY */ { ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_WS_FRAME, ST_WS_CLOSE, ST_ERR},
/* WS_FRAME */ { ST_WS_FRAME, ST_WS_FRAME, ST_WS_FRAME, ST_WS_FRAME, ST_ERR, ST_WS_READY, ST_WS_FRAME },
/* WS_CLOSE */ { ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_WS_CLOSE, ST_ERR, ST_ERR },
/* DONE */ { ST_DONE, ST_DONE, ST_DONE, ST_DONE, ST_DONE, ST_DONE, ST_DONE },
/* ERR */ { ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_ERR, ST_ERR }
};
// Convert an input character to the parser's input token.
int charToInput(char ch) {
switch(ch) {
case ' ':
return INPUT_SPACE;
case '\r':
return INPUT_CR;
case '\n':
return INPUT_LF;
case ':':
return INPUT_COLON;
case 0x0:
return INPUT_00;
case static_cast<char>(-1):
return INPUT_FF;
}
return INPUT_DEFAULT;
}
bool HttpListenSocket::ParseHeaders(HttpServerRequestInfo* info) {
int pos = 0;
int data_len = recv_data_.length();
int state = is_web_socket_ ? ST_WS_READY : ST_METHOD;
std::string buffer;
std::string header_name;
std::string header_value;
while (pos < data_len) {
char ch = recv_data_[pos++];
int input = charToInput(ch);
int next_state = parser_state[state][input];
bool transition = (next_state != state);
if (transition) {
// Do any actions based on state transitions.
switch (state) {
case ST_METHOD:
info->method = buffer;
buffer.clear();
break;
case ST_URL:
info->path = buffer;
buffer.clear();
break;
case ST_PROTO:
// TODO(mbelshe): Deal better with parsing protocol.
DCHECK(buffer == "HTTP/1.1");
buffer.clear();
break;
case ST_NAME:
header_name = buffer;
buffer.clear();
break;
case ST_VALUE:
header_value = buffer;
// TODO(mbelshe): Deal better with duplicate headers
DCHECK(info->headers.find(header_name) == info->headers.end());
info->headers[header_name] = header_value;
buffer.clear();
break;
case ST_SEPARATOR:
buffer.append(&ch, 1);
break;
case ST_WS_FRAME:
recv_data_ = recv_data_.substr(pos);
info->data = buffer;
buffer.clear();
return true;
break;
}
state = next_state;
} else {
// Do any actions based on current state
switch (state) {
case ST_METHOD:
case ST_URL:
case ST_PROTO:
case ST_VALUE:
case ST_NAME:
case ST_WS_FRAME:
buffer.append(&ch, 1);
break;
case ST_DONE:
recv_data_ = recv_data_.substr(pos);
info->data = recv_data_;
recv_data_.clear();
return true;
case ST_WS_CLOSE:
is_web_socket_ = false;
return false;
case ST_ERR:
return false;
}
}
}
// No more characters, but we haven't finished parsing yet.
return false;
}
void HttpListenSocket::Close() {
ListenSocket::Close();
}
void HttpListenSocket::Listen() {
ListenSocket::Listen();
}
void HttpListenSocket::DidAccept(ListenSocket* server,
ListenSocket* connection) {
connection->AddRef();
}
void HttpListenSocket::DidRead(ListenSocket*,
const char* data,
int len) {
recv_data_.append(data, len);
while (recv_data_.length()) {
HttpServerRequestInfo request;
if (!ParseHeaders(&request))
break;
if (is_web_socket_) {
delegate_->OnWebSocketMessage(this, request.data);
continue;
}
std::string connection = GetHeaderValue(request, "Connection");
if (connection == "Upgrade") {
// Is this WebSocket and if yes, upgrade the connection.
std::string key1 = GetHeaderValue(request, "Sec-WebSocket-Key1");
std::string key2 = GetHeaderValue(request, "Sec-WebSocket-Key2");
if (!key1.empty() && !key2.empty()) {
delegate_->OnWebSocketRequest(this, request);
continue;
}
}
delegate_->OnHttpRequest(this, request);
}
}
void HttpListenSocket::DidClose(ListenSocket* sock) {
delegate_->OnClose(this);
sock->Release();
}
<|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_TEST_OPERATORS_WEIGHTED_L2_HH
#define DUNE_GDT_TEST_OPERATORS_WEIGHTED_L2_HH
#include <dune/stuff/common/string.hh>
#include <dune/stuff/test/gtest/gtest.h>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/weighted-l2.hh>
#include "base.hh"
namespace Dune {
namespace GDT {
namespace Tests {
/**
* \note The values in correct_for_constant_arguments(), etc., are valid for the d-dimendional unit cube.
*/
template <class SpaceType>
struct WeightedL2ProductBase
{
typedef typename SpaceType::GridViewType GridViewType;
typedef typename GridViewType::Grid GridType;
typedef Dune::Stuff::Grid::Providers::Cube<GridType> GridProviderType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
typedef typename SpaceType::DomainFieldType DomainFieldType;
static const size_t dimDomain = SpaceType::dimDomain;
typedef typename SpaceType::RangeFieldType RangeFieldType;
typedef Stuff::Functions::Expression<EntityType, DomainFieldType, dimDomain, RangeFieldType, 1>
ExpressionFunctionType;
static const int weight_value = 42;
WeightedL2ProductBase() // linker error if int(...) is missing, at least with clang
: weight_("x", DSC::toString(int(weight_value)), 0),
constant_("x", "1.0", 0),
linear_("x", "x[0] - 1.0", 1),
quadratic_("x", "x[0]*x[0]", 2)
{
}
virtual ~WeightedL2ProductBase() = default;
virtual RangeFieldType compute(const ExpressionFunctionType& function) const = 0;
void correct_for_constant_arguments() const
{
check(compute(constant_), weight_value * 1.0);
}
void correct_for_linear_arguments() const
{
check(compute(linear_), weight_value * (1.0 / 3.0));
}
void correct_for_quadratic_arguments() const
{
check(compute(quadratic_), weight_value * (1.0 / 5.0));
}
void check(const RangeFieldType& result, const RangeFieldType& expected,
const RangeFieldType epsilon = 2.14e-14) const
{
const auto error = std::abs(expected - result);
EXPECT_LE(error, epsilon) << "result: " << result << "\n"
<< "expected: " << expected << "\n"
<< "difference: " << std::scientific << error;
} // ... check(...)
const ExpressionFunctionType weight_;
const ExpressionFunctionType constant_;
const ExpressionFunctionType linear_;
const ExpressionFunctionType quadratic_;
}; // struct WeightedL2ProductBase
template <class SpaceType>
struct WeightedL2LocalizableProductTest : public WeightedL2ProductBase<SpaceType>,
public LocalizableProductBase<SpaceType>
{
typedef WeightedL2ProductBase<SpaceType> WeightedL2BaseType;
typedef LocalizableProductBase<SpaceType> LocalizableBaseType;
using typename LocalizableBaseType::GridViewType;
using typename WeightedL2BaseType::ExpressionFunctionType;
using typename LocalizableBaseType::ScalarFunctionType;
using typename LocalizableBaseType::RangeFieldType;
void constructible_by_ctor()
{
const auto& weight = this->weight_;
const auto& grid_view = this->space_.grid_view();
const auto& source = this->scalar_function_;
const auto& range = this->scalar_function_;
typedef WeightedL2LocalizableProduct<ExpressionFunctionType,
GridViewType,
ScalarFunctionType,
ScalarFunctionType,
double> CtorTestProductType;
CtorTestProductType DUNE_UNUSED(wo_over_integrate)(weight, grid_view, range, source);
CtorTestProductType DUNE_UNUSED(with_over_integrate)(1, weight, grid_view, range, source);
} // ... constructible_by_ctor(...)
void constructible_by_factory()
{
const auto& weight = this->weight_;
const auto& grid_view = this->space_.grid_view();
const auto& source = this->scalar_function_;
const auto& range = this->scalar_function_;
auto DUNE_UNUSED(wo_over_integrate) = make_weighted_l2_localizable_product(weight, grid_view, range, source);
auto DUNE_UNUSED(with_over_integrate) = make_weighted_l2_localizable_product(weight, grid_view, range, source, 1);
} // ... constructible_by_factory()
virtual RangeFieldType compute(const ExpressionFunctionType& function) const override final
{
const auto& weight = this->weight_;
const auto& grid_view = this->space_.grid_view();
auto product = make_weighted_l2_localizable_product(weight, grid_view, function, function);
const auto result = product->apply2();
auto product_tbb = make_weighted_l2_localizable_product(weight, grid_view, function, function);
product_tbb->walk(true);
const auto result_tbb = product_tbb->apply2();
EXPECT_EQ(result_tbb, result);
return result;
} // ... compute(...)
void is_localizable_product()
{
const auto& weight = this->weight_;
const auto& grid_view = this->space_.grid_view();
const auto& source = this->scalar_function_;
const auto& range = this->scalar_function_;
auto product = make_weighted_l2_localizable_product(weight, grid_view, range, source);
this->localizable_product_test(*product);
} // ... is_localizable_product(...)
}; // struct WeightedL2LocalizableProductTest
} // namespace Tests
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_TEST_OPERATORS_WEIGHTED_L2_HH
<commit_msg>[tests.operators.weighted-l2] add tests for WeightedL2MatrixOperator<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_TEST_OPERATORS_WEIGHTED_L2_HH
#define DUNE_GDT_TEST_OPERATORS_WEIGHTED_L2_HH
#include <dune/stuff/common/string.hh>
#include <dune/stuff/test/gtest/gtest.h>
#include <dune/gdt/operators/projections.hh>
#include <dune/gdt/operators/weighted-l2.hh>
#include "base.hh"
namespace Dune {
namespace GDT {
namespace Tests {
/**
* \note The values in correct_for_constant_arguments(), etc., are valid for the d-dimendional unit cube.
*/
template <class SpaceType>
struct WeightedL2ProductBase
{
typedef typename SpaceType::GridViewType GridViewType;
typedef typename GridViewType::Grid GridType;
typedef Dune::Stuff::Grid::Providers::Cube<GridType> GridProviderType;
typedef typename GridViewType::template Codim<0>::Entity EntityType;
typedef typename SpaceType::DomainFieldType DomainFieldType;
static const size_t dimDomain = SpaceType::dimDomain;
typedef typename SpaceType::RangeFieldType RangeFieldType;
typedef Stuff::Functions::Expression<EntityType, DomainFieldType, dimDomain, RangeFieldType, 1>
ExpressionFunctionType;
static const int weight_value = 42;
WeightedL2ProductBase() // linker error if int(...) is missing, at least with clang
: weight_("x", DSC::toString(int(weight_value)), 0),
constant_("x", "1.0", 0),
linear_("x", "x[0] - 1.0", 1),
quadratic_("x", "x[0]*x[0]", 2)
{
}
virtual ~WeightedL2ProductBase() = default;
virtual RangeFieldType compute(const ExpressionFunctionType& function) const = 0;
void correct_for_constant_arguments() const
{
check(compute(constant_), weight_value * 1.0);
}
void correct_for_linear_arguments() const
{
check(compute(linear_), weight_value * (1.0 / 3.0));
}
void correct_for_quadratic_arguments() const
{
check(compute(quadratic_), weight_value * (1.0 / 5.0));
}
void check(const RangeFieldType& result, const RangeFieldType& expected,
const RangeFieldType epsilon = 2.14e-14) const
{
const auto error = std::abs(expected - result);
EXPECT_LE(error, epsilon) << "result: " << result << "\n"
<< "expected: " << expected << "\n"
<< "difference: " << std::scientific << error;
} // ... check(...)
const ExpressionFunctionType weight_;
const ExpressionFunctionType constant_;
const ExpressionFunctionType linear_;
const ExpressionFunctionType quadratic_;
}; // struct WeightedL2ProductBase
template <class SpaceType>
struct WeightedL2LocalizableProductTest : public WeightedL2ProductBase<SpaceType>,
public LocalizableProductBase<SpaceType>
{
typedef WeightedL2ProductBase<SpaceType> WeightedL2BaseType;
typedef LocalizableProductBase<SpaceType> LocalizableBaseType;
using typename LocalizableBaseType::GridViewType;
using typename WeightedL2BaseType::ExpressionFunctionType;
using typename LocalizableBaseType::ScalarFunctionType;
using typename LocalizableBaseType::RangeFieldType;
void constructible_by_ctor()
{
const auto& weight = this->weight_;
const auto& grid_view = this->space_.grid_view();
const auto& source = this->scalar_function_;
const auto& range = this->scalar_function_;
typedef WeightedL2LocalizableProduct<ExpressionFunctionType,
GridViewType,
ScalarFunctionType,
ScalarFunctionType,
double> CtorTestProductType;
CtorTestProductType DUNE_UNUSED(wo_over_integrate)(weight, grid_view, range, source);
CtorTestProductType DUNE_UNUSED(with_over_integrate)(1, weight, grid_view, range, source);
} // ... constructible_by_ctor(...)
void constructible_by_factory()
{
const auto& weight = this->weight_;
const auto& grid_view = this->space_.grid_view();
const auto& source = this->scalar_function_;
const auto& range = this->scalar_function_;
auto DUNE_UNUSED(wo_over_integrate) = make_weighted_l2_localizable_product(weight, grid_view, range, source);
auto DUNE_UNUSED(with_over_integrate) = make_weighted_l2_localizable_product(weight, grid_view, range, source, 1);
} // ... constructible_by_factory()
virtual RangeFieldType compute(const ExpressionFunctionType& function) const override final
{
const auto& weight = this->weight_;
const auto& grid_view = this->space_.grid_view();
auto product = make_weighted_l2_localizable_product(weight, grid_view, function, function);
const auto result = product->apply2();
auto product_tbb = make_weighted_l2_localizable_product(weight, grid_view, function, function);
product_tbb->walk(true);
const auto result_tbb = product_tbb->apply2();
EXPECT_EQ(result_tbb, result);
return result;
} // ... compute(...)
void is_localizable_product()
{
const auto& weight = this->weight_;
const auto& grid_view = this->space_.grid_view();
const auto& source = this->scalar_function_;
const auto& range = this->scalar_function_;
auto product = make_weighted_l2_localizable_product(weight, grid_view, range, source);
this->localizable_product_test(*product);
} // ... is_localizable_product(...)
}; // struct WeightedL2LocalizableProductTest
/**
* \note Assumes that Operators::Projection does the right thing!
*/
template <class SpaceType>
struct WeightedL2MatrixOperatorTest : public WeightedL2ProductBase<SpaceType>, public MatrixOperatorBase<SpaceType>
{
typedef WeightedL2ProductBase<SpaceType> WeightedL2BaseType;
typedef MatrixOperatorBase<SpaceType> MatrixBaseType;
using typename MatrixBaseType::GridViewType;
using typename WeightedL2BaseType::ExpressionFunctionType;
using typename MatrixBaseType::DiscreteFunctionType;
using typename MatrixBaseType::ScalarFunctionType;
using typename MatrixBaseType::RangeFieldType;
using typename MatrixBaseType::MatrixType;
void constructible_by_ctor()
{
const auto& weight = this->weight_;
const auto& space = this->space_;
const auto& grid_view = this->space_.grid_view();
// without matrix
// without over_integrate
// simplified argument list
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType> DUNE_UNUSED(no_matrix_1)(weight, space);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType> DUNE_UNUSED(no_matrix_2)(weight, space, grid_view);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType> DUNE_UNUSED(no_matrix_3)(
weight, space, space, grid_view);
// full argument list
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType, MatrixType, GridViewType, SpaceType, double>
DUNE_UNUSED(no_matrix_4)(weight, space);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType, MatrixType, GridViewType, SpaceType, double>
DUNE_UNUSED(no_matrix_5)(weight, space, grid_view);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType, MatrixType, GridViewType, SpaceType, double>
DUNE_UNUSED(no_matrix_6)(weight, space, space, grid_view);
// with over_integrate
// simplified argument list
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType> DUNE_UNUSED(no_matrix_7)(1, weight, space);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType> DUNE_UNUSED(no_matrix_8)(1, weight, space, grid_view);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType> DUNE_UNUSED(no_matrix_9)(
1, weight, space, space, grid_view);
// full argument list
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType, MatrixType, GridViewType, SpaceType, double>
DUNE_UNUSED(no_matrix_10)(1, weight, space);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType, MatrixType, GridViewType, SpaceType, double>
DUNE_UNUSED(no_matrix_11)(1, weight, space, grid_view);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType, MatrixType, GridViewType, SpaceType, double>
DUNE_UNUSED(no_matrix_12)(1, weight, space, space, grid_view);
// with matrix
MatrixType matrix(space.mapper().size(), space.mapper().size(), space.compute_volume_pattern());
// without over_integrate
// simplified argument list
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType> DUNE_UNUSED(matrix_1)(weight, matrix, space);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType> DUNE_UNUSED(matrix_2)(weight, matrix, space, grid_view);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType> DUNE_UNUSED(matrix_3)(
weight, matrix, space, space, grid_view);
// full argument list
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType, MatrixType, GridViewType, SpaceType, double>
DUNE_UNUSED(matrix_4)(weight, matrix, space);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType, MatrixType, GridViewType, SpaceType, double>
DUNE_UNUSED(matrix_5)(weight, matrix, space, grid_view);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType, MatrixType, GridViewType, SpaceType, double>
DUNE_UNUSED(matrix_6)(weight, matrix, space, space, grid_view);
// with over_integrate
// simplified argument list
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType> DUNE_UNUSED(matrix_7)(1, weight, matrix, space);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType> DUNE_UNUSED(matrix_8)(
1, weight, matrix, space, grid_view);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType> DUNE_UNUSED(matrix_9)(
1, weight, matrix, space, space, grid_view);
// full argument list
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType, MatrixType, GridViewType, SpaceType, double>
DUNE_UNUSED(matrix_10)(1, weight, matrix, space);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType, MatrixType, GridViewType, SpaceType, double>
DUNE_UNUSED(matrix_11)(1, weight, matrix, space, grid_view);
WeightedL2MatrixOperator<ExpressionFunctionType, SpaceType, MatrixType, GridViewType, SpaceType, double>
DUNE_UNUSED(matrix_12)(1, weight, matrix, space, space, grid_view);
} // ... constructible_by_ctor(...)
void constructible_by_factory()
{
const auto& weight = this->weight_;
const auto& space = this->space_;
const auto& grid_view = this->space_.grid_view();
MatrixType matrix(space.mapper().size(), space.mapper().size(), space.compute_volume_pattern());
// without matrix
auto DUNE_UNUSED(op_01) = make_weighted_l2_matrix_operator<MatrixType>(weight, space);
auto DUNE_UNUSED(op_02) = make_weighted_l2_matrix_operator<MatrixType>(weight, space, 1);
auto DUNE_UNUSED(op_03) = make_weighted_l2_matrix_operator<MatrixType>(weight, space, grid_view);
auto DUNE_UNUSED(op_04) = make_weighted_l2_matrix_operator<MatrixType>(weight, space, grid_view, 1);
auto DUNE_UNUSED(op_05) = make_weighted_l2_matrix_operator<MatrixType>(weight, space, space, grid_view);
auto DUNE_UNUSED(op_06) = make_weighted_l2_matrix_operator<MatrixType>(weight, space, space, grid_view, 1);
// with matrix
auto DUNE_UNUSED(op_07) = make_weighted_l2_matrix_operator(weight, matrix, space);
auto DUNE_UNUSED(op_08) = make_weighted_l2_matrix_operator(weight, matrix, space, 1);
auto DUNE_UNUSED(op_09) = make_weighted_l2_matrix_operator(weight, matrix, space, grid_view);
auto DUNE_UNUSED(op_10) = make_weighted_l2_matrix_operator(weight, matrix, space, grid_view, 1);
auto DUNE_UNUSED(op_11) = make_weighted_l2_matrix_operator(weight, matrix, space, space, grid_view);
auto DUNE_UNUSED(op_12) = make_weighted_l2_matrix_operator(weight, matrix, space, space, grid_view, 1);
} // ... constructible_by_factory()
virtual RangeFieldType compute(const ExpressionFunctionType& function) const override final
{
const auto& weight = this->weight_;
const auto& space = this->space_;
// project the function
DiscreteFunctionType discrete_function(space);
project(function, discrete_function);
// compute product
auto product = make_weighted_l2_matrix_operator<MatrixType>(weight, space);
const auto result = product->apply2(discrete_function, discrete_function);
auto product_tbb = make_weighted_l2_matrix_operator<MatrixType>(weight, space);
product_tbb->assemble(true);
const auto result_tbb = product_tbb->apply2(discrete_function, discrete_function);
EXPECT_DOUBLE_EQ(result_tbb, result);
return result;
} // ... compute(...)
void is_matrix_operator()
{
const auto& weight = this->weight_;
const auto& space = this->space_;
auto op = make_weighted_l2_matrix_operator<MatrixType>(weight, space);
this->matrix_operator_test(*op);
} // ... is_matrix_operator(...)
}; // struct WeightedL2MatrixOperatorTest
} // namespace Tests
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_TEST_OPERATORS_WEIGHTED_L2_HH
<|endoftext|> |
<commit_before>#include <config.h>
#include "grid_creation.hh"
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/grid/structuredgridfactory.hh>
#include <dune/stuff/grid/information.hh>
// Helper struct to make overlap for SPGrid possible
// Declared in unnamed namespace to avoid naming conflicts
namespace {
template< class GridType >
class MyGridFactory {
typedef typename GridType::ctype ctype;
static const int dimworld = GridType::dimensionworld;
static const int dim = GridType::dim;
public:
static std::shared_ptr<GridType>
createCubeGrid(const Dune::FieldVector<ctype,dimworld>& lowerLeft,
const Dune::FieldVector<ctype,dimworld>& upperRight,
const Dune::array<unsigned int,dim>& elements,
const Dune::array<unsigned int,dim>& /*overlap*/) {
// structured grid factory allows overlap only for SPGrid at the moment, hence the following check
BOOST_ASSERT_MSG((DSC_CONFIG_GET("msfem.oversampling_layers", 0)==0),
"Oversampling may only be used in combination with SPGrid!");
return Dune::StructuredGridFactory<GridType>::createCubeGrid(lowerLeft, upperRight, elements);
}
};
template< class ct, int dim, Dune::SPRefinementStrategy strategy, class Comm >
class MyGridFactory< Dune::SPGrid< ct, dim, strategy, Comm > > {
typedef Dune::SPGrid< ct, dim, strategy, Comm > GridType;
typedef typename GridType::ctype ctype;
static const int dimworld = GridType::dimensionworld;
public:
static std::shared_ptr<GridType>
createCubeGrid(const Dune::FieldVector<ctype,dimworld>& lowerLeft,
const Dune::FieldVector<ctype,dimworld>& upperRight,
const Dune::array<unsigned int,dim>& elements,
const Dune::array<unsigned int,dim>& overlap) {
return Dune::StructuredGridFactory<GridType>::createCubeGrid(lowerLeft, upperRight, elements, overlap);
}
};
}
std::pair<std::shared_ptr<Dune::Multiscale::CommonTraits::GridType>,
std::shared_ptr<Dune::Multiscale::CommonTraits::GridType>>
Dune::Multiscale::make_grids() {
const int dim_world = CommonTraits::GridType::dimensionworld;
typedef FieldVector<typename CommonTraits::GridType::ctype, dim_world> CoordType;
CoordType lowerLeft(0.0);
CoordType upperRight(1.0);
const auto oversamplingLayers = DSC_CONFIG_GET("msfem.oversampling_layers", 0);
const auto microPerMacro = DSC_CONFIG_GET("msfem.micro_cells_per_macrocell_dim", 8);
const int overlapLayers = std::ceil(double(oversamplingLayers)/double(microPerMacro));
const auto coarse_cells = DSC_CONFIG_GET("global.macro_cells_per_dim", 8);
array<unsigned int, dim_world> elements;
array<unsigned int, dim_world> overCoarse;
for (const auto i : DSC::valueRange(dim_world)) {
elements[i] = coarse_cells;
overCoarse[i] = overlapLayers;
}
auto coarse_gridptr =
MyGridFactory<CommonTraits::GridType>::createCubeGrid(lowerLeft, upperRight, elements, overCoarse);
for (const auto i : DSC::valueRange(dim_world)) {
elements[i] = coarse_cells * DSC_CONFIG_GET("global.micro_cells_per_macrocell_dim", 8);
}
auto fine_gridptr = StructuredGridFactory<CommonTraits::GridType>::createCubeGrid(lowerLeft, upperRight, elements);
return {coarse_gridptr, fine_gridptr};
}
<commit_msg>Removed superfluous parameter<commit_after>#include <config.h>
#include "grid_creation.hh"
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/grid/structuredgridfactory.hh>
#include <dune/stuff/grid/information.hh>
// Helper struct to make overlap for SPGrid possible
// Declared in unnamed namespace to avoid naming conflicts
namespace {
template< class GridType >
class MyGridFactory {
typedef typename GridType::ctype ctype;
static const int dimworld = GridType::dimensionworld;
static const int dim = GridType::dim;
public:
static std::shared_ptr<GridType>
createCubeGrid(const Dune::FieldVector<ctype,dimworld>& lowerLeft,
const Dune::FieldVector<ctype,dimworld>& upperRight,
const Dune::array<unsigned int,dim>& elements,
const Dune::array<unsigned int,dim>& /*overlap*/) {
// structured grid factory allows overlap only for SPGrid at the moment, hence the following check
BOOST_ASSERT_MSG((DSC_CONFIG_GET("msfem.oversampling_layers", 0)==0),
"Oversampling may only be used in combination with SPGrid!");
return Dune::StructuredGridFactory<GridType>::createCubeGrid(lowerLeft, upperRight, elements);
}
};
template< class ct, int dim, Dune::SPRefinementStrategy strategy, class Comm >
class MyGridFactory< Dune::SPGrid< ct, dim, strategy, Comm > > {
typedef Dune::SPGrid< ct, dim, strategy, Comm > GridType;
typedef typename GridType::ctype ctype;
static const int dimworld = GridType::dimensionworld;
public:
static std::shared_ptr<GridType>
createCubeGrid(const Dune::FieldVector<ctype,dimworld>& lowerLeft,
const Dune::FieldVector<ctype,dimworld>& upperRight,
const Dune::array<unsigned int,dim>& elements,
const Dune::array<unsigned int,dim>& overlap) {
return Dune::StructuredGridFactory<GridType>::createCubeGrid(lowerLeft, upperRight, elements, overlap);
}
};
}
std::pair<std::shared_ptr<Dune::Multiscale::CommonTraits::GridType>,
std::shared_ptr<Dune::Multiscale::CommonTraits::GridType>>
Dune::Multiscale::make_grids() {
const int dim_world = CommonTraits::GridType::dimensionworld;
typedef FieldVector<typename CommonTraits::GridType::ctype, dim_world> CoordType;
CoordType lowerLeft(0.0);
CoordType upperRight(1.0);
const auto oversamplingLayers = DSC_CONFIG_GET("msfem.oversampling_layers", 0);
const auto microPerMacro = DSC_CONFIG_GET("msfem.micro_cells_per_macrocell_dim", 8);
const int overlapLayers = std::ceil(double(oversamplingLayers)/double(microPerMacro));
const auto coarse_cells = DSC_CONFIG_GET("global.macro_cells_per_dim", 8);
array<unsigned int, dim_world> elements;
array<unsigned int, dim_world> overCoarse;
for (const auto i : DSC::valueRange(dim_world)) {
elements[i] = coarse_cells;
overCoarse[i] = overlapLayers;
}
auto coarse_gridptr =
MyGridFactory<CommonTraits::GridType>::createCubeGrid(lowerLeft, upperRight, elements, overCoarse);
for (const auto i : DSC::valueRange(dim_world)) {
elements[i] = coarse_cells * microPerMacro;
}
auto fine_gridptr = StructuredGridFactory<CommonTraits::GridType>::createCubeGrid(lowerLeft, upperRight, elements);
return {coarse_gridptr, fine_gridptr};
}
<|endoftext|> |
<commit_before>#ifndef SILICIUM_ASIO_TCP_ACCEPTOR_HPP
#define SILICIUM_ASIO_TCP_ACCEPTOR_HPP
#include <silicium/observable/observer.hpp>
#include <silicium/exchange.hpp>
#include <silicium/error_or.hpp>
#include <boost/asio/ip/tcp.hpp>
namespace Si
{
namespace asio
{
typedef error_or<std::shared_ptr<boost::asio::ip::tcp::socket>> tcp_acceptor_result; //until socket itself is noexcept-movable
template <class AcceptorPtrLike>
struct tcp_acceptor
{
typedef tcp_acceptor_result element_type;
tcp_acceptor()
: underlying(nullptr)
, receiver_(nullptr)
{
}
explicit tcp_acceptor(AcceptorPtrLike underlying)
: underlying(std::move(underlying))
, receiver_(nullptr)
{
}
tcp_acceptor(tcp_acceptor &&other) BOOST_NOEXCEPT
: underlying(std::move(other.underlying))
, next_client(std::move(other.next_client))
, receiver_(other.receiver_)
{
}
tcp_acceptor &operator = (tcp_acceptor &&other) BOOST_NOEXCEPT
{
underlying = std::move(other.underlying);
next_client = std::move(other.next_client);
receiver_ = other.receiver_;
return *this;
}
~tcp_acceptor()
{
if (!receiver_ || !underlying)
{
return;
}
underlying->cancel();
}
void async_get_one(ptr_observer<observer<element_type>> receiver)
{
assert(!receiver_);
assert(underlying);
next_client = std::make_shared<boost::asio::ip::tcp::socket>(underlying->get_io_service());
receiver_ = receiver.get();
underlying->async_accept(*next_client, [this](boost::system::error_code error)
{
if (!this->receiver_)
{
//can happen when cancel has been called on the observable when the callback was
//already posted to the io_service
return;
}
if (error)
{
if (error == boost::asio::error::operation_aborted)
{
return;
}
Si::exchange(this->receiver_, nullptr)->got_element(tcp_acceptor_result{error});
}
else
{
Si::exchange(this->receiver_, nullptr)->got_element(tcp_acceptor_result{std::move(next_client)});
}
});
}
private:
AcceptorPtrLike underlying;
std::shared_ptr<boost::asio::ip::tcp::socket> next_client;
observer<element_type> *receiver_;
SILICIUM_DELETED_FUNCTION(tcp_acceptor(tcp_acceptor const &))
SILICIUM_DELETED_FUNCTION(tcp_acceptor &operator = (tcp_acceptor const &))
};
template <class AcceptorPtrLike>
auto make_tcp_acceptor(AcceptorPtrLike &&acceptor)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
-> tcp_acceptor<typename std::decay<AcceptorPtrLike>::type>
#endif
{
return tcp_acceptor<typename std::decay<AcceptorPtrLike>::type>(std::forward<AcceptorPtrLike>(acceptor));
}
}
}
#endif
<commit_msg>tcp_acceptor works with stateful observers and is really movable now<commit_after>#ifndef SILICIUM_ASIO_TCP_ACCEPTOR_HPP
#define SILICIUM_ASIO_TCP_ACCEPTOR_HPP
#include <silicium/observable/observer.hpp>
#include <silicium/exchange.hpp>
#include <silicium/error_or.hpp>
#include <boost/asio/ip/tcp.hpp>
namespace Si
{
namespace asio
{
typedef error_or<std::shared_ptr<boost::asio::ip::tcp::socket>> tcp_acceptor_result; //until socket itself is noexcept-movable
template <class AcceptorPtrLike>
struct tcp_acceptor
{
typedef tcp_acceptor_result element_type;
tcp_acceptor()
: underlying(nullptr)
{
}
explicit tcp_acceptor(AcceptorPtrLike underlying)
: underlying(std::move(underlying))
{
}
tcp_acceptor(tcp_acceptor &&other) BOOST_NOEXCEPT
: underlying(std::move(other.underlying))
, next_client(std::move(other.next_client))
{
}
tcp_acceptor &operator = (tcp_acceptor &&other) BOOST_NOEXCEPT
{
underlying = std::move(other.underlying);
next_client = std::move(other.next_client);
return *this;
}
~tcp_acceptor()
{
}
template <class Observer>
void async_get_one(Observer &&receiver)
{
assert(underlying);
next_client = std::make_shared<boost::asio::ip::tcp::socket>(underlying->get_io_service());
underlying->async_accept(*next_client, [this, receiver](boost::system::error_code error) mutable
{
if (error)
{
if (error == boost::asio::error::operation_aborted)
{
return;
}
std::forward<Observer>(receiver).got_element(tcp_acceptor_result{error});
}
else
{
std::forward<Observer>(receiver).got_element(tcp_acceptor_result{std::move(next_client)});
}
});
}
private:
AcceptorPtrLike underlying;
std::shared_ptr<boost::asio::ip::tcp::socket> next_client;
SILICIUM_DELETED_FUNCTION(tcp_acceptor(tcp_acceptor const &))
SILICIUM_DELETED_FUNCTION(tcp_acceptor &operator = (tcp_acceptor const &))
};
template <class AcceptorPtrLike>
auto make_tcp_acceptor(AcceptorPtrLike &&acceptor)
#if !SILICIUM_COMPILER_HAS_AUTO_RETURN_TYPE
-> tcp_acceptor<typename std::decay<AcceptorPtrLike>::type>
#endif
{
return tcp_acceptor<typename std::decay<AcceptorPtrLike>::type>(std::forward<AcceptorPtrLike>(acceptor));
}
}
}
#endif
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright 2012-2016 Masanori Morise. All Rights Reserved.
// Author: mmorise [at] yamanashi.ac.jp (Masanori Morise)
//
// common.cpp includes functions used in at least two files.
// (1) Common functions
// (2) FFT, IFFT and minimum phase analysis.
//
// In FFT analysis and minimum phase analysis,
// Functions "Initialize*()" allocate the mamory.
// Functions "Destroy*()" free the accolated memory.
// FFT size is used for initialization, and structs are used to keep the memory.
// Functions "GetMinimumPhaseSpectrum()" calculate minimum phase spectrum.
// Forward and inverse FFT do not have the function "Get*()",
// because forward FFT and inverse FFT can run in one step.
//
//-----------------------------------------------------------------------------
#include "./common.h"
#include <math.h>
#include "./constantnumbers.h"
#include "./matlabfunctions.h"
namespace {
//-----------------------------------------------------------------------------
// SetParametersForLinearSmoothing() is used in LinearSmoothing()
//-----------------------------------------------------------------------------
static void SetParametersForLinearSmoothing(int boundary, int fft_size, int fs,
double width, const double *power_spectrum, double *mirroring_spectrum,
double *mirroring_segment, double *frequency_axis) {
for (int i = 0; i < boundary; ++i)
mirroring_spectrum[i] = power_spectrum[boundary - i];
for (int i = boundary; i < fft_size / 2 + boundary; ++i)
mirroring_spectrum[i] = power_spectrum[i - boundary];
for (int i = fft_size / 2 + boundary; i <= fft_size / 2 + boundary * 2; ++i)
mirroring_spectrum[i] =
power_spectrum[fft_size / 2 - (i - (fft_size / 2 + boundary))];
mirroring_segment[0] = mirroring_spectrum[0] * fs / fft_size;
for (int i = 1; i < fft_size / 2 + boundary * 2 + 1; ++i)
mirroring_segment[i] = mirroring_spectrum[i] * fs / fft_size +
mirroring_segment[i - 1];
for (int i = 0; i <= fft_size / 2; ++i)
frequency_axis[i] = static_cast<double>(i) / fft_size *
fs - width / 2.0;
}
} // namespace
//-----------------------------------------------------------------------------
// Fundamental functions
int GetSuitableFFTSize(int sample) {
return static_cast<int>(pow(2.0,
static_cast<int>(log(static_cast<double>(sample)) / world::kLog2) + 1.0));
}
//-----------------------------------------------------------------------------
// DCCorrection() corrects the input spectrum from 0 to f0 Hz because the
// general signal does not contain the DC (Direct Current) component.
// It is used in CheapTrick() and D4C().
//-----------------------------------------------------------------------------
void DCCorrection(const double *input, double current_f0, int fs, int fft_size,
double *output) {
int upper_limit = 1 +
static_cast<int>(1.2 * current_f0 * fft_size / fs);
double *low_frequency_replica = new double[upper_limit];
double *low_frequency_axis = new double[upper_limit];
for (int i = 0; i < upper_limit; ++i)
low_frequency_axis[i] = static_cast<double>(i) * fs / fft_size;
int upper_limit_replica = 1 + static_cast<int>(current_f0 * fft_size / fs);
interp1Q(current_f0 - low_frequency_axis[0],
-static_cast<double>(fs) / fft_size, input, upper_limit + 1,
low_frequency_axis, upper_limit_replica, low_frequency_replica);
for (int i = 0; i < upper_limit_replica; ++i)
output[i] = input[i] + low_frequency_replica[i];
delete[] low_frequency_replica;
delete[] low_frequency_axis;
}
//-----------------------------------------------------------------------------
// LinearSmoothing() carries out the spectral smoothing by rectangular window
// whose length is width Hz and is used in CheapTrick() and D4C().
//-----------------------------------------------------------------------------
void LinearSmoothing(const double *input, double width, int fs, int fft_size,
double *output) {
int boundary = static_cast<int>(width * fft_size / fs) + 1;
// These parameters are set by the other function.
double *mirroring_spectrum = new double[fft_size / 2 + boundary * 2 + 1];
double *mirroring_segment = new double[fft_size / 2 + boundary * 2 + 1];
double *frequency_axis = new double[fft_size / 2 + 1];
SetParametersForLinearSmoothing(boundary, fft_size, fs, width,
input, mirroring_spectrum, mirroring_segment, frequency_axis);
double *low_levels = new double[fft_size / 2 + 1];
double *high_levels = new double[fft_size / 2 + 1];
double origin_of_mirroring_axis =
-(static_cast<double>(boundary) - 0.5) * fs / fft_size;
double discrete_frequency_interval = static_cast<double>(fs) / fft_size;
interp1Q(origin_of_mirroring_axis, discrete_frequency_interval,
mirroring_segment, fft_size / 2 + boundary * 2 + 1, frequency_axis,
fft_size / 2 + 1, low_levels);
for (int i = 0; i <= fft_size / 2; ++i) frequency_axis[i] += width;
interp1Q(origin_of_mirroring_axis, discrete_frequency_interval,
mirroring_segment, fft_size / 2 + boundary * 2 + 1, frequency_axis,
fft_size / 2 + 1, high_levels);
for (int i = 0; i <= fft_size / 2; ++i)
output[i] = (high_levels[i] - low_levels[i]) / width;
delete[] mirroring_spectrum;
delete[] mirroring_segment;
delete[] frequency_axis;
delete[] low_levels;
delete[] high_levels;
}
//-----------------------------------------------------------------------------
// NuttallWindow() calculates the coefficients of Nuttall window whose length
// is y_length and is used in Dio() and D4C().
//-----------------------------------------------------------------------------
void NuttallWindow(int y_length, double *y) {
double tmp;
for (int i = 0; i < y_length; ++i) {
tmp = static_cast<double>(i) / (y_length - 1);
y[i] = 0.355768 - 0.487396 * cos(2.0 * world::kPi * tmp) +
0.144232 * cos(4.0 * world::kPi * tmp) -
0.012604 * cos(6.0 * world::kPi * tmp);
}
}
//-----------------------------------------------------------------------------
// FFT, IFFT and minimum phase analysis
void InitializeForwardRealFFT(int fft_size, ForwardRealFFT *forward_real_fft) {
forward_real_fft->fft_size = fft_size;
forward_real_fft->waveform = new double[fft_size];
forward_real_fft->spectrum = new fft_complex[fft_size];
forward_real_fft->forward_fft = fft_plan_dft_r2c_1d(fft_size,
forward_real_fft->waveform, forward_real_fft->spectrum, FFT_ESTIMATE);
}
void DestroyForwardRealFFT(ForwardRealFFT *forward_real_fft) {
fft_destroy_plan(forward_real_fft->forward_fft);
delete[] forward_real_fft->spectrum;
delete[] forward_real_fft->waveform;
}
void InitializeInverseRealFFT(int fft_size, InverseRealFFT *inverse_real_fft) {
inverse_real_fft->fft_size = fft_size;
inverse_real_fft->waveform = new double[fft_size];
inverse_real_fft->spectrum = new fft_complex[fft_size];
inverse_real_fft->inverse_fft = fft_plan_dft_c2r_1d(fft_size,
inverse_real_fft->spectrum, inverse_real_fft->waveform, FFT_ESTIMATE);
}
void DestroyInverseRealFFT(InverseRealFFT *inverse_real_fft) {
fft_destroy_plan(inverse_real_fft->inverse_fft);
delete[] inverse_real_fft->spectrum;
delete[] inverse_real_fft->waveform;
}
void InitializeMinimumPhaseAnalysis(int fft_size,
MinimumPhaseAnalysis *minimum_phase) {
minimum_phase->fft_size = fft_size;
minimum_phase->log_spectrum = new double[fft_size];
minimum_phase->minimum_phase_spectrum = new fft_complex[fft_size];
minimum_phase->cepstrum = new fft_complex[fft_size];
minimum_phase->inverse_fft = fft_plan_dft_r2c_1d(fft_size,
minimum_phase->log_spectrum, minimum_phase->cepstrum, FFT_ESTIMATE);
minimum_phase->forward_fft = fft_plan_dft_1d(fft_size,
minimum_phase->cepstrum, minimum_phase->minimum_phase_spectrum,
FFT_FORWARD, FFT_ESTIMATE);
}
void GetMinimumPhaseSpectrum(const MinimumPhaseAnalysis *minimum_phase) {
// Mirroring
for (int i = minimum_phase->fft_size / 2 + 1;
i < minimum_phase->fft_size; ++i)
minimum_phase->log_spectrum[i] =
minimum_phase->log_spectrum[minimum_phase->fft_size - i];
// This fft_plan carries out "forward" FFT.
// To carriy out the Inverse FFT, the sign of imaginary part
// is inverted after FFT.
fft_execute(minimum_phase->inverse_fft);
minimum_phase->cepstrum[0][1] *= -1.0;
for (int i = 1; i < minimum_phase->fft_size / 2; ++i) {
minimum_phase->cepstrum[i][0] *= 2.0;
minimum_phase->cepstrum[i][1] *= -2.0;
}
minimum_phase->cepstrum[minimum_phase->fft_size / 2][1] *= -1.0;
for (int i = minimum_phase->fft_size / 2 + 1;
i < minimum_phase->fft_size; ++i) {
minimum_phase->cepstrum[i][0] = 0.0;
minimum_phase->cepstrum[i][1] = 0.0;
}
fft_execute(minimum_phase->forward_fft);
// Since x is complex number, calculation of exp(x) is as following.
// Note: This FFT library does not keep the aliasing.
double tmp;
for (int i = 0; i <= minimum_phase->fft_size / 2; ++i) {
tmp = exp(minimum_phase->minimum_phase_spectrum[i][0] /
minimum_phase->fft_size);
minimum_phase->minimum_phase_spectrum[i][0] = tmp *
cos(minimum_phase->minimum_phase_spectrum[i][1] /
minimum_phase->fft_size);
minimum_phase->minimum_phase_spectrum[i][1] = tmp *
sin(minimum_phase->minimum_phase_spectrum[i][1] /
minimum_phase->fft_size);
}
}
void DestroyMinimumPhaseAnalysis(MinimumPhaseAnalysis *minimum_phase) {
fft_destroy_plan(minimum_phase->forward_fft);
fft_destroy_plan(minimum_phase->inverse_fft);
delete[] minimum_phase->cepstrum;
delete[] minimum_phase->log_spectrum;
delete[] minimum_phase->minimum_phase_spectrum;
}
<commit_msg>Include headers with world/ prefix in common.cpp.<commit_after>//-----------------------------------------------------------------------------
// Copyright 2012-2016 Masanori Morise. All Rights Reserved.
// Author: mmorise [at] yamanashi.ac.jp (Masanori Morise)
//
// common.cpp includes functions used in at least two files.
// (1) Common functions
// (2) FFT, IFFT and minimum phase analysis.
//
// In FFT analysis and minimum phase analysis,
// Functions "Initialize*()" allocate the mamory.
// Functions "Destroy*()" free the accolated memory.
// FFT size is used for initialization, and structs are used to keep the memory.
// Functions "GetMinimumPhaseSpectrum()" calculate minimum phase spectrum.
// Forward and inverse FFT do not have the function "Get*()",
// because forward FFT and inverse FFT can run in one step.
//
//-----------------------------------------------------------------------------
#include "world/common.h"
#include <math.h>
#include "world/constantnumbers.h"
#include "world/matlabfunctions.h"
namespace {
//-----------------------------------------------------------------------------
// SetParametersForLinearSmoothing() is used in LinearSmoothing()
//-----------------------------------------------------------------------------
static void SetParametersForLinearSmoothing(int boundary, int fft_size, int fs,
double width, const double *power_spectrum, double *mirroring_spectrum,
double *mirroring_segment, double *frequency_axis) {
for (int i = 0; i < boundary; ++i)
mirroring_spectrum[i] = power_spectrum[boundary - i];
for (int i = boundary; i < fft_size / 2 + boundary; ++i)
mirroring_spectrum[i] = power_spectrum[i - boundary];
for (int i = fft_size / 2 + boundary; i <= fft_size / 2 + boundary * 2; ++i)
mirroring_spectrum[i] =
power_spectrum[fft_size / 2 - (i - (fft_size / 2 + boundary))];
mirroring_segment[0] = mirroring_spectrum[0] * fs / fft_size;
for (int i = 1; i < fft_size / 2 + boundary * 2 + 1; ++i)
mirroring_segment[i] = mirroring_spectrum[i] * fs / fft_size +
mirroring_segment[i - 1];
for (int i = 0; i <= fft_size / 2; ++i)
frequency_axis[i] = static_cast<double>(i) / fft_size *
fs - width / 2.0;
}
} // namespace
//-----------------------------------------------------------------------------
// Fundamental functions
int GetSuitableFFTSize(int sample) {
return static_cast<int>(pow(2.0,
static_cast<int>(log(static_cast<double>(sample)) / world::kLog2) + 1.0));
}
//-----------------------------------------------------------------------------
// DCCorrection() corrects the input spectrum from 0 to f0 Hz because the
// general signal does not contain the DC (Direct Current) component.
// It is used in CheapTrick() and D4C().
//-----------------------------------------------------------------------------
void DCCorrection(const double *input, double current_f0, int fs, int fft_size,
double *output) {
int upper_limit = 1 +
static_cast<int>(1.2 * current_f0 * fft_size / fs);
double *low_frequency_replica = new double[upper_limit];
double *low_frequency_axis = new double[upper_limit];
for (int i = 0; i < upper_limit; ++i)
low_frequency_axis[i] = static_cast<double>(i) * fs / fft_size;
int upper_limit_replica = 1 + static_cast<int>(current_f0 * fft_size / fs);
interp1Q(current_f0 - low_frequency_axis[0],
-static_cast<double>(fs) / fft_size, input, upper_limit + 1,
low_frequency_axis, upper_limit_replica, low_frequency_replica);
for (int i = 0; i < upper_limit_replica; ++i)
output[i] = input[i] + low_frequency_replica[i];
delete[] low_frequency_replica;
delete[] low_frequency_axis;
}
//-----------------------------------------------------------------------------
// LinearSmoothing() carries out the spectral smoothing by rectangular window
// whose length is width Hz and is used in CheapTrick() and D4C().
//-----------------------------------------------------------------------------
void LinearSmoothing(const double *input, double width, int fs, int fft_size,
double *output) {
int boundary = static_cast<int>(width * fft_size / fs) + 1;
// These parameters are set by the other function.
double *mirroring_spectrum = new double[fft_size / 2 + boundary * 2 + 1];
double *mirroring_segment = new double[fft_size / 2 + boundary * 2 + 1];
double *frequency_axis = new double[fft_size / 2 + 1];
SetParametersForLinearSmoothing(boundary, fft_size, fs, width,
input, mirroring_spectrum, mirroring_segment, frequency_axis);
double *low_levels = new double[fft_size / 2 + 1];
double *high_levels = new double[fft_size / 2 + 1];
double origin_of_mirroring_axis =
-(static_cast<double>(boundary) - 0.5) * fs / fft_size;
double discrete_frequency_interval = static_cast<double>(fs) / fft_size;
interp1Q(origin_of_mirroring_axis, discrete_frequency_interval,
mirroring_segment, fft_size / 2 + boundary * 2 + 1, frequency_axis,
fft_size / 2 + 1, low_levels);
for (int i = 0; i <= fft_size / 2; ++i) frequency_axis[i] += width;
interp1Q(origin_of_mirroring_axis, discrete_frequency_interval,
mirroring_segment, fft_size / 2 + boundary * 2 + 1, frequency_axis,
fft_size / 2 + 1, high_levels);
for (int i = 0; i <= fft_size / 2; ++i)
output[i] = (high_levels[i] - low_levels[i]) / width;
delete[] mirroring_spectrum;
delete[] mirroring_segment;
delete[] frequency_axis;
delete[] low_levels;
delete[] high_levels;
}
//-----------------------------------------------------------------------------
// NuttallWindow() calculates the coefficients of Nuttall window whose length
// is y_length and is used in Dio() and D4C().
//-----------------------------------------------------------------------------
void NuttallWindow(int y_length, double *y) {
double tmp;
for (int i = 0; i < y_length; ++i) {
tmp = static_cast<double>(i) / (y_length - 1);
y[i] = 0.355768 - 0.487396 * cos(2.0 * world::kPi * tmp) +
0.144232 * cos(4.0 * world::kPi * tmp) -
0.012604 * cos(6.0 * world::kPi * tmp);
}
}
//-----------------------------------------------------------------------------
// FFT, IFFT and minimum phase analysis
void InitializeForwardRealFFT(int fft_size, ForwardRealFFT *forward_real_fft) {
forward_real_fft->fft_size = fft_size;
forward_real_fft->waveform = new double[fft_size];
forward_real_fft->spectrum = new fft_complex[fft_size];
forward_real_fft->forward_fft = fft_plan_dft_r2c_1d(fft_size,
forward_real_fft->waveform, forward_real_fft->spectrum, FFT_ESTIMATE);
}
void DestroyForwardRealFFT(ForwardRealFFT *forward_real_fft) {
fft_destroy_plan(forward_real_fft->forward_fft);
delete[] forward_real_fft->spectrum;
delete[] forward_real_fft->waveform;
}
void InitializeInverseRealFFT(int fft_size, InverseRealFFT *inverse_real_fft) {
inverse_real_fft->fft_size = fft_size;
inverse_real_fft->waveform = new double[fft_size];
inverse_real_fft->spectrum = new fft_complex[fft_size];
inverse_real_fft->inverse_fft = fft_plan_dft_c2r_1d(fft_size,
inverse_real_fft->spectrum, inverse_real_fft->waveform, FFT_ESTIMATE);
}
void DestroyInverseRealFFT(InverseRealFFT *inverse_real_fft) {
fft_destroy_plan(inverse_real_fft->inverse_fft);
delete[] inverse_real_fft->spectrum;
delete[] inverse_real_fft->waveform;
}
void InitializeMinimumPhaseAnalysis(int fft_size,
MinimumPhaseAnalysis *minimum_phase) {
minimum_phase->fft_size = fft_size;
minimum_phase->log_spectrum = new double[fft_size];
minimum_phase->minimum_phase_spectrum = new fft_complex[fft_size];
minimum_phase->cepstrum = new fft_complex[fft_size];
minimum_phase->inverse_fft = fft_plan_dft_r2c_1d(fft_size,
minimum_phase->log_spectrum, minimum_phase->cepstrum, FFT_ESTIMATE);
minimum_phase->forward_fft = fft_plan_dft_1d(fft_size,
minimum_phase->cepstrum, minimum_phase->minimum_phase_spectrum,
FFT_FORWARD, FFT_ESTIMATE);
}
void GetMinimumPhaseSpectrum(const MinimumPhaseAnalysis *minimum_phase) {
// Mirroring
for (int i = minimum_phase->fft_size / 2 + 1;
i < minimum_phase->fft_size; ++i)
minimum_phase->log_spectrum[i] =
minimum_phase->log_spectrum[minimum_phase->fft_size - i];
// This fft_plan carries out "forward" FFT.
// To carriy out the Inverse FFT, the sign of imaginary part
// is inverted after FFT.
fft_execute(minimum_phase->inverse_fft);
minimum_phase->cepstrum[0][1] *= -1.0;
for (int i = 1; i < minimum_phase->fft_size / 2; ++i) {
minimum_phase->cepstrum[i][0] *= 2.0;
minimum_phase->cepstrum[i][1] *= -2.0;
}
minimum_phase->cepstrum[minimum_phase->fft_size / 2][1] *= -1.0;
for (int i = minimum_phase->fft_size / 2 + 1;
i < minimum_phase->fft_size; ++i) {
minimum_phase->cepstrum[i][0] = 0.0;
minimum_phase->cepstrum[i][1] = 0.0;
}
fft_execute(minimum_phase->forward_fft);
// Since x is complex number, calculation of exp(x) is as following.
// Note: This FFT library does not keep the aliasing.
double tmp;
for (int i = 0; i <= minimum_phase->fft_size / 2; ++i) {
tmp = exp(minimum_phase->minimum_phase_spectrum[i][0] /
minimum_phase->fft_size);
minimum_phase->minimum_phase_spectrum[i][0] = tmp *
cos(minimum_phase->minimum_phase_spectrum[i][1] /
minimum_phase->fft_size);
minimum_phase->minimum_phase_spectrum[i][1] = tmp *
sin(minimum_phase->minimum_phase_spectrum[i][1] /
minimum_phase->fft_size);
}
}
void DestroyMinimumPhaseAnalysis(MinimumPhaseAnalysis *minimum_phase) {
fft_destroy_plan(minimum_phase->forward_fft);
fft_destroy_plan(minimum_phase->inverse_fft);
delete[] minimum_phase->cepstrum;
delete[] minimum_phase->log_spectrum;
delete[] minimum_phase->minimum_phase_spectrum;
}
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2015-2019, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <common.hpp>
#include <window.hpp>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cmath>
using namespace fg;
using namespace std;
typedef struct {
GLuint vertex;
GLuint fragment;
} shaders_t;
GLenum gl_dtype(fg::dtype val)
{
switch(val) {
case s8: return GL_BYTE;
case u8: return GL_UNSIGNED_BYTE;
case s32: return GL_INT;
case u32: return GL_UNSIGNED_INT;
case s16: return GL_SHORT;
case u16: return GL_UNSIGNED_SHORT;
default: return GL_FLOAT;
}
}
GLenum gl_ctype(ChannelFormat mode)
{
switch(mode) {
case FG_GRAY: return GL_RED;
case FG_RG : return GL_RG;
case FG_RGB : return GL_RGB;
case FG_BGR : return GL_BGR;
case FG_BGRA: return GL_BGRA;
default : return GL_RGBA;
}
}
GLenum gl_ictype(ChannelFormat mode)
{
if (mode==FG_GRAY)
return GL_RED;
else if (mode==FG_RG)
return GL_RG;
else if (mode==FG_RGB || mode==FG_BGR)
return GL_RGB;
else
return GL_RGBA;
}
char* loadFile(const char * fname, GLint &fSize)
{
std::ifstream file(fname,std::ios::in|std::ios::binary|std::ios::ate);
if (file.is_open())
{
unsigned int size = (unsigned int)file.tellg();
fSize = size;
char *memblock = new char [size];
file.seekg (0, std::ios::beg);
file.read (memblock, size);
file.close();
std::cerr << "file " << fname << " loaded" << std::endl;
return memblock;
}
char buffer[64];
sprintf(buffer, "Unable to open file %s", fname);
throw fg::Error("loadFile", __LINE__, buffer, FG_ERR_GL_ERROR);
}
void printShaderInfoLog(GLint shader)
{
int infoLogLen = 0;
int charsWritten = 0;
GLchar *infoLog;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLen);
if (infoLogLen > 1)
{
infoLog = new GLchar[infoLogLen];
glGetShaderInfoLog(shader,infoLogLen, &charsWritten, infoLog);
std::cerr << "InfoLog:" << std::endl << infoLog << std::endl;
delete [] infoLog;
throw fg::Error("printShaderInfoLog", __LINE__, "OpenGL Shader compilation failed", FG_ERR_GL_ERROR);
}
}
void printLinkInfoLog(GLint prog)
{
int infoLogLen = 0;
int charsWritten = 0;
GLchar *infoLog;
glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &infoLogLen);
if (infoLogLen > 1)
{
infoLog = new GLchar[infoLogLen];
// error check for fail to allocate memory omitted
glGetProgramInfoLog(prog,infoLogLen, &charsWritten, infoLog);
std::cerr << "InfoLog:" << std::endl << infoLog << std::endl;
delete [] infoLog;
throw fg::Error("printLinkInfoLog", __LINE__, "OpenGL Shader linking failed", FG_ERR_GL_ERROR);
}
}
void attachAndLinkProgram(GLuint program, shaders_t shaders)
{
glAttachShader(program, shaders.vertex);
glAttachShader(program, shaders.fragment);
glLinkProgram(program);
GLint linked;
glGetProgramiv(program,GL_LINK_STATUS, &linked);
if (!linked)
{
std::cerr << "Program did not link." << std::endl;
throw fg::Error("attachAndLinkProgram", __LINE__, "OpenGL program linking failed", FG_ERR_GL_ERROR);
}
printLinkInfoLog(program);
}
shaders_t loadShaders(const char * vert_code, const char * frag_code)
{
GLuint f, v;
v = glCreateShader(GL_VERTEX_SHADER);
f = glCreateShader(GL_FRAGMENT_SHADER);
// load shaders & get length of each
glShaderSource(v, 1, &vert_code, NULL);
glShaderSource(f, 1, &frag_code, NULL);
GLint compiled;
glCompileShader(v);
glGetShaderiv(v, GL_COMPILE_STATUS, &compiled);
if (!compiled)
{
std::cerr << "Vertex shader not compiled." << std::endl;
printShaderInfoLog(v);
}
glCompileShader(f);
glGetShaderiv(f, GL_COMPILE_STATUS, &compiled);
if (!compiled)
{
std::cerr << "Fragment shader not compiled." << std::endl;
printShaderInfoLog(f);
}
shaders_t out; out.vertex = v; out.fragment = f;
return out;
}
GLuint initShaders(const char* vshader_code, const char* fshader_code)
{
shaders_t shaders = loadShaders(vshader_code, fshader_code);
GLuint shader_program = glCreateProgram();
attachAndLinkProgram(shader_program, shaders);
return shader_program;
}
int next_p2(int value)
{
return int(std::pow(2, (std::ceil(std::log2(value)))));
}
float clampTo01(float a)
{
return (a < 0.0f ? 0.0f : (a>1.0f ? 1.0f : a));
}
#ifdef OS_WIN
#include <windows.h>
#include <strsafe.h>
void getFontFilePaths(std::vector<std::string>& pFiles, std::string pDir, std::string pExt)
{
WIN32_FIND_DATA ffd;
LARGE_INTEGER filesize;
TCHAR szDir[MAX_PATH];
size_t length_of_arg;
DWORD dwError=0;
HANDLE hFind = INVALID_HANDLE_VALUE;
// Check that the input path plus 3 is not longer than MAX_PATH.
// Three characters are for the "\*" plus NULL appended below.
StringCchLength(pDir.c_str(), MAX_PATH, &length_of_arg);
if (length_of_arg > (MAX_PATH - 3)) {
throw fg::Error("getImageFilePaths", __LINE__,
"WIN API call: Directory path is too long",
FG_ERR_FILE_NOT_FOUND);
}
//printf("\nTarget directory is %s\n\n", pDir.c_str());
// Prepare string for use with FindFile functions. First, copy the
// string to a buffer, then append '\*' to the directory name.
StringCchCopy(szDir, MAX_PATH, pDir.c_str());
std::string wildcard = "\\*" + pExt;
StringCchCat(szDir, MAX_PATH, wildcard.c_str());
// Find the first file in the directory.
hFind = FindFirstFile(szDir, &ffd);
if (INVALID_HANDLE_VALUE == hFind) {
throw fg::Error("getImageFilePaths", __LINE__,
"WIN API call: file fetch in DIR failed",
FG_ERR_FILE_NOT_FOUND);
}
// List all the files in the directory with some info about them.
do {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
// It is a directory, skip the entry
//_tprintf(TEXT(" %s <DIR>\n"), ffd.cFileName);
} else {
filesize.LowPart = ffd.nFileSizeLow;
filesize.HighPart = ffd.nFileSizeHigh;
//_tprintf(TEXT(" %s %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
pFiles.push_back(std::string(ffd.cFileName));
}
} while (FindNextFile(hFind, &ffd) != 0);
dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES) {
throw fg::Error("getImageFilePaths", __LINE__,
"WIN API call: files fetch returned no files",
FG_ERR_FILE_NOT_FOUND);
}
FindClose(hFind);
}
#endif
std::string toString(float pVal, const int n)
{
std::ostringstream out;
out << std::fixed << std::setprecision(n) << pVal;
return out.str();
}
<commit_msg>Typo fix for GRAYSCALE enum value<commit_after>/*******************************************************
* Copyright (c) 2015-2019, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <common.hpp>
#include <window.hpp>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <cmath>
using namespace fg;
using namespace std;
typedef struct {
GLuint vertex;
GLuint fragment;
} shaders_t;
GLenum gl_dtype(fg::dtype val)
{
switch(val) {
case s8: return GL_BYTE;
case u8: return GL_UNSIGNED_BYTE;
case s32: return GL_INT;
case u32: return GL_UNSIGNED_INT;
case s16: return GL_SHORT;
case u16: return GL_UNSIGNED_SHORT;
default: return GL_FLOAT;
}
}
GLenum gl_ctype(ChannelFormat mode)
{
switch(mode) {
case FG_GRAYSCALE: return GL_RED;
case FG_RG : return GL_RG;
case FG_RGB : return GL_RGB;
case FG_BGR : return GL_BGR;
case FG_BGRA: return GL_BGRA;
default : return GL_RGBA;
}
}
GLenum gl_ictype(ChannelFormat mode)
{
if (mode==FG_GRAYSCALE)
return GL_RED;
else if (mode==FG_RG)
return GL_RG;
else if (mode==FG_RGB || mode==FG_BGR)
return GL_RGB;
else
return GL_RGBA;
}
char* loadFile(const char * fname, GLint &fSize)
{
std::ifstream file(fname,std::ios::in|std::ios::binary|std::ios::ate);
if (file.is_open())
{
unsigned int size = (unsigned int)file.tellg();
fSize = size;
char *memblock = new char [size];
file.seekg (0, std::ios::beg);
file.read (memblock, size);
file.close();
std::cerr << "file " << fname << " loaded" << std::endl;
return memblock;
}
char buffer[64];
sprintf(buffer, "Unable to open file %s", fname);
throw fg::Error("loadFile", __LINE__, buffer, FG_ERR_GL_ERROR);
}
void printShaderInfoLog(GLint shader)
{
int infoLogLen = 0;
int charsWritten = 0;
GLchar *infoLog;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLen);
if (infoLogLen > 1)
{
infoLog = new GLchar[infoLogLen];
glGetShaderInfoLog(shader,infoLogLen, &charsWritten, infoLog);
std::cerr << "InfoLog:" << std::endl << infoLog << std::endl;
delete [] infoLog;
throw fg::Error("printShaderInfoLog", __LINE__, "OpenGL Shader compilation failed", FG_ERR_GL_ERROR);
}
}
void printLinkInfoLog(GLint prog)
{
int infoLogLen = 0;
int charsWritten = 0;
GLchar *infoLog;
glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &infoLogLen);
if (infoLogLen > 1)
{
infoLog = new GLchar[infoLogLen];
// error check for fail to allocate memory omitted
glGetProgramInfoLog(prog,infoLogLen, &charsWritten, infoLog);
std::cerr << "InfoLog:" << std::endl << infoLog << std::endl;
delete [] infoLog;
throw fg::Error("printLinkInfoLog", __LINE__, "OpenGL Shader linking failed", FG_ERR_GL_ERROR);
}
}
void attachAndLinkProgram(GLuint program, shaders_t shaders)
{
glAttachShader(program, shaders.vertex);
glAttachShader(program, shaders.fragment);
glLinkProgram(program);
GLint linked;
glGetProgramiv(program,GL_LINK_STATUS, &linked);
if (!linked)
{
std::cerr << "Program did not link." << std::endl;
throw fg::Error("attachAndLinkProgram", __LINE__, "OpenGL program linking failed", FG_ERR_GL_ERROR);
}
printLinkInfoLog(program);
}
shaders_t loadShaders(const char * vert_code, const char * frag_code)
{
GLuint f, v;
v = glCreateShader(GL_VERTEX_SHADER);
f = glCreateShader(GL_FRAGMENT_SHADER);
// load shaders & get length of each
glShaderSource(v, 1, &vert_code, NULL);
glShaderSource(f, 1, &frag_code, NULL);
GLint compiled;
glCompileShader(v);
glGetShaderiv(v, GL_COMPILE_STATUS, &compiled);
if (!compiled)
{
std::cerr << "Vertex shader not compiled." << std::endl;
printShaderInfoLog(v);
}
glCompileShader(f);
glGetShaderiv(f, GL_COMPILE_STATUS, &compiled);
if (!compiled)
{
std::cerr << "Fragment shader not compiled." << std::endl;
printShaderInfoLog(f);
}
shaders_t out; out.vertex = v; out.fragment = f;
return out;
}
GLuint initShaders(const char* vshader_code, const char* fshader_code)
{
shaders_t shaders = loadShaders(vshader_code, fshader_code);
GLuint shader_program = glCreateProgram();
attachAndLinkProgram(shader_program, shaders);
return shader_program;
}
int next_p2(int value)
{
return int(std::pow(2, (std::ceil(std::log2(value)))));
}
float clampTo01(float a)
{
return (a < 0.0f ? 0.0f : (a>1.0f ? 1.0f : a));
}
#ifdef OS_WIN
#include <windows.h>
#include <strsafe.h>
void getFontFilePaths(std::vector<std::string>& pFiles, std::string pDir, std::string pExt)
{
WIN32_FIND_DATA ffd;
LARGE_INTEGER filesize;
TCHAR szDir[MAX_PATH];
size_t length_of_arg;
DWORD dwError=0;
HANDLE hFind = INVALID_HANDLE_VALUE;
// Check that the input path plus 3 is not longer than MAX_PATH.
// Three characters are for the "\*" plus NULL appended below.
StringCchLength(pDir.c_str(), MAX_PATH, &length_of_arg);
if (length_of_arg > (MAX_PATH - 3)) {
throw fg::Error("getImageFilePaths", __LINE__,
"WIN API call: Directory path is too long",
FG_ERR_FILE_NOT_FOUND);
}
//printf("\nTarget directory is %s\n\n", pDir.c_str());
// Prepare string for use with FindFile functions. First, copy the
// string to a buffer, then append '\*' to the directory name.
StringCchCopy(szDir, MAX_PATH, pDir.c_str());
std::string wildcard = "\\*" + pExt;
StringCchCat(szDir, MAX_PATH, wildcard.c_str());
// Find the first file in the directory.
hFind = FindFirstFile(szDir, &ffd);
if (INVALID_HANDLE_VALUE == hFind) {
throw fg::Error("getImageFilePaths", __LINE__,
"WIN API call: file fetch in DIR failed",
FG_ERR_FILE_NOT_FOUND);
}
// List all the files in the directory with some info about them.
do {
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
// It is a directory, skip the entry
//_tprintf(TEXT(" %s <DIR>\n"), ffd.cFileName);
} else {
filesize.LowPart = ffd.nFileSizeLow;
filesize.HighPart = ffd.nFileSizeHigh;
//_tprintf(TEXT(" %s %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
pFiles.push_back(std::string(ffd.cFileName));
}
} while (FindNextFile(hFind, &ffd) != 0);
dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES) {
throw fg::Error("getImageFilePaths", __LINE__,
"WIN API call: files fetch returned no files",
FG_ERR_FILE_NOT_FOUND);
}
FindClose(hFind);
}
#endif
std::string toString(float pVal, const int n)
{
std::ostringstream out;
out << std::fixed << std::setprecision(n) << pVal;
return out.str();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "include/Sales_item.h"
int main()
{
Sales_item item1, item2;
std::cin >> item1 >> item2;
if (item1.isbn() == item2.isbn())
{
std::cout << item1 + item2 << std::endl;
return 0;
}
else
{
std::cerr << "Data must refer to same ISBN." << std::endl;
return -1;
}
}
<commit_msg>Update ex1_21.cpp<commit_after>#include <iostream>
#include "include/Sales_item.h"
using std::cin;
using std::cout;
using std::endl;
using std::cerr;
int main()
{
Sales_item item1, item2;
cin >> item1 >> item2;
if (item1.isbn() == item2.isbn())
cout << item1 + item2 << endl;
else
cerr << "Different ISBN." << endl;
}
<|endoftext|> |
<commit_before>// bdls_processutil.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <bdls_processutil.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdls_processutil_cpp,"$Id$ $CSID$")
#include <bdlma_localsequentialallocator.h>
#include <bdlsb_memoutstreambuf.h>
#include <bsls_assert.h>
#include <bsls_platform.h>
#include <bsl_iostream.h>
#include <bsl_fstream.h>
#ifdef BSLS_PLATFORM_OS_WINDOWS
#include <windows.h>
#include <bdlde_charconvertutf16.h>
#else
#include <unistd.h>
#endif
#if defined(BSLS_PLATFORM_OS_SOLARIS)
#include <procfs.h>
#include <fcntl.h>
#elif defined(BSLS_PLATFORM_OS_AIX)
#include <sys/procfs.h>
#include <fcntl.h>
#elif defined(BSLS_PLATFORM_OS_LINUX) || defined(BSLS_PLATFORM_OS_CYGWIN)
#include <fcntl.h>
#elif defined(BSLS_PLATFORM_OS_HPUX)
#include <sys/pstat.h>
#elif defined(BSLS_PLATFORM_OS_DARWIN)
#include <libproc.h>
#endif
namespace BloombergLP {
namespace bdls {
// ------------------
// struct ProcessUtil
// ------------------
// CLASS METHODS
int ProcessUtil::getProcessId() {
#ifdef BSLS_PLATFORM_OS_WINDOWS
return static_cast<int>(GetCurrentProcessId());
#else
return static_cast<int>(getpid());
#endif
}
int ProcessUtil::getProcessName(bsl::string *result)
{
BSLS_ASSERT(result);
result->clear();
#if defined BSLS_PLATFORM_OS_WINDOWS
bdlma::LocalSequentialAllocator<MAX_PATH + 1> la;
bsl::wstring wResult(MAX_PATH, 0, &la);
while (wResult.length() <= 4 * MAX_PATH) {
DWORD length = GetModuleFileNameW(0, &wResult[0], wResult.length());
if (length <= 0) { // Error
return 1; // RETURN
}
else if (length < wResult.length()) { // Success
wResult.resize(length);
return bdlde::CharConvertUtf16::utf16ToUtf8(result, wResult);
// RETURN
}
else { // Not enough space for the process name in 'wResult'
wResult.resize(wResult.length() * 2); // Make more space
}
}
return -1;
#else
# if defined BSLS_PLATFORM_OS_HPUX
result->resize(256);
int rc = pstat_getcommandline(&(*result->begin()),
result->size(), 1,
getpid());
if (rc < 0)
{
return -1;
}
bsl::string::size_type pos = result->find_first_of(' ');
if (bsl::string::npos != pos) {
result->resize(pos);
}
# elif defined BSLS_PLATFORM_OS_LINUX || defined BSLS_PLATFORM_OS_CYGWIN
enum { NUM_ELEMENTS = 14 + 16 }; // "/proc/<pid>/cmdline"
bdlsb::MemOutStreamBuf osb(NUM_ELEMENTS);
bsl::ostream os(&osb);
os << "/proc/" << getpid() << "/cmdline" << bsl::ends;
const char *procfs = osb.data();
bsl::ifstream ifs;
ifs.open(procfs, bsl::ios_base::in | bsl::ios_base::binary);
if (ifs.fail()) {
return -1; // RETURN
}
ifs >> *result;
bsl::string::size_type pos = result->find_first_of('\0');
if (bsl::string::npos != pos) {
result->resize(pos);
}
# elif defined BSLS_PLATFORM_OS_DARWIN
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
if (proc_pidpath (getpid(), pathbuf, sizeof(pathbuf)) <= 0) {
return -1;
}
result->assign(pathbuf);
# else
# if defined BSLS_PLATFORM_OS_AIX
enum { NUM_ELEMENTS = 14 + 16 }; // "/proc/<pid>/psinfo"
bdlsb::MemOutStreamBuf osb(NUM_ELEMENTS);
bsl::ostream os(&osb);
os << "/proc/" << getpid() << "/psinfo" << bsl::ends;
const char *procfs = osb.data();
# else
const char *procfs = "/proc/self/psinfo";
# endif
int fd = open(procfs, O_RDONLY);
if (fd == -1) {
return -1;
}
psinfo_t psinfo;
bool readFailed = (sizeof psinfo != read(fd, &psinfo, sizeof psinfo));
int rc = close(fd);
if (readFailed || 0 != rc) {
return -1;
}
result->assign(psinfo.pr_psargs);
bsl::string::size_type pos = result->find_first_of(' ');
if (bsl::string::npos != pos) {
result->resize(pos);
}
# endif
#endif
return result->empty();
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Move header #include.<commit_after>// bdls_processutil.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <bdls_processutil.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bdls_processutil_cpp,"$Id$ $CSID$")
#include <bdlsb_memoutstreambuf.h>
#include <bsls_assert.h>
#include <bsls_platform.h>
#include <bsl_iostream.h>
#include <bsl_fstream.h>
#ifdef BSLS_PLATFORM_OS_WINDOWS
#include <windows.h>
#include <bdlde_charconvertutf16.h>
#include <bdlma_localsequentialallocator.h>
#else
#include <unistd.h>
#endif
#if defined(BSLS_PLATFORM_OS_SOLARIS)
#include <procfs.h>
#include <fcntl.h>
#elif defined(BSLS_PLATFORM_OS_AIX)
#include <sys/procfs.h>
#include <fcntl.h>
#elif defined(BSLS_PLATFORM_OS_LINUX) || defined(BSLS_PLATFORM_OS_CYGWIN)
#include <fcntl.h>
#elif defined(BSLS_PLATFORM_OS_HPUX)
#include <sys/pstat.h>
#elif defined(BSLS_PLATFORM_OS_DARWIN)
#include <libproc.h>
#endif
namespace BloombergLP {
namespace bdls {
// ------------------
// struct ProcessUtil
// ------------------
// CLASS METHODS
int ProcessUtil::getProcessId() {
#ifdef BSLS_PLATFORM_OS_WINDOWS
return static_cast<int>(GetCurrentProcessId());
#else
return static_cast<int>(getpid());
#endif
}
int ProcessUtil::getProcessName(bsl::string *result)
{
BSLS_ASSERT(result);
result->clear();
#if defined BSLS_PLATFORM_OS_WINDOWS
bdlma::LocalSequentialAllocator<MAX_PATH + 1> la;
bsl::wstring wResult(MAX_PATH, 0, &la);
while (wResult.length() <= 4 * MAX_PATH) {
DWORD length = GetModuleFileNameW(0, &wResult[0], wResult.length());
if (length <= 0) { // Error
return 1; // RETURN
}
else if (length < wResult.length()) { // Success
wResult.resize(length);
return bdlde::CharConvertUtf16::utf16ToUtf8(result, wResult);
// RETURN
}
else { // Not enough space for the process name in 'wResult'
wResult.resize(wResult.length() * 2); // Make more space
}
}
return -1;
#else
# if defined BSLS_PLATFORM_OS_HPUX
result->resize(256);
int rc = pstat_getcommandline(&(*result->begin()),
result->size(), 1,
getpid());
if (rc < 0)
{
return -1;
}
bsl::string::size_type pos = result->find_first_of(' ');
if (bsl::string::npos != pos) {
result->resize(pos);
}
# elif defined BSLS_PLATFORM_OS_LINUX || defined BSLS_PLATFORM_OS_CYGWIN
enum { NUM_ELEMENTS = 14 + 16 }; // "/proc/<pid>/cmdline"
bdlsb::MemOutStreamBuf osb(NUM_ELEMENTS);
bsl::ostream os(&osb);
os << "/proc/" << getpid() << "/cmdline" << bsl::ends;
const char *procfs = osb.data();
bsl::ifstream ifs;
ifs.open(procfs, bsl::ios_base::in | bsl::ios_base::binary);
if (ifs.fail()) {
return -1; // RETURN
}
ifs >> *result;
bsl::string::size_type pos = result->find_first_of('\0');
if (bsl::string::npos != pos) {
result->resize(pos);
}
# elif defined BSLS_PLATFORM_OS_DARWIN
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
if (proc_pidpath (getpid(), pathbuf, sizeof(pathbuf)) <= 0) {
return -1;
}
result->assign(pathbuf);
# else
# if defined BSLS_PLATFORM_OS_AIX
enum { NUM_ELEMENTS = 14 + 16 }; // "/proc/<pid>/psinfo"
bdlsb::MemOutStreamBuf osb(NUM_ELEMENTS);
bsl::ostream os(&osb);
os << "/proc/" << getpid() << "/psinfo" << bsl::ends;
const char *procfs = osb.data();
# else
const char *procfs = "/proc/self/psinfo";
# endif
int fd = open(procfs, O_RDONLY);
if (fd == -1) {
return -1;
}
psinfo_t psinfo;
bool readFailed = (sizeof psinfo != read(fd, &psinfo, sizeof psinfo));
int rc = close(fd);
if (readFailed || 0 != rc) {
return -1;
}
result->assign(psinfo.pr_psargs);
bsl::string::size_type pos = result->find_first_of(' ');
if (bsl::string::npos != pos) {
result->resize(pos);
}
# endif
#endif
return result->empty();
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.