text
stringlengths
54
60.6k
<commit_before>/******************************************************************************* * This file is part of "Patrick's Programming Library", Version 7 (PPL7). * Web: http://www.pfp.de/ppl/ * * $Author$ * $Revision$ * $Date$ * $Id$ * ******************************************************************************* * Copyright (c) 2013, Patrick Fedick <patrick@pfp.de> * 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 HOLDER AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND 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 "prolog.h" #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_ERRNO_H #include <errno.h> #endif #include "ppl7.h" #include "ppl7-inet.h" namespace ppl7 { Exception::Exception() throw() { ErrorText=NULL; } Exception::~Exception() throw() { if (ErrorText) free(ErrorText); } const char* Exception::what() const throw() { return "PPLException"; } Exception::Exception(const Exception &other) throw() { if (other.ErrorText) { ErrorText=strdup(other.ErrorText); } else { ErrorText=NULL; } } Exception& Exception::operator= (const Exception &other) throw() { if (other.ErrorText) { ErrorText=strdup(other.ErrorText); } else { ErrorText=NULL; } return *this; } Exception::Exception(const char *msg, ...) throw() { if (msg) { String Msg; va_list args; va_start(args, msg); try { Msg.vasprintf(msg,args); ErrorText=strdup((const char*)Msg); } catch (...) { ErrorText=NULL; } va_end(args); } else { ErrorText=NULL; } } void Exception::copyText(const char *str) throw() { free(ErrorText); ErrorText=strdup(str); } void Exception::copyText(const char *fmt, va_list args) throw() { free(ErrorText); try { String Msg; Msg.vasprintf(fmt,args); ErrorText=strdup((const char*)Msg); } catch (...) { ErrorText=NULL; } } const char* Exception::text() const throw() { if (ErrorText) return ErrorText; else return ""; } String Exception::toString() const throw() { String str; str.setf("%s",what()); if (ErrorText) str.appendf(" [%s]",(const char*)ErrorText); return str; } void Exception::print() const { PrintDebug("Exception: %s",what()); if (ErrorText) PrintDebug(" [%s]",(const char*)ErrorText); PrintDebug ("\n"); } std::ostream& operator<<(std::ostream& s, const Exception &e) { String str=e.toString(); return s.write((const char*)str,str.size()); } /*!\brief %Exception anhand errno-Variable werfen * * \desc * Diese Funktion wird verwendet, um nach Auftreten eines Fehlers, anhand der globalen * "errno"-Variablen die passende Exception zu werfen. * * @param e Errorcode aus der errno-Variablen * @param info Zusätzliche Informationen zum Fehler (optional) */ void throwExceptionFromErrno(int e,const String &info) { switch (e) { case ENOMEM: throw OutOfMemoryException(); case EINVAL: throw InvalidArgumentsException(); case ENOTDIR: case ENAMETOOLONG: throw InvalidFileNameException(info); case EACCES: case EPERM: throw PermissionDeniedException(info); case ENOENT: throw FileNotFoundException(info); #ifdef ELOOP case ELOOP: throw TooManySymbolicLinksException(info); #endif case EISDIR: throw NoRegularFileException(info); case EROFS: throw ReadOnlyException(info); case EMFILE: throw TooManyOpenFilesException(); #ifdef EOPNOTSUPP case EOPNOTSUPP: throw UnsupportedFileOperationException(info); #endif case ENOSPC: throw FilesystemFullException(); #ifdef EDQUOT case EDQUOT: throw QuotaExceededException(); #endif case EIO: throw IOErrorException(); case EBADF: throw BadFiledescriptorException(); case EFAULT: throw BadAddressException(); #ifdef EOVERFLOW case EOVERFLOW: throw OverflowException(); #endif case EEXIST: throw FileExistsException(); case EAGAIN: throw OperationBlockedException(); case EDEADLK: throw DeadlockException(); case EINTR: throw OperationInterruptedException(); case ENOLCK: throw TooManyLocksException(); case ESPIPE: throw IllegalOperationOnPipeException(); case ETIMEDOUT: throw TimeoutException(info); case ENETDOWN: throw NetworkDownException(info); case ENETUNREACH: throw NetworkUnreachableException(info); case ENETRESET: throw NetworkDroppedConnectionOnResetException(info); case ECONNABORTED: throw SoftwareCausedConnectionAbortException(info); case ECONNRESET: throw ConnectionResetByPeerException(info); case ENOBUFS: throw NoBufferSpaceException(info); case EISCONN: throw SocketIsAlreadyConnectedException(info); case ENOTCONN: throw NotConnectedException(info); case ESHUTDOWN: throw CantSendAfterSocketShutdownException(info); case ETOOMANYREFS: throw TooManyReferencesException(info); case ECONNREFUSED: throw ConnectionRefusedException(info); case EHOSTDOWN: throw HostDownException(info); case EHOSTUNREACH: throw NoRouteToHostException(info); case ENOTSOCK: throw InvalidSocketException(info); case ENOPROTOOPT: throw UnknownOptionException(info); /* * */ default: { String ret=strerror(e); ret+=": "+info; throw UnknownException(ret); } } } } <commit_msg>EPIPE zu Exception<commit_after>/******************************************************************************* * This file is part of "Patrick's Programming Library", Version 7 (PPL7). * Web: http://www.pfp.de/ppl/ * * $Author$ * $Revision$ * $Date$ * $Id$ * ******************************************************************************* * Copyright (c) 2013, Patrick Fedick <patrick@pfp.de> * 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 HOLDER AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER AND 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 "prolog.h" #ifdef HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_ERRNO_H #include <errno.h> #endif #include "ppl7.h" #include "ppl7-inet.h" namespace ppl7 { Exception::Exception() throw() { ErrorText=NULL; } Exception::~Exception() throw() { if (ErrorText) free(ErrorText); } const char* Exception::what() const throw() { return "PPLException"; } Exception::Exception(const Exception &other) throw() { if (other.ErrorText) { ErrorText=strdup(other.ErrorText); } else { ErrorText=NULL; } } Exception& Exception::operator= (const Exception &other) throw() { if (other.ErrorText) { ErrorText=strdup(other.ErrorText); } else { ErrorText=NULL; } return *this; } Exception::Exception(const char *msg, ...) throw() { if (msg) { String Msg; va_list args; va_start(args, msg); try { Msg.vasprintf(msg,args); ErrorText=strdup((const char*)Msg); } catch (...) { ErrorText=NULL; } va_end(args); } else { ErrorText=NULL; } } void Exception::copyText(const char *str) throw() { free(ErrorText); ErrorText=strdup(str); } void Exception::copyText(const char *fmt, va_list args) throw() { free(ErrorText); try { String Msg; Msg.vasprintf(fmt,args); ErrorText=strdup((const char*)Msg); } catch (...) { ErrorText=NULL; } } const char* Exception::text() const throw() { if (ErrorText) return ErrorText; else return ""; } String Exception::toString() const throw() { String str; str.setf("%s",what()); if (ErrorText) str.appendf(" [%s]",(const char*)ErrorText); return str; } void Exception::print() const { PrintDebug("Exception: %s",what()); if (ErrorText) PrintDebug(" [%s]",(const char*)ErrorText); PrintDebug ("\n"); } std::ostream& operator<<(std::ostream& s, const Exception &e) { String str=e.toString(); return s.write((const char*)str,str.size()); } /*!\brief %Exception anhand errno-Variable werfen * * \desc * Diese Funktion wird verwendet, um nach Auftreten eines Fehlers, anhand der globalen * "errno"-Variablen die passende Exception zu werfen. * * @param e Errorcode aus der errno-Variablen * @param info Zusätzliche Informationen zum Fehler (optional) */ void throwExceptionFromErrno(int e,const String &info) { switch (e) { case ENOMEM: throw OutOfMemoryException(); case EINVAL: throw InvalidArgumentsException(); case ENOTDIR: case ENAMETOOLONG: throw InvalidFileNameException(info); case EACCES: case EPERM: throw PermissionDeniedException(info); case ENOENT: throw FileNotFoundException(info); #ifdef ELOOP case ELOOP: throw TooManySymbolicLinksException(info); #endif case EISDIR: throw NoRegularFileException(info); case EROFS: throw ReadOnlyException(info); case EMFILE: throw TooManyOpenFilesException(); #ifdef EOPNOTSUPP case EOPNOTSUPP: throw UnsupportedFileOperationException(info); #endif case ENOSPC: throw FilesystemFullException(); #ifdef EDQUOT case EDQUOT: throw QuotaExceededException(); #endif case EIO: throw IOErrorException(); case EBADF: throw BadFiledescriptorException(); case EFAULT: throw BadAddressException(); #ifdef EOVERFLOW case EOVERFLOW: throw OverflowException(); #endif case EEXIST: throw FileExistsException(); case EAGAIN: throw OperationBlockedException(); case EDEADLK: throw DeadlockException(); case EINTR: throw OperationInterruptedException(); case ENOLCK: throw TooManyLocksException(); case ESPIPE: throw IllegalOperationOnPipeException(); case ETIMEDOUT: throw TimeoutException(info); case ENETDOWN: throw NetworkDownException(info); case ENETUNREACH: throw NetworkUnreachableException(info); case ENETRESET: throw NetworkDroppedConnectionOnResetException(info); case ECONNABORTED: throw SoftwareCausedConnectionAbortException(info); case ECONNRESET: throw ConnectionResetByPeerException(info); case ENOBUFS: throw NoBufferSpaceException(info); case EISCONN: throw SocketIsAlreadyConnectedException(info); case ENOTCONN: throw NotConnectedException(info); case ESHUTDOWN: throw CantSendAfterSocketShutdownException(info); case ETOOMANYREFS: throw TooManyReferencesException(info); case ECONNREFUSED: throw ConnectionRefusedException(info); case EHOSTDOWN: throw HostDownException(info); case EHOSTUNREACH: throw NoRouteToHostException(info); case ENOTSOCK: throw InvalidSocketException(info); case ENOPROTOOPT: throw UnknownOptionException(info); case EPIPE: throw BrokenPipeException(info); /* * */ default: { String ret=strerror(e); ret+=": "+info; throw UnknownException(ret); } } } } <|endoftext|>
<commit_before>/* * Copyright 2011 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkAdvancedTypefaceMetrics.h" #include "SkFontDescriptor.h" #include "SkFontHost.h" #include "SkFontStream.h" #include "SkStream.h" #include "SkTypeface.h" SK_DEFINE_INST_COUNT(SkTypeface) //#define TRACE_LIFECYCLE #ifdef TRACE_LIFECYCLE static int32_t gTypefaceCounter; #endif SkTypeface::SkTypeface(Style style, SkFontID fontID, bool isFixedPitch) : fUniqueID(fontID), fStyle(style), fIsFixedPitch(isFixedPitch) { #ifdef TRACE_LIFECYCLE SkDebugf("SkTypeface: create %p fontID %d total %d\n", this, fontID, ++gTypefaceCounter); #endif } SkTypeface::~SkTypeface() { #ifdef TRACE_LIFECYCLE SkDebugf("SkTypeface: destroy %p fontID %d total %d\n", this, fUniqueID, --gTypefaceCounter); #endif } /////////////////////////////////////////////////////////////////////////////// SkTypeface* SkTypeface::GetDefaultTypeface() { // we keep a reference to this guy for all time, since if we return its // fontID, the font cache may later on ask to resolve that back into a // typeface object. static SkTypeface* gDefaultTypeface; if (NULL == gDefaultTypeface) { gDefaultTypeface = SkFontHost::CreateTypeface(NULL, NULL, SkTypeface::kNormal); } return gDefaultTypeface; } SkTypeface* SkTypeface::RefDefault() { return SkRef(GetDefaultTypeface()); } uint32_t SkTypeface::UniqueID(const SkTypeface* face) { if (NULL == face) { face = GetDefaultTypeface(); } return face->uniqueID(); } bool SkTypeface::Equal(const SkTypeface* facea, const SkTypeface* faceb) { return SkTypeface::UniqueID(facea) == SkTypeface::UniqueID(faceb); } /////////////////////////////////////////////////////////////////////////////// SkTypeface* SkTypeface::CreateFromName(const char name[], Style style) { return SkFontHost::CreateTypeface(NULL, name, style); } SkTypeface* SkTypeface::CreateFromTypeface(const SkTypeface* family, Style s) { if (family && family->style() == s) { family->ref(); return const_cast<SkTypeface*>(family); } return SkFontHost::CreateTypeface(family, NULL, s); } SkTypeface* SkTypeface::CreateFromStream(SkStream* stream) { return SkFontHost::CreateTypefaceFromStream(stream); } SkTypeface* SkTypeface::CreateFromFile(const char path[]) { return SkFontHost::CreateTypefaceFromFile(path); } /////////////////////////////////////////////////////////////////////////////// void SkTypeface::serialize(SkWStream* wstream) const { bool isLocal = false; SkFontDescriptor desc(this->style()); this->onGetFontDescriptor(&desc, &isLocal); desc.serialize(wstream); if (isLocal) { int ttcIndex; // TODO: write this to the stream? SkAutoTUnref<SkStream> rstream(this->openStream(&ttcIndex)); if (rstream.get()) { size_t length = rstream->getLength(); wstream->writePackedUInt(length); wstream->writeStream(rstream, length); } else { wstream->writePackedUInt(0); } } else { wstream->writePackedUInt(0); } } SkTypeface* SkTypeface::Deserialize(SkStream* stream) { SkFontDescriptor desc(stream); size_t length = stream->readPackedUInt(); if (length > 0) { void* addr = sk_malloc_flags(length, 0); if (addr) { SkAutoTUnref<SkStream> localStream(SkNEW_ARGS(SkMemoryStream, (addr, length, false))); stream->skip(length); return SkTypeface::CreateFromStream(localStream.get()); } // failed to allocate, so just skip and create-from-name stream->skip(length); } return SkTypeface::CreateFromName(desc.getFamilyName(), desc.getStyle()); } /////////////////////////////////////////////////////////////////////////////// int SkTypeface::countTables() const { return this->onGetTableTags(NULL); } int SkTypeface::getTableTags(SkFontTableTag tags[]) const { return this->onGetTableTags(tags); } size_t SkTypeface::getTableSize(SkFontTableTag tag) const { return this->onGetTableData(tag, 0, ~0U, NULL); } size_t SkTypeface::getTableData(SkFontTableTag tag, size_t offset, size_t length, void* data) const { return this->onGetTableData(tag, offset, length, data); } SkStream* SkTypeface::openStream(int* ttcIndex) const { int ttcIndexStorage; if (NULL == ttcIndex) { // So our subclasses don't need to check for null param ttcIndex = &ttcIndexStorage; } return this->onOpenStream(ttcIndex); } int SkTypeface::getUnitsPerEm() const { // should we try to cache this in the base-class? return this->onGetUPEM(); } SkAdvancedTypefaceMetrics* SkTypeface::getAdvancedTypefaceMetrics( SkAdvancedTypefaceMetrics::PerGlyphInfo info, const uint32_t* glyphIDs, uint32_t glyphIDsCount) const { return this->onGetAdvancedTypefaceMetrics(info, glyphIDs, glyphIDsCount); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// int SkTypeface::onGetUPEM() const { int upem = 0; SkAdvancedTypefaceMetrics* metrics; metrics = this->getAdvancedTypefaceMetrics( SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo, NULL, 0); if (metrics) { upem = metrics->fEmSize; metrics->unref(); } return upem; } int SkTypeface::onGetTableTags(SkFontTableTag tags[]) const { int ttcIndex; SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex)); return stream.get() ? SkFontStream::GetTableTags(stream, ttcIndex, tags) : 0; } size_t SkTypeface::onGetTableData(SkFontTableTag tag, size_t offset, size_t length, void* data) const { int ttcIndex; SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex)); return stream.get() ? SkFontStream::GetTableData(stream, ttcIndex, tag, offset, length, data) : 0; } <commit_msg>Make SkTypeFace::Deserialize work for embedded fonts. https://codereview.appspot.com/8584044/<commit_after>/* * Copyright 2011 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkAdvancedTypefaceMetrics.h" #include "SkFontDescriptor.h" #include "SkFontHost.h" #include "SkFontStream.h" #include "SkStream.h" #include "SkTypeface.h" SK_DEFINE_INST_COUNT(SkTypeface) //#define TRACE_LIFECYCLE #ifdef TRACE_LIFECYCLE static int32_t gTypefaceCounter; #endif SkTypeface::SkTypeface(Style style, SkFontID fontID, bool isFixedPitch) : fUniqueID(fontID), fStyle(style), fIsFixedPitch(isFixedPitch) { #ifdef TRACE_LIFECYCLE SkDebugf("SkTypeface: create %p fontID %d total %d\n", this, fontID, ++gTypefaceCounter); #endif } SkTypeface::~SkTypeface() { #ifdef TRACE_LIFECYCLE SkDebugf("SkTypeface: destroy %p fontID %d total %d\n", this, fUniqueID, --gTypefaceCounter); #endif } /////////////////////////////////////////////////////////////////////////////// SkTypeface* SkTypeface::GetDefaultTypeface() { // we keep a reference to this guy for all time, since if we return its // fontID, the font cache may later on ask to resolve that back into a // typeface object. static SkTypeface* gDefaultTypeface; if (NULL == gDefaultTypeface) { gDefaultTypeface = SkFontHost::CreateTypeface(NULL, NULL, SkTypeface::kNormal); } return gDefaultTypeface; } SkTypeface* SkTypeface::RefDefault() { return SkRef(GetDefaultTypeface()); } uint32_t SkTypeface::UniqueID(const SkTypeface* face) { if (NULL == face) { face = GetDefaultTypeface(); } return face->uniqueID(); } bool SkTypeface::Equal(const SkTypeface* facea, const SkTypeface* faceb) { return SkTypeface::UniqueID(facea) == SkTypeface::UniqueID(faceb); } /////////////////////////////////////////////////////////////////////////////// SkTypeface* SkTypeface::CreateFromName(const char name[], Style style) { return SkFontHost::CreateTypeface(NULL, name, style); } SkTypeface* SkTypeface::CreateFromTypeface(const SkTypeface* family, Style s) { if (family && family->style() == s) { family->ref(); return const_cast<SkTypeface*>(family); } return SkFontHost::CreateTypeface(family, NULL, s); } SkTypeface* SkTypeface::CreateFromStream(SkStream* stream) { return SkFontHost::CreateTypefaceFromStream(stream); } SkTypeface* SkTypeface::CreateFromFile(const char path[]) { return SkFontHost::CreateTypefaceFromFile(path); } /////////////////////////////////////////////////////////////////////////////// void SkTypeface::serialize(SkWStream* wstream) const { bool isLocal = false; SkFontDescriptor desc(this->style()); this->onGetFontDescriptor(&desc, &isLocal); desc.serialize(wstream); if (isLocal) { int ttcIndex; // TODO: write this to the stream? SkAutoTUnref<SkStream> rstream(this->openStream(&ttcIndex)); if (rstream.get()) { size_t length = rstream->getLength(); wstream->writePackedUInt(length); wstream->writeStream(rstream, length); } else { wstream->writePackedUInt(0); } } else { wstream->writePackedUInt(0); } } SkTypeface* SkTypeface::Deserialize(SkStream* stream) { SkFontDescriptor desc(stream); size_t length = stream->readPackedUInt(); if (length > 0) { void* addr = sk_malloc_flags(length, 0); if (addr) { SkAutoTUnref<SkStream> localStream(SkNEW_ARGS(SkMemoryStream, (addr, length, false))); if (stream->read(addr, length) == length) { return SkTypeface::CreateFromStream(localStream.get()); } else { // Failed to read the full font data, so fall through and try to create from name. // If this is because of EOF, all subsequent reads from the stream will be EOF. // If this is because of a stream error, the stream is in an error state, // do not attempt to skip any remaining bytes. } } else { // failed to allocate, so just skip and create-from-name stream->skip(length); } } return SkTypeface::CreateFromName(desc.getFamilyName(), desc.getStyle()); } /////////////////////////////////////////////////////////////////////////////// int SkTypeface::countTables() const { return this->onGetTableTags(NULL); } int SkTypeface::getTableTags(SkFontTableTag tags[]) const { return this->onGetTableTags(tags); } size_t SkTypeface::getTableSize(SkFontTableTag tag) const { return this->onGetTableData(tag, 0, ~0U, NULL); } size_t SkTypeface::getTableData(SkFontTableTag tag, size_t offset, size_t length, void* data) const { return this->onGetTableData(tag, offset, length, data); } SkStream* SkTypeface::openStream(int* ttcIndex) const { int ttcIndexStorage; if (NULL == ttcIndex) { // So our subclasses don't need to check for null param ttcIndex = &ttcIndexStorage; } return this->onOpenStream(ttcIndex); } int SkTypeface::getUnitsPerEm() const { // should we try to cache this in the base-class? return this->onGetUPEM(); } SkAdvancedTypefaceMetrics* SkTypeface::getAdvancedTypefaceMetrics( SkAdvancedTypefaceMetrics::PerGlyphInfo info, const uint32_t* glyphIDs, uint32_t glyphIDsCount) const { return this->onGetAdvancedTypefaceMetrics(info, glyphIDs, glyphIDsCount); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// int SkTypeface::onGetUPEM() const { int upem = 0; SkAdvancedTypefaceMetrics* metrics; metrics = this->getAdvancedTypefaceMetrics( SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo, NULL, 0); if (metrics) { upem = metrics->fEmSize; metrics->unref(); } return upem; } int SkTypeface::onGetTableTags(SkFontTableTag tags[]) const { int ttcIndex; SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex)); return stream.get() ? SkFontStream::GetTableTags(stream, ttcIndex, tags) : 0; } size_t SkTypeface::onGetTableData(SkFontTableTag tag, size_t offset, size_t length, void* data) const { int ttcIndex; SkAutoTUnref<SkStream> stream(this->openStream(&ttcIndex)); return stream.get() ? SkFontStream::GetTableData(stream, ttcIndex, tag, offset, length, data) : 0; } <|endoftext|>
<commit_before> /* * Copyright 2011 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkAdvancedTypefaceMetrics.h" #include "SkTypeface.h" #include "SkFontHost.h" SK_DEFINE_INST_COUNT(SkTypeface) //#define TRACE_LIFECYCLE #ifdef TRACE_LIFECYCLE static int32_t gTypefaceCounter; #endif SkTypeface::SkTypeface(Style style, SkFontID fontID, bool isFixedWidth) : fUniqueID(fontID), fStyle(style), fIsFixedWidth(isFixedWidth) { #ifdef TRACE_LIFECYCLE SkDebugf("SkTypeface: create %p fontID %d total %d\n", this, fontID, ++gTypefaceCounter); #endif } SkTypeface::~SkTypeface() { #ifdef TRACE_LIFECYCLE SkDebugf("SkTypeface: destroy %p fontID %d total %d\n", this, fUniqueID, --gTypefaceCounter); #endif } /////////////////////////////////////////////////////////////////////////////// SkTypeface* SkTypeface::GetDefaultTypeface() { // we keep a reference to this guy for all time, since if we return its // fontID, the font cache may later on ask to resolve that back into a // typeface object. static SkTypeface* gDefaultTypeface; if (NULL == gDefaultTypeface) { gDefaultTypeface = SkFontHost::CreateTypeface(NULL, NULL, SkTypeface::kNormal); } return gDefaultTypeface; } uint32_t SkTypeface::UniqueID(const SkTypeface* face) { if (NULL == face) { face = GetDefaultTypeface(); } return face->uniqueID(); } bool SkTypeface::Equal(const SkTypeface* facea, const SkTypeface* faceb) { return SkTypeface::UniqueID(facea) == SkTypeface::UniqueID(faceb); } /////////////////////////////////////////////////////////////////////////////// SkTypeface* SkTypeface::CreateFromName(const char name[], Style style) { return SkFontHost::CreateTypeface(NULL, name, style); } SkTypeface* SkTypeface::CreateFromTypeface(const SkTypeface* family, Style s) { return SkFontHost::CreateTypeface(family, NULL, s); } SkTypeface* SkTypeface::CreateFromStream(SkStream* stream) { return SkFontHost::CreateTypefaceFromStream(stream); } SkTypeface* SkTypeface::CreateFromFile(const char path[]) { return SkFontHost::CreateTypefaceFromFile(path); } /////////////////////////////////////////////////////////////////////////////// void SkTypeface::serialize(SkWStream* stream) const { SkFontHost::Serialize(this, stream); } SkTypeface* SkTypeface::Deserialize(SkStream* stream) { return SkFontHost::Deserialize(stream); } SkAdvancedTypefaceMetrics* SkTypeface::getAdvancedTypefaceMetrics( SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo, const uint32_t* glyphIDs, uint32_t glyphIDsCount) const { return SkFontHost::GetAdvancedTypefaceMetrics(fUniqueID, perGlyphInfo, glyphIDs, glyphIDsCount); } /////////////////////////////////////////////////////////////////////////////// int SkTypeface::countTables() const { return SkFontHost::CountTables(fUniqueID); } int SkTypeface::getTableTags(SkFontTableTag tags[]) const { return SkFontHost::GetTableTags(fUniqueID, tags); } size_t SkTypeface::getTableSize(SkFontTableTag tag) const { return SkFontHost::GetTableSize(fUniqueID, tag); } size_t SkTypeface::getTableData(SkFontTableTag tag, size_t offset, size_t length, void* data) const { return SkFontHost::GetTableData(fUniqueID, tag, offset, length, data); } int SkTypeface::getUnitsPerEm() const { int upem = 0; #ifdef SK_BUILD_FOR_ANDROID upem = SkFontHost::GetUnitsPerEm(fUniqueID); #else SkAdvancedTypefaceMetrics* metrics; metrics = SkFontHost::GetAdvancedTypefaceMetrics(fUniqueID, SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo, NULL, 0); if (metrics) { upem = metrics->fEmSize; metrics->unref(); } #endif return upem; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #include "SkFontDescriptor.h" int SkTypeface::onGetUPEM() const { return 0; } int SkTypeface::onGetTableTags(SkFontTableTag tags[]) const { return 0; } size_t SkTypeface::onGetTableData(SkFontTableTag, size_t offset, size_t length, void* data) const { return 0; } SkScalerContext* SkTypeface::onCreateScalerContext(const SkDescriptor*) const { return NULL; } void SkTypeface::onFilterRec(SkScalerContextRec*) const {} void SkTypeface::onGetFontDescriptor(SkFontDescriptor* desc) const { desc->setStyle(this->style()); } <commit_msg>short-circuit if the requested typeface matches what we've been given.<commit_after> /* * Copyright 2011 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkAdvancedTypefaceMetrics.h" #include "SkTypeface.h" #include "SkFontHost.h" SK_DEFINE_INST_COUNT(SkTypeface) //#define TRACE_LIFECYCLE #ifdef TRACE_LIFECYCLE static int32_t gTypefaceCounter; #endif SkTypeface::SkTypeface(Style style, SkFontID fontID, bool isFixedWidth) : fUniqueID(fontID), fStyle(style), fIsFixedWidth(isFixedWidth) { #ifdef TRACE_LIFECYCLE SkDebugf("SkTypeface: create %p fontID %d total %d\n", this, fontID, ++gTypefaceCounter); #endif } SkTypeface::~SkTypeface() { #ifdef TRACE_LIFECYCLE SkDebugf("SkTypeface: destroy %p fontID %d total %d\n", this, fUniqueID, --gTypefaceCounter); #endif } /////////////////////////////////////////////////////////////////////////////// SkTypeface* SkTypeface::GetDefaultTypeface() { // we keep a reference to this guy for all time, since if we return its // fontID, the font cache may later on ask to resolve that back into a // typeface object. static SkTypeface* gDefaultTypeface; if (NULL == gDefaultTypeface) { gDefaultTypeface = SkFontHost::CreateTypeface(NULL, NULL, SkTypeface::kNormal); } return gDefaultTypeface; } uint32_t SkTypeface::UniqueID(const SkTypeface* face) { if (NULL == face) { face = GetDefaultTypeface(); } return face->uniqueID(); } bool SkTypeface::Equal(const SkTypeface* facea, const SkTypeface* faceb) { return SkTypeface::UniqueID(facea) == SkTypeface::UniqueID(faceb); } /////////////////////////////////////////////////////////////////////////////// SkTypeface* SkTypeface::CreateFromName(const char name[], Style style) { return SkFontHost::CreateTypeface(NULL, name, style); } SkTypeface* SkTypeface::CreateFromTypeface(const SkTypeface* family, Style s) { if (family && family->style() == s) { family->ref(); return const_cast<SkTypeface*>(family); } return SkFontHost::CreateTypeface(family, NULL, s); } SkTypeface* SkTypeface::CreateFromStream(SkStream* stream) { return SkFontHost::CreateTypefaceFromStream(stream); } SkTypeface* SkTypeface::CreateFromFile(const char path[]) { return SkFontHost::CreateTypefaceFromFile(path); } /////////////////////////////////////////////////////////////////////////////// void SkTypeface::serialize(SkWStream* stream) const { SkFontHost::Serialize(this, stream); } SkTypeface* SkTypeface::Deserialize(SkStream* stream) { return SkFontHost::Deserialize(stream); } SkAdvancedTypefaceMetrics* SkTypeface::getAdvancedTypefaceMetrics( SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo, const uint32_t* glyphIDs, uint32_t glyphIDsCount) const { return SkFontHost::GetAdvancedTypefaceMetrics(fUniqueID, perGlyphInfo, glyphIDs, glyphIDsCount); } /////////////////////////////////////////////////////////////////////////////// int SkTypeface::countTables() const { return SkFontHost::CountTables(fUniqueID); } int SkTypeface::getTableTags(SkFontTableTag tags[]) const { return SkFontHost::GetTableTags(fUniqueID, tags); } size_t SkTypeface::getTableSize(SkFontTableTag tag) const { return SkFontHost::GetTableSize(fUniqueID, tag); } size_t SkTypeface::getTableData(SkFontTableTag tag, size_t offset, size_t length, void* data) const { return SkFontHost::GetTableData(fUniqueID, tag, offset, length, data); } int SkTypeface::getUnitsPerEm() const { int upem = 0; #ifdef SK_BUILD_FOR_ANDROID upem = SkFontHost::GetUnitsPerEm(fUniqueID); #else SkAdvancedTypefaceMetrics* metrics; metrics = SkFontHost::GetAdvancedTypefaceMetrics(fUniqueID, SkAdvancedTypefaceMetrics::kNo_PerGlyphInfo, NULL, 0); if (metrics) { upem = metrics->fEmSize; metrics->unref(); } #endif return upem; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #include "SkFontDescriptor.h" int SkTypeface::onGetUPEM() const { return 0; } int SkTypeface::onGetTableTags(SkFontTableTag tags[]) const { return 0; } size_t SkTypeface::onGetTableData(SkFontTableTag, size_t offset, size_t length, void* data) const { return 0; } SkScalerContext* SkTypeface::onCreateScalerContext(const SkDescriptor*) const { return NULL; } void SkTypeface::onFilterRec(SkScalerContextRec*) const {} void SkTypeface::onGetFontDescriptor(SkFontDescriptor* desc) const { desc->setStyle(this->style()); } <|endoftext|>
<commit_before>/* * Copyright (c) 2021, Jan de Visser <jan@finiandarcy.com> * * SPDX-License-Identifier: GPL-3.0-or-later */ // // Created by Jan de Visser on 2021-09-20. // #include <cassert> #include <cctype> #include <core/StringUtil.h> namespace Obelix { int stricmp(const char* a, const char* b) { unsigned char ca, cb; do { ca = tolower(toupper((unsigned char)*a++)); cb = tolower(toupper((unsigned char)*b++)); } while (ca == cb && ca != '\0'); return ca - cb; } std::string to_upper(std::string const& input) { std::string ret; for (auto& ch : input) { ret += (char) toupper((int) ch); } return ret; } std::string to_lower(std::string const& input) { std::string ret; for (auto& ch : input) { ret += (char) tolower((int) ch); } return ret; } std::string c_escape(std::string const& s) { std::string ret; for (char c : s) { if (c == '"' || c == '\'' || c == '\\') { ret += "\\"; } ret += c; } return ret; } std::vector<std::string> split(std::string const& s, char sep) { auto start = 0u; auto ptr = 0u; std::vector<std::string> ret; do { start = ptr; for (; (ptr < s.length()) && (s[ptr] != sep); ptr++) ; ret.push_back(s.substr(start, ptr - start)); start = ++ptr; } while (ptr < s.length()); if (s[s.length() - 1] == sep) // This is ugly... ret.emplace_back(""); return ret; } std::string join(std::vector<std::string> const& collection, std::string const& sep) { std::string ret; auto first = true; for (auto& elem : collection) { if (!first) { ret += sep; } ret += elem; first = false; } return ret; } std::string join(std::vector<std::string> const& collection, char sep) { std::string sep_str; sep_str += sep; return join(collection, sep_str); } std::string strip(std::string const& s) { size_t start; for (start = 0; (start < s.length()) && std::isspace(s[start]); start++) ; if (start == s.length()) { return {}; } size_t end; for (end = s.length() - 1; std::isspace(s[end]); end--) ; return s.substr(start, end - start + 1); } std::string rstrip(std::string const& s) { size_t end; for (end = s.length() - 1; std::isspace(s[end]); end--) ; return s.substr(0, end + 1); } std::string lstrip(std::string const& s) { size_t start; for (start = 0; (start < s.length()) && std::isspace(s[start]); start++) ; return s.substr(start, s.length() - start); } std::vector<std::pair<std::string, std::string>> parse_pairs(std::string const& s, char pair_sep, char name_value_sep) { auto pairs = split(s, pair_sep); std::vector<std::pair<std::string, std::string>> ret; for (auto& pair : pairs) { auto nvp = split(strip(pair), name_value_sep); switch (nvp.size()) { case 0: break; case 1: if (!strip(nvp[0]).empty()) ret.emplace_back(strip(nvp[0]), ""); break; case 2: if (!strip(nvp[0]).empty()) ret.emplace_back(strip(nvp[0]), strip(nvp[1])); break; default: if (!strip(nvp[0]).empty()) { std::vector<std::string> tail; for (auto ix = 1u; ix < nvp.size(); ix++) { tail.push_back(nvp[ix]); } auto value = strip(join(tail, name_value_sep)); ret.emplace_back(strip(nvp[0]), strip(value)); } } } return ret; } std::string to_string(long value) { char buf[80]; snprintf(buf, 79, "%ld", value); return buf; } std::string to_hex_string(long value) { char buf[80]; snprintf(buf, 79, "%lx", value); return buf; } std::string to_string(double value) { char buf[80]; snprintf(buf, 79, "%f", value); return buf; } std::string to_string(bool value) { return (value) ? "true" : "false"; } bool check_zero(std::string const& str) { int zeroes = 0; for (auto& ch : str) { switch (ch) { case 'x': case 'X': if (zeroes != 1) return false; break; case '0': zeroes += (ch == '0') ? 1 : 0; break; default: return false; } } return true; } unsigned long parse_binary(char const* str, char const** end) { unsigned long ret = 0; if ((strlen(str) > 2) && (str[0] == '0') && (toupper(str[1]) == 'B')) { str += 2; } *end = str; for (*end = str; **end; (*end)++) { if (**end == '0') { ret <<= 1; continue; } if (**end == '1') { ret = (ret<<1) + 1; continue; } break; } return ret; } std::optional<long> to_long(std::string const& str) { char const* end; errno = 0; if (str.empty()) return {}; std::string s = str; if ((s.length() > 1) && (s[0] == '$')) s = "0x" + s.substr(1); long ret; if ((s.length() > 2) && (s[0] == '0') && (toupper(s[1]) == 'B')) { ret = (long)parse_binary(s.c_str(), &end); } else { ret = strtol(s.c_str(), const_cast<char**>(&end), 0); } if ((end != (s.c_str() + s.length())) || (errno != 0)) return {}; if ((ret == 0) && !check_zero(str)) return {}; return ret; } std::optional<unsigned long> to_ulong(std::string const& str) { char const* end; errno = 0; std::string s = str; if ((s.length() > 1) && (s[0] == '$')) s = "0x" + s.substr(1); unsigned long ret; if ((s.length() > 2) && (s[0] == '0') && (toupper(s[1]) == 'B')) { ret = parse_binary(s.c_str(), &end); } else { ret = strtoul(s.c_str(), const_cast<char**>(&end), 0); } if ((ret == 0) && !check_zero(str)) return {}; return ret; } long to_long_unconditional(std::string const& str) { auto ret = to_long(str); assert(ret.has_value()); return ret.value(); } std::optional<double> to_double(std::string const& str) { char* end; errno = 0; auto ret = strtod(str.c_str(), &end); if ((end != (str.c_str() + str.length())) || (errno != 0)) return {}; if (ret == 0) { for (auto& ch : str) { if ((ch != '.') && (ch != '0')) return {}; } } return ret; } double to_double_unconditional(std::string const& str) { auto ret = to_double(str); assert(ret.has_value()); return ret.value(); } std::optional<bool> to_bool(std::string const& str) { if (str == "true" || str == "True" || str == "TRUE") return true; if (str == "false" || str == "False" || str == "FALSE") return true; auto ret = to_long(str); if (!ret.has_value()) return {}; return (ret.value() != 0); } bool to_bool_unconditional(std::string const& str) { auto ret = to_bool(str); assert(ret.has_value()); return ret.value(); } } <commit_msg>$0000 wouldn't parse as a zero hex value<commit_after>/* * Copyright (c) 2021, Jan de Visser <jan@finiandarcy.com> * * SPDX-License-Identifier: GPL-3.0-or-later */ // // Created by Jan de Visser on 2021-09-20. // #include <cassert> #include <cctype> #include <core/StringUtil.h> namespace Obelix { int stricmp(const char* a, const char* b) { unsigned char ca, cb; do { ca = tolower(toupper((unsigned char)*a++)); cb = tolower(toupper((unsigned char)*b++)); } while (ca == cb && ca != '\0'); return ca - cb; } std::string to_upper(std::string const& input) { std::string ret; for (auto& ch : input) { ret += (char) toupper((int) ch); } return ret; } std::string to_lower(std::string const& input) { std::string ret; for (auto& ch : input) { ret += (char) tolower((int) ch); } return ret; } std::string c_escape(std::string const& s) { std::string ret; for (char c : s) { if (c == '"' || c == '\'' || c == '\\') { ret += "\\"; } ret += c; } return ret; } std::vector<std::string> split(std::string const& s, char sep) { auto start = 0u; auto ptr = 0u; std::vector<std::string> ret; do { start = ptr; for (; (ptr < s.length()) && (s[ptr] != sep); ptr++) ; ret.push_back(s.substr(start, ptr - start)); start = ++ptr; } while (ptr < s.length()); if (s[s.length() - 1] == sep) // This is ugly... ret.emplace_back(""); return ret; } std::string join(std::vector<std::string> const& collection, std::string const& sep) { std::string ret; auto first = true; for (auto& elem : collection) { if (!first) { ret += sep; } ret += elem; first = false; } return ret; } std::string join(std::vector<std::string> const& collection, char sep) { std::string sep_str; sep_str += sep; return join(collection, sep_str); } std::string strip(std::string const& s) { size_t start; for (start = 0; (start < s.length()) && std::isspace(s[start]); start++) ; if (start == s.length()) { return {}; } size_t end; for (end = s.length() - 1; std::isspace(s[end]); end--) ; return s.substr(start, end - start + 1); } std::string rstrip(std::string const& s) { size_t end; for (end = s.length() - 1; std::isspace(s[end]); end--) ; return s.substr(0, end + 1); } std::string lstrip(std::string const& s) { size_t start; for (start = 0; (start < s.length()) && std::isspace(s[start]); start++) ; return s.substr(start, s.length() - start); } std::vector<std::pair<std::string, std::string>> parse_pairs(std::string const& s, char pair_sep, char name_value_sep) { auto pairs = split(s, pair_sep); std::vector<std::pair<std::string, std::string>> ret; for (auto& pair : pairs) { auto nvp = split(strip(pair), name_value_sep); switch (nvp.size()) { case 0: break; case 1: if (!strip(nvp[0]).empty()) ret.emplace_back(strip(nvp[0]), ""); break; case 2: if (!strip(nvp[0]).empty()) ret.emplace_back(strip(nvp[0]), strip(nvp[1])); break; default: if (!strip(nvp[0]).empty()) { std::vector<std::string> tail; for (auto ix = 1u; ix < nvp.size(); ix++) { tail.push_back(nvp[ix]); } auto value = strip(join(tail, name_value_sep)); ret.emplace_back(strip(nvp[0]), strip(value)); } } } return ret; } std::string to_string(long value) { char buf[80]; snprintf(buf, 79, "%ld", value); return buf; } std::string to_hex_string(long value) { char buf[80]; snprintf(buf, 79, "%lx", value); return buf; } std::string to_string(double value) { char buf[80]; snprintf(buf, 79, "%f", value); return buf; } std::string to_string(bool value) { return (value) ? "true" : "false"; } bool check_zero(std::string const& str) { int zeroes = 0; for (auto& ch : str) { switch (ch) { case '$': if (zeroes != 0) return false; break; case 'x': case 'X': if (zeroes != 1) return false; break; case '0': zeroes += (ch == '0') ? 1 : 0; break; default: return false; } } return true; } unsigned long parse_binary(char const* str, char const** end) { unsigned long ret = 0; if ((strlen(str) > 2) && (str[0] == '0') && (toupper(str[1]) == 'B')) { str += 2; } *end = str; for (*end = str; **end; (*end)++) { if (**end == '0') { ret <<= 1; continue; } if (**end == '1') { ret = (ret<<1) + 1; continue; } break; } return ret; } std::optional<long> to_long(std::string const& str) { char const* end; errno = 0; if (str.empty()) return {}; std::string s = str; if ((s.length() > 1) && (s[0] == '$')) s = "0x" + s.substr(1); long ret; if ((s.length() > 2) && (s[0] == '0') && (toupper(s[1]) == 'B')) { ret = (long)parse_binary(s.c_str(), &end); } else { ret = strtol(s.c_str(), const_cast<char**>(&end), 0); } if ((end != (s.c_str() + s.length())) || (errno != 0)) return {}; if ((ret == 0) && !check_zero(str)) return {}; return ret; } std::optional<unsigned long> to_ulong(std::string const& str) { char const* end; errno = 0; std::string s = str; if ((s.length() > 1) && (s[0] == '$')) s = "0x" + s.substr(1); unsigned long ret; if ((s.length() > 2) && (s[0] == '0') && (toupper(s[1]) == 'B')) { ret = parse_binary(s.c_str(), &end); } else { ret = strtoul(s.c_str(), const_cast<char**>(&end), 0); } if ((ret == 0) && !check_zero(str)) return {}; return ret; } long to_long_unconditional(std::string const& str) { auto ret = to_long(str); assert(ret.has_value()); return ret.value(); } std::optional<double> to_double(std::string const& str) { char* end; errno = 0; auto ret = strtod(str.c_str(), &end); if ((end != (str.c_str() + str.length())) || (errno != 0)) return {}; if (ret == 0) { for (auto& ch : str) { if ((ch != '.') && (ch != '0')) return {}; } } return ret; } double to_double_unconditional(std::string const& str) { auto ret = to_double(str); assert(ret.has_value()); return ret.value(); } std::optional<bool> to_bool(std::string const& str) { if (str == "true" || str == "True" || str == "TRUE") return true; if (str == "false" || str == "False" || str == "FALSE") return true; auto ret = to_long(str); if (!ret.has_value()) return {}; return (ret.value() != 0); } bool to_bool_unconditional(std::string const& str) { auto ret = to_bool(str); assert(ret.has_value()); return ret.value(); } } <|endoftext|>
<commit_before>/* * This file is part of `et engine` * Copyright 2009-2014 by Sergey Reznik * Please, do not modify content without approval. * */ #include <et/core/et.h> #include <et/core/dictionary.h> using namespace et; void printDictionary(const Dictionary& dict, const std::string& tabs); void printArray(ArrayValue arr, const std::string& tabs); void Dictionary::printContent() const { log::info("<"); printDictionary(*this, "\t"); log::info(">"); } void ArrayValue::printContent() const { log::info("{"); printArray(*this, "\t"); log::info("}"); } ValueBase::Pointer Dictionary::baseValueForKeyPathInHolder(const std::vector<std::string>& path, ValueBase::Pointer holder) const { if (holder->valueClass() == ValueClass_Dictionary) { Dictionary dictionary(holder); auto value = dictionary->content.find(path.front()); if (value == dictionary->content.end()) return Dictionary(); return (path.size() == 1) ? value->second : baseValueForKeyPathInHolder( std::vector<std::string>(path.begin() + 1, path.end()), value->second); } else if (holder->valueClass() == ValueClass_Array) { size_t index = strToInt(path.front()); ArrayValue array(holder); if (index >= array->content.size()) return ArrayValue(); ValueBase::Pointer value = array->content.at(index); return (path.size() == 1) ? value : baseValueForKeyPathInHolder( std::vector<std::string>(path.begin() + 1, path.end()), value); } else if (holder->valueClass() == ValueClass_String) { StringValue string(holder); log::warning("Trying to extract subvalue `%s` from string `%s`", path.front().c_str(), string->content.c_str()); } else if (holder->valueClass() == ValueClass_Integer) { IntegerValue number(holder); log::warning("Trying to extract subvalue `%s` from number %lld.", path.front().c_str(), number->content); } else { ET_FAIL("Invalid value class."); } return ValueBase::Pointer(); } ValueBase::Pointer Dictionary::objectForKeyPath(const std::vector<std::string>& path) const { ET_ASSERT(path.size() > 0); return baseValueForKeyPathInHolder(path, *this); } ValueBase::Pointer Dictionary::objectForKey(const std::string& key) const { return hasKey(key) ? reference().content.at(key) : ValueBase::Pointer(); } bool Dictionary::valueForKeyPathIsClassOf(const std::vector<std::string>& key, ValueClass c) const { auto v = objectForKeyPath(key); return v.valid() && (v->valueClass() == c); } bool Dictionary::hasKey(const std::string& key) const { return reference().content.count(key) > 0; } ValueClass Dictionary::valueClassForKey(const std::string& key) const { return hasKey(key) ? objectForKeyPath(StringList(1, key))->valueClass() : ValueClass_Invalid; } StringList Dictionary::allKeyPaths() { StringList result; addKeyPathsFromHolder(*this, std::string(), result); return result; } void Dictionary::addKeyPathsFromHolder(ValueBase::Pointer holder, const std::string& baseKeyPath, StringList& keyPaths) const { std::string nextKeyPath = baseKeyPath.empty() ? std::string() : (baseKeyPath + "/"); if (holder->valueClass() == ValueClass_Dictionary) { Dictionary d(holder); for (auto& v : d->content) { std::string keyPath = nextKeyPath + v.first; keyPaths.push_back(keyPath); addKeyPathsFromHolder(v.second, keyPath, keyPaths); } } else if (holder->valueClass() == ValueClass_Array) { size_t index = 0; ArrayValue a(holder); for (auto& v : a->content) { std::string keyPath = nextKeyPath + intToStr(index++); keyPaths.push_back(keyPath); addKeyPathsFromHolder(v, keyPath, keyPaths); } } } /* * Service functions */ void printArray(ArrayValue arr, const std::string& tabs) { for (auto i : arr->content) { if (i->valueClass() == ValueClass_Integer) { IntegerValue val = i; log::info("%s%lld", tabs.c_str(), val->content); } if (i->valueClass() == ValueClass_Float) { FloatValue val = i; log::info("%s%f", tabs.c_str(), val->content); } else if (i->valueClass() == ValueClass_String) { StringValue val = i; log::info("%s\"%s\"", tabs.c_str(), val->content.c_str()); } else if (i->valueClass() == ValueClass_Array) { log::info("%s{", tabs.c_str()); printArray(i, tabs + "\t"); log::info("%s}", tabs.c_str()); } else if (i->valueClass() == ValueClass_Dictionary) { Dictionary val = i; log::info("%s<", tabs.c_str()); printDictionary(val, tabs + "\t"); log::info("%s>", tabs.c_str()); } } } void printDictionary(const Dictionary& dict, const std::string& tabs) { for (auto i : dict->content) { if (i.second->valueClass() == ValueClass_Integer) { IntegerValue val = i.second; log::info("%s%s = %lld", tabs.c_str(), i.first.c_str(), val->content); } else if (i.second->valueClass() == ValueClass_Float) { FloatValue val = i.second; log::info("%s%s = %f", tabs.c_str(), i.first.c_str(), val->content); } else if (i.second->valueClass() == ValueClass_String) { StringValue val = i.second; log::info("%s%s = \"%s\"", tabs.c_str(), i.first.c_str(), val->content.c_str()); } else if (i.second->valueClass() == ValueClass_Array) { ArrayValue val = i.second; log::info("%s%s =", tabs.c_str(), i.first.c_str()); log::info("%s{", tabs.c_str()); printArray(val, tabs + "\t"); log::info("%s}", tabs.c_str()); } else if (i.second->valueClass() == ValueClass_Dictionary) { Dictionary val = i.second; log::info("%s%s =", tabs.c_str(), i.first.c_str()); log::info("%s<", tabs.c_str()); printDictionary(val, tabs + "\t"); log::info("%s>", tabs.c_str()); } } } <commit_msg>fix for objectForKey in Dictionary. Now it returns Dicrionary() instead of invalid pointer in case of missing object for specifiied key<commit_after>/* * This file is part of `et engine` * Copyright 2009-2014 by Sergey Reznik * Please, do not modify content without approval. * */ #include <et/core/et.h> #include <et/core/dictionary.h> using namespace et; void printDictionary(const Dictionary& dict, const std::string& tabs); void printArray(ArrayValue arr, const std::string& tabs); void Dictionary::printContent() const { log::info("<"); printDictionary(*this, "\t"); log::info(">"); } void ArrayValue::printContent() const { log::info("{"); printArray(*this, "\t"); log::info("}"); } ValueBase::Pointer Dictionary::baseValueForKeyPathInHolder(const std::vector<std::string>& path, ValueBase::Pointer holder) const { if (holder->valueClass() == ValueClass_Dictionary) { Dictionary dictionary(holder); auto value = dictionary->content.find(path.front()); if (value == dictionary->content.end()) return Dictionary(); return (path.size() == 1) ? value->second : baseValueForKeyPathInHolder( std::vector<std::string>(path.begin() + 1, path.end()), value->second); } else if (holder->valueClass() == ValueClass_Array) { size_t index = strToInt(path.front()); ArrayValue array(holder); if (index >= array->content.size()) return ArrayValue(); ValueBase::Pointer value = array->content.at(index); return (path.size() == 1) ? value : baseValueForKeyPathInHolder( std::vector<std::string>(path.begin() + 1, path.end()), value); } else if (holder->valueClass() == ValueClass_String) { StringValue string(holder); log::warning("Trying to extract subvalue `%s` from string `%s`", path.front().c_str(), string->content.c_str()); } else if (holder->valueClass() == ValueClass_Integer) { IntegerValue number(holder); log::warning("Trying to extract subvalue `%s` from number %lld.", path.front().c_str(), number->content); } else { ET_FAIL("Invalid value class."); } return ValueBase::Pointer(); } ValueBase::Pointer Dictionary::objectForKeyPath(const std::vector<std::string>& path) const { ET_ASSERT(path.size() > 0); return baseValueForKeyPathInHolder(path, *this); } ValueBase::Pointer Dictionary::objectForKey(const std::string& key) const { if (hasKey(key)) return reference().content.at(key); return Dictionary(); } bool Dictionary::valueForKeyPathIsClassOf(const std::vector<std::string>& key, ValueClass c) const { auto v = objectForKeyPath(key); return v.valid() && (v->valueClass() == c); } bool Dictionary::hasKey(const std::string& key) const { return reference().content.count(key) > 0; } ValueClass Dictionary::valueClassForKey(const std::string& key) const { return hasKey(key) ? objectForKeyPath(StringList(1, key))->valueClass() : ValueClass_Invalid; } StringList Dictionary::allKeyPaths() { StringList result; addKeyPathsFromHolder(*this, std::string(), result); return result; } void Dictionary::addKeyPathsFromHolder(ValueBase::Pointer holder, const std::string& baseKeyPath, StringList& keyPaths) const { std::string nextKeyPath = baseKeyPath.empty() ? std::string() : (baseKeyPath + "/"); if (holder->valueClass() == ValueClass_Dictionary) { Dictionary d(holder); for (auto& v : d->content) { std::string keyPath = nextKeyPath + v.first; keyPaths.push_back(keyPath); addKeyPathsFromHolder(v.second, keyPath, keyPaths); } } else if (holder->valueClass() == ValueClass_Array) { size_t index = 0; ArrayValue a(holder); for (auto& v : a->content) { std::string keyPath = nextKeyPath + intToStr(index++); keyPaths.push_back(keyPath); addKeyPathsFromHolder(v, keyPath, keyPaths); } } } /* * Service functions */ void printArray(ArrayValue arr, const std::string& tabs) { for (auto i : arr->content) { if (i->valueClass() == ValueClass_Integer) { IntegerValue val = i; log::info("%s%lld", tabs.c_str(), val->content); } if (i->valueClass() == ValueClass_Float) { FloatValue val = i; log::info("%s%f", tabs.c_str(), val->content); } else if (i->valueClass() == ValueClass_String) { StringValue val = i; log::info("%s\"%s\"", tabs.c_str(), val->content.c_str()); } else if (i->valueClass() == ValueClass_Array) { log::info("%s{", tabs.c_str()); printArray(i, tabs + "\t"); log::info("%s}", tabs.c_str()); } else if (i->valueClass() == ValueClass_Dictionary) { Dictionary val = i; log::info("%s<", tabs.c_str()); printDictionary(val, tabs + "\t"); log::info("%s>", tabs.c_str()); } } } void printDictionary(const Dictionary& dict, const std::string& tabs) { for (auto i : dict->content) { if (i.second->valueClass() == ValueClass_Integer) { IntegerValue val = i.second; log::info("%s%s = %lld", tabs.c_str(), i.first.c_str(), val->content); } else if (i.second->valueClass() == ValueClass_Float) { FloatValue val = i.second; log::info("%s%s = %f", tabs.c_str(), i.first.c_str(), val->content); } else if (i.second->valueClass() == ValueClass_String) { StringValue val = i.second; log::info("%s%s = \"%s\"", tabs.c_str(), i.first.c_str(), val->content.c_str()); } else if (i.second->valueClass() == ValueClass_Array) { ArrayValue val = i.second; log::info("%s%s =", tabs.c_str(), i.first.c_str()); log::info("%s{", tabs.c_str()); printArray(val, tabs + "\t"); log::info("%s}", tabs.c_str()); } else if (i.second->valueClass() == ValueClass_Dictionary) { Dictionary val = i.second; log::info("%s%s =", tabs.c_str(), i.first.c_str()); log::info("%s<", tabs.c_str()); printDictionary(val, tabs + "\t"); log::info("%s>", tabs.c_str()); } } } <|endoftext|>
<commit_before>#pragma once #ifndef CUDA_API_WRAPPERS_MEMORY_HPP_ #define CUDA_API_WRAPPERS_MEMORY_HPP_ #include "cuda/api/error.hpp" #include "cuda_runtime.h" // needed, rather than cuda_runtime_api.h, e.g. for cudaMalloc #include <memory> #include <cstring> // for std::memset namespace cuda { namespace memory { namespace mapped { // This namespace regards memory appearing both on the device // and on the host, with the regions mapped to each other. // TODO: Perhaps make this an array of size 2 and use aspects to index it? // Or maybe inherit a pair? struct region_pair { struct allocation_options { bool portable_across_cuda_contexts; bool cpu_write_combining; }; void* host_side; void* device_side; // size_t size_in_bytes; // common to both sides // allocation_options properties; // operator std::pair<void*, void*>() { return make_pair(host_side, device_side); } // size_t size() { return size_in_bytes; } }; namespace detail { inline unsigned make_cuda_host_alloc_flags(region_pair::allocation_options options) { return cudaHostAllocMapped & (options.portable_across_cuda_contexts ? cudaHostAllocPortable : 0) & (options.cpu_write_combining ? cudaHostAllocWriteCombined: 0); } } // namespace detail } // namespace mapped } // namespace memory namespace memory { namespace device { namespace detail { template <typename T = void> T* malloc(size_t num_bytes) { T* allocated = nullptr; // Note: the typed cudaMalloc also takes its size in bytes, apparently, // not in number of elements auto status = cudaMalloc<T>(&allocated, num_bytes); if (is_success(status) && allocated == nullptr) { // Can this even happen? hopefully not status = cudaErrorUnknown; } throw_if_error(status, "Failed allocating " + std::to_string(num_bytes) + " bytes of global memory on CUDA device"); return allocated; } } // namespace detail inline void free(void* ptr) { auto result = cudaFree(ptr); throw_if_error(result, "Freeing device memory at 0x" + cuda::detail::ptr_as_hex(ptr)); } namespace detail { struct allocator { // Allocates on the current device! void* operator()(size_t num_bytes) const { return detail::malloc(num_bytes); } }; struct deleter { void operator()(void* ptr) const { cuda::memory::device::free(ptr); } }; } // namespace detail inline void set(void* buffer_start, int byte_value, size_t num_bytes) { auto result = cudaMemset(buffer_start, byte_value, num_bytes); throw_if_error(result, "memsetting an on-device buffer"); } inline void zero(void* buffer_start, size_t num_bytes) { return set(buffer_start, 0, num_bytes); } } // namespace device /** * Copies data between memory spaces or within a memory space. * * @note Since we assume Compute Capability >= 2.0, all devices support the * Unified Virtual Address Space, so the CUDA driver can determine, for each pointer, * where the data is located, and one does not have to specify this. * * @param dst A pointer to a num_bytes-long buffer, either in main memory or on any CUDA device's global memory * @param src A pointer to a num_bytes-long buffer, either in main memory or on any CUDA device's global memory * @param num_bytes The number of bytes to copy from @ref src to @ref dst */ inline void copy(void *destination, const void *source, size_t num_bytes) { auto result = cudaMemcpy(destination, source, num_bytes, cudaMemcpyDefault); if (is_failure(result)) { std::string error_message("Synchronously copying data"); // TODO: Determine whether it was from host to device, device to host etc and // add this information to the error string throw_if_error(result, error_message); } } template <typename T> inline void copy_single(T& destination, const T& source) { copy(&destination, &source, sizeof(T)); } namespace async { inline void copy(void *destination, const void *source, size_t num_bytes, stream::id_t stream_id = stream::default_stream_id) { auto result = cudaMemcpyAsync(destination, source, num_bytes, cudaMemcpyDefault, stream_id); if (is_failure(result)) { std::string error_message("Scheduling a memory copy on stream " + cuda::detail::ptr_as_hex(stream_id)); // TODO: Determine whether it was from host to device, device to host etc and // add this information to the error string throw_if_error(result, error_message); } } template <typename T> inline void copy_single(T& destination, const T& source, stream::id_t stream_id = stream::default_stream_id) { copy(&destination, &source, sizeof(T), stream_id); } inline void set(void* buffer_start, int byte_value, size_t num_bytes, stream::id_t stream_id = stream::default_stream_id) { auto result = cudaMemsetAsync(buffer_start, byte_value, num_bytes, stream_id); throw_if_error(result, "memsetting an on-device buffer"); } inline void zero(void* buffer_start, size_t num_bytes, stream::id_t stream_id = stream::default_stream_id) { return set(buffer_start, 0, num_bytes, stream_id); } } // namespace async namespace host { // TODO: Consider a variant of this supporting the cudaHostAlloc flags template <typename T> inline T* allocate(size_t size_in_bytes /* write me:, bool recognized_by_all_contexts */) { T* allocated = nullptr; // Note: the typed cudaMallocHost also takes its size in bytes, apparently, not in number of elements auto result = cudaMallocHost<T>(&allocated, size_in_bytes); if (is_success(result) && allocated == nullptr) { // Can this even happen? hopefully not result = cudaErrorUnknown; } throw_if_error(result, "Failed allocating " + std::to_string(size_in_bytes) + " bytes of host memory"); return allocated; } /** * Allocates 'pinned' host memory, for which the CUDA driver knows the TLB entries * (and which is faster for I/O transactions with the GPU) * * @param size_in_bytes number of bytes to allocate * @result host pointer to the allocated memory region; this must be freed with ::cuda::host::free() * rather than C++'s delete() . */ inline void* allocate(size_t size_in_bytes) { return (void*) allocate<char>(size_in_bytes); } inline void free(void* host_ptr) { auto result = cudaFreeHost(host_ptr); throw_if_error(result, "Freeing pinned host memory at 0x" + cuda::detail::ptr_as_hex(host_ptr)); } namespace detail { struct allocator { void* operator()(size_t num_bytes) const { return cuda::memory::host::allocate(num_bytes); } }; struct deleter { void operator()(void* ptr) const { cuda::memory::host::free(ptr); } }; inline void register_(void *ptr, size_t size, unsigned flags) { auto result = cudaHostRegister(ptr, size, flags); throw_if_error(result, "Could not register a region of page-locked host memory"); } } // namespace detail enum mapped_io_space : bool { is_mapped_io_space = true, is_not_mapped_io_space = false }; enum mapped_into_device_memory : bool { is_mapped_into_device_memory = true, is_not_mapped_into_device_memory = false }; enum accessibility_on_all_devices : bool { is_accessible_on_all_devices = true, is_not_accessible_on_all_devices = false }; // Can't use register(), since that's a reserved word inline void register_(void *ptr, size_t size, bool register_mapped_io_space, bool map_into_device_space, bool make_device_side_accesible_to_all) { return detail::register_( ptr, size, register_mapped_io_space ? cudaHostRegisterIoMemory : 0 | map_into_device_space ? cudaHostRegisterMapped : 0 | make_device_side_accesible_to_all ? cudaHostRegisterPortable : 0 ); } inline void register_(void *ptr, size_t size) { detail::register_(ptr, size, cudaHostRegisterDefault); } // the CUDA API calls this "unregister", but that's semantically // inaccurate. The registration is not undone, rolled back, it's // just ended inline void deregister(void *ptr) { auto result = cudaHostUnregister(ptr); throw_if_error(result, "Could not unregister the memory segment starting at address *a"); } inline void set(void* buffer_start, int byte_value, size_t num_bytes) { std::memset(buffer_start, byte_value, num_bytes); // TODO: Error handling? } inline void zero(void* buffer_start, size_t num_bytes) { return set(buffer_start, 0, num_bytes); // TODO: Error handling? } } // namespace host namespace managed { enum class initial_visibility_t { to_all_devices, to_supporters_of_concurrent_managed_access, }; namespace detail { template <typename T = void> T* malloc( size_t num_bytes, initial_visibility_t initial_visibility = initial_visibility_t::to_all_devices) { T* allocated = nullptr; auto flags = (initial_visibility == initial_visibility_t::to_all_devices) ? cudaMemAttachGlobal : cudaMemAttachHost; // Note: Despite the templating by T, the size is still in bytes, // not in number of T's auto status = cudaMallocManaged<T>(&allocated, num_bytes, flags); if (is_success(status) && allocated == nullptr) { // Can this even happen? hopefully not status = (status_t) cuda::error::unknown; } throw_if_error(status, "Failed allocating " + std::to_string(num_bytes) + " bytes of managed CUDA memory"); return allocated; } inline void free(void* ptr) { auto result = cudaFree(ptr); throw_if_error(result, "Freeing managed memory at 0x" + cuda::detail::ptr_as_hex(ptr)); } template <initial_visibility_t InitialVisibility = initial_visibility_t::to_all_devices> struct allocator { // Allocates on the current device! void* operator()(size_t num_bytes) const { return detail::malloc(num_bytes, InitialVisibility); } }; struct deleter { void operator()(void* ptr) const { cuda::memory::device::free(ptr); } }; } // namespace detail } // namespace managed namespace mapped { inline void free(region_pair pair) { auto result = cudaFreeHost(pair.host_side); throw_if_error(result, "Could not free the (supposed) region pair passed."); } inline void free_region_pair_of(void* ptr) { cudaPointerAttributes attributes; auto result = cudaPointerGetAttributes(&attributes, ptr); throw_if_error(result, "Could not obtain the properties for the pointer" ", being necessary for freeing the region pair it's (supposedly) " "associated with."); cudaFreeHost(attributes.hostPointer); } // Mostly for debugging purposes inline bool is_part_of_a_region_pair(void* ptr) { cudaPointerAttributes attributes; auto result = cudaPointerGetAttributes(&attributes, ptr); throw_if_error(result, "Could not obtain device pointer attributes"); #ifdef DEBUG auto self_copy = (attributes.memoryType == cudaMemoryTypeHost) ? attributes.hostPointer : attributes.devicePointer ; if (self_copy != ptr) { throw runtime_error(cudaErrorUnknown, "Inconsistent data obtained from the CUDA runtime API"); } #endif auto corresponding_buffer_ptr = (attributes.memoryType == cudaMemoryTypeHost) ? attributes.devicePointer : attributes.hostPointer; return (corresponding_buffer_ptr != nullptr); } } // namespace mapped } // namespace memory } // namespace cuda #endif /* CUDA_API_WRAPPERS_MEMORY_HPP_ */ <commit_msg>Changed my mind about previous commit, it's not a good idea.<commit_after>#pragma once #ifndef CUDA_API_WRAPPERS_MEMORY_HPP_ #define CUDA_API_WRAPPERS_MEMORY_HPP_ #include "cuda/api/error.hpp" #include "cuda_runtime.h" // needed, rather than cuda_runtime_api.h, e.g. for cudaMalloc #include <memory> #include <cstring> // for std::memset namespace cuda { namespace memory { namespace mapped { // This namespace regards memory appearing both on the device // and on the host, with the regions mapped to each other. // TODO: Perhaps make this an array of size 2 and use aspects to index it? // Or maybe inherit a pair? struct region_pair { struct allocation_options { bool portable_across_cuda_contexts; bool cpu_write_combining; }; void* host_side; void* device_side; // size_t size_in_bytes; // common to both sides // allocation_options properties; // operator std::pair<void*, void*>() { return make_pair(host_side, device_side); } // size_t size() { return size_in_bytes; } }; namespace detail { inline unsigned make_cuda_host_alloc_flags(region_pair::allocation_options options) { return cudaHostAllocMapped & (options.portable_across_cuda_contexts ? cudaHostAllocPortable : 0) & (options.cpu_write_combining ? cudaHostAllocWriteCombined: 0); } } // namespace detail } // namespace mapped } // namespace memory namespace memory { namespace device { namespace detail { template <typename T = void> T* malloc(size_t num_bytes) { T* allocated = nullptr; // Note: the typed cudaMalloc also takes its size in bytes, apparently, // not in number of elements auto status = cudaMalloc<T>(&allocated, num_bytes); if (is_success(status) && allocated == nullptr) { // Can this even happen? hopefully not status = cudaErrorUnknown; } throw_if_error(status, "Failed allocating " + std::to_string(num_bytes) + " bytes of global memory on CUDA device"); return allocated; } } // namespace detail inline void free(void* ptr) { auto result = cudaFree(ptr); throw_if_error(result, "Freeing device memory at 0x" + cuda::detail::ptr_as_hex(ptr)); } namespace detail { struct allocator { // Allocates on the current device! void* operator()(size_t num_bytes) const { return detail::malloc(num_bytes); } }; struct deleter { void operator()(void* ptr) const { cuda::memory::device::free(ptr); } }; } // namespace detail inline void set(void* buffer_start, int byte_value, size_t num_bytes) { auto result = cudaMemset(buffer_start, byte_value, num_bytes); throw_if_error(result, "memsetting an on-device buffer"); } inline void zero(void* buffer_start, size_t num_bytes) { return set(buffer_start, 0, num_bytes); } } // namespace device /** * Copies data between memory spaces or within a memory space. * * @note Since we assume Compute Capability >= 2.0, all devices support the * Unified Virtual Address Space, so the CUDA driver can determine, for each pointer, * where the data is located, and one does not have to specify this. * * @param dst A pointer to a num_bytes-long buffer, either in main memory or on any CUDA device's global memory * @param src A pointer to a num_bytes-long buffer, either in main memory or on any CUDA device's global memory * @param num_bytes The number of bytes to copy from @ref src to @ref dst */ inline void copy(void *destination, const void *source, size_t num_bytes) { auto result = cudaMemcpy(destination, source, num_bytes, cudaMemcpyDefault); if (is_failure(result)) { std::string error_message("Synchronously copying data"); // TODO: Determine whether it was from host to device, device to host etc and // add this information to the error string throw_if_error(result, error_message); } } template <typename T> inline void copy_single(T& destination, const T& source) { copy(&destination, &source, sizeof(T)); } namespace async { inline void copy(void *destination, const void *source, size_t num_bytes, stream::id_t stream_id) { auto result = cudaMemcpyAsync(destination, source, num_bytes, cudaMemcpyDefault, stream_id); if (is_failure(result)) { std::string error_message("Scheduling a memory copy on stream " + cuda::detail::ptr_as_hex(stream_id)); // TODO: Determine whether it was from host to device, device to host etc and // add this information to the error string throw_if_error(result, error_message); } } template <typename T> inline void copy_single(T& destination, const T& source, stream::id_t stream_id) { copy(&destination, &source, sizeof(T), stream_id); } inline void set(void* buffer_start, int byte_value, size_t num_bytes, stream::id_t stream_id) { auto result = cudaMemsetAsync(buffer_start, byte_value, num_bytes, stream_id); throw_if_error(result, "memsetting an on-device buffer"); } inline void zero(void* buffer_start, size_t num_bytes, stream::id_t stream_id = stream::default_stream_id) { return set(buffer_start, 0, num_bytes, stream_id); } } // namespace async namespace host { // TODO: Consider a variant of this supporting the cudaHostAlloc flags template <typename T> inline T* allocate(size_t size_in_bytes /* write me:, bool recognized_by_all_contexts */) { T* allocated = nullptr; // Note: the typed cudaMallocHost also takes its size in bytes, apparently, not in number of elements auto result = cudaMallocHost<T>(&allocated, size_in_bytes); if (is_success(result) && allocated == nullptr) { // Can this even happen? hopefully not result = cudaErrorUnknown; } throw_if_error(result, "Failed allocating " + std::to_string(size_in_bytes) + " bytes of host memory"); return allocated; } /** * Allocates 'pinned' host memory, for which the CUDA driver knows the TLB entries * (and which is faster for I/O transactions with the GPU) * * @param size_in_bytes number of bytes to allocate * @result host pointer to the allocated memory region; this must be freed with ::cuda::host::free() * rather than C++'s delete() . */ inline void* allocate(size_t size_in_bytes) { return (void*) allocate<char>(size_in_bytes); } inline void free(void* host_ptr) { auto result = cudaFreeHost(host_ptr); throw_if_error(result, "Freeing pinned host memory at 0x" + cuda::detail::ptr_as_hex(host_ptr)); } namespace detail { struct allocator { void* operator()(size_t num_bytes) const { return cuda::memory::host::allocate(num_bytes); } }; struct deleter { void operator()(void* ptr) const { cuda::memory::host::free(ptr); } }; inline void register_(void *ptr, size_t size, unsigned flags) { auto result = cudaHostRegister(ptr, size, flags); throw_if_error(result, "Could not register a region of page-locked host memory"); } } // namespace detail enum mapped_io_space : bool { is_mapped_io_space = true, is_not_mapped_io_space = false }; enum mapped_into_device_memory : bool { is_mapped_into_device_memory = true, is_not_mapped_into_device_memory = false }; enum accessibility_on_all_devices : bool { is_accessible_on_all_devices = true, is_not_accessible_on_all_devices = false }; // Can't use register(), since that's a reserved word inline void register_(void *ptr, size_t size, bool register_mapped_io_space, bool map_into_device_space, bool make_device_side_accesible_to_all) { return detail::register_( ptr, size, register_mapped_io_space ? cudaHostRegisterIoMemory : 0 | map_into_device_space ? cudaHostRegisterMapped : 0 | make_device_side_accesible_to_all ? cudaHostRegisterPortable : 0 ); } inline void register_(void *ptr, size_t size) { detail::register_(ptr, size, cudaHostRegisterDefault); } // the CUDA API calls this "unregister", but that's semantically // inaccurate. The registration is not undone, rolled back, it's // just ended inline void deregister(void *ptr) { auto result = cudaHostUnregister(ptr); throw_if_error(result, "Could not unregister the memory segment starting at address *a"); } inline void set(void* buffer_start, int byte_value, size_t num_bytes) { std::memset(buffer_start, byte_value, num_bytes); // TODO: Error handling? } inline void zero(void* buffer_start, size_t num_bytes) { return set(buffer_start, 0, num_bytes); // TODO: Error handling? } } // namespace host namespace managed { enum class initial_visibility_t { to_all_devices, to_supporters_of_concurrent_managed_access, }; namespace detail { template <typename T = void> T* malloc( size_t num_bytes, initial_visibility_t initial_visibility = initial_visibility_t::to_all_devices) { T* allocated = nullptr; auto flags = (initial_visibility == initial_visibility_t::to_all_devices) ? cudaMemAttachGlobal : cudaMemAttachHost; // Note: Despite the templating by T, the size is still in bytes, // not in number of T's auto status = cudaMallocManaged<T>(&allocated, num_bytes, flags); if (is_success(status) && allocated == nullptr) { // Can this even happen? hopefully not status = (status_t) cuda::error::unknown; } throw_if_error(status, "Failed allocating " + std::to_string(num_bytes) + " bytes of managed CUDA memory"); return allocated; } inline void free(void* ptr) { auto result = cudaFree(ptr); throw_if_error(result, "Freeing managed memory at 0x" + cuda::detail::ptr_as_hex(ptr)); } template <initial_visibility_t InitialVisibility = initial_visibility_t::to_all_devices> struct allocator { // Allocates on the current device! void* operator()(size_t num_bytes) const { return detail::malloc(num_bytes, InitialVisibility); } }; struct deleter { void operator()(void* ptr) const { cuda::memory::device::free(ptr); } }; } // namespace detail } // namespace managed namespace mapped { inline void free(region_pair pair) { auto result = cudaFreeHost(pair.host_side); throw_if_error(result, "Could not free the (supposed) region pair passed."); } inline void free_region_pair_of(void* ptr) { cudaPointerAttributes attributes; auto result = cudaPointerGetAttributes(&attributes, ptr); throw_if_error(result, "Could not obtain the properties for the pointer" ", being necessary for freeing the region pair it's (supposedly) " "associated with."); cudaFreeHost(attributes.hostPointer); } // Mostly for debugging purposes inline bool is_part_of_a_region_pair(void* ptr) { cudaPointerAttributes attributes; auto result = cudaPointerGetAttributes(&attributes, ptr); throw_if_error(result, "Could not obtain device pointer attributes"); #ifdef DEBUG auto self_copy = (attributes.memoryType == cudaMemoryTypeHost) ? attributes.hostPointer : attributes.devicePointer ; if (self_copy != ptr) { throw runtime_error(cudaErrorUnknown, "Inconsistent data obtained from the CUDA runtime API"); } #endif auto corresponding_buffer_ptr = (attributes.memoryType == cudaMemoryTypeHost) ? attributes.devicePointer : attributes.hostPointer; return (corresponding_buffer_ptr != nullptr); } } // namespace mapped } // namespace memory } // namespace cuda #endif /* CUDA_API_WRAPPERS_MEMORY_HPP_ */ <|endoftext|>
<commit_before>#include "string.h" namespace allpix { /** * @throws std::overflow_error If the converted unit overflows the requested type * * The unit type is internally converted to the type \ref Units::UnitType. After multiplying the unit, the output is * checked for overflow problems before the type is converted back to the original type. */ template <typename T> T Units::get(T inp, std::string str) { UnitType out = static_cast<UnitType>(inp) * get(std::move(str)); if(out > static_cast<UnitType>(std::numeric_limits<T>::max()) || out < static_cast<UnitType>(std::numeric_limits<T>::lowest())) { throw std::overflow_error("unit conversion overflows the type"); } return static_cast<T>(out); } // Getters for single and inverse units template <typename T> T Units::getSingle(T inp, std::string str) { UnitType out = static_cast<UnitType>(inp) * getSingle(std::move(str)); if(out > static_cast<UnitType>(std::numeric_limits<T>::max()) || out < static_cast<UnitType>(std::numeric_limits<T>::lowest())) { throw std::overflow_error("unit conversion overflows the type"); } return static_cast<T>(out); } template <typename T> T Units::getSingleInverse(T inp, std::string str) { UnitType out = static_cast<UnitType>(inp) / getSingle(std::move(str)); if(out > static_cast<UnitType>(std::numeric_limits<T>::max()) || out < static_cast<UnitType>(std::numeric_limits<T>::lowest())) { throw std::overflow_error("unit conversion overflows the type"); } return static_cast<T>(out); } template <typename T> T Units::getInverse(T inp, std::string str) { UnitType out = static_cast<UnitType>(inp) / get(std::move(str)); if(out > static_cast<UnitType>(std::numeric_limits<T>::max()) || out < static_cast<UnitType>(std::numeric_limits<T>::lowest())) { throw std::overflow_error("unit conversion overflows the type"); } return static_cast<T>(out); } // Display function for vectors template <typename T> std::string Units::display(T inp, std::initializer_list<std::string> units) { auto split = allpix::split<Units::UnitType>(allpix::to_string(inp)); std::string ret_str = "("; for(auto& element : split) { ret_str += Units::display(element, units); ret_str += ","; } ret_str[ret_str.size() - 1] = ')'; return ret_str; } } // namespace allpix <commit_msg>keep same behavior for non-vector units<commit_after>#include "string.h" namespace allpix { /** * @throws std::overflow_error If the converted unit overflows the requested type * * The unit type is internally converted to the type \ref Units::UnitType. After multiplying the unit, the output is * checked for overflow problems before the type is converted back to the original type. */ template <typename T> T Units::get(T inp, std::string str) { UnitType out = static_cast<UnitType>(inp) * get(std::move(str)); if(out > static_cast<UnitType>(std::numeric_limits<T>::max()) || out < static_cast<UnitType>(std::numeric_limits<T>::lowest())) { throw std::overflow_error("unit conversion overflows the type"); } return static_cast<T>(out); } // Getters for single and inverse units template <typename T> T Units::getSingle(T inp, std::string str) { UnitType out = static_cast<UnitType>(inp) * getSingle(std::move(str)); if(out > static_cast<UnitType>(std::numeric_limits<T>::max()) || out < static_cast<UnitType>(std::numeric_limits<T>::lowest())) { throw std::overflow_error("unit conversion overflows the type"); } return static_cast<T>(out); } template <typename T> T Units::getSingleInverse(T inp, std::string str) { UnitType out = static_cast<UnitType>(inp) / getSingle(std::move(str)); if(out > static_cast<UnitType>(std::numeric_limits<T>::max()) || out < static_cast<UnitType>(std::numeric_limits<T>::lowest())) { throw std::overflow_error("unit conversion overflows the type"); } return static_cast<T>(out); } template <typename T> T Units::getInverse(T inp, std::string str) { UnitType out = static_cast<UnitType>(inp) / get(std::move(str)); if(out > static_cast<UnitType>(std::numeric_limits<T>::max()) || out < static_cast<UnitType>(std::numeric_limits<T>::lowest())) { throw std::overflow_error("unit conversion overflows the type"); } return static_cast<T>(out); } // Display function for vectors template <typename T> std::string Units::display(T inp, std::initializer_list<std::string> units) { auto split = allpix::split<Units::UnitType>(allpix::to_string(inp)); std::string ret_str; if(split.size() > 1) { ret_str += "("; } for(auto& element : split) { ret_str += Units::display(element, units); ret_str += ","; } if(split.size() > 1) { ret_str[ret_str.size() - 1] = ')'; } else { ret_str.pop_back(); } return ret_str; } } // namespace allpix <|endoftext|>
<commit_before>/* * Fork a process and delegate open() to it. The subprocess returns * the file descriptor over a unix socket. * * author: Max Kellermann <mk@cm4all.com> */ #include "Client.hxx" #include "Handler.hxx" #include "Protocol.hxx" #include "please.hxx" #include "system/fd_util.h" #include "gerrno.h" #include "pool.hxx" #include "event/SocketEvent.hxx" #include "util/Cancellable.hxx" #include "util/Macros.hxx" #include <assert.h> #include <string.h> #include <sys/socket.h> struct DelegateClient final : Cancellable { struct lease_ref lease_ref; const int fd; SocketEvent event; struct pool &pool; DelegateHandler &handler; DelegateClient(EventLoop &event_loop, int _fd, Lease &lease, struct pool &_pool, DelegateHandler &_handler) :fd(_fd), event(event_loop, fd, SocketEvent::READ, BIND_THIS_METHOD(SocketEventCallback)), pool(_pool), handler(_handler) { p_lease_ref_set(lease_ref, lease, _pool, "delegate_client_lease"); event.Add(); } ~DelegateClient() { pool_unref(&pool); } void Destroy() { this->~DelegateClient(); } void ReleaseSocket(bool reuse) { assert(fd >= 0); p_lease_release(lease_ref, reuse, pool); } void DestroyError(GError *error) { ReleaseSocket(false); handler.OnDelegateError(error); Destroy(); } void HandleFd(const struct msghdr &msg, size_t length); void HandleErrno(size_t length); void HandleMsg(const struct msghdr &msg, DelegateResponseCommand command, size_t length); void TryRead(); private: void SocketEventCallback(unsigned) { TryRead(); } /* virtual methods from class Cancellable */ void Cancel() override { event.Delete(); ReleaseSocket(false); Destroy(); } }; gcc_const static inline GQuark delegate_client_quark(void) { return g_quark_from_static_string("delegate_client"); } inline void DelegateClient::HandleFd(const struct msghdr &msg, size_t length) { if (length != 0) { GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid message length"); DestroyError(error); return; } struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); if (cmsg == nullptr) { GError *error = g_error_new_literal(delegate_client_quark(), 0, "No fd passed"); DestroyError(error); return; } if (cmsg->cmsg_type != SCM_RIGHTS) { GError *error = g_error_new(delegate_client_quark(), 0, "got control message of unknown type %d", cmsg->cmsg_type); DestroyError(error); return; } ReleaseSocket(true); const void *data = CMSG_DATA(cmsg); const int *fd_p = (const int *)data; int new_fd = *fd_p; handler.OnDelegateSuccess(new_fd); Destroy(); } inline void DelegateClient::HandleErrno(size_t length) { int e; if (length != sizeof(e)) { GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid message length"); DestroyError(error); return; } ssize_t nbytes = recv(fd, &e, sizeof(e), 0); GError *error; if (nbytes == sizeof(e)) { ReleaseSocket(true); error = new_error_errno2(e); } else { ReleaseSocket(false); error = g_error_new_literal(delegate_client_quark(), 0, "Failed to receive errno"); } handler.OnDelegateError(error); Destroy(); } inline void DelegateClient::HandleMsg(const struct msghdr &msg, DelegateResponseCommand command, size_t length) { switch (command) { case DelegateResponseCommand::FD: HandleFd(msg, length); return; case DelegateResponseCommand::ERRNO: /* i/o error */ HandleErrno(length); return; } GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid delegate response"); DestroyError(error); } inline void DelegateClient::TryRead() { struct iovec iov; int new_fd; char ccmsg[CMSG_SPACE(sizeof(new_fd))]; struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = &iov, .msg_iovlen = 1, .msg_control = ccmsg, .msg_controllen = sizeof(ccmsg), }; DelegateResponseHeader header; ssize_t nbytes; iov.iov_base = &header; iov.iov_len = sizeof(header); nbytes = recvmsg_cloexec(fd, &msg, 0); if (nbytes < 0) { GError *error = new_error_errno_msg("recvmsg() failed"); DestroyError(error); return; } if ((size_t)nbytes != sizeof(header)) { GError *error = g_error_new_literal(delegate_client_quark(), 0, "short recvmsg()"); DestroyError(error); return; } HandleMsg(msg, header.command, header.length); } /* * constructor * */ static bool SendDelegatePacket(int fd, DelegateRequestCommand cmd, const void *payload, size_t length, GError **error_r) { const DelegateRequestHeader header = { .length = (uint16_t)length, .command = cmd, }; struct iovec v[] = { { const_cast<void *>((const void *)&header), sizeof(header) }, { const_cast<void *>(payload), length }, }; struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = v, .msg_iovlen = ARRAY_SIZE(v), .msg_control = nullptr, .msg_controllen = 0, .msg_flags = 0, }; auto nbytes = sendmsg(fd, &msg, MSG_DONTWAIT); if (nbytes < 0) { set_error_errno_msg(error_r, "Failed to send to delegate"); return false; } if (size_t(nbytes) != sizeof(header) + length) { g_set_error_literal(error_r, delegate_client_quark(), 0, "Short send to delegate"); return false; } return true; } void delegate_open(EventLoop &event_loop, int fd, Lease &lease, struct pool *pool, const char *path, DelegateHandler &handler, CancellablePointer &cancel_ptr) { GError *error = nullptr; if (!SendDelegatePacket(fd, DelegateRequestCommand::OPEN, path, strlen(path), &error)) { lease.ReleaseLease(false); handler.OnDelegateError(error); return; } auto d = NewFromPool<DelegateClient>(*pool, event_loop, fd, lease, *pool, handler); pool_ref(pool); cancel_ptr = *d; } <commit_msg>delegate/Client: add DestroyError() overload with "const char *"<commit_after>/* * Fork a process and delegate open() to it. The subprocess returns * the file descriptor over a unix socket. * * author: Max Kellermann <mk@cm4all.com> */ #include "Client.hxx" #include "Handler.hxx" #include "Protocol.hxx" #include "please.hxx" #include "system/fd_util.h" #include "gerrno.h" #include "pool.hxx" #include "event/SocketEvent.hxx" #include "util/Cancellable.hxx" #include "util/Macros.hxx" #include <assert.h> #include <string.h> #include <sys/socket.h> gcc_const static inline GQuark delegate_client_quark(void) { return g_quark_from_static_string("delegate_client"); } struct DelegateClient final : Cancellable { struct lease_ref lease_ref; const int fd; SocketEvent event; struct pool &pool; DelegateHandler &handler; DelegateClient(EventLoop &event_loop, int _fd, Lease &lease, struct pool &_pool, DelegateHandler &_handler) :fd(_fd), event(event_loop, fd, SocketEvent::READ, BIND_THIS_METHOD(SocketEventCallback)), pool(_pool), handler(_handler) { p_lease_ref_set(lease_ref, lease, _pool, "delegate_client_lease"); event.Add(); } ~DelegateClient() { pool_unref(&pool); } void Destroy() { this->~DelegateClient(); } void ReleaseSocket(bool reuse) { assert(fd >= 0); p_lease_release(lease_ref, reuse, pool); } void DestroyError(GError *error) { ReleaseSocket(false); handler.OnDelegateError(error); Destroy(); } void DestroyError(const char *msg) { DestroyError(g_error_new_literal(delegate_client_quark(), 0, msg)); } void HandleFd(const struct msghdr &msg, size_t length); void HandleErrno(size_t length); void HandleMsg(const struct msghdr &msg, DelegateResponseCommand command, size_t length); void TryRead(); private: void SocketEventCallback(unsigned) { TryRead(); } /* virtual methods from class Cancellable */ void Cancel() override { event.Delete(); ReleaseSocket(false); Destroy(); } }; inline void DelegateClient::HandleFd(const struct msghdr &msg, size_t length) { if (length != 0) { DestroyError("Invalid message length"); return; } struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); if (cmsg == nullptr) { DestroyError("No fd passed"); return; } if (cmsg->cmsg_type != SCM_RIGHTS) { DestroyError("got control message of unknown type"); return; } ReleaseSocket(true); const void *data = CMSG_DATA(cmsg); const int *fd_p = (const int *)data; int new_fd = *fd_p; handler.OnDelegateSuccess(new_fd); Destroy(); } inline void DelegateClient::HandleErrno(size_t length) { int e; if (length != sizeof(e)) { DestroyError("Invalid message length"); return; } ssize_t nbytes = recv(fd, &e, sizeof(e), 0); GError *error; if (nbytes == sizeof(e)) { ReleaseSocket(true); error = new_error_errno2(e); } else { ReleaseSocket(false); error = g_error_new_literal(delegate_client_quark(), 0, "Failed to receive errno"); } handler.OnDelegateError(error); Destroy(); } inline void DelegateClient::HandleMsg(const struct msghdr &msg, DelegateResponseCommand command, size_t length) { switch (command) { case DelegateResponseCommand::FD: HandleFd(msg, length); return; case DelegateResponseCommand::ERRNO: /* i/o error */ HandleErrno(length); return; } DestroyError("Invalid delegate response"); } inline void DelegateClient::TryRead() { struct iovec iov; int new_fd; char ccmsg[CMSG_SPACE(sizeof(new_fd))]; struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = &iov, .msg_iovlen = 1, .msg_control = ccmsg, .msg_controllen = sizeof(ccmsg), }; DelegateResponseHeader header; ssize_t nbytes; iov.iov_base = &header; iov.iov_len = sizeof(header); nbytes = recvmsg_cloexec(fd, &msg, 0); if (nbytes < 0) { GError *error = new_error_errno_msg("recvmsg() failed"); DestroyError(error); return; } if ((size_t)nbytes != sizeof(header)) { DestroyError("short recvmsg()"); return; } HandleMsg(msg, header.command, header.length); } /* * constructor * */ static bool SendDelegatePacket(int fd, DelegateRequestCommand cmd, const void *payload, size_t length, GError **error_r) { const DelegateRequestHeader header = { .length = (uint16_t)length, .command = cmd, }; struct iovec v[] = { { const_cast<void *>((const void *)&header), sizeof(header) }, { const_cast<void *>(payload), length }, }; struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = v, .msg_iovlen = ARRAY_SIZE(v), .msg_control = nullptr, .msg_controllen = 0, .msg_flags = 0, }; auto nbytes = sendmsg(fd, &msg, MSG_DONTWAIT); if (nbytes < 0) { set_error_errno_msg(error_r, "Failed to send to delegate"); return false; } if (size_t(nbytes) != sizeof(header) + length) { g_set_error_literal(error_r, delegate_client_quark(), 0, "Short send to delegate"); return false; } return true; } void delegate_open(EventLoop &event_loop, int fd, Lease &lease, struct pool *pool, const char *path, DelegateHandler &handler, CancellablePointer &cancel_ptr) { GError *error = nullptr; if (!SendDelegatePacket(fd, DelegateRequestCommand::OPEN, path, strlen(path), &error)) { lease.ReleaseLease(false); handler.OnDelegateError(error); return; } auto d = NewFromPool<DelegateClient>(*pool, event_loop, fd, lease, *pool, handler); pool_ref(pool); cancel_ptr = *d; } <|endoftext|>
<commit_before>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Fork a process and delegate open() to it. The subprocess returns * the file descriptor over a unix socket. */ #include "Protocol.hxx" #include "net/ScmRightsBuilder.hxx" #include "io/Iovec.hxx" #include "util/Compiler.h" #include <stdbool.h> #include <sys/socket.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/un.h> #include <unistd.h> static bool delegate_send(const void *data, size_t length) { ssize_t nbytes = send(0, data, length, 0); if (nbytes < 0) { fprintf(stderr, "send() on delegate socket failed: %s\n", strerror(errno)); return false; } if ((size_t)nbytes != length) { fprintf(stderr, "short send() on delegate socket\n"); return false; } return true; } static bool delegate_send_int(DelegateResponseCommand command, int value) { const DelegateIntPacket packet = { .header = { .length = sizeof(packet) - sizeof(packet.header), .command = command, }, .value = value, }; return delegate_send(&packet, sizeof(packet)); } static bool delegate_send_fd(DelegateResponseCommand command, int fd) { DelegateResponseHeader header = { .length = 0, .command = command, }; auto vec = MakeIovecT(header); struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = &vec, .msg_iovlen = 1, .msg_control = nullptr, .msg_controllen = 0, .msg_flags = 0, }; ScmRightsBuilder<1> srb(msg); srb.push_back(fd); srb.Finish(msg); if (sendmsg(0, &msg, 0) < 0) { fprintf(stderr, "failed to send fd: %s\n", strerror(errno)); return false; } return true; } static bool delegate_handle_open(const char *payload) { int fd = open(payload, O_RDONLY|O_CLOEXEC|O_NOCTTY); if (fd >= 0) { bool success = delegate_send_fd(DelegateResponseCommand::FD, fd); close(fd); return success; } else { /* error: send error code to client */ return delegate_send_int(DelegateResponseCommand::ERRNO, errno); } } static bool delegate_handle(DelegateRequestCommand command, const char *payload, size_t length) { (void)length; switch (command) { case DelegateRequestCommand::OPEN: return delegate_handle_open(payload); } fprintf(stderr, "unknown command: %d\n", int(command)); return false; } int main(int argc gcc_unused, char **argv gcc_unused) { while (true) { DelegateRequestHeader header; ssize_t nbytes = recv(0, &header, sizeof(header), 0); if (nbytes < 0) { fprintf(stderr, "recv() on delegate socket failed: %s\n", strerror(errno)); return 2; } if (nbytes == 0) break; if ((size_t)nbytes != sizeof(header)) { fprintf(stderr, "short recv() on delegate socket\n"); return 2; } char payload[4096]; if (header.length >= sizeof(payload)) { fprintf(stderr, "delegate payload too large\n"); return 2; } size_t length = 0; while (length < header.length) { nbytes = recv(0, payload + length, sizeof(payload) - 1 - length, 0); if (nbytes < 0) { fprintf(stderr, "recv() on delegate socket failed: %s\n", strerror(errno)); return 2; } if (nbytes == 0) break; length += (size_t)nbytes; } payload[length] = 0; if (!delegate_handle(header.command, payload, length)) return 2; } return 0; } <commit_msg>delegate/Helper: use MakeMsgHdr()<commit_after>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Fork a process and delegate open() to it. The subprocess returns * the file descriptor over a unix socket. */ #include "Protocol.hxx" #include "net/ScmRightsBuilder.hxx" #include "net/MsgHdr.hxx" #include "io/Iovec.hxx" #include "util/Compiler.h" #include <stdbool.h> #include <sys/socket.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/un.h> #include <unistd.h> static bool delegate_send(const void *data, size_t length) { ssize_t nbytes = send(0, data, length, 0); if (nbytes < 0) { fprintf(stderr, "send() on delegate socket failed: %s\n", strerror(errno)); return false; } if ((size_t)nbytes != length) { fprintf(stderr, "short send() on delegate socket\n"); return false; } return true; } static bool delegate_send_int(DelegateResponseCommand command, int value) { const DelegateIntPacket packet = { .header = { .length = sizeof(packet) - sizeof(packet.header), .command = command, }, .value = value, }; return delegate_send(&packet, sizeof(packet)); } static bool delegate_send_fd(DelegateResponseCommand command, int fd) { DelegateResponseHeader header = { .length = 0, .command = command, }; auto vec = MakeIovecT(header); auto msg = MakeMsgHdr({&vec, 1}); ScmRightsBuilder<1> srb(msg); srb.push_back(fd); srb.Finish(msg); if (sendmsg(0, &msg, 0) < 0) { fprintf(stderr, "failed to send fd: %s\n", strerror(errno)); return false; } return true; } static bool delegate_handle_open(const char *payload) { int fd = open(payload, O_RDONLY|O_CLOEXEC|O_NOCTTY); if (fd >= 0) { bool success = delegate_send_fd(DelegateResponseCommand::FD, fd); close(fd); return success; } else { /* error: send error code to client */ return delegate_send_int(DelegateResponseCommand::ERRNO, errno); } } static bool delegate_handle(DelegateRequestCommand command, const char *payload, size_t length) { (void)length; switch (command) { case DelegateRequestCommand::OPEN: return delegate_handle_open(payload); } fprintf(stderr, "unknown command: %d\n", int(command)); return false; } int main(int argc gcc_unused, char **argv gcc_unused) { while (true) { DelegateRequestHeader header; ssize_t nbytes = recv(0, &header, sizeof(header), 0); if (nbytes < 0) { fprintf(stderr, "recv() on delegate socket failed: %s\n", strerror(errno)); return 2; } if (nbytes == 0) break; if ((size_t)nbytes != sizeof(header)) { fprintf(stderr, "short recv() on delegate socket\n"); return 2; } char payload[4096]; if (header.length >= sizeof(payload)) { fprintf(stderr, "delegate payload too large\n"); return 2; } size_t length = 0; while (length < header.length) { nbytes = recv(0, payload + length, sizeof(payload) - 1 - length, 0); if (nbytes < 0) { fprintf(stderr, "recv() on delegate socket failed: %s\n", strerror(errno)); return 2; } if (nbytes == 0) break; length += (size_t)nbytes; } payload[length] = 0; if (!delegate_handle(header.command, payload, length)) return 2; } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2002-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * XSEC * * DSIGObject := Defines the container class used by dsig to hold objects * inside a signture * * $Id$ * */ // XSEC Includes #include <xsec/framework/XSECDefs.hpp> #include <xsec/framework/XSECEnv.hpp> #include <xsec/framework/XSECError.hpp> #include <xsec/dsig/DSIGConstants.hpp> #include <xsec/dsig/DSIGObject.hpp> #include <xsec/utils/XSECDOMUtils.hpp> #include <xercesc/dom/DOM.hpp> #include <xercesc/util/XMLUniDefs.hpp> XERCES_CPP_NAMESPACE_USE // -------------------------------------------------------------------------------- // String Constants // -------------------------------------------------------------------------------- static XMLCh s_Object[] = { chLatin_O, chLatin_b, chLatin_j, chLatin_e, chLatin_c, chLatin_t, chNull }; static XMLCh s_Id[] = { chLatin_I, chLatin_d, chNull }; static XMLCh s_MimeType[] = { chLatin_M, chLatin_i, chLatin_m, chLatin_e, chLatin_T, chLatin_y, chLatin_p, chLatin_e, chNull }; static XMLCh s_Encoding[] = { chLatin_E, chLatin_n, chLatin_c, chLatin_o, chLatin_d, chLatin_i, chLatin_n, chLatin_g, chNull }; // -------------------------------------------------------------------------------- // Constructors/Destructor // -------------------------------------------------------------------------------- DSIGObject::DSIGObject(const XSECEnv * env, XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *dom) { mp_env = env; mp_objectNode = dom; mp_idAttr = NULL; mp_mimeTypeAttr = NULL; mp_encodingAttr = NULL; } DSIGObject::DSIGObject(const XSECEnv * env) { mp_env = env; mp_objectNode = NULL; mp_idAttr = NULL; mp_mimeTypeAttr = NULL; mp_encodingAttr = NULL; } DSIGObject::~DSIGObject() {} // -------------------------------------------------------------------------------- // Library only // -------------------------------------------------------------------------------- void DSIGObject::load(void) { if (mp_objectNode == NULL || mp_objectNode->getNodeType() != DOMNode::ELEMENT_NODE || !strEquals(getDSIGLocalName(mp_objectNode), s_Object)) { throw XSECException(XSECException::ObjectError, "Expected <Object> Node in DSIGObject::load"); } mp_idAttr = ((DOMElement *) mp_objectNode)->getAttributeNodeNS(NULL, s_Id); mp_mimeTypeAttr = ((DOMElement *) mp_objectNode)->getAttributeNodeNS(NULL, s_MimeType); mp_encodingAttr = ((DOMElement *) mp_objectNode)->getAttributeNodeNS(NULL, s_Encoding); } DOMElement * DSIGObject::createBlankObject(void) { safeBuffer str; const XMLCh * prefix; DOMDocument *doc = mp_env->getParentDocument(); prefix = mp_env->getDSIGNSPrefix(); // Create the transform node makeQName(str, prefix, s_Object); mp_objectNode = doc->createElementNS(DSIGConstants::s_unicodeStrURIDSIG, str.rawXMLChBuffer()); mp_idAttr = NULL; mp_mimeTypeAttr = NULL; mp_encodingAttr = NULL; return (DOMElement *) mp_objectNode; } // -------------------------------------------------------------------------------- // Get functions // -------------------------------------------------------------------------------- const XMLCh * DSIGObject::getId(void) { if (mp_idAttr != NULL) return mp_idAttr->getNodeValue(); return NULL; } const XMLCh * DSIGObject::getMimeType(void) { if (mp_mimeTypeAttr != NULL) return mp_mimeTypeAttr->getNodeValue(); return NULL; } const XMLCh * DSIGObject::getEncoding(void) { if (mp_encodingAttr != NULL) return mp_encodingAttr->getNodeValue(); return NULL; } const DOMElement * DSIGObject::getElement(void) { return (DOMElement *) mp_objectNode; } // -------------------------------------------------------------------------------- // Set Functions // -------------------------------------------------------------------------------- void DSIGObject::setId(const XMLCh * id) { if (mp_idAttr != NULL) { mp_idAttr->setNodeValue(id); } else { ((DOMElement *) mp_objectNode)->setAttributeNS(NULL, s_Id, id); // Mark as an ID #if defined (XSEC_XERCES_HAS_SETIDATTRIBUTE) ((DOMElement *) mp_objectNode)->setIdAttributeNS(NULL, s_Id); #else # if defined (XSEC_XERCES_HAS_BOOLSETIDATTRIBUTE) ((DOMElement *) mp_objectNode)->setIdAttributeNS(NULL, s_Id, true); # endif #endif mp_idAttr = ((DOMElement *) mp_objectNode)->getAttributeNodeNS(NULL, s_Id); } } void DSIGObject::setMimeType(const XMLCh * type) { if (mp_mimeTypeAttr != NULL) { mp_mimeTypeAttr->setNodeValue(type); } else { ((DOMElement *) mp_objectNode)->setAttributeNS(NULL, s_MimeType, type); mp_mimeTypeAttr = ((DOMElement *) mp_objectNode)->getAttributeNodeNS(NULL, s_MimeType); } } void DSIGObject::setEncoding(const XMLCh * encoding) { if (mp_encodingAttr != NULL) { mp_encodingAttr->setNodeValue(encoding); } else { ((DOMElement *) mp_objectNode)->setAttributeNS(NULL, s_Encoding, encoding); mp_encodingAttr = ((DOMElement *) mp_objectNode)->getAttributeNodeNS(NULL, s_Encoding); } } void DSIGObject::appendChild(DOMNode * child) { if (mp_objectNode == NULL) { throw XSECException(XSECException::ObjectError, "DSIGObject::appendChild - Object node has not been created"); } mp_objectNode->appendChild(child); } <commit_msg>Guarantee IDness when loading Object elements.<commit_after>/* * Copyright 2002-2010 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * XSEC * * DSIGObject := Defines the container class used by dsig to hold objects * inside a signture * * $Id$ * */ // XSEC Includes #include <xsec/framework/XSECDefs.hpp> #include <xsec/framework/XSECEnv.hpp> #include <xsec/framework/XSECError.hpp> #include <xsec/dsig/DSIGConstants.hpp> #include <xsec/dsig/DSIGObject.hpp> #include <xsec/utils/XSECDOMUtils.hpp> #include <xercesc/dom/DOM.hpp> #include <xercesc/util/XMLUniDefs.hpp> XERCES_CPP_NAMESPACE_USE // -------------------------------------------------------------------------------- // String Constants // -------------------------------------------------------------------------------- static XMLCh s_Object[] = { chLatin_O, chLatin_b, chLatin_j, chLatin_e, chLatin_c, chLatin_t, chNull }; static XMLCh s_Id[] = { chLatin_I, chLatin_d, chNull }; static XMLCh s_MimeType[] = { chLatin_M, chLatin_i, chLatin_m, chLatin_e, chLatin_T, chLatin_y, chLatin_p, chLatin_e, chNull }; static XMLCh s_Encoding[] = { chLatin_E, chLatin_n, chLatin_c, chLatin_o, chLatin_d, chLatin_i, chLatin_n, chLatin_g, chNull }; // -------------------------------------------------------------------------------- // Constructors/Destructor // -------------------------------------------------------------------------------- DSIGObject::DSIGObject(const XSECEnv * env, XERCES_CPP_NAMESPACE_QUALIFIER DOMNode *dom) { mp_env = env; mp_objectNode = dom; mp_idAttr = NULL; mp_mimeTypeAttr = NULL; mp_encodingAttr = NULL; } DSIGObject::DSIGObject(const XSECEnv * env) { mp_env = env; mp_objectNode = NULL; mp_idAttr = NULL; mp_mimeTypeAttr = NULL; mp_encodingAttr = NULL; } DSIGObject::~DSIGObject() {} // -------------------------------------------------------------------------------- // Library only // -------------------------------------------------------------------------------- void DSIGObject::load(void) { if (mp_objectNode == NULL || mp_objectNode->getNodeType() != DOMNode::ELEMENT_NODE || !strEquals(getDSIGLocalName(mp_objectNode), s_Object)) { throw XSECException(XSECException::ObjectError, "Expected <Object> Node in DSIGObject::load"); } mp_idAttr = ((DOMElement *) mp_objectNode)->getAttributeNodeNS(NULL, s_Id); #if defined (XSEC_XERCES_HAS_SETIDATTRIBUTE) ((DOMElement *) mp_objectNode)->setIdAttributeNS(NULL, s_Id); #else # if defined (XSEC_XERCES_HAS_BOOLSETIDATTRIBUTE) ((DOMElement *) mp_objectNode)->setIdAttributeNS(NULL, s_Id, true); # endif #endif mp_mimeTypeAttr = ((DOMElement *) mp_objectNode)->getAttributeNodeNS(NULL, s_MimeType); mp_encodingAttr = ((DOMElement *) mp_objectNode)->getAttributeNodeNS(NULL, s_Encoding); } DOMElement * DSIGObject::createBlankObject(void) { safeBuffer str; const XMLCh * prefix; DOMDocument *doc = mp_env->getParentDocument(); prefix = mp_env->getDSIGNSPrefix(); // Create the transform node makeQName(str, prefix, s_Object); mp_objectNode = doc->createElementNS(DSIGConstants::s_unicodeStrURIDSIG, str.rawXMLChBuffer()); mp_idAttr = NULL; mp_mimeTypeAttr = NULL; mp_encodingAttr = NULL; return (DOMElement *) mp_objectNode; } // -------------------------------------------------------------------------------- // Get functions // -------------------------------------------------------------------------------- const XMLCh * DSIGObject::getId(void) { if (mp_idAttr != NULL) return mp_idAttr->getNodeValue(); return NULL; } const XMLCh * DSIGObject::getMimeType(void) { if (mp_mimeTypeAttr != NULL) return mp_mimeTypeAttr->getNodeValue(); return NULL; } const XMLCh * DSIGObject::getEncoding(void) { if (mp_encodingAttr != NULL) return mp_encodingAttr->getNodeValue(); return NULL; } const DOMElement * DSIGObject::getElement(void) { return (DOMElement *) mp_objectNode; } // -------------------------------------------------------------------------------- // Set Functions // -------------------------------------------------------------------------------- void DSIGObject::setId(const XMLCh * id) { if (mp_idAttr != NULL) { mp_idAttr->setNodeValue(id); } else { ((DOMElement *) mp_objectNode)->setAttributeNS(NULL, s_Id, id); // Mark as an ID #if defined (XSEC_XERCES_HAS_SETIDATTRIBUTE) ((DOMElement *) mp_objectNode)->setIdAttributeNS(NULL, s_Id); #else # if defined (XSEC_XERCES_HAS_BOOLSETIDATTRIBUTE) ((DOMElement *) mp_objectNode)->setIdAttributeNS(NULL, s_Id, true); # endif #endif mp_idAttr = ((DOMElement *) mp_objectNode)->getAttributeNodeNS(NULL, s_Id); } } void DSIGObject::setMimeType(const XMLCh * type) { if (mp_mimeTypeAttr != NULL) { mp_mimeTypeAttr->setNodeValue(type); } else { ((DOMElement *) mp_objectNode)->setAttributeNS(NULL, s_MimeType, type); mp_mimeTypeAttr = ((DOMElement *) mp_objectNode)->getAttributeNodeNS(NULL, s_MimeType); } } void DSIGObject::setEncoding(const XMLCh * encoding) { if (mp_encodingAttr != NULL) { mp_encodingAttr->setNodeValue(encoding); } else { ((DOMElement *) mp_objectNode)->setAttributeNS(NULL, s_Encoding, encoding); mp_encodingAttr = ((DOMElement *) mp_objectNode)->getAttributeNodeNS(NULL, s_Encoding); } } void DSIGObject::appendChild(DOMNode * child) { if (mp_objectNode == NULL) { throw XSECException(XSECException::ObjectError, "DSIGObject::appendChild - Object node has not been created"); } mp_objectNode->appendChild(child); } <|endoftext|>
<commit_before>/** * @author Cyrille Collette - ccollette@aldebaran-robotics.com * Aldebaran Robotics (c) 2009 All Rights Reserved * */ //#include <almath/types/alquaternion.h> #include <almath/tools/altransformhelpers.h> #include <almath/tools/altrigonometry.h> #include <almath/tools/almathio.h> #include <cmath> #include <gtest/gtest.h> #include <stdexcept> TEST(ALQuaternionTest, creation) { AL::Math::Transform pT1 = AL::Math::Transform(); AL::Math::Transform pT2 = AL::Math::Transform(); AL::Math::Transform pT3 = AL::Math::Transform(); AL::Math::Quaternion pQua1 = AL::Math::Quaternion(); AL::Math::Quaternion pQua2 = AL::Math::Quaternion(); AL::Math::Quaternion pQua3 = AL::Math::Quaternion(); // create Quaternion() pQua1 = AL::Math::Quaternion(); EXPECT_TRUE(pQua1.w == 1.0f); EXPECT_TRUE(pQua1.x == 0.0f); EXPECT_TRUE(pQua1.y == 0.0f); EXPECT_TRUE(pQua1.z == 0.0f); // create Quaternion(w, x, y, z) pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_TRUE(pQua1.w == 0.1f); EXPECT_TRUE(pQua1.x == 0.2f); EXPECT_TRUE(pQua1.y == 0.3f); EXPECT_TRUE(pQua1.z == 0.4f); // create Quaternion(const std::vector<float>& pFloats) std::vector<float> listQuaternion; listQuaternion.push_back(0.1f); listQuaternion.push_back(0.2f); listQuaternion.push_back(0.3f); listQuaternion.push_back(0.4f); pQua1 = AL::Math::Quaternion(listQuaternion); EXPECT_TRUE(pQua1.w == 0.1f); EXPECT_TRUE(pQua1.x == 0.2f); EXPECT_TRUE(pQua1.y == 0.3f); EXPECT_TRUE(pQua1.z == 0.4f); // operator == with Quaternion pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_TRUE((pQua1==pQua2)); // operator != with Quaternion pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.11f, 0.2f, 0.3f, 0.4f); EXPECT_TRUE((pQua1!=pQua2)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.21f, 0.3f, 0.4f); EXPECT_TRUE((pQua1!=pQua2)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.31f, 0.4f); EXPECT_TRUE((pQua1!=pQua2)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.41f); EXPECT_TRUE((pQua1!=pQua2)); // operator *= with float pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua1 *= 2.0f; pQua2 = AL::Math::Quaternion(0.2f, 0.4f, 0.6f, 0.8f); EXPECT_TRUE((pQua1==pQua2)); // operator /= with float pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.2f, 0.4f, 0.6f, 0.8f); pQua2 /= 2.0f; EXPECT_TRUE((pQua1==pQua2)); // isNear pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.2f, 0.4f, 0.6f, 0.8f); EXPECT_FALSE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(-0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_FALSE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(0.1f, -0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_FALSE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, -0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_FALSE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, -0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_FALSE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_TRUE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(-0.1f, -0.2f, -0.3f, -0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_TRUE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(-0.1f, -0.2f, -0.3f, -0.4f); EXPECT_TRUE(pQua1.isNear(pQua2, 0.0001f)); // norm pQua1 = AL::Math::Quaternion(1.0f, 2.0f, 3.0f, 4.0f); float normQua = pQua1.norm(); EXPECT_NEAR(normQua, sqrtf(30), 0.0001f); // normalize pQua1 = AL::Math::Quaternion(0.0f, 0.0f, 0.0f, 0.0f); ASSERT_THROW(AL::Math::normalize(pQua1), std::runtime_error); // inverse // fromAngleAndAxisRotation // toVector // function quaternionFromAngleAndAxisRotation // function norm // function normalize // function quaternionInverse // function angleAndAxisRotationFromQuaternion // pT1 // pT2 // pQua1 // pQua2 // pQua3 // operator *= with Quaternion // operator * with Quaternion unsigned int nbX = 10; unsigned int nbY = 10; unsigned int nbZ = 10; for (unsigned int i=0; i<nbX; i++) { for (unsigned int j=0; j<nbY; j++) { for (unsigned int k=0; k<nbZ; k++) { float angleX = ((float)i)/(float(nbX))*AL::Math::_2_PI_; float angleY = ((float)j)/(float(nbY))*AL::Math::_2_PI_; float angleZ = ((float)k)/(float(nbZ))*AL::Math::_2_PI_; pT1 = AL::Math::Transform::fromRotX(angleX)* AL::Math::Transform::fromRotY(angleY)* AL::Math::Transform::fromRotZ(angleZ); pT2 = AL::Math::Transform::fromRotZ(angleY)* AL::Math::Transform::fromRotX(-angleZ)* AL::Math::Transform::fromRotY(-angleX); pT3 = pT1*pT2; pQua1 = AL::Math::quaternionFromTransform(pT1); pQua2 = AL::Math::quaternionFromTransform(pT2); pQua3 = pQua1*pQua2; EXPECT_TRUE(pQua3.isNear(AL::Math::quaternionFromTransform(pT3), 0.0001f)); // if (!pQua3.isNear(AL::Math::quaternionFromTransform(pT3), 0.0001f)) // { // std::cout << pQua3.isNear(AL::Math::quaternionFromTransform(pT3)) << " " // << angleX*AL::Math::TO_DEG << " " // << angleY*AL::Math::TO_DEG << " " // << angleZ*AL::Math::TO_DEG << std::endl; // std::cout << "pQua3" << std::endl << pQua3 << std::endl; // std::cout << "AL::Math::quaternionFromTransform(pT3)" << std::endl // << AL::Math::quaternionFromTransform(pT3) << std::endl; // std::cout << std::endl; // } // if (!pTIn.isNear(pTOut, 0.0001f)) // { // std::cout << "[angleX, angleY, angleZ, i, j, k]: " // << angleX << " " << angleY << " " << angleZ // << i << " " << j << " " << k << std::endl; // } } } } } TEST(ALQuaternionTest, normalize) { AL::Math::Quaternion pQuaD1 = AL::Math::Quaternion(); } <commit_msg>ALMATH: add quaternion test<commit_after>/** * @author Cyrille Collette - ccollette@aldebaran-robotics.com * Aldebaran Robotics (c) 2009 All Rights Reserved * */ //#include <almath/types/alquaternion.h> #include <almath/tools/altransformhelpers.h> #include <almath/tools/altrigonometry.h> #include <almath/tools/almathio.h> #include <cmath> #include <gtest/gtest.h> #include <stdexcept> TEST(ALQuaternionTest, creation) { AL::Math::Transform pT1 = AL::Math::Transform(); AL::Math::Transform pT2 = AL::Math::Transform(); AL::Math::Transform pT3 = AL::Math::Transform(); AL::Math::Quaternion pQua1 = AL::Math::Quaternion(); AL::Math::Quaternion pQua2 = AL::Math::Quaternion(); AL::Math::Quaternion pQua3 = AL::Math::Quaternion(); // create Quaternion() pQua1 = AL::Math::Quaternion(); EXPECT_TRUE(pQua1.w == 1.0f); EXPECT_TRUE(pQua1.x == 0.0f); EXPECT_TRUE(pQua1.y == 0.0f); EXPECT_TRUE(pQua1.z == 0.0f); // create Quaternion(w, x, y, z) pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_TRUE(pQua1.w == 0.1f); EXPECT_TRUE(pQua1.x == 0.2f); EXPECT_TRUE(pQua1.y == 0.3f); EXPECT_TRUE(pQua1.z == 0.4f); // create Quaternion(const std::vector<float>& pFloats) std::vector<float> listQuaternion; listQuaternion.push_back(0.1f); listQuaternion.push_back(0.2f); listQuaternion.push_back(0.3f); listQuaternion.push_back(0.4f); pQua1 = AL::Math::Quaternion(listQuaternion); EXPECT_TRUE(pQua1.w == 0.1f); EXPECT_TRUE(pQua1.x == 0.2f); EXPECT_TRUE(pQua1.y == 0.3f); EXPECT_TRUE(pQua1.z == 0.4f); // operator == with Quaternion pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_TRUE((pQua1==pQua2)); // operator != with Quaternion pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.11f, 0.2f, 0.3f, 0.4f); EXPECT_TRUE((pQua1!=pQua2)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.21f, 0.3f, 0.4f); EXPECT_TRUE((pQua1!=pQua2)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.31f, 0.4f); EXPECT_TRUE((pQua1!=pQua2)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.41f); EXPECT_TRUE((pQua1!=pQua2)); // operator *= with float pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua1 *= 2.0f; pQua2 = AL::Math::Quaternion(0.2f, 0.4f, 0.6f, 0.8f); EXPECT_TRUE((pQua1==pQua2)); // operator /= with float pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.2f, 0.4f, 0.6f, 0.8f); pQua2 /= 2.0f; EXPECT_TRUE((pQua1==pQua2)); // isNear pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.2f, 0.4f, 0.6f, 0.8f); EXPECT_FALSE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(-0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_FALSE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(0.1f, -0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_FALSE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, -0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_FALSE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, -0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_FALSE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_TRUE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(-0.1f, -0.2f, -0.3f, -0.4f); pQua2 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); EXPECT_TRUE(pQua1.isNear(pQua2, 0.0001f)); pQua1 = AL::Math::Quaternion(0.1f, 0.2f, 0.3f, 0.4f); pQua2 = AL::Math::Quaternion(-0.1f, -0.2f, -0.3f, -0.4f); EXPECT_TRUE(pQua1.isNear(pQua2, 0.0001f)); // norm // function norm pQua1 = AL::Math::Quaternion(1.0f, 2.0f, 3.0f, 4.0f); float normQua = pQua1.norm(); EXPECT_NEAR(normQua, sqrtf(30), 0.0001f); // normalize // function normalize pQua1 = AL::Math::Quaternion(0.0f, 0.0f, 0.0f, 0.0f); ASSERT_THROW(AL::Math::normalize(pQua1), std::runtime_error); // toVector pQua1 = AL::Math::Quaternion(1.0f, 2.0f, 3.0f, 4.0f); std::vector<float> pQua1Vect = pQua1.toVector(); EXPECT_NEAR(pQua1Vect.at(0), 1.0f, 0.0001f); EXPECT_NEAR(pQua1Vect.at(1), 2.0f, 0.0001f); EXPECT_NEAR(pQua1Vect.at(2), 3.0f, 0.0001f); EXPECT_NEAR(pQua1Vect.at(3), 4.0f, 0.0001f); // function angleAndAxisRotationFromQuaternion float pAngle = 0.0f; float pAxeX = 0.0f; float pAxeY = 0.0f; float pAxeZ = 0.0f; // TODO: fix // float angleDes = 10.0f*AL::Math::TO_RAD; // pQua1 = AL::Math::quaternionFromTransform(AL::Math::Transform::fromRotX(angleDes)); // AL::Math::angleAndAxisRotationFromQuaternion(pQua1, pAngle, pAxeX, pAxeY, pAxeZ); // EXPECT_NEAR(pAngle, angleDes, 0.0001f); // EXPECT_NEAR(pAxeX, 1.0f, 0.0001f); // EXPECT_NEAR(pAxeY, 0.0f, 0.0001f); // EXPECT_NEAR(pAxeZ, 0.0f, 0.0001f); unsigned int nbX = 10; unsigned int nbY = 10; unsigned int nbZ = 10; // fromAngleAndAxisRotation // function quaternionFromAngleAndAxisRotation for (unsigned int i=0; i<nbX; i++) { float angle = ((float)i)/(float(nbX))*AL::Math::_2_PI_; pQua1 = AL::Math::Quaternion::fromAngleAndAxisRotation(angle, 1.0f, 0.0f, 0.0f); pT1 = AL::Math::Transform::fromRotX(angle); EXPECT_TRUE(pQua1.isNear(AL::Math::quaternionFromTransform(pT1), 0.0001f)); pQua1 = AL::Math::Quaternion::fromAngleAndAxisRotation(angle, 0.0f, 1.0f, 0.0f); pT1 = AL::Math::Transform::fromRotY(angle); EXPECT_TRUE(pQua1.isNear(AL::Math::quaternionFromTransform(pT1), 0.0001f)); pQua1 = AL::Math::Quaternion::fromAngleAndAxisRotation(angle, 0.0f, 0.0f, 1.0f); pT1 = AL::Math::Transform::fromRotZ(angle); EXPECT_TRUE(pQua1.isNear(AL::Math::quaternionFromTransform(pT1), 0.0001f)); } for (unsigned int i=0; i<nbX; i++) { for (unsigned int j=0; j<nbY; j++) { for (unsigned int k=0; k<nbZ; k++) { float angleX = ((float)i)/(float(nbX))*AL::Math::_2_PI_; float angleY = ((float)j)/(float(nbY))*AL::Math::_2_PI_; float angleZ = ((float)k)/(float(nbZ))*AL::Math::_2_PI_; pT1 = AL::Math::Transform::fromRotX(angleX)* AL::Math::Transform::fromRotY(angleY)* AL::Math::Transform::fromRotZ(angleZ); pT2 = AL::Math::Transform::fromRotZ(angleY)* AL::Math::Transform::fromRotX(-angleZ)* AL::Math::Transform::fromRotY(-angleX); pT3 = pT1*pT2; pQua1 = AL::Math::quaternionFromTransform(pT1); pQua2 = AL::Math::quaternionFromTransform(pT2); pQua3 = pQua1*pQua2; // operator *= with Quaternion // operator * with Quaternion EXPECT_TRUE(pQua3.isNear(AL::Math::quaternionFromTransform(pT3), 0.0001f)); pT1 = AL::Math::Transform::fromRotX(angleX)* AL::Math::Transform::fromRotY(angleY)* AL::Math::Transform::fromRotZ(angleZ); pQua1 = AL::Math::quaternionFromTransform(pT1); pQua2 = pQua1.inverse(); // inverse // function quaternionInverse EXPECT_TRUE(pQua2.isNear(AL::Math::quaternionFromTransform(pT1.inverse()), 0.0001f)); // if (!pQua3.isNear(AL::Math::quaternionFromTransform(pT3), 0.0001f)) // { // std::cout << pQua3.isNear(AL::Math::quaternionFromTransform(pT3)) << " " // << angleX*AL::Math::TO_DEG << " " // << angleY*AL::Math::TO_DEG << " " // << angleZ*AL::Math::TO_DEG << std::endl; // std::cout << "pQua3" << std::endl << pQua3 << std::endl; // std::cout << "AL::Math::quaternionFromTransform(pT3)" << std::endl // << AL::Math::quaternionFromTransform(pT3) << std::endl; // std::cout << std::endl; // } // if (!pTIn.isNear(pTOut, 0.0001f)) // { // std::cout << "[angleX, angleY, angleZ, i, j, k]: " // << angleX << " " << angleY << " " << angleZ // << i << " " << j << " " << k << std::endl; // } } } } } TEST(ALQuaternionTest, normalize) { AL::Math::Quaternion pQuaD1 = AL::Math::Quaternion(); } <|endoftext|>
<commit_before>#ifndef EE_X_WHEN_ALL_HPP #define EE_X_WHEN_ALL_HPP #ifdef __cplusplus #include <vector> #include "ee/core/LambdaAwaiter.hpp" #include "ee/core/NoAwait.hpp" #include "ee/core/Task.hpp" namespace ee { namespace core { namespace detail { template <class T> Task<> toVoidTask(T&& task) { co_await task; co_return; } } // namespace detail template <class... Args> Task<> whenAll(Args&&... args) { std::vector<Task<>> tasks = { detail::toVoidTask(std::forward<Args>(args))...}; auto counter = std::make_shared<std::size_t>(tasks.size()); co_await LambdaAwaiter<>([&tasks, counter](auto&& resolve) { // for (auto&& task : tasks) { noAwait([&task, counter, resolve]() -> Task<> { co_await task; --(*counter); if (*counter == 0) { resolve(); } }); } }); co_return; } } // namespace core } // namespace ee #endif // __cplusplus #endif // EE_X_WHEN_ALL_HPP <commit_msg>Alias ee::core::whenAll to ee::whenAll.<commit_after>#ifndef EE_X_WHEN_ALL_HPP #define EE_X_WHEN_ALL_HPP #ifdef __cplusplus #include <vector> #include "ee/core/LambdaAwaiter.hpp" #include "ee/core/NoAwait.hpp" #include "ee/core/Task.hpp" namespace ee { namespace core { namespace detail { template <class T> Task<> toVoidTask(T&& task) { co_await task; co_return; } } // namespace detail template <class... Args> Task<> whenAll(Args&&... args) { std::vector<Task<>> tasks = { detail::toVoidTask(std::forward<Args>(args))...}; auto counter = std::make_shared<std::size_t>(tasks.size()); co_await LambdaAwaiter<>([&tasks, counter](auto&& resolve) { // for (auto&& task : tasks) { noAwait([&task, counter, resolve]() -> Task<> { co_await task; --(*counter); if (*counter == 0) { resolve(); } }); } }); co_return; } } // namespace core using core::whenAll; } // namespace ee #endif // __cplusplus #endif // EE_X_WHEN_ALL_HPP <|endoftext|>
<commit_before>#ifdef DE #include"global.h" #include"grid3D.h" #include<stdio.h> #include<stdlib.h> #include"math.h" #include <iostream> #ifdef PARALLEL_OMP #include"parallel_omp.h" #endif #ifdef MPI_CHOLLA #include"mpi_routines.h" #endif int Grid3D::Select_Internal_Energy_From_DE( Real E, Real U_total, Real U_advected ){ Real eta = DE_LIMIT; if( U_total / E > eta ) return 0; else return 1; } void Grid3D::Sync_Energies_3D_CPU(){ #ifndef PARALLEL_OMP Sync_Energies_3D_CPU_function( 0, H.nz_real ); #ifdef TEMPERATURE_FLOOR Apply_Temperature_Floor_CPU_function( 0, H.nz_real ); #endif #else #pragma omp parallel num_threads( N_OMP_THREADS ) { int omp_id, n_omp_procs; int g_start, g_end; omp_id = omp_get_thread_num(); n_omp_procs = omp_get_num_threads(); Get_OMP_Grid_Indxs( H.nz_real, n_omp_procs, omp_id, &g_start, &g_end ); Sync_Energies_3D_CPU_function( g_start, g_end ); #ifdef TEMPERATURE_FLOOR #pragma omp barrier Apply_Temperature_Floor_CPU_function( g_start, g_end ); #endif } #endif } void Grid3D::Sync_Energies_3D_CPU_function( int g_start, int g_end ){ int nx_grid, ny_grid, nz_grid, nGHST_grid; nGHST_grid = H.n_ghost; nx_grid = H.nx; ny_grid = H.ny; nz_grid = H.nz; int nx, ny, nz; nx = H.nx_real; ny = H.ny_real; nz = H.nz_real; int nGHST = nGHST_grid ; Real d, d_inv, vx, vy, vz, E, Ek, ge_total, ge_advected, Emax; int k, j, i, id; int k_g, j_g, i_g; Real eta = DE_LIMIT; int imo, ipo, jmo, jpo, kmo, kpo; for ( k_g=g_start; k_g<g_end; k_g++ ){ for ( j_g=0; j_g<ny; j_g++ ){ for ( i_g=0; i_g<nx; i_g++ ){ i = i_g + nGHST; j = j_g + nGHST; k = k_g + nGHST; id = (i) + (j)*nx_grid + (k)*ny_grid*nx_grid; imo = (i-1) + (j)*nx_grid + (k)*ny_grid*nx_grid; ipo = (i+1) + (j)*nx_grid + (k)*ny_grid*nx_grid; jmo = (i) + (j-1)*nx_grid + (k)*ny_grid*nx_grid; jpo = (i) + (j+1)*nx_grid + (k)*ny_grid*nx_grid; kmo = (i) + (j)*nx_grid + (k-1)*ny_grid*nx_grid; kpo = (i) + (j)*nx_grid + (k+1)*ny_grid*nx_grid; d = C.density[id]; d_inv = 1/d; vx = C.momentum_x[id] * d_inv; vy = C.momentum_y[id] * d_inv; vz = C.momentum_z[id] * d_inv; E = C.Energy[id]; // if (E < 0.0 || E != E) continue; // BUG: This leads to negative Energy Ek = 0.5*d*(vx*vx + vy*vy + vz*vz); ge_total = E - Ek; ge_advected = C.GasEnergy[id]; //Dont Change Internal energies based on first condition, //This condition is used only to compute pressure and Intenal energy for cooling step // #ifdef LIMIT_DE_EKINETIC // if (ge2 > 0.0 && E > 0.0 && ge2/E > eta && Ek/H.Ekin_avrg > 0.4 ){ // #else // if (ge2 > 0.0 && E > 0.0 && ge2/E > eta ) { // #endif // C.GasEnergy[id] = ge2; // ge1 = ge2; // } //Syncronize advected internal energy with total internal energy when using total internal energy for dynamical purposes if (ge_total > 0.0 && E > 0.0 && ge_total/E > eta ) C.GasEnergy[id] = ge_total; //Syncronize advected internal energy with total internal energy when using total internal energy based on local maxEnergy condition //find the max nearby total energy Emax = E; Emax = std::max(C.Energy[imo], E); Emax = std::max(Emax, C.Energy[ipo]); Emax = std::max(Emax, C.Energy[jmo]); Emax = std::max(Emax, C.Energy[jpo]); Emax = std::max(Emax, C.Energy[kmo]); Emax = std::max(Emax, C.Energy[kpo]); if (ge_total/Emax > 0.1 && ge_total > 0.0 && Emax > 0.0) { C.GasEnergy[id] = ge_total; } //Dont Change total energy // // sync the total energy with the internal energy // else { // if (ge1 > 0.0) C.Energy[id] += ge1 - ge2; // else C.GasEnergy[id] = ge2; // } } } } } #ifdef TEMPERATURE_FLOOR void Grid3D::Apply_Temperature_Floor_CPU_function( int g_start, int g_end ){ Real U_floor = H.temperature_floor / (gama - 1) / MP * KB * 1e-10; #ifdef COSMOLOGY U_floor /= Cosmo.v_0_gas * Cosmo.v_0_gas / Cosmo.current_a / Cosmo.current_a; #endif int nx_grid, ny_grid, nz_grid, nGHST_grid; nGHST_grid = H.n_ghost; nx_grid = H.nx; ny_grid = H.ny; nz_grid = H.nz; int nx, ny, nz; nx = H.nx_real; ny = H.ny_real; nz = H.nz_real; int nGHST = nGHST_grid ; Real d, vx, vy, vz, Ekin, E, U, GE; int k, j, i, id; for ( k=g_start; k<g_end; k++ ){ for ( j=0; j<ny; j++ ){ for ( i=0; i<nx; i++ ){ id = (i+nGHST) + (j+nGHST)*nx_grid + (k+nGHST)*ny_grid*nx_grid; d = C.density[id]; vx = C.momentum_x[id] / d; vy = C.momentum_y[id] / d; vz = C.momentum_z[id] / d; Ekin = 0.5 * d * (vx*vx + vy*vy + vz*vz); E = C.Energy[id]; U = ( E - Ekin ) / d; if ( U < U_floor ) C.Energy[id] = Ekin + d*U_floor; #ifdef DE GE = C.GasEnergy[id]; U = GE / d; if ( U < U_floor ) C.GasEnergy[id] = d*U_floor; #endif } } } } #endif //TEMPERATURE_FLOOR Real Grid3D::Get_Average_Kinetic_Energy_function( int g_start, int g_end ){ int nx_grid, ny_grid, nz_grid, nGHST; nGHST = H.n_ghost; nx_grid = H.nx; ny_grid = H.ny; nz_grid = H.nz; int nx, ny, nz; nx = H.nx_real; ny = H.ny_real; nz = H.nz_real; Real Ek_sum = 0; Real d, d_inv, vx, vy, vz, E, Ek; int k, j, i, id; for ( k=g_start; k<g_end; k++ ){ for ( j=0; j<ny; j++ ){ for ( i=0; i<nx; i++ ){ id = (i+nGHST) + (j+nGHST)*nx_grid + (k+nGHST)*ny_grid*nx_grid; d = C.density[id]; d_inv = 1/d; vx = C.momentum_x[id] * d_inv; vy = C.momentum_y[id] * d_inv; vz = C.momentum_z[id] * d_inv; E = C.Energy[id]; Ek = 0.5*d*(vx*vx + vy*vy + vz*vz); Ek_sum += Ek; } } } return Ek_sum; } void Grid3D::Get_Average_Kinetic_Energy(){ Real Ek_sum; #ifndef PARALLEL_OMP Ek_sum = Get_Average_Kinetic_Energy_function( 0, H.nz_real ); #else Ek_sum = 0; Real Ek_sum_all[N_OMP_THREADS]; #pragma omp parallel num_threads( N_OMP_THREADS ) { int omp_id, n_omp_procs; int g_start, g_end; omp_id = omp_get_thread_num(); n_omp_procs = omp_get_num_threads(); Get_OMP_Grid_Indxs( H.nz_real, n_omp_procs, omp_id, &g_start, &g_end ); Ek_sum_all[omp_id] = Get_Average_Kinetic_Energy_function( g_start, g_end ); } for ( int i=0; i<N_OMP_THREADS; i++ ){ Ek_sum += Ek_sum_all[i]; } #endif #ifdef MPI_CHOLLA Ek_sum /= ( H.nx_real * H.ny_real * H.nz_real); H.Ekin_avrg = ReduceRealAvg(Ek_sum); #else H.Ekin_avrg = Ek_sum / ( H.nx_real * H.ny_real * H.nz_real); #endif } #endif<commit_msg>the advected internal energy is not syncronized to the total internal enrgy at all<commit_after>#ifdef DE #include"global.h" #include"grid3D.h" #include<stdio.h> #include<stdlib.h> #include"math.h" #include <iostream> #ifdef PARALLEL_OMP #include"parallel_omp.h" #endif #ifdef MPI_CHOLLA #include"mpi_routines.h" #endif int Grid3D::Select_Internal_Energy_From_DE( Real E, Real U_total, Real U_advected ){ Real eta = DE_LIMIT; if( U_total / E > eta ) return 0; else return 1; } void Grid3D::Sync_Energies_3D_CPU(){ #ifndef PARALLEL_OMP Sync_Energies_3D_CPU_function( 0, H.nz_real ); #ifdef TEMPERATURE_FLOOR Apply_Temperature_Floor_CPU_function( 0, H.nz_real ); #endif #else #pragma omp parallel num_threads( N_OMP_THREADS ) { int omp_id, n_omp_procs; int g_start, g_end; omp_id = omp_get_thread_num(); n_omp_procs = omp_get_num_threads(); Get_OMP_Grid_Indxs( H.nz_real, n_omp_procs, omp_id, &g_start, &g_end ); Sync_Energies_3D_CPU_function( g_start, g_end ); #ifdef TEMPERATURE_FLOOR #pragma omp barrier Apply_Temperature_Floor_CPU_function( g_start, g_end ); #endif } #endif } void Grid3D::Sync_Energies_3D_CPU_function( int g_start, int g_end ){ int nx_grid, ny_grid, nz_grid, nGHST_grid; nGHST_grid = H.n_ghost; nx_grid = H.nx; ny_grid = H.ny; nz_grid = H.nz; int nx, ny, nz; nx = H.nx_real; ny = H.ny_real; nz = H.nz_real; int nGHST = nGHST_grid ; Real d, d_inv, vx, vy, vz, E, Ek, ge_total, ge_advected, Emax; int k, j, i, id; int k_g, j_g, i_g; Real eta = DE_LIMIT; int imo, ipo, jmo, jpo, kmo, kpo; for ( k_g=g_start; k_g<g_end; k_g++ ){ for ( j_g=0; j_g<ny; j_g++ ){ for ( i_g=0; i_g<nx; i_g++ ){ i = i_g + nGHST; j = j_g + nGHST; k = k_g + nGHST; id = (i) + (j)*nx_grid + (k)*ny_grid*nx_grid; imo = (i-1) + (j)*nx_grid + (k)*ny_grid*nx_grid; ipo = (i+1) + (j)*nx_grid + (k)*ny_grid*nx_grid; jmo = (i) + (j-1)*nx_grid + (k)*ny_grid*nx_grid; jpo = (i) + (j+1)*nx_grid + (k)*ny_grid*nx_grid; kmo = (i) + (j)*nx_grid + (k-1)*ny_grid*nx_grid; kpo = (i) + (j)*nx_grid + (k+1)*ny_grid*nx_grid; d = C.density[id]; d_inv = 1/d; vx = C.momentum_x[id] * d_inv; vy = C.momentum_y[id] * d_inv; vz = C.momentum_z[id] * d_inv; E = C.Energy[id]; // if (E < 0.0 || E != E) continue; // BUG: This leads to negative Energy Ek = 0.5*d*(vx*vx + vy*vy + vz*vz); ge_total = E - Ek; ge_advected = C.GasEnergy[id]; //Dont Change Internal energies based on first condition, //This condition is used only to compute pressure and Intenal energy for cooling step // #ifdef LIMIT_DE_EKINETIC // if (ge2 > 0.0 && E > 0.0 && ge2/E > eta && Ek/H.Ekin_avrg > 0.4 ){ // #else // if (ge2 > 0.0 && E > 0.0 && ge2/E > eta ) { // #endif // C.GasEnergy[id] = ge2; // ge1 = ge2; // } // //Syncronize advected internal energy with total internal energy when using total internal energy for dynamical purposes // if (ge_total > 0.0 && E > 0.0 && ge_total/E > eta ) C.GasEnergy[id] = ge_total; // // //Syncronize advected internal energy with total internal energy when using total internal energy based on local maxEnergy condition // //find the max nearby total energy // Emax = E; // Emax = std::max(C.Energy[imo], E); // Emax = std::max(Emax, C.Energy[ipo]); // Emax = std::max(Emax, C.Energy[jmo]); // Emax = std::max(Emax, C.Energy[jpo]); // Emax = std::max(Emax, C.Energy[kmo]); // Emax = std::max(Emax, C.Energy[kpo]); // if (ge_total/Emax > 0.1 && ge_total > 0.0 && Emax > 0.0) { // C.GasEnergy[id] = ge_total; // } //Dont Change total energy // // sync the total energy with the internal energy // else { // if (ge1 > 0.0) C.Energy[id] += ge1 - ge2; // else C.GasEnergy[id] = ge2; // } } } } } #ifdef TEMPERATURE_FLOOR void Grid3D::Apply_Temperature_Floor_CPU_function( int g_start, int g_end ){ Real U_floor = H.temperature_floor / (gama - 1) / MP * KB * 1e-10; #ifdef COSMOLOGY U_floor /= Cosmo.v_0_gas * Cosmo.v_0_gas / Cosmo.current_a / Cosmo.current_a; #endif int nx_grid, ny_grid, nz_grid, nGHST_grid; nGHST_grid = H.n_ghost; nx_grid = H.nx; ny_grid = H.ny; nz_grid = H.nz; int nx, ny, nz; nx = H.nx_real; ny = H.ny_real; nz = H.nz_real; int nGHST = nGHST_grid ; Real d, vx, vy, vz, Ekin, E, U, GE; int k, j, i, id; for ( k=g_start; k<g_end; k++ ){ for ( j=0; j<ny; j++ ){ for ( i=0; i<nx; i++ ){ id = (i+nGHST) + (j+nGHST)*nx_grid + (k+nGHST)*ny_grid*nx_grid; d = C.density[id]; vx = C.momentum_x[id] / d; vy = C.momentum_y[id] / d; vz = C.momentum_z[id] / d; Ekin = 0.5 * d * (vx*vx + vy*vy + vz*vz); E = C.Energy[id]; U = ( E - Ekin ) / d; if ( U < U_floor ) C.Energy[id] = Ekin + d*U_floor; #ifdef DE GE = C.GasEnergy[id]; U = GE / d; if ( U < U_floor ) C.GasEnergy[id] = d*U_floor; #endif } } } } #endif //TEMPERATURE_FLOOR Real Grid3D::Get_Average_Kinetic_Energy_function( int g_start, int g_end ){ int nx_grid, ny_grid, nz_grid, nGHST; nGHST = H.n_ghost; nx_grid = H.nx; ny_grid = H.ny; nz_grid = H.nz; int nx, ny, nz; nx = H.nx_real; ny = H.ny_real; nz = H.nz_real; Real Ek_sum = 0; Real d, d_inv, vx, vy, vz, E, Ek; int k, j, i, id; for ( k=g_start; k<g_end; k++ ){ for ( j=0; j<ny; j++ ){ for ( i=0; i<nx; i++ ){ id = (i+nGHST) + (j+nGHST)*nx_grid + (k+nGHST)*ny_grid*nx_grid; d = C.density[id]; d_inv = 1/d; vx = C.momentum_x[id] * d_inv; vy = C.momentum_y[id] * d_inv; vz = C.momentum_z[id] * d_inv; E = C.Energy[id]; Ek = 0.5*d*(vx*vx + vy*vy + vz*vz); Ek_sum += Ek; } } } return Ek_sum; } void Grid3D::Get_Average_Kinetic_Energy(){ Real Ek_sum; #ifndef PARALLEL_OMP Ek_sum = Get_Average_Kinetic_Energy_function( 0, H.nz_real ); #else Ek_sum = 0; Real Ek_sum_all[N_OMP_THREADS]; #pragma omp parallel num_threads( N_OMP_THREADS ) { int omp_id, n_omp_procs; int g_start, g_end; omp_id = omp_get_thread_num(); n_omp_procs = omp_get_num_threads(); Get_OMP_Grid_Indxs( H.nz_real, n_omp_procs, omp_id, &g_start, &g_end ); Ek_sum_all[omp_id] = Get_Average_Kinetic_Energy_function( g_start, g_end ); } for ( int i=0; i<N_OMP_THREADS; i++ ){ Ek_sum += Ek_sum_all[i]; } #endif #ifdef MPI_CHOLLA Ek_sum /= ( H.nx_real * H.ny_real * H.nz_real); H.Ekin_avrg = ReduceRealAvg(Ek_sum); #else H.Ekin_avrg = Ek_sum / ( H.nx_real * H.ny_real * H.nz_real); #endif } #endif<|endoftext|>
<commit_before>#include "metadata.h" #include "engine/fs/os_file.h" #include <cstdio> namespace Lumix { static const char* METADATA_FILENAME = "metadata.bin"; static const u32 METADATA_MAGIC = 0x4D455441; // 'META' enum class MetadataVersion : i32 { FIRST, LATEST }; Metadata::Metadata(IAllocator& allocator) : m_allocator(allocator) , m_data(allocator) { } bool Metadata::load() { FS::OsFile file; if (!file.open(METADATA_FILENAME, FS::Mode::OPEN_AND_READ)) return false; m_data.clear(); int count; u32 magic; file.read(&magic, sizeof(magic)); if (magic != METADATA_MAGIC) { file.close(); return false; } i32 version; file.read(&version, sizeof(version)); if (version > (int)MetadataVersion::LATEST) { file.close(); return false; } file.read(&count, sizeof(count)); for (int i = 0; i < count; ++i) { u32 key; file.read(&key, sizeof(key)); auto& file_data = m_data.emplace(key, m_allocator); int inner_count; file.read(&inner_count, sizeof(inner_count)); for (int j = 0; j < inner_count; ++j) { file.read(&key, sizeof(key)); DataItem& value = file_data.insert(key); file.read(&value.m_type, sizeof(value.m_type)); switch (value.m_type) { case DataItem::INT: file.read(&value.m_int, sizeof(value.m_int)); break; case DataItem::STRING: { int len; file.read(&len, sizeof(len)); file.read(value.m_string, len); } break; case DataItem::RAW_MEMORY: { int len; file.read(&len, sizeof(len)); value.m_raw.memory = m_allocator.allocate(len); file.read(value.m_raw.memory, len); } break; default: ASSERT(false); break; } } } file.close(); return true; } bool Metadata::save() { FS::OsFile file; if (!file.open(METADATA_FILENAME, FS::Mode::CREATE_AND_WRITE)) return false; file.write(&METADATA_MAGIC, sizeof(METADATA_MAGIC)); i32 version = (int)MetadataVersion::LATEST; file.write(&version, sizeof(version)); int count = m_data.size(); file.write(&count, sizeof(count)); for (int i = 0; i < m_data.size(); ++i) { auto key = m_data.getKey(i); file.write(&key, sizeof(key)); auto& file_data = m_data.at(i); count = file_data.size(); file.write(&count, sizeof(count)); for (int j = 0; j < file_data.size(); ++j) { key = file_data.getKey(j); file.write(&key, sizeof(key)); auto& value = file_data.at(j); file.write(&value.m_type, sizeof(value.m_type)); switch (value.m_type) { case DataItem::INT: file.write(&value.m_int, sizeof(value.m_int)); break; case DataItem::STRING: { int len = stringLength(value.m_string); file.write(&len, sizeof(len)); file.write(value.m_string, len); } break; case DataItem::RAW_MEMORY: { int len = (int)value.m_raw.size; file.write(&len, sizeof(len)); file.write(value.m_raw.memory, len); } break; default: ASSERT(false); break; } } } file.close(); return true; } Metadata::~Metadata() { for (int i = 0; i < m_data.size(); ++i) { auto& x = m_data.at(i); for (int j = 0; j < x.size(); ++j) { auto& data = x.at(j); if (data.m_type == DataItem::RAW_MEMORY) { m_allocator.deallocate(data.m_raw.memory); } } } } Metadata::DataItem* Metadata::getOrCreateData(u32 file, u32 key) { int index = m_data.find(file); if (index < 0) { index = m_data.insert(file, AssociativeArray<u32, DataItem>(m_allocator)); } auto& file_data = m_data.at(index); index = file_data.find(key); if (index >= 0) return &file_data.at(index); return &file_data.insert(key); } const Metadata::DataItem* Metadata::getData(u32 file, u32 key) const { int index = m_data.find(file); if (index < 0) return nullptr; auto& file_data = m_data.at(index); index = file_data.find(key); if (index < 0) return nullptr; return &file_data.at(index); } const void* Metadata::getRawMemory(u32 file, u32 key) const { const auto* data = getData(file, key); if (!data || data->m_type != DataItem::RAW_MEMORY) return nullptr; return data->m_raw.memory; } size_t Metadata::getRawMemorySize(u32 file, u32 key) const { const auto* data = getData(file, key); if (!data || data->m_type != DataItem::RAW_MEMORY) return 0; return data->m_raw.size; } bool Metadata::setRawMemory(u32 file, u32 key, const void* mem, size_t size) { auto* data = getOrCreateData(file, key); if (!data) return false; data->m_type = DataItem::RAW_MEMORY; data->m_raw.memory = m_allocator.allocate(size); copyMemory(data->m_raw.memory, mem, size); data->m_raw.size = size; return true; } bool Metadata::setInt(u32 file, u32 key, int value) { auto* data = getOrCreateData(file, key); if (!data) return false; data->m_type = DataItem::INT; data->m_int = value; return true; } bool Metadata::setString(u32 file, u32 key, const char* value) { auto* data = getOrCreateData(file, key); if (!data) return false; data->m_type = DataItem::STRING; copyString(data->m_string, value); return true; } bool Metadata::hasKey(u32 file, u32 key) const { return getData(file, key) != nullptr; } int Metadata::getInt(u32 file, u32 key) const { const auto* data = getData(file, key); if (!data || data->m_type != DataItem::INT) return 0; return data->m_int; } bool Metadata::getString(u32 file, u32 key, char* out, int max_size) const { const auto* data = getData(file, key); if (!data || data->m_type != DataItem::STRING) return false; copyString(out, max_size, data->m_string); return true; } } // namespace Lumix<commit_msg>Fix memory leak. (#1189)<commit_after>#include "metadata.h" #include "engine/fs/os_file.h" #include <cstdio> namespace Lumix { static const char* METADATA_FILENAME = "metadata.bin"; static const u32 METADATA_MAGIC = 0x4D455441; // 'META' enum class MetadataVersion : i32 { FIRST, LATEST }; Metadata::Metadata(IAllocator& allocator) : m_allocator(allocator) , m_data(allocator) { } bool Metadata::load() { FS::OsFile file; if (!file.open(METADATA_FILENAME, FS::Mode::OPEN_AND_READ)) return false; m_data.clear(); int count; u32 magic; file.read(&magic, sizeof(magic)); if (magic != METADATA_MAGIC) { file.close(); return false; } i32 version; file.read(&version, sizeof(version)); if (version > (int)MetadataVersion::LATEST) { file.close(); return false; } file.read(&count, sizeof(count)); for (int i = 0; i < count; ++i) { u32 key; file.read(&key, sizeof(key)); auto& file_data = m_data.emplace(key, m_allocator); int inner_count; file.read(&inner_count, sizeof(inner_count)); for (int j = 0; j < inner_count; ++j) { file.read(&key, sizeof(key)); DataItem& value = file_data.insert(key); file.read(&value.m_type, sizeof(value.m_type)); switch (value.m_type) { case DataItem::INT: file.read(&value.m_int, sizeof(value.m_int)); break; case DataItem::STRING: { int len; file.read(&len, sizeof(len)); file.read(value.m_string, len); } break; case DataItem::RAW_MEMORY: { int len; file.read(&len, sizeof(len)); value.m_raw.memory = m_allocator.allocate(len); file.read(value.m_raw.memory, len); } break; default: ASSERT(false); break; } } } file.close(); return true; } bool Metadata::save() { FS::OsFile file; if (!file.open(METADATA_FILENAME, FS::Mode::CREATE_AND_WRITE)) return false; file.write(&METADATA_MAGIC, sizeof(METADATA_MAGIC)); i32 version = (int)MetadataVersion::LATEST; file.write(&version, sizeof(version)); int count = m_data.size(); file.write(&count, sizeof(count)); for (int i = 0; i < m_data.size(); ++i) { auto key = m_data.getKey(i); file.write(&key, sizeof(key)); auto& file_data = m_data.at(i); count = file_data.size(); file.write(&count, sizeof(count)); for (int j = 0; j < file_data.size(); ++j) { key = file_data.getKey(j); file.write(&key, sizeof(key)); auto& value = file_data.at(j); file.write(&value.m_type, sizeof(value.m_type)); switch (value.m_type) { case DataItem::INT: file.write(&value.m_int, sizeof(value.m_int)); break; case DataItem::STRING: { int len = stringLength(value.m_string); file.write(&len, sizeof(len)); file.write(value.m_string, len); } break; case DataItem::RAW_MEMORY: { int len = (int)value.m_raw.size; file.write(&len, sizeof(len)); file.write(value.m_raw.memory, len); } break; default: ASSERT(false); break; } } } file.close(); return true; } Metadata::~Metadata() { for (int i = 0; i < m_data.size(); ++i) { auto& x = m_data.at(i); for (int j = 0; j < x.size(); ++j) { auto& data = x.at(j); if (data.m_type == DataItem::RAW_MEMORY) { m_allocator.deallocate(data.m_raw.memory); } } } } Metadata::DataItem* Metadata::getOrCreateData(u32 file, u32 key) { int index = m_data.find(file); if (index < 0) { index = m_data.insert(file, AssociativeArray<u32, DataItem>(m_allocator)); } auto& file_data = m_data.at(index); index = file_data.find(key); if (index >= 0) return &file_data.at(index); return &file_data.insert(key); } const Metadata::DataItem* Metadata::getData(u32 file, u32 key) const { int index = m_data.find(file); if (index < 0) return nullptr; auto& file_data = m_data.at(index); index = file_data.find(key); if (index < 0) return nullptr; return &file_data.at(index); } const void* Metadata::getRawMemory(u32 file, u32 key) const { const auto* data = getData(file, key); if (!data || data->m_type != DataItem::RAW_MEMORY) return nullptr; return data->m_raw.memory; } size_t Metadata::getRawMemorySize(u32 file, u32 key) const { const auto* data = getData(file, key); if (!data || data->m_type != DataItem::RAW_MEMORY) return 0; return data->m_raw.size; } bool Metadata::setRawMemory(u32 file, u32 key, const void* mem, size_t size) { auto* data = getOrCreateData(file, key); if (!data) return false; data->m_type = DataItem::RAW_MEMORY; m_allocator.deallocate(data->m_raw.memory); data->m_raw.memory = m_allocator.allocate(size); copyMemory(data->m_raw.memory, mem, size); data->m_raw.size = size; return true; } bool Metadata::setInt(u32 file, u32 key, int value) { auto* data = getOrCreateData(file, key); if (!data) return false; data->m_type = DataItem::INT; data->m_int = value; return true; } bool Metadata::setString(u32 file, u32 key, const char* value) { auto* data = getOrCreateData(file, key); if (!data) return false; data->m_type = DataItem::STRING; copyString(data->m_string, value); return true; } bool Metadata::hasKey(u32 file, u32 key) const { return getData(file, key) != nullptr; } int Metadata::getInt(u32 file, u32 key) const { const auto* data = getData(file, key); if (!data || data->m_type != DataItem::INT) return 0; return data->m_int; } bool Metadata::getString(u32 file, u32 key, char* out, int max_size) const { const auto* data = getData(file, key); if (!data || data->m_type != DataItem::STRING) return false; copyString(out, max_size, data->m_string); return true; } } // namespace Lumix<|endoftext|>
<commit_before>#include "featuresmanager.h" #include <functional> #include <fstream> #include "exchangemanager.h" #include "features.h" static const unsigned int MIN_SEQUENCE_SIZE = 5; // Otherwise, the sequence is ignored bool replace(std::string &str, const std::string &from, const std::string &to) { size_t start_pos = str.find(from); if(start_pos == std::string::npos) return false; str.replace(start_pos, from.length(), to); return true; } FeaturesManager::FeaturesManager() { // Loading the lists of sequences // Two options: // 1) From the sequences extracted from the camera // 2) From the labelized trace file (computed with the network visualizer) ifstream fileListPersons("../../Data/OutputReid/trace_labelized.txt"); if(!fileListPersons.is_open()) { fileListPersons.open("../../Data/Traces/traces.txt"); if(!fileListPersons.is_open()) { cout << "Error: Impossible to load the trace file" << endl; exit(0); } } else { cout << "Labelized traces loaded !!!" << endl; } // /!\ Warning: No verification on the file for(string line; std::getline(fileListPersons, line); ) { // If new group of image if(line.find("-----") != std::string::npos) { replace(line, "----- ", ""); replace(line, " -----", ""); listSequences.push_back(Sequence(line)); } } fileListPersons.close(); // Start with the first sequence currentSequenceId = 0; // Allocation of the array arrayToSend = nullptr; } FeaturesManager::~FeaturesManager() { delete arrayToSend; } void FeaturesManager::sendNext() { if(ExchangeManager::getInstance().getIsActive() && !ExchangeManager::getInstance().getIsLocked() && currentSequenceId < listSequences.size()) { Sequence &currentSequence = listSequences.at(currentSequenceId); cout << "Sequence: " << currentSequence.getName() << endl; if(currentSequence.getListImageIds().size() < MIN_SEQUENCE_SIZE) { cout << "Sequence ignored (too short)"<< endl; } else { vector<FeaturesElement> listCurrentSequenceFeatures; // Selection of some images of the sequence (we don't send the entire sequence) for(unsigned int i = 0 ; i < MIN_SEQUENCE_SIZE ; ++i) { listCurrentSequenceFeatures.push_back(FeaturesElement()); int index = i * ((currentSequence.getListImageIds().size()-1)/MIN_SEQUENCE_SIZE); // Linear function (0,0) to (MIN_SEQUENCE_SIZE, listImageIds().size()-1) Features::computeFeature("../../Data/Traces/" + currentSequence.getListImageIds().at(index), listCurrentSequenceFeatures.back()); } // Fill the array size_t arrayToSendSize = 0; // Offset if(sizeof(size_t)/sizeof(float) != 2) // Depending of the computer architecture { cout << "Error: wrong architecture 2!=" << sizeof(size_t)/sizeof(float) << ", cannot send the size_t" << endl; } arrayToSendSize += 2; // Hashcode sequence name arrayToSendSize += 2; // Hashcode camera name arrayToSendSize += 2; // Entrance and exit time arrayToSendSize += 8; // Entrance and exit vectors Features::computeArray(arrayToSend, arrayToSendSize, listCurrentSequenceFeatures); // Add offset values to the array computeAddInfo(arrayToSend, currentSequence); // Send the features over the network ExchangeManager::getInstance().publishFeatures(arrayToSendSize*sizeof(float),arrayToSend); } ++currentSequenceId; } } void FeaturesManager::computeAddInfo(float *&array, const Sequence &sequence) { if(sizeof(float) != sizeof(int)) // For casting { cout << "Error: convertion float<->int impossible" << endl; exit(0); } int value = 0; // Used as intermediate for bit copy into float FileStorage fileTraceCam("../../Data/Traces/" + sequence.getCamInfoId() + ".yml", FileStorage::READ); if(!fileTraceCam.isOpened()) { cout << "Error: Cannot open the additional information file for the sequence " << sequence.getCamInfoId() << endl; exit(0); } // Save the sequence name id size_t hashCode = 0; unsigned int mostSignificantBits = 0; unsigned int leastSignificantBits = 0; hashCode = std::hash<std::string>()(sequence.getName()); // Hashcode used as id leastSignificantBits = hashCode & 0xFFFFFFFF; mostSignificantBits = hashCode >> 32 & 0xFFFFFFFF; array[0] = reinterpret_cast<float&>(leastSignificantBits); array[1] = reinterpret_cast<float&>(mostSignificantBits); // Save the cam id hashCode = std::hash<std::string>()(fileTraceCam["camId"]); leastSignificantBits = hashCode & 0xFFFFFFFF; mostSignificantBits = hashCode >> 32 & 0xFFFFFFFF; array[2] = reinterpret_cast<float&>(leastSignificantBits); array[3] = reinterpret_cast<float&>(mostSignificantBits); // Save the entrance and exit time value = fileTraceCam["beginDate"]; array[4] = reinterpret_cast<float&>(value); value = fileTraceCam["endDate"]; array[5] = reinterpret_cast<float&>(value); // Save the entrance and exit direction FileNode nodeVector; nodeVector = fileTraceCam["entranceVector"]; array[6] = static_cast<float>(nodeVector["x1"]); array[7] = static_cast<float>(nodeVector["y1"]); array[8] = static_cast<float>(nodeVector["x2"]); array[9] = static_cast<float>(nodeVector["y2"]); nodeVector = fileTraceCam["exitVector"]; array[10] = static_cast<float>(nodeVector["x1"]); array[11] = static_cast<float>(nodeVector["y1"]); array[12] = static_cast<float>(nodeVector["x2"]); array[13] = static_cast<float>(nodeVector["y2"]); fileTraceCam.release(); } <commit_msg>Correct the name of the input traces file<commit_after>#include "featuresmanager.h" #include <functional> #include <fstream> #include "exchangemanager.h" #include "features.h" static const unsigned int MIN_SEQUENCE_SIZE = 5; // Otherwise, the sequence is ignored bool replace(std::string &str, const std::string &from, const std::string &to) { size_t start_pos = str.find(from); if(start_pos == std::string::npos) return false; str.replace(start_pos, from.length(), to); return true; } FeaturesManager::FeaturesManager() { // Loading the lists of sequences // Two options: // 1) From the sequences extracted from the camera // 2) From the labelized trace file (computed with the network visualizer) ifstream fileListPersons("../../Data/OutputReid/traces_labelized.txt"); if(!fileListPersons.is_open()) { fileListPersons.open("../../Data/Traces/traces.txt"); if(!fileListPersons.is_open()) { cout << "Error: Impossible to load the trace file" << endl; exit(0); } } else { cout << "------------------------------------------------------------------" << endl; cout << "------WARNING: LABELLED TRACES FILE DETECTED AND USED !!!!!!------" << endl; cout << "------------------------------------------------------------------" << endl; } // /!\ Warning: No verification on the file for(string line; std::getline(fileListPersons, line); ) { // If new group of image if(line.find("-----") != std::string::npos) { replace(line, "----- ", ""); replace(line, " -----", ""); listSequences.push_back(Sequence(line)); } } fileListPersons.close(); // Start with the first sequence currentSequenceId = 0; // Allocation of the array arrayToSend = nullptr; } FeaturesManager::~FeaturesManager() { delete arrayToSend; } void FeaturesManager::sendNext() { if(ExchangeManager::getInstance().getIsActive() && !ExchangeManager::getInstance().getIsLocked() && currentSequenceId < listSequences.size()) { Sequence &currentSequence = listSequences.at(currentSequenceId); cout << "Sequence: " << currentSequence.getName() << endl; if(currentSequence.getListImageIds().size() < MIN_SEQUENCE_SIZE) { cout << "Sequence ignored (too short)"<< endl; } else { vector<FeaturesElement> listCurrentSequenceFeatures; // Selection of some images of the sequence (we don't send the entire sequence) for(unsigned int i = 0 ; i < MIN_SEQUENCE_SIZE ; ++i) { listCurrentSequenceFeatures.push_back(FeaturesElement()); int index = i * ((currentSequence.getListImageIds().size()-1)/MIN_SEQUENCE_SIZE); // Linear function (0,0) to (MIN_SEQUENCE_SIZE, listImageIds().size()-1) Features::computeFeature("../../Data/Traces/" + currentSequence.getListImageIds().at(index), listCurrentSequenceFeatures.back()); } // Fill the array size_t arrayToSendSize = 0; // Offset if(sizeof(size_t)/sizeof(float) != 2) // Depending of the computer architecture { cout << "Error: wrong architecture 2!=" << sizeof(size_t)/sizeof(float) << ", cannot send the size_t" << endl; } arrayToSendSize += 2; // Hashcode sequence name arrayToSendSize += 2; // Hashcode camera name arrayToSendSize += 2; // Entrance and exit time arrayToSendSize += 8; // Entrance and exit vectors Features::computeArray(arrayToSend, arrayToSendSize, listCurrentSequenceFeatures); // Add offset values to the array computeAddInfo(arrayToSend, currentSequence); // Send the features over the network ExchangeManager::getInstance().publishFeatures(arrayToSendSize*sizeof(float),arrayToSend); } ++currentSequenceId; } } void FeaturesManager::computeAddInfo(float *&array, const Sequence &sequence) { if(sizeof(float) != sizeof(int)) // For casting { cout << "Error: convertion float<->int impossible" << endl; exit(0); } int value = 0; // Used as intermediate for bit copy into float FileStorage fileTraceCam("../../Data/Traces/" + sequence.getCamInfoId() + ".yml", FileStorage::READ); if(!fileTraceCam.isOpened()) { cout << "Error: Cannot open the additional information file for the sequence " << sequence.getCamInfoId() << endl; exit(0); } // Save the sequence name id size_t hashCode = 0; unsigned int mostSignificantBits = 0; unsigned int leastSignificantBits = 0; hashCode = std::hash<std::string>()(sequence.getName()); // Hashcode used as id leastSignificantBits = hashCode & 0xFFFFFFFF; mostSignificantBits = hashCode >> 32 & 0xFFFFFFFF; array[0] = reinterpret_cast<float&>(leastSignificantBits); array[1] = reinterpret_cast<float&>(mostSignificantBits); // Save the cam id hashCode = std::hash<std::string>()(fileTraceCam["camId"]); leastSignificantBits = hashCode & 0xFFFFFFFF; mostSignificantBits = hashCode >> 32 & 0xFFFFFFFF; array[2] = reinterpret_cast<float&>(leastSignificantBits); array[3] = reinterpret_cast<float&>(mostSignificantBits); // Save the entrance and exit time value = fileTraceCam["beginDate"]; array[4] = reinterpret_cast<float&>(value); value = fileTraceCam["endDate"]; array[5] = reinterpret_cast<float&>(value); // Save the entrance and exit direction FileNode nodeVector; nodeVector = fileTraceCam["entranceVector"]; array[6] = static_cast<float>(nodeVector["x1"]); array[7] = static_cast<float>(nodeVector["y1"]); array[8] = static_cast<float>(nodeVector["x2"]); array[9] = static_cast<float>(nodeVector["y2"]); nodeVector = fileTraceCam["exitVector"]; array[10] = static_cast<float>(nodeVector["x1"]); array[11] = static_cast<float>(nodeVector["y1"]); array[12] = static_cast<float>(nodeVector["x2"]); array[13] = static_cast<float>(nodeVector["y2"]); fileTraceCam.release(); } <|endoftext|>
<commit_before>#include "NavarroSeq.h" #include <string> #include <fstream> #include <sstream> using namespace std; char HOMOZYGOUS = 0x31; char HETEROZYGOUS = 0x32; string get_high_frequency_variants(string filename, unsigned int population_size, unsigned int numrows, double freq_cutoff) { // Bounds check if (NavarroSeq::get_size(filename) < population_size*numrows) return ""; stringstream ss; unsigned int cumulative_rank = 0; for (unsigned int i=0; i<numrows; i++) { unsigned int homozygous_count = NavarroSeq::rank(filename, HOMOZYGOUS, (i+1)*population_size - 1); unsigned int heterozygous_count = NavarroSeq::rank(filename, HETEROZYGOUS, (i+1)*population_size - 1); unsigned int row_count = homozygous_count + heterozygous_count - cumulative_rank; if (((double) row_count)/population_size >= freq_cutoff) ss << i; cumulative_rank = homozygous_count + heterozygous_count; } return ss.str(); } int main(int argc, char** argv) { bool compress = false; if (argc > 1) { if (strcmp("-compress", argv[1]) == 0) { compress = true; } } if (compress) { NavarroSeq::compress("testin.txt", "testout.txt"); } else { string s = get_high_frequency_variants("testout.txt", 20, 10, 0.5); cout << "RESULT STRING: (row indices where percent variants >= cutoff): " << s << endl; } }<commit_msg>Added command-line flags to main method.<commit_after>#include "NavarroSeq.h" #include <string> #include <fstream> #include <sstream> using namespace std; char HOMOZYGOUS = 0x31; char HETEROZYGOUS = 0x32; string get_high_frequency_variants(string filename, unsigned int population_size, unsigned int numrows, double freq_cutoff) { // Bounds check if (NavarroSeq::get_size(filename) < population_size*numrows) return ""; stringstream ss; unsigned int cumulative_rank = 0; for (unsigned int i=0; i<numrows; i++) { unsigned int homozygous_count = NavarroSeq::rank(filename, HOMOZYGOUS, (i+1)*population_size - 1); unsigned int heterozygous_count = NavarroSeq::rank(filename, HETEROZYGOUS, (i+1)*population_size - 1); unsigned int row_count = homozygous_count + heterozygous_count - cumulative_rank; if (((double) row_count)/population_size >= freq_cutoff) ss << i; cumulative_rank = homozygous_count + heterozygous_count; } return ss.str(); } int main(int argc, char** argv) { bool compress = false; bool decompress = false; string fileIn = ""; string fileOut = ""; if (argc > 1) { if (strcmp("-compress", argv[1]) == 0) { compress = true; fileIn = argv[2]; fileOut = argv[3]; } else if (strcmp("-decompress", argv[1]) == 0) { decompress = true; fileIn = argv[2]; } else { fileIn = argv[1]; } } else { cout << "Not enough arguments!" << endl; return 0; } if (compress) { NavarroSeq::compress(fileIn, fileOut); } else if (decompress) { NavarroSeq::decompress(fileIn); } else { string s = get_high_frequency_variants(fileIn, 20, 10, 0.5); cout << "RESULT STRING: (row indices where percent variants >= cutoff): " << s << endl; } } <|endoftext|>
<commit_before>#include "../allocwrapper.h" #include "../mallocator.h" #include <gtest/gtest.h> using AllocToTest = AllocWrapper<Mallocator>; TEST(AllocWrapper, allocate) { AllocToTest myAlloc; const size_t size = sizeof(char) * 100; ASSERT_NE(myAlloc.allocate(size), nullptr); } TEST(AllocWrapper, deallocate) { AllocToTest myAlloc; const size_t size = sizeof(char) * 100; const auto ptr = myAlloc.allocate(size); ASSERT_NE(ptr, nullptr); myAlloc.deallocate(ptr); } TEST(AllocWrapper, goodSize) { const size_t size = sizeof(char) * 100; ASSERT_GE(AllocToTest::goodSize(size), size); } TEST(AllocWrapper, goodSizeAligned) { const size_t size = sizeof(char) * 100; ASSERT_EQ(0, AllocToTest::goodSize(size) % AllocToTest::alignment()); } #define TAG_STR "test-tag" TEST(AllocWrapper, setsTag) { size_t size = 100 * sizeof(char); AllocToTest myAlloc; auto ptr = myAlloc.allocate(size, TAG_STR); ASSERT_NE(nullptr, ptr); auto tlr = AllocToTest::getTailer(ptr); ASSERT_STREQ(TAG_STR, tlr->tag); } TEST(AllocWrapper, reallocPreservesTag) { AllocToTest myAlloc; auto ptr = myAlloc.allocate(100 * sizeof(char), TAG_STR); ASSERT_NE(nullptr, ptr); // make it allocate something fairly big to try to force the os to realloc. auto newPtr = myAlloc.reallocate(ptr, 10*1024*1024* sizeof(char)); // TODO: use a segregated allocator, this should realloc across pools. ASSERT_NE(nullptr, newPtr); ASSERT_NE(ptr, newPtr); auto tlr = AllocToTest::getTailer(newPtr); ASSERT_STREQ(TAG_STR, tlr->tag); } TEST(AllocWrapper, blockRecoverable) { const size_t size = 100 * sizeof(char); const size_t allocSize = AllocToTest::goodSize(size); AllocToTest myAlloc; auto ptr = myAlloc.allocate(size, TAG_STR); ASSERT_NE(nullptr, ptr); auto blk = AllocToTest::getBlock(ptr); ASSERT_EQ(allocSize, blk.size); } TEST(AllocWrapper, dataStart) { const size_t size = 100 * sizeof(char); const size_t allocSize = AllocToTest::goodSize(size); AllocToTest myAlloc; auto ptr = myAlloc.allocate(size, TAG_STR); ASSERT_NE(nullptr, ptr); auto blk = AllocToTest::getBlock(ptr); ASSERT_EQ(ptr, AllocToTest::getDataBegin(blk)); } TEST(AllocWrapper, reallocate) { const size_t size = 100 * sizeof(char); const size_t allocSize = AllocToTest::goodSize(size); AllocToTest myAlloc; auto ptr = myAlloc.allocate(size); ASSERT_NE(nullptr, ptr); auto blk = AllocToTest::getBlock(ptr); auto newAllocSize = allocSize * 2; auto newPtr = myAlloc.reallocate(ptr, newAllocSize); ASSERT_NE(nullptr, newPtr); auto newBlk = AllocToTest::getBlock(ptr); ASSERT_GE(newBlk.size, newAllocSize); } TEST(AllocWrapper, owns) { // This is a bit of a non test. // The Mallocator will always say true. // TODO: Use a different backing allocator. AllocToTest myAlloc; const size_t size = sizeof(char) * 100; auto ptr = myAlloc.allocate(size); ASSERT_NE(ptr, nullptr); ASSERT_TRUE(myAlloc.owns(ptr)); } // This test attempts to reallocate a thing of the same length. // Reallocation should report sucessful, // but not actually do anything to the memory in question TEST(AllocWrapper, reallocateNotNeeded) { AllocToTest myAlloc; auto ptr = myAlloc.allocate(100); ASSERT_NE(nullptr, ptr); auto blk = AllocToTest::getBlock(ptr); auto newPtr = myAlloc.reallocate(ptr, sizeof(char) * 100); ASSERT_NE(nullptr, ptr); auto newBlk = AllocToTest::getBlock(ptr); ASSERT_EQ(blk.ptr, newBlk.ptr); ASSERT_EQ(blk.size, newBlk.size); }<commit_msg>Fixed a test and removed warnings<commit_after>#include "../allocwrapper.h" #include "../mallocator.h" #include <gtest/gtest.h> using AllocToTest = AllocWrapper<Mallocator>; TEST(AllocWrapper, allocate) { AllocToTest myAlloc; const size_t size = sizeof(char) * 100; ASSERT_NE(myAlloc.allocate(size), nullptr); } TEST(AllocWrapper, deallocate) { AllocToTest myAlloc; const size_t size = sizeof(char) * 100; const auto ptr = myAlloc.allocate(size); ASSERT_NE(ptr, nullptr); myAlloc.deallocate(ptr); } TEST(AllocWrapper, goodSize) { const size_t size = sizeof(char) * 100; ASSERT_GE(AllocToTest::goodSize(size), size); } TEST(AllocWrapper, goodSizeAligned) { const size_t size = sizeof(char) * 100; ASSERT_EQ(0, AllocToTest::goodSize(size) % AllocToTest::alignment()); } #define TAG_STR "test-tag" TEST(AllocWrapper, setsTag) { size_t size = 100 * sizeof(char); AllocToTest myAlloc; auto ptr = myAlloc.allocate(size, TAG_STR); ASSERT_NE(nullptr, ptr); auto tlr = AllocToTest::getTailer(ptr); ASSERT_STREQ(TAG_STR, tlr->tag); } TEST(AllocWrapper, reallocPreservesTag) { AllocToTest myAlloc; auto ptr = myAlloc.allocate(100 * sizeof(char), TAG_STR); ASSERT_NE(nullptr, ptr); // make it allocate something fairly big to try to force the os to realloc. auto newPtr = myAlloc.reallocate(ptr, 10*1024*1024* sizeof(char)); // TODO: use a segregated allocator, this should realloc across pools. ASSERT_NE(nullptr, newPtr); ASSERT_NE(ptr, newPtr); auto tlr = AllocToTest::getTailer(newPtr); ASSERT_STREQ(TAG_STR, tlr->tag); } TEST(AllocWrapper, blockRecoverable) { const size_t size = 100 * sizeof(char); const size_t allocSize = AllocToTest::goodSize(size); AllocToTest myAlloc; auto ptr = myAlloc.allocate(size, TAG_STR); ASSERT_NE(nullptr, ptr); auto blk = AllocToTest::getBlock(ptr); ASSERT_EQ(allocSize, blk.size); } TEST(AllocWrapper, dataStart) { const size_t size = 100 * sizeof(char); AllocToTest myAlloc; auto ptr = myAlloc.allocate(size, TAG_STR); ASSERT_NE(nullptr, ptr); auto blk = AllocToTest::getBlock(ptr); ASSERT_EQ(ptr, AllocToTest::getDataBegin(blk)); } TEST(AllocWrapper, reallocate) { const size_t size = 100 * sizeof(char); const size_t allocSize = AllocToTest::goodSize(size); AllocToTest myAlloc; auto ptr = myAlloc.allocate(size); ASSERT_NE(nullptr, ptr); auto newAllocSize = allocSize * 2; auto newPtr = myAlloc.reallocate(ptr, newAllocSize); ASSERT_NE(nullptr, newPtr); auto newBlk = AllocToTest::getBlock(ptr); ASSERT_GE(newBlk.size, newAllocSize); } TEST(AllocWrapper, owns) { // This is a bit of a non test. // The Mallocator will always say true. // TODO: Use a different backing allocator. AllocToTest myAlloc; const size_t size = sizeof(char) * 100; auto ptr = myAlloc.allocate(size); ASSERT_NE(ptr, nullptr); ASSERT_TRUE(myAlloc.owns(ptr)); } // This test attempts to reallocate a thing of the same length. // Reallocation should report sucessful, // but not actually do anything to the memory in question TEST(AllocWrapper, reallocateNotNeeded) { AllocToTest myAlloc; const size_t size = sizeof(char) * 100; auto ptr = myAlloc.allocate(size); ASSERT_NE(nullptr, ptr); auto blk = AllocToTest::getBlock(ptr); auto newPtr = myAlloc.reallocate(ptr, size); ASSERT_NE(nullptr, newPtr); ASSERT_EQ(ptr, newPtr); auto newBlk = AllocToTest::getBlock(newPtr); ASSERT_EQ(blk.ptr, newBlk.ptr); ASSERT_EQ(blk.size, newBlk.size); }<|endoftext|>
<commit_before>/** * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io> * Authors: * - Laura Schlimmer <laura@eventql.io> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * 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 license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include <iostream> #include <unistd.h> #include "eventql/eventql.h" #include "eventql/util/application.h" #include "eventql/util/io/inputstream.h" #include "eventql/util/io/TerminalOutputStream.h" #include "eventql/util/cli/flagparser.h" #include "eventql/cli/benchmark.h" int main(int argc, const char** argv) { cli::FlagParser flags; flags.defineFlag( "host", cli::FlagParser::T_STRING, false, "h", "localhost", "eventql server hostname", "<host>"); flags.defineFlag( "port", cli::FlagParser::T_INTEGER, false, "p", "9175", "eventql server port", "<port>"); flags.defineFlag( "database", cli::FlagParser::T_STRING, false, "d", NULL, "database", "<db>"); flags.defineFlag( "connections", cli::FlagParser::T_INTEGER, false, "c", "10", "number of connections", "<threads>"); flags.defineFlag( "rate", cli::FlagParser::T_INTEGER, false, "r", "1", "number of requests per second", "<rate>"); flags.defineFlag( "num", cli::FlagParser::T_INTEGER, false, "n", NULL, "total number of request (inifite if unset)", "<rate>"); flags.defineFlag( "help", cli::FlagParser::T_SWITCH, false, "?", NULL, "help", "<help>"); flags.defineFlag( "version", cli::FlagParser::T_SWITCH, false, "v", NULL, "print version", "<switch>"); Application::init(); auto stdout_os = TerminalOutputStream::fromStream(OutputStream::getStdout()); try { flags.parseArgv(argc, argv); } catch (const std::exception& e) { std::cerr << StringUtil::format("ERROR: $0\n", e.what()); return 1; } Vector<String> cmd_argv = flags.getArgv(); bool print_help = flags.isSet("help"); bool print_version = flags.isSet("version"); if (print_version || print_help) { stdout_os->print( StringUtil::format( "EventQL $0 ($1)\n" "Copyright (c) 2016, DeepCortex GmbH. All rights reserved.\n\n", eventql::kVersionString, eventql::kBuildID)); } if (print_version) { return 1; } if (print_help) { stdout_os->print( "Usage: $ evqlslap [OPTIONS]\n\n" " -h, --host <hostname> Set the EventQL server hostname\n" " -p, --port <port> Set the EventQL server port\n" " -D, --database <db> Select a database\n" " -c, --connections <num> Number of concurrent connections\n" " -r, --rate <rate> Maximum rate of requests in RPS\n" " -n, --num <num> Maximum total number of request (default is inifite)\n" " -?, --help Display the help text and exit\n" " -v, --version Display the version of this binary and exit\n"); return 1; } auto request_handler = []() { usleep(1000); return ReturnCode::success(); }; auto on_progress = [&stdout_os](eventql::cli::BenchmarkStats* stats) { try { stdout_os->eraseLine(); stdout_os->print(StringUtil::format( "\rRunning... rate=$0r/s, avg_runtime=$1ms, total=$2, running=$3, " "errors=$4 ($5%)", stats->getRollingRPS(), stats->getRollingAverageRuntime() / double(kMicrosPerMilli), stats->getTotalRequestCount(), stats->getRunningRequestCount(), stats->getTotalErrorCount(), stats->getTotalErrorRate() * 100.0f)); } catch (const std::exception& e) { /* fallthrough */ } }; eventql::cli::Benchmark benchmark( flags.getInt("connections"), flags.getInt("rate"), flags.isSet("num") ? flags.getInt("num") : -1); benchmark.setRequestHandler(request_handler); benchmark.setProgressCallback(on_progress); benchmark.setProgressRateLimit(kMicrosPerSecond / 10); auto rc = benchmark.connect( flags.getString("host"), flags.getInt("port"), {}); if (rc.isSuccess()) { rc = benchmark.run(); } stdout_os->eraseLine(); if (rc.isSuccess()) { std::cout << "success" << std::endl; return 0; } else { std::cerr << "ERROR: " << rc.getMessage() << std::endl; return 1; } return 0; } <commit_msg>pass auth data<commit_after>/** * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io> * Authors: * - Laura Schlimmer <laura@eventql.io> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * 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 license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include <iostream> #include <unistd.h> #include "eventql/eventql.h" #include "eventql/util/application.h" #include "eventql/util/io/inputstream.h" #include "eventql/util/io/TerminalOutputStream.h" #include "eventql/util/cli/flagparser.h" #include "eventql/cli/benchmark.h" int main(int argc, const char** argv) { cli::FlagParser flags; flags.defineFlag( "host", cli::FlagParser::T_STRING, false, "h", "localhost", "eventql server hostname", "<host>"); flags.defineFlag( "port", cli::FlagParser::T_INTEGER, false, "p", "9175", "eventql server port", "<port>"); flags.defineFlag( "database", cli::FlagParser::T_STRING, false, "d", NULL, "database", "<db>"); flags.defineFlag( "user", cli::FlagParser::T_STRING, false, NULL, NULL, "username", "<user>"); flags.defineFlag( "password", cli::FlagParser::T_STRING, false, NULL, NULL, "password", "<password>"); flags.defineFlag( "auth_token", cli::FlagParser::T_STRING, false, NULL, NULL, "auth token", "<auth_token>"); flags.defineFlag( "connections", cli::FlagParser::T_INTEGER, false, "c", "10", "number of connections", "<threads>"); flags.defineFlag( "rate", cli::FlagParser::T_INTEGER, false, "r", "1", "number of requests per second", "<rate>"); flags.defineFlag( "num", cli::FlagParser::T_INTEGER, false, "n", NULL, "total number of request (inifite if unset)", "<rate>"); flags.defineFlag( "help", cli::FlagParser::T_SWITCH, false, "?", NULL, "help", "<help>"); flags.defineFlag( "version", cli::FlagParser::T_SWITCH, false, "v", NULL, "print version", "<switch>"); Application::init(); auto stdout_os = TerminalOutputStream::fromStream(OutputStream::getStdout()); try { flags.parseArgv(argc, argv); } catch (const std::exception& e) { std::cerr << StringUtil::format("ERROR: $0\n", e.what()); return 1; } Vector<String> cmd_argv = flags.getArgv(); bool print_help = flags.isSet("help"); bool print_version = flags.isSet("version"); if (print_version || print_help) { stdout_os->print( StringUtil::format( "EventQL $0 ($1)\n" "Copyright (c) 2016, DeepCortex GmbH. All rights reserved.\n\n", eventql::kVersionString, eventql::kBuildID)); } if (print_version) { return 1; } if (print_help) { stdout_os->print( "Usage: $ evqlslap [OPTIONS]\n\n" " -h, --host <hostname> Set the EventQL server hostname\n" " -p, --port <port> Set the EventQL server port\n" " -d, --database <db> Select a database\n" " --user <user> Set the EventQL username\n" " --password <password> Set the password\n" " --auth_token <token> Set the EventQL auth token\n" " -c, --connections <num> Number of concurrent connections\n" " -r, --rate <rate> Maximum rate of requests in RPS\n" " -n, --num <num> Maximum total number of request (default is inifite)\n" " -?, --help Display the help text and exit\n" " -v, --version Display the version of this binary and exit\n"); return 1; } std::vector<std::pair<std::string, std::string>> auth_data; if (flags.isSet("auth_token")) { auth_data.emplace_back("auth_token", flags.getString("auth_token")); } if (flags.isSet("user")) { auth_data.emplace_back("user", flags.getString("user")); } if (flags.isSet("password")) { auth_data.emplace_back("password", flags.getString("password")); } auto request_handler = []() { usleep(1000); return ReturnCode::success(); }; auto on_progress = [&stdout_os](eventql::cli::BenchmarkStats* stats) { try { stdout_os->eraseLine(); stdout_os->print(StringUtil::format( "\rRunning... rate=$0r/s, avg_runtime=$1ms, total=$2, running=$3, " "errors=$4 ($5%)", stats->getRollingRPS(), stats->getRollingAverageRuntime() / double(kMicrosPerMilli), stats->getTotalRequestCount(), stats->getRunningRequestCount(), stats->getTotalErrorCount(), stats->getTotalErrorRate() * 100.0f)); } catch (const std::exception& e) { /* fallthrough */ } }; eventql::cli::Benchmark benchmark( flags.getInt("connections"), flags.getInt("rate"), flags.isSet("num") ? flags.getInt("num") : -1); benchmark.setRequestHandler(request_handler); benchmark.setProgressCallback(on_progress); benchmark.setProgressRateLimit(kMicrosPerSecond / 10); auto rc = benchmark.connect( flags.getString("host"), flags.getInt("port"), auth_data); if (rc.isSuccess()) { rc = benchmark.run(); } stdout_os->eraseLine(); if (rc.isSuccess()) { std::cout << "success" << std::endl; return 0; } else { std::cerr << "ERROR: " << rc.getMessage() << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>#include <cstdio> #include <iostream> #include <libHierGA/HierGA.hpp> #include "SphereFitness.hpp" using namespace std; int main(void) { HierarchicalEA ea(100); vector<Locus*> baseLoci(32, new NumericSetLocus<double>(-50, 50)); ea.addNode<EANode>( 6, baseLoci, {new SphereFitness()}, new SphereToString(), {new IterationCountEnd(100)}, "P1", true, true, new MuPlusLambdaES( new UniformCrossover(), 6 ) ); ea.setEvolutionOrder({"P1"}); ea.run(true); ea.deleteAllNodes(); } <commit_msg>[Sphere Example]: Increased lambda parameter<commit_after>#include <cstdio> #include <iostream> #include <libHierGA/HierGA.hpp> #include "SphereFitness.hpp" using namespace std; int main(void) { HierarchicalEA ea(100); vector<Locus*> baseLoci(32, new NumericSetLocus<double>(-50, 50)); ea.addNode<EANode>( 6, baseLoci, {new SphereFitness()}, new SphereToString(), {new IterationCountEnd(100)}, "P1", true, true, new MuPlusLambdaES( new UniformCrossover(), 24 ) ); ea.setEvolutionOrder({"P1"}); ea.run(true); ea.deleteAllNodes(); } <|endoftext|>
<commit_before>#include "gemini.h" #include "parameters.h" #include "curl_fun.h" #include "utils/restapi.h" #include "utils/base64.h" #include "openssl/sha.h" #include "openssl/hmac.h" #include "jansson.h" #include <unistd.h> #include <math.h> #include <sstream> #include <iomanip> #include <sys/time.h> namespace Gemini { static RestApi& queryHandle(Parameters &params) { static RestApi query ("https://api.gemini.com", params.cacert.c_str(), *params.logFile); return query; } quote_t getQuote(Parameters &params) { auto &exchange = queryHandle(params); json_t *root = exchange.getRequest("/v1/book/BTCUSD"); const char *quote = json_string_value(json_object_get(json_array_get(json_object_get(root, "bids"), 0), "price")); auto bidValue = quote ? std::stod(quote) : 0.0; quote = json_string_value(json_object_get(json_array_get(json_object_get(root, "asks"), 0), "price")); auto askValue = quote ? std::stod(quote) : 0.0; json_decref(root); return std::make_pair(bidValue, askValue); } double getAvail(Parameters& params, std::string currency) { json_t* root = authRequest(params, "https://api.gemini.com/v1/balances", "balances", ""); while (json_object_get(root, "message") != NULL) { sleep(1.0); *params.logFile << "<Gemini> Error with JSON: " << json_dumps(root, 0) << ". Retrying..." << std::endl; root = authRequest(params, "https://api.gemini.com/v1/balances", "balances", ""); } // go through the list size_t arraySize = json_array_size(root); double availability = 0.0; const char* returnedText; std::string currencyAllCaps; if (currency.compare("btc") == 0) { currencyAllCaps = "BTC"; } else if (currency.compare("usd") == 0) { currencyAllCaps = "USD"; } for (size_t i = 0; i < arraySize; i++) { std::string tmpCurrency = json_string_value(json_object_get(json_array_get(root, i), "currency")); if (tmpCurrency.compare(currencyAllCaps.c_str()) == 0) { returnedText = json_string_value(json_object_get(json_array_get(root, i), "amount")); if (returnedText != NULL) { availability = atof(returnedText); } else { *params.logFile << "<Gemini> Error with the credentials." << std::endl; availability = 0.0; } } } json_decref(root); return availability; } std::string sendLongOrder(Parameters& params, std::string direction, double quantity, double price) { *params.logFile << "<Gemini> Trying to send a \"" << direction << "\" limit order: " << std::setprecision(6) << quantity << "@$" << std::setprecision(2) << price << "...\n"; std::ostringstream oss; oss << "\"symbol\":\"BTCUSD\", \"amount\":\"" << quantity << "\", \"price\":\"" << price << "\", \"side\":\"" << direction << "\", \"type\":\"exchange limit\""; std::string options = oss.str(); json_t* root = authRequest(params, "https://api.gemini.com/v1/order/new", "order/new", options); std::string orderId = json_string_value(json_object_get(root, "order_id")); *params.logFile << "<Gemini> Done (order ID: " << orderId << ")\n" << std::endl; json_decref(root); return orderId; } bool isOrderComplete(Parameters& params, std::string orderId) { if (orderId == "0") return true; auto options = "\"order_id\":" + orderId; json_t* root = authRequest(params, "https://api.gemini.com/v1/order/status", "order/status", options); bool isComplete = json_is_false(json_object_get(root, "is_live")); json_decref(root); return isComplete; } double getActivePos(Parameters& params) { return getAvail(params, "btc"); } double getLimitPrice(Parameters& params, double volume, bool isBid) { auto &exchange = queryHandle(params); json_t* root = exchange.getRequest("/v1/book/btcusd"); auto bidask = json_object_get(root, isBid ? "bids" : "asks"); // loop on volume *params.logFile << "<Gemini> Looking for a limit price to fill " << std::setprecision(6) << fabs(volume) << " BTC...\n"; double tmpVol = 0.0; double p; double v; int i = 0; while (tmpVol < fabs(volume) * params.orderBookFactor) { p = atof(json_string_value(json_object_get(json_array_get(bidask, i), "price"))); v = atof(json_string_value(json_object_get(json_array_get(bidask, i), "amount"))); *params.logFile << "<Gemini> order book: " << std::setprecision(6) << v << "@$" << std::setprecision(2) << p << std::endl; tmpVol += v; i++; } double limPrice = 0.0; limPrice = atof(json_string_value(json_object_get(json_array_get(bidask, i-1), "price"))); json_decref(root); return limPrice; } json_t* authRequest(Parameters& params, std::string url, std::string request, std::string options) { struct timeval tv; gettimeofday(&tv, NULL); unsigned long long nonce = (tv.tv_sec * 1000.0) + (tv.tv_usec * 0.001) + 0.5; // check if options parameter is empty std::ostringstream oss; if (options.empty()) { oss << "{\"request\":\"/v1/" << request << "\",\"nonce\":\"" << nonce << "\"}"; } else { oss << "{\"request\":\"/v1/" << request << "\",\"nonce\":\"" << nonce << "\", " << options << "}"; } std::string tmpPayload = base64_encode(reinterpret_cast<const unsigned char*>(oss.str().c_str()), oss.str().length()); oss.clear(); oss.str(""); oss << "X-GEMINI-PAYLOAD:" << tmpPayload; std::string payload; payload = oss.str(); oss.clear(); oss.str(""); // build the signature uint8_t *digest = HMAC(EVP_sha384(), params.geminiSecret.c_str(), params.geminiSecret.size(), (uint8_t*)tmpPayload.c_str(), tmpPayload.size(), NULL, NULL); char mdString[SHA384_DIGEST_LENGTH+100]; // FIXME +100 for (int i = 0; i < SHA384_DIGEST_LENGTH; ++i) { sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]); } oss.clear(); oss.str(""); oss << "X-GEMINI-SIGNATURE:" << mdString; struct curl_slist *headers = NULL; std::string api = "X-GEMINI-APIKEY:" + std::string(params.geminiApi); headers = curl_slist_append(headers, api.c_str()); headers = curl_slist_append(headers, payload.c_str()); headers = curl_slist_append(headers, oss.str().c_str()); CURLcode resCurl; if (params.curl) { std::string readBuffer; curl_easy_setopt(params.curl, CURLOPT_POST, 1L); curl_easy_setopt(params.curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(params.curl, CURLOPT_POSTFIELDS, ""); curl_easy_setopt(params.curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(params.curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(params.curl, CURLOPT_WRITEDATA, &readBuffer); curl_easy_setopt(params.curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(params.curl, CURLOPT_CONNECTTIMEOUT, 10L); resCurl = curl_easy_perform(params.curl); json_t *root; json_error_t error; while (resCurl != CURLE_OK) { *params.logFile << "<Gemini> Error with cURL. Retry in 2 sec..." << std::endl; sleep(2.0); readBuffer = ""; resCurl = curl_easy_perform(params.curl); } root = json_loads(readBuffer.c_str(), 0, &error); while (!root) { *params.logFile << "<Gemini> Error with JSON:\n" << error.text << std::endl; *params.logFile << "<Gemini> Buffer:\n" << readBuffer.c_str() << std::endl; *params.logFile << "<Gemini> Retrying..." << std::endl; sleep(2.0); readBuffer = ""; resCurl = curl_easy_perform(params.curl); while (resCurl != CURLE_OK) { *params.logFile << "<Gemini> Error with cURL. Retry in 2 sec..." << std::endl; sleep(2.0); readBuffer = ""; resCurl = curl_easy_perform(params.curl); } root = json_loads(readBuffer.c_str(), 0, &error); } curl_slist_free_all(headers); curl_easy_reset(params.curl); return root; } else { *params.logFile << "<Gemini> Error with cURL init." << std::endl; return NULL; } } } <commit_msg>No more manual json_t management in gemini.<commit_after>#include "gemini.h" #include "parameters.h" #include "curl_fun.h" #include "utils/restapi.h" #include "utils/base64.h" #include "unique_json.hpp" #include "openssl/sha.h" #include "openssl/hmac.h" #include <unistd.h> #include <math.h> #include <sstream> #include <iomanip> #include <sys/time.h> namespace Gemini { static RestApi& queryHandle(Parameters &params) { static RestApi query ("https://api.gemini.com", params.cacert.c_str(), *params.logFile); return query; } quote_t getQuote(Parameters &params) { auto &exchange = queryHandle(params); unique_json root { exchange.getRequest("/v1/book/BTCUSD") }; const char *quote = json_string_value(json_object_get(json_array_get(json_object_get(root.get(), "bids"), 0), "price")); auto bidValue = quote ? std::stod(quote) : 0.0; quote = json_string_value(json_object_get(json_array_get(json_object_get(root.get(), "asks"), 0), "price")); auto askValue = quote ? std::stod(quote) : 0.0; return std::make_pair(bidValue, askValue); } double getAvail(Parameters& params, std::string currency) { unique_json root { authRequest(params, "https://api.gemini.com/v1/balances", "balances", "") }; while (json_object_get(root.get(), "message") != NULL) { sleep(1.0); *params.logFile << "<Gemini> Error with JSON: " << json_dumps(root.get(), 0) << ". Retrying..." << std::endl; root.reset(authRequest(params, "https://api.gemini.com/v1/balances", "balances", "")); } // go through the list size_t arraySize = json_array_size(root.get()); double availability = 0.0; const char* returnedText; std::string currencyAllCaps; if (currency.compare("btc") == 0) { currencyAllCaps = "BTC"; } else if (currency.compare("usd") == 0) { currencyAllCaps = "USD"; } for (size_t i = 0; i < arraySize; i++) { std::string tmpCurrency = json_string_value(json_object_get(json_array_get(root.get(), i), "currency")); if (tmpCurrency.compare(currencyAllCaps.c_str()) == 0) { returnedText = json_string_value(json_object_get(json_array_get(root.get(), i), "amount")); if (returnedText != NULL) { availability = atof(returnedText); } else { *params.logFile << "<Gemini> Error with the credentials." << std::endl; availability = 0.0; } } } return availability; } std::string sendLongOrder(Parameters& params, std::string direction, double quantity, double price) { *params.logFile << "<Gemini> Trying to send a \"" << direction << "\" limit order: " << std::setprecision(6) << quantity << "@$" << std::setprecision(2) << price << "...\n"; std::ostringstream oss; oss << "\"symbol\":\"BTCUSD\", \"amount\":\"" << quantity << "\", \"price\":\"" << price << "\", \"side\":\"" << direction << "\", \"type\":\"exchange limit\""; std::string options = oss.str(); unique_json root { authRequest(params, "https://api.gemini.com/v1/order/new", "order/new", options) }; std::string orderId = json_string_value(json_object_get(root.get(), "order_id")); *params.logFile << "<Gemini> Done (order ID: " << orderId << ")\n" << std::endl; return orderId; } bool isOrderComplete(Parameters& params, std::string orderId) { if (orderId == "0") return true; auto options = "\"order_id\":" + orderId; unique_json root { authRequest(params, "https://api.gemini.com/v1/order/status", "order/status", options) }; return json_is_false(json_object_get(root.get(), "is_live")); } double getActivePos(Parameters& params) { return getAvail(params, "btc"); } double getLimitPrice(Parameters& params, double volume, bool isBid) { auto &exchange = queryHandle(params); unique_json root { exchange.getRequest("/v1/book/btcusd") }; auto bidask = json_object_get(root.get(), isBid ? "bids" : "asks"); // loop on volume *params.logFile << "<Gemini> Looking for a limit price to fill " << std::setprecision(6) << fabs(volume) << " BTC...\n"; double tmpVol = 0.0; double p = 0.0; double v; int i = 0; while (tmpVol < fabs(volume) * params.orderBookFactor) { p = atof(json_string_value(json_object_get(json_array_get(bidask, i), "price"))); v = atof(json_string_value(json_object_get(json_array_get(bidask, i), "amount"))); *params.logFile << "<Gemini> order book: " << std::setprecision(6) << v << "@$" << std::setprecision(2) << p << std::endl; tmpVol += v; i++; } return p; } json_t* authRequest(Parameters& params, std::string url, std::string request, std::string options) { struct timeval tv; gettimeofday(&tv, NULL); unsigned long long nonce = (tv.tv_sec * 1000.0) + (tv.tv_usec * 0.001) + 0.5; // check if options parameter is empty std::ostringstream oss; if (options.empty()) { oss << "{\"request\":\"/v1/" << request << "\",\"nonce\":\"" << nonce << "\"}"; } else { oss << "{\"request\":\"/v1/" << request << "\",\"nonce\":\"" << nonce << "\", " << options << "}"; } std::string tmpPayload = base64_encode(reinterpret_cast<const unsigned char*>(oss.str().c_str()), oss.str().length()); oss.clear(); oss.str(""); oss << "X-GEMINI-PAYLOAD:" << tmpPayload; std::string payload; payload = oss.str(); oss.clear(); oss.str(""); // build the signature uint8_t *digest = HMAC(EVP_sha384(), params.geminiSecret.c_str(), params.geminiSecret.size(), (uint8_t*)tmpPayload.c_str(), tmpPayload.size(), NULL, NULL); char mdString[SHA384_DIGEST_LENGTH+100]; // FIXME +100 for (int i = 0; i < SHA384_DIGEST_LENGTH; ++i) { sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]); } oss.clear(); oss.str(""); oss << "X-GEMINI-SIGNATURE:" << mdString; struct curl_slist *headers = NULL; std::string api = "X-GEMINI-APIKEY:" + std::string(params.geminiApi); headers = curl_slist_append(headers, api.c_str()); headers = curl_slist_append(headers, payload.c_str()); headers = curl_slist_append(headers, oss.str().c_str()); CURLcode resCurl; if (params.curl) { std::string readBuffer; curl_easy_setopt(params.curl, CURLOPT_POST, 1L); curl_easy_setopt(params.curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(params.curl, CURLOPT_POSTFIELDS, ""); curl_easy_setopt(params.curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(params.curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(params.curl, CURLOPT_WRITEDATA, &readBuffer); curl_easy_setopt(params.curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(params.curl, CURLOPT_CONNECTTIMEOUT, 10L); resCurl = curl_easy_perform(params.curl); json_t *root; json_error_t error; while (resCurl != CURLE_OK) { *params.logFile << "<Gemini> Error with cURL. Retry in 2 sec..." << std::endl; sleep(2.0); readBuffer = ""; resCurl = curl_easy_perform(params.curl); } root = json_loads(readBuffer.c_str(), 0, &error); while (!root) { *params.logFile << "<Gemini> Error with JSON:\n" << error.text << std::endl; *params.logFile << "<Gemini> Buffer:\n" << readBuffer.c_str() << std::endl; *params.logFile << "<Gemini> Retrying..." << std::endl; sleep(2.0); readBuffer = ""; resCurl = curl_easy_perform(params.curl); while (resCurl != CURLE_OK) { *params.logFile << "<Gemini> Error with cURL. Retry in 2 sec..." << std::endl; sleep(2.0); readBuffer = ""; resCurl = curl_easy_perform(params.curl); } root = json_loads(readBuffer.c_str(), 0, &error); } curl_slist_free_all(headers); curl_easy_reset(params.curl); return root; } else { *params.logFile << "<Gemini> Error with cURL init." << std::endl; return NULL; } } } <|endoftext|>
<commit_before>// Copyright 2010-2013 Google // 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 <string> #include "base/integral_types.h" #include "base/logging.h" #include "base/hash.h" #include "base/map_util.h" #include "flatzinc2/model.h" #include "flatzinc2/sat_constraint.h" #include "flatzinc2/solver.h" #include "constraint_solver/constraint_solver.h" #include "util/string_array.h" DECLARE_bool(fz_logging); DECLARE_bool(fz_verbose); DECLARE_bool(fz_debug); DEFINE_bool(use_sat, true, "Use a sat solver for propagating on booleans."); namespace operations_research { IntExpr* FzSolver::GetExpression(const FzArgument& arg) { switch (arg.type) { case FzArgument::INT_VALUE: { return solver_.MakeIntConst(arg.Value()); } case FzArgument::INT_VAR_REF: { return Extract(arg.variables[0]); } default: { LOG(FATAL) << "Cannot extract " << arg.DebugString() << " as a variable"; return nullptr; } } } std::vector<IntVar*> FzSolver::GetVariableArray(const FzArgument& arg) { std::vector<IntVar*> result; if (arg.type == FzArgument::INT_VAR_REF_ARRAY) { result.resize(arg.variables.size()); for (int i = 0; i < arg.variables.size(); ++i) { result[i] = Extract(arg.variables[i])->Var(); } } else if (arg.type == FzArgument::INT_LIST) { result.resize(arg.values.size()); for (int i = 0; i < arg.values.size(); ++i) { result[i] = solver_.MakeIntConst(arg.values[i]); } } else { LOG(FATAL) << "Cannot extract " << arg.DebugString() << " as a variable array"; } return result; } IntExpr* FzSolver::Extract(FzIntegerVariable* var) { IntExpr* result = FindPtrOrNull(extrated_map_, var); if (result != nullptr) { return result; } if (var->domain.IsSingleton()) { result = solver_.MakeIntConst(var->domain.values.back()); } else if (var->IsAllInt64()) { result = solver_.MakeIntVar(kint32min, kint32max, var->name); } else if (var->domain.is_interval) { result = solver_.MakeIntVar(std::max<int64>(var->Min(), kint32min), std::min<int64>(var->Max(), kint32max), var->name); } else { result = solver_.MakeIntVar(var->domain.values, var->name); } FZVLOG << "Extract " << var->DebugString() << FZENDL; FZVLOG << " - created " << result->DebugString() << FZENDL; extrated_map_[var] = result; return result; } void FzSolver::SetExtracted(FzIntegerVariable* fz_var, IntExpr* expr) { CHECK(!ContainsKey(extrated_map_, fz_var)); if (!expr->IsVar() && !fz_var->domain.is_interval) { FZVLOG << " - lift to var" << FZENDL; expr = expr->Var(); } extrated_map_[fz_var] = expr; } // The format is fixed in the flatzinc specification. std::string FzSolver::SolutionString(const FzOnSolutionOutput& output) { if (output.variable != nullptr) { return StringPrintf("%s = %" GG_LL_FORMAT "d;", output.name.c_str(), Extract(output.variable)->Var()->Value()); } else { const int bound_size = output.bounds.size(); std::string result = StringPrintf("%s = array%dd(", output.name.c_str(), bound_size); for (int i = 0; i < bound_size; ++i) { result.append(StringPrintf("%" GG_LL_FORMAT "d..%" GG_LL_FORMAT "d, ", output.bounds[i].min_value, output.bounds[i].max_value)); } result.append("["); for (int i = 0; i < output.flat_variables.size(); ++i) { result.append( StringPrintf("%" GG_LL_FORMAT "d", Extract(output.flat_variables[i])->Var()->Value())); if (i != output.flat_variables.size() - 1) { result.append(", "); } } result.append("]);"); return result; } return ""; } namespace { struct ConstraintWithIo { FzConstraint* ct; int index; hash_set<FzIntegerVariable*> required; ConstraintWithIo(FzConstraint* cte, int i, const hash_set<FzIntegerVariable*>& defined) : ct(cte), index(i) { // Collect required variables. for (const FzArgument& arg : ct->arguments) { for (FzIntegerVariable* const var : arg.variables) { if (var != cte->target_variable && ContainsKey(defined, var)) { required.insert(var); } } } } }; int ComputeWeight(const ConstraintWithIo& ctio) { if (ctio.required.empty()) return 0; if (ctio.ct->target_variable != nullptr) return 1; return 2; } // Comparator to sort constraints based on numbers of required // elements and index. Reverse sorting to put elements to remove at the end. struct ConstraintWithIoComparator { bool operator()(ConstraintWithIo* a, ConstraintWithIo* b) const { const int a_weight = ComputeWeight(*a); const int b_weight = ComputeWeight(*b); if (a_weight > b_weight) { return true; } if (a_weight < b_weight) { return false; } if (a_weight != 1) { return a->index > b->index; } if (ContainsKey(a->required, b->ct->target_variable)) { return true; } if (ContainsKey(b->required, a->ct->target_variable)) { return false; } return false; } }; } // namespace bool FzSolver::Extract() { // Create the sat solver. if (FLAGS_use_sat) { FZLOG << " - Use sat" << FZENDL; sat_ = MakeSatPropagator(&solver_); solver_.AddConstraint(reinterpret_cast<Constraint*>(sat_)); } else { sat_ = nullptr; } // Build statistics. statistics_.BuildStatistics(); // Extract variables. FZLOG << "Extract variables" << FZENDL; int extracted_variables = 0; int skipped_variables = 0; hash_set<FzIntegerVariable*> defined_variables; for (FzIntegerVariable* const var : model_.variables()) { if (var->defining_constraint == nullptr && var->active) { Extract(var); extracted_variables++; } else { FZVLOG << "Skip " << var->DebugString() << FZENDL; if (var->defining_constraint != nullptr) { FZVLOG << " - defined by " << var->defining_constraint->DebugString() << FZENDL; } defined_variables.insert(var); skipped_variables++; } } FZLOG << " - " << extracted_variables << " variables created" << FZENDL; FZLOG << " - " << skipped_variables << " variables skipped" << FZENDL; // Parse model to store info. FZLOG << "Extract constraints" << FZENDL; for (FzConstraint* const ct : model_.constraints()) { if (ct->type == "all_different_int") { StoreAllDifferent(ct->Arg(0).variables); } } // Sort constraints such that defined variables are created before the // extraction of the constraints that use them. int index = 0; std::vector<ConstraintWithIo*> to_sort; std::vector<FzConstraint*> sorted; hash_map<const FzIntegerVariable*, std::vector<ConstraintWithIo*>> dependencies; for (FzConstraint* ct : model_.constraints()) { if (ct != nullptr && ct->active) { ConstraintWithIo* const ctio = new ConstraintWithIo(ct, index++, defined_variables); to_sort.push_back(ctio); for (FzIntegerVariable* const var : ctio->required) { dependencies[var].push_back(ctio); } } } // Sort a first time. std::sort(to_sort.begin(), to_sort.end(), ConstraintWithIoComparator()); // Topological sort. while (!to_sort.empty()) { if (!to_sort.back()->required.empty()) { // Sort again. std::sort(to_sort.begin(), to_sort.end(), ConstraintWithIoComparator()); } ConstraintWithIo* const ctio = to_sort.back(); if (!ctio->required.empty()) { // Recovery. FzIntegerVariable* fz_var = nullptr; if (ctio->required.size() == 1) { fz_var = *ctio->required.begin(); // Pick the only one. } else if (ctio->ct->target_variable != nullptr) { // We prefer to remove the target variable of the constraint. fz_var = ctio->ct->target_variable; } else { fz_var = *ctio->required.begin(); // Pick one. } ctio->ct->target_variable = nullptr; fz_var->defining_constraint = nullptr; if (fz_var != nullptr && ContainsKey(dependencies, fz_var)) { FZDLOG << " - clean " << fz_var->DebugString() << FZENDL; for (ConstraintWithIo* const to_clean : dependencies[fz_var]) { to_clean->required.erase(fz_var); } } continue; } to_sort.pop_back(); FZDLOG << "Pop " << ctio->ct->DebugString() << FZENDL; CHECK(ctio->required.empty()); // TODO(user): Implement recovery mode. sorted.push_back(ctio->ct); FzIntegerVariable* const var = ctio->ct->target_variable; if (var != nullptr && ContainsKey(dependencies, var)) { FZDLOG << " - clean " << var->DebugString() << FZENDL; for (ConstraintWithIo* const to_clean : dependencies[var]) { to_clean->required.erase(var); } } delete ctio; } for (FzConstraint* const ct : sorted) { ExtractConstraint(ct); } FZLOG << " - " << sorted.size() << " constraints created" << FZENDL; // Add domain constraints to created expressions. int domain_constraints = 0; for (FzIntegerVariable* const var : model_.variables()) { if (var->defining_constraint != nullptr && var->active) { const FzDomain& domain = var->domain; IntExpr* const expr = Extract(var); if (expr->IsVar() && domain.is_interval && !domain.values.empty() && (expr->Min() < domain.values[0] || expr->Max() > domain.values[1])) { FZVLOG << "Reduce variable domain of " << expr->DebugString() << " from " << domain.DebugString() << FZENDL; expr->Var()->SetRange(domain.values[0], domain.values[1]); } else if (expr->IsVar() && !domain.is_interval) { FZVLOG << "Reduce variable domain of " << expr->DebugString() << " from " << domain.DebugString() << FZENDL; expr->Var()->SetValues(domain.values); } else if (domain.is_interval && !domain.values.empty() && (expr->Min() < domain.values[0] || expr->Max() > domain.values[1])) { FZVLOG << "Add domain constraint " << domain.DebugString() << " onto " << expr->DebugString() << FZENDL; solver_.AddConstraint(solver_.MakeBetweenCt( expr->Var(), domain.values[0], domain.values[1])); domain_constraints++; } else if (!domain.is_interval) { FZVLOG << "Add domain constraint " << domain.DebugString() << " onto " << expr->DebugString() << FZENDL; solver_.AddConstraint(solver_.MakeMemberCt(expr->Var(), domain.values)); domain_constraints++; } } } FZLOG << " - " << domain_constraints << " domain constraints added" << FZENDL; return true; } // ----- Alldiff info support ----- void FzSolver::StoreAllDifferent(const std::vector<FzIntegerVariable*>& diffs) { std::vector<FzIntegerVariable*> local(diffs); std::sort(local.begin(), local.end()); FZVLOG << "Store AllDifferent info for [" << JoinDebugStringPtr(diffs, ", ") << "]" << FZENDL; alldiffs_[local.front()].push_back(local); } namespace { template <class T> bool EqualVector(const std::vector<T>& v1, const std::vector<T>& v2) { if (v1.size() != v2.size()) return false; for (int i = 0; i < v1.size(); ++i) { if (v1[i] != v2[i]) return false; } return true; } } // namespace bool FzSolver::IsAllDifferent(const std::vector<FzIntegerVariable*>& diffs) const { std::vector<FzIntegerVariable*> local(diffs); std::sort(local.begin(), local.end()); const FzIntegerVariable* const start = local.front(); if (!ContainsKey(alldiffs_, start)) return false; const std::vector<std::vector<FzIntegerVariable*>>& stored = FindOrDie(alldiffs_, start); for (const std::vector<FzIntegerVariable*>& one_diff : stored) { if (EqualVector(local, one_diff)) { return true; } } return false; } } // namespace operations_research <commit_msg>fix crash<commit_after>// Copyright 2010-2013 Google // 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 <string> #include "base/integral_types.h" #include "base/logging.h" #include "base/hash.h" #include "base/map_util.h" #include "flatzinc2/model.h" #include "flatzinc2/sat_constraint.h" #include "flatzinc2/solver.h" #include "constraint_solver/constraint_solver.h" #include "util/string_array.h" DECLARE_bool(fz_logging); DECLARE_bool(fz_verbose); DECLARE_bool(fz_debug); DEFINE_bool(use_sat, true, "Use a sat solver for propagating on booleans."); namespace operations_research { IntExpr* FzSolver::GetExpression(const FzArgument& arg) { switch (arg.type) { case FzArgument::INT_VALUE: { return solver_.MakeIntConst(arg.Value()); } case FzArgument::INT_VAR_REF: { return Extract(arg.variables[0]); } default: { LOG(FATAL) << "Cannot extract " << arg.DebugString() << " as a variable"; return nullptr; } } } std::vector<IntVar*> FzSolver::GetVariableArray(const FzArgument& arg) { std::vector<IntVar*> result; if (arg.type == FzArgument::INT_VAR_REF_ARRAY) { result.resize(arg.variables.size()); for (int i = 0; i < arg.variables.size(); ++i) { result[i] = Extract(arg.variables[i])->Var(); } } else if (arg.type == FzArgument::INT_LIST) { result.resize(arg.values.size()); for (int i = 0; i < arg.values.size(); ++i) { result[i] = solver_.MakeIntConst(arg.values[i]); } } else { LOG(FATAL) << "Cannot extract " << arg.DebugString() << " as a variable array"; } return result; } IntExpr* FzSolver::Extract(FzIntegerVariable* var) { IntExpr* result = FindPtrOrNull(extrated_map_, var); if (result != nullptr) { return result; } if (var->domain.IsSingleton()) { result = solver_.MakeIntConst(var->domain.values.back()); } else if (var->IsAllInt64()) { result = solver_.MakeIntVar(kint32min, kint32max, var->name); } else if (var->domain.is_interval) { result = solver_.MakeIntVar(std::max<int64>(var->Min(), kint32min), std::min<int64>(var->Max(), kint32max), var->name); } else { result = solver_.MakeIntVar(var->domain.values, var->name); } FZVLOG << "Extract " << var->DebugString() << FZENDL; FZVLOG << " - created " << result->DebugString() << FZENDL; extrated_map_[var] = result; return result; } void FzSolver::SetExtracted(FzIntegerVariable* fz_var, IntExpr* expr) { CHECK(!ContainsKey(extrated_map_, fz_var)); if (!expr->IsVar() && !fz_var->domain.is_interval) { FZVLOG << " - lift to var" << FZENDL; expr = expr->Var(); } extrated_map_[fz_var] = expr; } // The format is fixed in the flatzinc specification. std::string FzSolver::SolutionString(const FzOnSolutionOutput& output) { if (output.variable != nullptr) { return StringPrintf("%s = %" GG_LL_FORMAT "d;", output.name.c_str(), Extract(output.variable)->Var()->Value()); } else { const int bound_size = output.bounds.size(); std::string result = StringPrintf("%s = array%dd(", output.name.c_str(), bound_size); for (int i = 0; i < bound_size; ++i) { result.append(StringPrintf("%" GG_LL_FORMAT "d..%" GG_LL_FORMAT "d, ", output.bounds[i].min_value, output.bounds[i].max_value)); } result.append("["); for (int i = 0; i < output.flat_variables.size(); ++i) { result.append( StringPrintf("%" GG_LL_FORMAT "d", Extract(output.flat_variables[i])->Var()->Value())); if (i != output.flat_variables.size() - 1) { result.append(", "); } } result.append("]);"); return result; } return ""; } namespace { struct ConstraintWithIo { FzConstraint* ct; int index; hash_set<FzIntegerVariable*> required; ConstraintWithIo(FzConstraint* cte, int i, const hash_set<FzIntegerVariable*>& defined) : ct(cte), index(i) { // Collect required variables. for (const FzArgument& arg : ct->arguments) { for (FzIntegerVariable* const var : arg.variables) { if (var != cte->target_variable && ContainsKey(defined, var)) { required.insert(var); } } } } }; int ComputeWeight(const ConstraintWithIo& ctio) { if (ctio.required.empty()) return 0; if (ctio.ct->target_variable != nullptr) return 1; return 2; } // Comparator to sort constraints based on numbers of required // elements and index. Reverse sorting to put elements to remove at the end. struct ConstraintWithIoComparator { bool operator()(ConstraintWithIo* a, ConstraintWithIo* b) const { const int a_weight = ComputeWeight(*a); const int b_weight = ComputeWeight(*b); if (a_weight > b_weight) { return true; } if (a_weight < b_weight) { return false; } if (a_weight != 1) { return a->index > b->index; } if (ContainsKey(a->required, b->ct->target_variable)) { return true; } if (ContainsKey(b->required, a->ct->target_variable)) { return false; } return false; } }; } // namespace bool FzSolver::Extract() { // Create the sat solver. if (FLAGS_use_sat) { FZLOG << " - Use sat" << FZENDL; sat_ = MakeSatPropagator(&solver_); solver_.AddConstraint(reinterpret_cast<Constraint*>(sat_)); } else { sat_ = nullptr; } // Build statistics. statistics_.BuildStatistics(); // Extract variables. FZLOG << "Extract variables" << FZENDL; int extracted_variables = 0; int skipped_variables = 0; hash_set<FzIntegerVariable*> defined_variables; for (FzIntegerVariable* const var : model_.variables()) { if (var->defining_constraint == nullptr && var->active) { Extract(var); extracted_variables++; } else { FZVLOG << "Skip " << var->DebugString() << FZENDL; if (var->defining_constraint != nullptr) { FZVLOG << " - defined by " << var->defining_constraint->DebugString() << FZENDL; } defined_variables.insert(var); skipped_variables++; } } FZLOG << " - " << extracted_variables << " variables created" << FZENDL; FZLOG << " - " << skipped_variables << " variables skipped" << FZENDL; // Parse model to store info. FZLOG << "Extract constraints" << FZENDL; for (FzConstraint* const ct : model_.constraints()) { if (ct->type == "all_different_int") { StoreAllDifferent(ct->Arg(0).variables); } } // Sort constraints such that defined variables are created before the // extraction of the constraints that use them. int index = 0; std::vector<ConstraintWithIo*> to_sort; std::vector<FzConstraint*> sorted; hash_map<const FzIntegerVariable*, std::vector<ConstraintWithIo*>> dependencies; for (FzConstraint* ct : model_.constraints()) { if (ct != nullptr && ct->active) { ConstraintWithIo* const ctio = new ConstraintWithIo(ct, index++, defined_variables); to_sort.push_back(ctio); for (FzIntegerVariable* const var : ctio->required) { dependencies[var].push_back(ctio); } } } // Sort a first time. std::sort(to_sort.begin(), to_sort.end(), ConstraintWithIoComparator()); // Topological sort. while (!to_sort.empty()) { if (!to_sort.back()->required.empty()) { // Sort again. std::sort(to_sort.begin(), to_sort.end(), ConstraintWithIoComparator()); } ConstraintWithIo* const ctio = to_sort.back(); if (!ctio->required.empty()) { // Recovery. FzIntegerVariable* fz_var = nullptr; if (ctio->required.size() == 1) { fz_var = *ctio->required.begin(); // Pick the only one. } else if (ctio->ct->target_variable != nullptr) { // We prefer to remove the target variable of the constraint. fz_var = ctio->ct->target_variable; } else { fz_var = *ctio->required.begin(); // Pick one. } ctio->ct->target_variable = nullptr; fz_var->defining_constraint = nullptr; if (fz_var != nullptr && ContainsKey(dependencies, fz_var)) { FZDLOG << " - clean " << fz_var->DebugString() << FZENDL; for (ConstraintWithIo* const to_clean : dependencies[fz_var]) { to_clean->required.erase(fz_var); } } continue; } to_sort.pop_back(); FZDLOG << "Pop " << ctio->ct->DebugString() << FZENDL; CHECK(ctio->required.empty()); // TODO(user): Implement recovery mode. sorted.push_back(ctio->ct); FzIntegerVariable* const var = ctio->ct->target_variable; if (var != nullptr && ContainsKey(dependencies, var)) { FZDLOG << " - clean " << var->DebugString() << FZENDL; for (ConstraintWithIo* const to_clean : dependencies[var]) { to_clean->required.erase(var); } } delete ctio; } for (FzConstraint* const ct : sorted) { ExtractConstraint(ct); } FZLOG << " - " << sorted.size() << " constraints created" << FZENDL; // Add domain constraints to created expressions. int domain_constraints = 0; for (FzIntegerVariable* const var : model_.variables()) { if (var->defining_constraint != nullptr && var->active) { const FzDomain& domain = var->domain; IntExpr* const expr = Extract(var); if (expr->IsVar() && domain.is_interval && !domain.values.empty() && (expr->Min() < domain.values[0] || expr->Max() > domain.values[1])) { FZVLOG << "Reduce variable domain of " << expr->DebugString() << " from " << domain.DebugString() << FZENDL; expr->Var()->SetRange(domain.values[0], domain.values[1]); } else if (expr->IsVar() && !domain.is_interval) { FZVLOG << "Reduce variable domain of " << expr->DebugString() << " from " << domain.DebugString() << FZENDL; expr->Var()->SetValues(domain.values); } else if (domain.is_interval && !domain.values.empty() && (expr->Min() < domain.values[0] || expr->Max() > domain.values[1])) { FZVLOG << "Add domain constraint " << domain.DebugString() << " onto " << expr->DebugString() << FZENDL; solver_.AddConstraint(solver_.MakeBetweenCt( expr->Var(), domain.values[0], domain.values[1])); domain_constraints++; } else if (!domain.is_interval) { FZVLOG << "Add domain constraint " << domain.DebugString() << " onto " << expr->DebugString() << FZENDL; solver_.AddConstraint(solver_.MakeMemberCt(expr->Var(), domain.values)); domain_constraints++; } } } FZLOG << " - " << domain_constraints << " domain constraints added" << FZENDL; return true; } // ----- Alldiff info support ----- void FzSolver::StoreAllDifferent(const std::vector<FzIntegerVariable*>& diffs) { if (!diffs.empty()) { std::vector<FzIntegerVariable*> local(diffs); std::sort(local.begin(), local.end()); FZVLOG << "Store AllDifferent info for [" << JoinDebugStringPtr(diffs, ", ") << "]" << FZENDL; alldiffs_[local.front()].push_back(local); } } namespace { template <class T> bool EqualVector(const std::vector<T>& v1, const std::vector<T>& v2) { if (v1.size() != v2.size()) return false; for (int i = 0; i < v1.size(); ++i) { if (v1[i] != v2[i]) return false; } return true; } } // namespace bool FzSolver::IsAllDifferent(const std::vector<FzIntegerVariable*>& diffs) const { std::vector<FzIntegerVariable*> local(diffs); std::sort(local.begin(), local.end()); const FzIntegerVariable* const start = local.front(); if (!ContainsKey(alldiffs_, start)) return false; const std::vector<std::vector<FzIntegerVariable*>>& stored = FindOrDie(alldiffs_, start); for (const std::vector<FzIntegerVariable*>& one_diff : stored) { if (EqualVector(local, one_diff)) { return true; } } return false; } } // namespace operations_research <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/http_connection.hpp" #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <asio/ip/tcp.hpp> #include <string> using boost::bind; namespace libtorrent { void http_connection::get(std::string const& url, time_duration timeout) { std::string protocol; std::string hostname; std::string path; int port; boost::tie(protocol, hostname, port, path) = parse_url_components(url); std::stringstream headers; headers << "GET " << path << " HTTP/1.0\r\n" "Host:" << hostname << "Connection: close\r\n" "\r\n\r\n"; sendbuffer = headers.str(); start(hostname, boost::lexical_cast<std::string>(port), timeout); } void http_connection::start(std::string const& hostname, std::string const& port , time_duration timeout) { m_timeout = timeout; m_timer.expires_from_now(m_timeout); m_timer.async_wait(bind(&http_connection::on_timeout , boost::weak_ptr<http_connection>(shared_from_this()), _1)); m_called = false; if (m_sock.is_open() && m_hostname == hostname && m_port == port) { m_parser.reset(); asio::async_write(m_sock, asio::buffer(sendbuffer) , bind(&http_connection::on_write, shared_from_this(), _1)); } else { m_sock.close(); tcp::resolver::query query(hostname, port); m_resolver.async_resolve(query, bind(&http_connection::on_resolve , shared_from_this(), _1, _2)); m_hostname = hostname; m_port = port; } } void http_connection::on_timeout(boost::weak_ptr<http_connection> p , asio::error_code const& e) { if (e == asio::error::operation_aborted) return; boost::shared_ptr<http_connection> c = p.lock(); if (!c) return; if (c->m_bottled && c->m_called) return; if (c->m_last_receive + c->m_timeout < time_now()) { c->m_called = true; c->m_handler(asio::error::timed_out, c->m_parser, 0, 0); return; } c->m_timer.expires_at(c->m_last_receive + c->m_timeout); c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1)); } void http_connection::close() { m_timer.cancel(); m_limiter_timer.cancel(); m_sock.close(); m_hostname.clear(); m_port.clear(); } void http_connection::on_resolve(asio::error_code const& e , tcp::resolver::iterator i) { if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } assert(i != tcp::resolver::iterator()); m_sock.async_connect(*i, boost::bind(&http_connection::on_connect , shared_from_this(), _1/*, ++i*/)); } void http_connection::on_connect(asio::error_code const& e /*, tcp::resolver::iterator i*/) { if (!e) { m_last_receive = time_now(); asio::async_write(m_sock, asio::buffer(sendbuffer) , bind(&http_connection::on_write, shared_from_this(), _1)); } /* else if (i != tcp::resolver::iterator()) { // The connection failed. Try the next endpoint in the list. m_sock.close(); m_sock.async_connect(*i, bind(&http_connection::on_connect , shared_from_this(), _1, ++i)); } */ else { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); } } void http_connection::on_write(asio::error_code const& e) { if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } std::string().swap(sendbuffer); m_recvbuffer.resize(4096); int amount_to_read = m_recvbuffer.size() - m_read_pos; if (m_rate_limit > 0 && amount_to_read > m_download_quota) { amount_to_read = m_download_quota; if (m_download_quota == 0) { if (!m_limiter_timer_active) on_assign_bandwidth(asio::error_code()); return; } } m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); } void http_connection::on_read(asio::error_code const& e , std::size_t bytes_transferred) { if (m_rate_limit) { m_download_quota -= bytes_transferred; assert(m_download_quota >= 0); } if (e == asio::error::eof) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(asio::error_code(), m_parser, 0, 0); return; } if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } m_read_pos += bytes_transferred; assert(m_read_pos <= int(m_recvbuffer.size())); if (m_bottled || !m_parser.header_finished()) { libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0] , &m_recvbuffer[0] + m_read_pos); m_parser.incoming(rcv_buf); if (!m_bottled && m_parser.header_finished()) { if (m_read_pos > m_parser.body_start()) m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start() , m_read_pos - m_parser.body_start()); m_read_pos = 0; m_last_receive = time_now(); } else if (m_bottled && m_parser.finished()) { m_timer.cancel(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); } } else { assert(!m_bottled); m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos); m_read_pos = 0; m_last_receive = time_now(); } if (int(m_recvbuffer.size()) == m_read_pos) m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500)); if (m_read_pos == 1024 * 500) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(asio::error::eof, m_parser, 0, 0); return; } int amount_to_read = m_recvbuffer.size() - m_read_pos; if (m_rate_limit > 0 && amount_to_read > m_download_quota) { amount_to_read = m_download_quota; if (m_download_quota == 0) { if (!m_limiter_timer_active) on_assign_bandwidth(asio::error_code()); return; } } m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); } void http_connection::on_assign_bandwidth(asio::error_code const& e) { if ((e == asio::error::operation_aborted && m_limiter_timer_active) || !m_sock.is_open()) { if (!m_bottled || !m_called) m_handler(e, m_parser, 0, 0); } m_limiter_timer_active = false; if (e) return; if (m_download_quota > 0) return; m_download_quota = m_rate_limit / 4; int amount_to_read = m_recvbuffer.size() - m_read_pos; if (amount_to_read > m_download_quota) amount_to_read = m_download_quota; m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); m_limiter_timer_active = true; m_limiter_timer.expires_from_now(milliseconds(250)); m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth , shared_from_this(), _1)); } void http_connection::rate_limit(int limit) { if (!m_limiter_timer_active) { m_limiter_timer_active = true; m_limiter_timer.expires_from_now(milliseconds(250)); m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth , shared_from_this(), _1)); } m_rate_limit = limit; } } <commit_msg>completed previous fix<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/http_connection.hpp" #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <asio/ip/tcp.hpp> #include <string> using boost::bind; namespace libtorrent { void http_connection::get(std::string const& url, time_duration timeout) { std::string protocol; std::string hostname; std::string path; int port; boost::tie(protocol, hostname, port, path) = parse_url_components(url); std::stringstream headers; headers << "GET " << path << " HTTP/1.0\r\n" "Host:" << hostname << "Connection: close\r\n" "\r\n\r\n"; sendbuffer = headers.str(); start(hostname, boost::lexical_cast<std::string>(port), timeout); } void http_connection::start(std::string const& hostname, std::string const& port , time_duration timeout) { m_timeout = timeout; m_timer.expires_from_now(m_timeout); m_timer.async_wait(bind(&http_connection::on_timeout , boost::weak_ptr<http_connection>(shared_from_this()), _1)); m_called = false; if (m_sock.is_open() && m_hostname == hostname && m_port == port) { m_parser.reset(); asio::async_write(m_sock, asio::buffer(sendbuffer) , bind(&http_connection::on_write, shared_from_this(), _1)); } else { m_sock.close(); tcp::resolver::query query(hostname, port); m_resolver.async_resolve(query, bind(&http_connection::on_resolve , shared_from_this(), _1, _2)); m_hostname = hostname; m_port = port; } } void http_connection::on_timeout(boost::weak_ptr<http_connection> p , asio::error_code const& e) { if (e == asio::error::operation_aborted) return; boost::shared_ptr<http_connection> c = p.lock(); if (!c) return; if (c->m_bottled && c->m_called) return; if (c->m_last_receive + c->m_timeout < time_now()) { c->m_called = true; c->m_handler(asio::error::timed_out, c->m_parser, 0, 0); return; } c->m_timer.expires_at(c->m_last_receive + c->m_timeout); c->m_timer.async_wait(bind(&http_connection::on_timeout, p, _1)); } void http_connection::close() { m_timer.cancel(); m_limiter_timer.cancel(); m_sock.close(); m_hostname.clear(); m_port.clear(); } void http_connection::on_resolve(asio::error_code const& e , tcp::resolver::iterator i) { if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } assert(i != tcp::resolver::iterator()); m_sock.async_connect(*i, boost::bind(&http_connection::on_connect , shared_from_this(), _1/*, ++i*/)); } void http_connection::on_connect(asio::error_code const& e /*, tcp::resolver::iterator i*/) { if (!e) { m_last_receive = time_now(); asio::async_write(m_sock, asio::buffer(sendbuffer) , bind(&http_connection::on_write, shared_from_this(), _1)); } /* else if (i != tcp::resolver::iterator()) { // The connection failed. Try the next endpoint in the list. m_sock.close(); m_sock.async_connect(*i, bind(&http_connection::on_connect , shared_from_this(), _1, ++i)); } */ else { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); } } void http_connection::on_write(asio::error_code const& e) { if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } std::string().swap(sendbuffer); m_recvbuffer.resize(4096); int amount_to_read = m_recvbuffer.size() - m_read_pos; if (m_rate_limit > 0 && amount_to_read > m_download_quota) { amount_to_read = m_download_quota; if (m_download_quota == 0) { if (!m_limiter_timer_active) on_assign_bandwidth(asio::error_code()); return; } } m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); } void http_connection::on_read(asio::error_code const& e , std::size_t bytes_transferred) { if (m_rate_limit) { m_download_quota -= bytes_transferred; assert(m_download_quota >= 0); } if (e == asio::error::eof) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(asio::error_code(), m_parser, 0, 0); return; } if (e) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); return; } m_read_pos += bytes_transferred; assert(m_read_pos <= int(m_recvbuffer.size())); if (m_bottled || !m_parser.header_finished()) { libtorrent::buffer::const_interval rcv_buf(&m_recvbuffer[0] , &m_recvbuffer[0] + m_read_pos); m_parser.incoming(rcv_buf); if (!m_bottled && m_parser.header_finished()) { if (m_read_pos > m_parser.body_start()) m_handler(e, m_parser, &m_recvbuffer[0] + m_parser.body_start() , m_read_pos - m_parser.body_start()); m_read_pos = 0; m_last_receive = time_now(); } else if (m_bottled && m_parser.finished()) { m_timer.cancel(); if (m_bottled && m_called) return; m_called = true; m_handler(e, m_parser, 0, 0); } } else { assert(!m_bottled); m_handler(e, m_parser, &m_recvbuffer[0], m_read_pos); m_read_pos = 0; m_last_receive = time_now(); } if (int(m_recvbuffer.size()) == m_read_pos) m_recvbuffer.resize((std::min)(m_read_pos + 2048, 1024*500)); if (m_read_pos == 1024 * 500) { close(); if (m_bottled && m_called) return; m_called = true; m_handler(asio::error::eof, m_parser, 0, 0); return; } int amount_to_read = m_recvbuffer.size() - m_read_pos; if (m_rate_limit > 0 && amount_to_read > m_download_quota) { amount_to_read = m_download_quota; if (m_download_quota == 0) { if (!m_limiter_timer_active) on_assign_bandwidth(asio::error_code()); return; } } m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); } void http_connection::on_assign_bandwidth(asio::error_code const& e) { if ((e == asio::error::operation_aborted && m_limiter_timer_active) || !m_sock.is_open()) { if (!m_bottled || !m_called) m_handler(e, m_parser, 0, 0); return; } m_limiter_timer_active = false; if (e) return; if (m_download_quota > 0) return; m_download_quota = m_rate_limit / 4; int amount_to_read = m_recvbuffer.size() - m_read_pos; if (amount_to_read > m_download_quota) amount_to_read = m_download_quota; m_sock.async_read_some(asio::buffer(&m_recvbuffer[0] + m_read_pos , amount_to_read) , bind(&http_connection::on_read , shared_from_this(), _1, _2)); m_limiter_timer_active = true; m_limiter_timer.expires_from_now(milliseconds(250)); m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth , shared_from_this(), _1)); } void http_connection::rate_limit(int limit) { if (!m_limiter_timer_active) { m_limiter_timer_active = true; m_limiter_timer.expires_from_now(milliseconds(250)); m_limiter_timer.async_wait(bind(&http_connection::on_assign_bandwidth , shared_from_this(), _1)); } m_rate_limit = limit; } } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <cctype> #include <algorithm> #include <stdio.h> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" #include "libtorrent/escape_string.hpp" namespace { using namespace libtorrent; int decode_digit(char c) { if (is_digit(c)) return c - '0'; return unsigned(c) - 'A' + 10; } // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (id[0] != '-' || !is_print(id[1]) || (id[2] < '0') || (id[3] < '0') || (id[4] < '0') || (id[5] < '0') || (id[6] < '0') || id[7] != '-') return boost::optional<fingerprint>(); ret.name[0] = id[1]; ret.name[1] = id[2]; ret.major_version = decode_digit(id[3]); ret.minor_version = decode_digit(id[4]); ret.revision_version = decode_digit(id[5]); ret.tag_version = decode_digit(id[6]); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (!is_alpha(id[0]) && !is_digit(id[0])) return boost::optional<fingerprint>(); if (std::equal(id.begin()+4, id.begin()+6, "--")) { if ((id[1] < '0') || (id[2] < '0') || (id[3] < '0')) return boost::optional<fingerprint>(); ret.major_version = decode_digit(id[1]); ret.minor_version = decode_digit(id[2]); ret.revision_version = decode_digit(id[3]); } else { if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127) return boost::optional<fingerprint>(); ret.major_version = id[1]; ret.minor_version = id[2]; ret.revision_version = id[3]; } ret.name[0] = id[0]; ret.name[1] = 0; ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { char ids[21]; std::copy(id.begin(), id.end(), ids); ids[20] = 0; fingerprint ret("..", 0, 0, 0, 0); ret.name[1] = 0; ret.tag_version = 0; if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version , &ret.revision_version) != 4 || !is_print(ret.name[0])) return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } struct map_entry { char const* id; char const* name; }; // only support BitTorrentSpecification // must be ordered alphabetically map_entry name_map[] = { {"A", "ABC"} , {"AG", "Ares"} , {"AR", "Arctic Torrent"} , {"AV", "Avicora"} , {"AX", "BitPump"} , {"AZ", "Azureus"} , {"A~", "Ares"} , {"BB", "BitBuddy"} , {"BC", "BitComet"} , {"BF", "Bitflu"} , {"BG", "BTG"} , {"BR", "BitRocket"} , {"BS", "BTSlave"} , {"BX", "BittorrentX"} , {"CD", "Enhanced CTorrent"} , {"CT", "CTorrent"} , {"DE", "Deluge"} , {"EB", "EBit"} , {"ES", "electric sheep"} , {"HL", "Halite"} , {"HN", "Hydranode"} , {"KT", "KTorrent"} , {"LC", "LeechCraft"} , {"LK", "Linkage"} , {"LP", "lphant"} , {"LT", "libtorrent"} , {"M", "Mainline"} , {"ML", "MLDonkey"} , {"MO", "Mono Torrent"} , {"MP", "MooPolice"} , {"MR", "Miro"} , {"MT", "Moonlight Torrent"} , {"O", "Osprey Permaseed"} , {"PD", "Pando"} , {"Q", "BTQueue"} , {"QT", "Qt 4"} , {"R", "Tribler"} , {"S", "Shadow"} , {"SB", "Swiftbit"} , {"SN", "ShareNet"} , {"SS", "SwarmScope"} , {"ST", "SymTorrent"} , {"SZ", "Shareaza"} , {"S~", "Shareaza (beta)"} , {"T", "BitTornado"} , {"TN", "Torrent.NET"} , {"TR", "Transmission"} , {"TS", "TorrentStorm"} , {"TT", "TuoTu"} , {"U", "UPnP"} , {"UL", "uLeecher"} , {"UT", "uTorrent"} , {"XL", "Xunlei"} , {"XT", "XanTorrent"} , {"XX", "Xtorrent"} , {"ZT", "ZipTorrent"} , {"lt", "rTorrent"} , {"pX", "pHoeniX"} , {"qB", "qBittorrent"} , {"st", "SharkTorrent"} }; struct generic_map_entry { int offset; char const* id; char const* name; }; // non-standard names generic_map_entry generic_mappings[] = { {0, "Deadman Walking-", "Deadman"} , {5, "Azureus", "Azureus 2.0.3.2"} , {0, "DansClient", "XanTorrent"} , {4, "btfans", "SimpleBT"} , {0, "PRC.P---", "Bittorrent Plus! II"} , {0, "P87.P---", "Bittorrent Plus!"} , {0, "S587Plus", "Bittorrent Plus!"} , {0, "martini", "Martini Man"} , {0, "Plus---", "Bittorrent Plus"} , {0, "turbobt", "TurboBT"} , {0, "a00---0", "Swarmy"} , {0, "a02---0", "Swarmy"} , {0, "T00---0", "Teeweety"} , {0, "BTDWV-", "Deadman Walking"} , {2, "BS", "BitSpirit"} , {0, "Pando-", "Pando"} , {0, "LIME", "LimeWire"} , {0, "btuga", "BTugaXP"} , {0, "oernu", "BTugaXP"} , {0, "Mbrst", "Burst!"} , {0, "PEERAPP", "PeerApp"} , {0, "Plus", "Plus!"} , {0, "-Qt-", "Qt"} , {0, "exbc", "BitComet"} , {0, "DNA", "BitTorrent DNA"} , {0, "-G3", "G3 Torrent"} , {0, "-FG", "FlashGet"} , {0, "-ML", "MLdonkey"} , {0, "XBT", "XBT"} , {0, "OP", "Opera"} , {2, "RS", "Rufus"} , {0, "AZ2500BT", "BitTyrant"} }; bool compare_id(map_entry const& lhs, map_entry const& rhs) { return lhs.id[0] < rhs.id[0] || ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1])); } std::string lookup(fingerprint const& f) { char identity[200]; const int size = sizeof(name_map)/sizeof(name_map[0]); map_entry tmp = {f.name, ""}; map_entry* i = std::lower_bound(name_map, name_map + size , tmp, &compare_id); #ifndef NDEBUG for (int i = 1; i < size; ++i) { TORRENT_ASSERT(compare_id(name_map[i-1] , name_map[i])); } #endif char temp[3]; char const* name = 0; if (i < name_map + size && std::equal(f.name, f.name + 2, i->id)) { name = i->name; } else { // if we don't have this client in the list // just use the one or two letter code memcpy(temp, f.name, 2); temp[2] = 0; name = temp; } int num_chars = snprintf(identity, sizeof(identity), "%s %u.%u.%u", name , f.major_version, f.minor_version, f.revision_version); if (f.tag_version != 0) { snprintf(identity + num_chars, sizeof(identity) - num_chars , ".%u", f.tag_version); } return identity; } bool find_string(unsigned char const* id, char const* search) { return std::equal(search, search + std::strlen(search), id); } } namespace libtorrent { boost::optional<fingerprint> client_fingerprint(peer_id const& p) { // look for azureus style id boost::optional<fingerprint> f; f = parse_az_style(p); if (f) return f; // look for shadow style id f = parse_shadow_style(p); if (f) return f; // look for mainline style id f = parse_mainline_style(p); if (f) return f; return f; } std::string identify_client(peer_id const& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unknown"; // ---------------------- // non standard encodings // ---------------------- int num_generic_mappings = sizeof(generic_mappings) / sizeof(generic_mappings[0]); for (int i = 0; i < num_generic_mappings; ++i) { generic_map_entry const& e = generic_mappings[i]; if (find_string(PID + e.offset, e.id)) return e.name; } if (find_string(PID, "-BOW") && PID[7] == '-') return "Bits on Wheels " + std::string((char const*)PID + 4, (char const*)PID + 7); if (find_string(PID, "eX")) { std::string user((char const*)PID + 2, (char const*)PID + 14); return std::string("eXeem ('") + user.c_str() + "')"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) return "Experimental 3.2.1b2"; if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) return "Experimental 3.1"; // look for azureus style id f = parse_az_style(p); if (f) return lookup(*f); // look for shadow style id f = parse_shadow_style(p); if (f) return lookup(*f); // look for mainline style id f = parse_mainline_style(p); if (f) return lookup(*f); if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) return "Generic"; std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += is_print(char(*i))?*i:'.'; } unknown += "]"; return unknown; } } <commit_msg>added some clients to identify_client<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #include <cctype> #include <algorithm> #include <stdio.h> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" #include "libtorrent/escape_string.hpp" namespace { using namespace libtorrent; int decode_digit(char c) { if (is_digit(c)) return c - '0'; return unsigned(c) - 'A' + 10; } // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (id[0] != '-' || !is_print(id[1]) || (id[2] < '0') || (id[3] < '0') || (id[4] < '0') || (id[5] < '0') || (id[6] < '0') || id[7] != '-') return boost::optional<fingerprint>(); ret.name[0] = id[1]; ret.name[1] = id[2]; ret.major_version = decode_digit(id[3]); ret.minor_version = decode_digit(id[4]); ret.revision_version = decode_digit(id[5]); ret.tag_version = decode_digit(id[6]); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (!is_alpha(id[0]) && !is_digit(id[0])) return boost::optional<fingerprint>(); if (std::equal(id.begin()+4, id.begin()+6, "--")) { if ((id[1] < '0') || (id[2] < '0') || (id[3] < '0')) return boost::optional<fingerprint>(); ret.major_version = decode_digit(id[1]); ret.minor_version = decode_digit(id[2]); ret.revision_version = decode_digit(id[3]); } else { if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127) return boost::optional<fingerprint>(); ret.major_version = id[1]; ret.minor_version = id[2]; ret.revision_version = id[3]; } ret.name[0] = id[0]; ret.name[1] = 0; ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { char ids[21]; std::copy(id.begin(), id.end(), ids); ids[20] = 0; fingerprint ret("..", 0, 0, 0, 0); ret.name[1] = 0; ret.tag_version = 0; if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version , &ret.revision_version) != 4 || !is_print(ret.name[0])) return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } struct map_entry { char const* id; char const* name; }; // only support BitTorrentSpecification // must be ordered alphabetically map_entry name_map[] = { {"A", "ABC"} , {"AG", "Ares"} , {"AR", "Arctic Torrent"} , {"AV", "Avicora"} , {"AX", "BitPump"} , {"AZ", "Azureus"} , {"A~", "Ares"} , {"BB", "BitBuddy"} , {"BC", "BitComet"} , {"BF", "Bitflu"} , {"BG", "BTG"} , {"BR", "BitRocket"} , {"BS", "BTSlave"} , {"BX", "BittorrentX"} , {"CD", "Enhanced CTorrent"} , {"CT", "CTorrent"} , {"DE", "Deluge"} , {"EB", "EBit"} , {"ES", "electric sheep"} , {"HL", "Halite"} , {"HN", "Hydranode"} , {"KT", "KTorrent"} , {"LC", "LeechCraft"} , {"LK", "Linkage"} , {"LP", "lphant"} , {"LT", "libtorrent"} , {"M", "Mainline"} , {"ML", "MLDonkey"} , {"MO", "Mono Torrent"} , {"MP", "MooPolice"} , {"MR", "Miro"} , {"MT", "Moonlight Torrent"} , {"O", "Osprey Permaseed"} , {"PD", "Pando"} , {"Q", "BTQueue"} , {"QD", "QQDownload"} , {"QT", "Qt 4"} , {"R", "Tribler"} , {"S", "Shadow"} , {"SB", "Swiftbit"} , {"SD", "Xunlei"} , {"SN", "ShareNet"} , {"SS", "SwarmScope"} , {"ST", "SymTorrent"} , {"SZ", "Shareaza"} , {"S~", "Shareaza (beta)"} , {"T", "BitTornado"} , {"TN", "Torrent.NET"} , {"TR", "Transmission"} , {"TS", "TorrentStorm"} , {"TT", "TuoTu"} , {"U", "UPnP"} , {"UL", "uLeecher"} , {"UT", "uTorrent"} , {"VG", "Vagaa"} , {"XL", "Xunlei"} , {"XT", "XanTorrent"} , {"XX", "Xtorrent"} , {"ZT", "ZipTorrent"} , {"lt", "rTorrent"} , {"pX", "pHoeniX"} , {"qB", "qBittorrent"} , {"st", "SharkTorrent"} }; struct generic_map_entry { int offset; char const* id; char const* name; }; // non-standard names generic_map_entry generic_mappings[] = { {0, "Deadman Walking-", "Deadman"} , {5, "Azureus", "Azureus 2.0.3.2"} , {0, "DansClient", "XanTorrent"} , {4, "btfans", "SimpleBT"} , {0, "PRC.P---", "Bittorrent Plus! II"} , {0, "P87.P---", "Bittorrent Plus!"} , {0, "S587Plus", "Bittorrent Plus!"} , {0, "martini", "Martini Man"} , {0, "Plus---", "Bittorrent Plus"} , {0, "turbobt", "TurboBT"} , {0, "a00---0", "Swarmy"} , {0, "a02---0", "Swarmy"} , {0, "T00---0", "Teeweety"} , {0, "BTDWV-", "Deadman Walking"} , {2, "BS", "BitSpirit"} , {0, "Pando-", "Pando"} , {0, "LIME", "LimeWire"} , {0, "btuga", "BTugaXP"} , {0, "oernu", "BTugaXP"} , {0, "Mbrst", "Burst!"} , {0, "PEERAPP", "PeerApp"} , {0, "Plus", "Plus!"} , {0, "-Qt-", "Qt"} , {0, "exbc", "BitComet"} , {0, "DNA", "BitTorrent DNA"} , {0, "-G3", "G3 Torrent"} , {0, "-FG", "FlashGet"} , {0, "-ML", "MLdonkey"} , {0, "XBT", "XBT"} , {0, "OP", "Opera"} , {2, "RS", "Rufus"} , {0, "AZ2500BT", "BitTyrant"} }; bool compare_id(map_entry const& lhs, map_entry const& rhs) { return lhs.id[0] < rhs.id[0] || ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1])); } std::string lookup(fingerprint const& f) { char identity[200]; const int size = sizeof(name_map)/sizeof(name_map[0]); map_entry tmp = {f.name, ""}; map_entry* i = std::lower_bound(name_map, name_map + size , tmp, &compare_id); #ifndef NDEBUG for (int i = 1; i < size; ++i) { TORRENT_ASSERT(compare_id(name_map[i-1] , name_map[i])); } #endif char temp[3]; char const* name = 0; if (i < name_map + size && std::equal(f.name, f.name + 2, i->id)) { name = i->name; } else { // if we don't have this client in the list // just use the one or two letter code memcpy(temp, f.name, 2); temp[2] = 0; name = temp; } int num_chars = snprintf(identity, sizeof(identity), "%s %u.%u.%u", name , f.major_version, f.minor_version, f.revision_version); if (f.tag_version != 0) { snprintf(identity + num_chars, sizeof(identity) - num_chars , ".%u", f.tag_version); } return identity; } bool find_string(unsigned char const* id, char const* search) { return std::equal(search, search + std::strlen(search), id); } } namespace libtorrent { boost::optional<fingerprint> client_fingerprint(peer_id const& p) { // look for azureus style id boost::optional<fingerprint> f; f = parse_az_style(p); if (f) return f; // look for shadow style id f = parse_shadow_style(p); if (f) return f; // look for mainline style id f = parse_mainline_style(p); if (f) return f; return f; } std::string identify_client(peer_id const& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unknown"; // ---------------------- // non standard encodings // ---------------------- int num_generic_mappings = sizeof(generic_mappings) / sizeof(generic_mappings[0]); for (int i = 0; i < num_generic_mappings; ++i) { generic_map_entry const& e = generic_mappings[i]; if (find_string(PID + e.offset, e.id)) return e.name; } if (find_string(PID, "-BOW") && PID[7] == '-') return "Bits on Wheels " + std::string((char const*)PID + 4, (char const*)PID + 7); if (find_string(PID, "eX")) { std::string user((char const*)PID + 2, (char const*)PID + 14); return std::string("eXeem ('") + user.c_str() + "')"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) return "Experimental 3.2.1b2"; if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) return "Experimental 3.1"; // look for azureus style id f = parse_az_style(p); if (f) return lookup(*f); // look for shadow style id f = parse_shadow_style(p); if (f) return lookup(*f); // look for mainline style id f = parse_mainline_style(p); if (f) return lookup(*f); if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) return "Generic"; std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += is_print(char(*i))?*i:'.'; } unknown += "]"; return unknown; } } <|endoftext|>
<commit_before>/* Copyright (c) 2014-2015, ArrayFire Copyright (c) 2015 Gábor Mező aka unbornchikken (gabor.mezo@outlook.com) 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 ArrayFire 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 "ext.h" #include "imageprocessing.h" #include "helpers.h" #include "arraywrapper.h" #include "errors.h" #include "guard.h" #include "worker.h" using namespace v8; using namespace std; using namespace node; NAN_METHOD(LoadImage) { NanScope(); try { ARGS_LEN(2); String::Utf8Value str(args[0]); string fn(*str); bool isColor = false; if (args.Length() > 1) { isColor = args[1]->BooleanValue(); } ArrayWrapper::NewAsync( args, [=](){ Guard(); return new af::array(af::loadImage(fn.c_str(), isColor)); }); } FIRE_CATCH; } NAN_METHOD(SaveImage) { NanScope(); try { ARGS_LEN(3); String::Utf8Value str(args[0]); string fn(*str); auto array = *ArrayWrapper::GetArrayAt(args, 1); auto exec = [=]() { Guard(); af::saveImage(fn.c_str(), array); }; auto worker = new Worker<void>(GetCallback(args), move(exec)); NanAsyncQueueWorker(worker); NanReturnUndefined(); } FIRE_CATCH; } NAN_METHOD(ColorSpace) { NanScope(); try { ARGS_LEN(3); auto pArray = ArrayWrapper::GetArrayAt(args, 0); auto to = (af::CSpace)args[1]->Uint32Value(); auto from = (af::CSpace)args[2]->Uint32Value(); Guard(); ArrayWrapper::New(af::colorSpace(*pArray, to, from)); } FIRE_CATCH; } FIRE_SYNC_METHOD_ARR_FLOAT_FLOAT_FLOAT(Gray2RGB, gray2rgb, 1.0f, 1.0f, 1.0f) FIRE_SYNC_METHOD_ARR_FLOAT_FLOAT_FLOAT(RGB2Gray, rgb2gray, 0.2126f, 0.7152f, 0.0722f) FIRE_SYNC_METHOD_ARR(HSV2RGB, hsv2rgb) FIRE_SYNC_METHOD_ARR(RGB2HSV, rgb2hsv) NAN_METHOD(Regions) { NanScope(); try { ARGS_LEN(1); auto pArray = ArrayWrapper::GetArrayAt(args, 0); af::connectivity conn = AF_CONNECTIVITY_4; af::dtype dtype = f32; if (args.Length() > 1) conn = (af::connectivity)args[1]->Uint32Value(); if (args.Length() > 2) dtype = GetDTypeInfo(args[2]).first; Guard(); ArrayWrapper::New(af::regions(*pArray, conn, dtype)); } FIRE_CATCH; } NAN_METHOD(Bilateral) { NanScope(); try { ARGS_LEN(3); auto pArray = ArrayWrapper::GetArrayAt(args, 0); float spatialSigma = args[1]->NumberValue(); float chromaticSigma = args[2]->NumberValue(); bool isColor = false; if (args.Length() > 3) isColor = args[3]->BooleanValue(); Guard(); ArrayWrapper::New(af::bilateral(*pArray, spatialSigma, chromaticSigma, isColor)); } FIRE_CATCH; } #define FIRE_FILT_METHOD(F, f)\ NAN_METHOD(F)\ {\ NanScope();\ try\ {\ ARGS_LEN(1);\ auto pArray = ArrayWrapper::GetArrayAt(args, 0);\ dim_t windLength = 3;\ dim_t windWidth = 3;\ af::borderType edgePad = AF_PAD_ZERO;\ if (args.Length() > 1) windLength = args[1]->Uint32Value();\ if (args.Length() > 2) windWidth = args[2]->Uint32Value();\ if (args.Length() > 3) edgePad = (af::borderType)args[3]->Uint32Value();\ Guard();\ ArrayWrapper::New(af::f(*pArray, windLength, windWidth, edgePad));\ }\ FIRE_CATCH;\ } FIRE_FILT_METHOD(MaxFilt, maxfilt) FIRE_FILT_METHOD(MinFilt, minfilt) FIRE_FILT_METHOD(MedFilt, medfilt) #undef FIRE_FILT_METHOD NAN_METHOD(MeanShift) { NanScope(); try { ARGS_LEN(4); auto pArray = ArrayWrapper::GetArrayAt(args, 0); float spatialSigma = args[1]->NumberValue(); float chromaticSigma = args[2]->NumberValue(); unsigned iter = args[3]->Uint32Value(); bool isColor = false; if (args.Length() > 4) isColor = args[4]->BooleanValue(); Guard(); ArrayWrapper::New(af::meanShift(*pArray, spatialSigma, chromaticSigma, iter, isColor)); } FIRE_CATCH; } NAN_METHOD(Sobel) { NanScope(); try { ARGS_LEN(1); auto pArray = ArrayWrapper::GetArrayAt(args, 0); unsigned kerSize = 3; if (args.Length() > 1) kerSize = args[1]->Uint32Value(); Guard(); af::array dx, dy; af::sobel(dx, dy, *pArray, kerSize); auto result = NanNew<Object>(); result->Set(NanNew(Symbols::DX), ArrayWrapper::New(dx)); result->Set(NanNew(Symbols::DY), ArrayWrapper::New(dy)); NanReturnValue(result); } FIRE_CATCH; } FIRE_SYNC_METHOD_ARR_ARR(HistEqual, histEqual) NAN_METHOD(Histogram) { NanScope(); try { ARGS_LEN(2); auto pArray = ArrayWrapper::GetArrayAt(args, 0); unsigned nbins = args[1]->Uint32Value(); double minval = numeric_limits<double>::min(); double maxval = numeric_limits<double>::max(); if (args.Length() > 2) minval = args[2]->NumberValue(); if (args.Length() > 3) maxval = args[3]->NumberValue(); Guard(); ArrayWrapper::New(af::histogram(*pArray, nbins, minval, maxval)); } FIRE_CATCH; } //AFAPI array resize (const array &in, const dim_t odim0, const dim_t odim1, const interpType method=AF_INTERP_NEAREST) //AFAPI array resize (const float scale, const array &in, const interpType method=AF_INTERP_NEAREST) //AFAPI array resize (const float scale0, const float scale1, const array &in, const interpType method=AF_INTERP_NEAREST) //AFAPI array rotate (const array &in, const float theta, const bool crop=true, const interpType method=AF_INTERP_NEAREST) //AFAPI array scale (const array &in, const float scale0, const float scale1, const dim_t odim0=0, const dim_t odim1=0, const interpType method=AF_INTERP_NEAREST) //AFAPI array skew (const array &in, const float skew0, const float skew1, const dim_t odim0=0, const dim_t odim1=0, const bool inverse=true, const interpType method=AF_INTERP_NEAREST) //AFAPI array transform (const array &in, const array &transform, const dim_t odim0=0, const dim_t odim1=0, const interpType method=AF_INTERP_NEAREST, const bool inverse=true) //AFAPI array translate (const array &in, const float trans0, const float trans1, const dim_t odim0=0, const dim_t odim1=0, const interpType method=AF_INTERP_NEAREST) FIRE_SYNC_METHOD_ARR_ARR(Dilate, dilate) FIRE_SYNC_METHOD_ARR_ARR(Dilate3, dilate3) FIRE_SYNC_METHOD_ARR_ARR(Erode, erode) FIRE_SYNC_METHOD_ARR_ARR(Erode3, erode3) //AFAPI array gaussiankernel (const int rows, const int cols, const double sig_r=0, const double sig_c=0) void InitImageProcessing(v8::Handle<v8::Object> exports) { exports->Set(NanNew("loadImage"), NanNew<FunctionTemplate>(LoadImage)->GetFunction()); exports->Set(NanNew("saveImage"), NanNew<FunctionTemplate>(SaveImage)->GetFunction()); exports->Set(NanNew("colorSpace"), NanNew<FunctionTemplate>(ColorSpace)->GetFunction()); exports->Set(NanNew("gray2rgb"), NanNew<FunctionTemplate>(Gray2RGB)->GetFunction()); exports->Set(NanNew("rgb2gray"), NanNew<FunctionTemplate>(RGB2Gray)->GetFunction()); exports->Set(NanNew("hsv2rgb"), NanNew<FunctionTemplate>(HSV2RGB)->GetFunction()); exports->Set(NanNew("rgb2hsv"), NanNew<FunctionTemplate>(RGB2HSV)->GetFunction()); exports->Set(NanNew("regions"), NanNew<FunctionTemplate>(Regions)->GetFunction()); } <commit_msg>imageprocessing *.*<commit_after>/* Copyright (c) 2014-2015, ArrayFire Copyright (c) 2015 Gábor Mező aka unbornchikken (gabor.mezo@outlook.com) 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 ArrayFire 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 "ext.h" #include "imageprocessing.h" #include "helpers.h" #include "arraywrapper.h" #include "errors.h" #include "guard.h" #include "worker.h" using namespace v8; using namespace std; using namespace node; NAN_METHOD(LoadImage) { NanScope(); try { ARGS_LEN(2); String::Utf8Value str(args[0]); string fn(*str); bool isColor = false; if (args.Length() > 1) { isColor = args[1]->BooleanValue(); } ArrayWrapper::NewAsync( args, [=](){ Guard(); return new af::array(af::loadImage(fn.c_str(), isColor)); }); } FIRE_CATCH; } NAN_METHOD(SaveImage) { NanScope(); try { ARGS_LEN(3); String::Utf8Value str(args[0]); string fn(*str); auto array = *ArrayWrapper::GetArrayAt(args, 1); auto exec = [=]() { Guard(); af::saveImage(fn.c_str(), array); }; auto worker = new Worker<void>(GetCallback(args), move(exec)); NanAsyncQueueWorker(worker); NanReturnUndefined(); } FIRE_CATCH; } NAN_METHOD(ColorSpace) { NanScope(); try { ARGS_LEN(3); auto pArray = ArrayWrapper::GetArrayAt(args, 0); auto to = (af::CSpace)args[1]->Uint32Value(); auto from = (af::CSpace)args[2]->Uint32Value(); Guard(); ArrayWrapper::New(af::colorSpace(*pArray, to, from)); } FIRE_CATCH; } FIRE_SYNC_METHOD_ARR_FLOAT_FLOAT_FLOAT(Gray2RGB, gray2rgb, 1.0f, 1.0f, 1.0f) FIRE_SYNC_METHOD_ARR_FLOAT_FLOAT_FLOAT(RGB2Gray, rgb2gray, 0.2126f, 0.7152f, 0.0722f) FIRE_SYNC_METHOD_ARR(HSV2RGB, hsv2rgb) FIRE_SYNC_METHOD_ARR(RGB2HSV, rgb2hsv) NAN_METHOD(Regions) { NanScope(); try { ARGS_LEN(1); auto pArray = ArrayWrapper::GetArrayAt(args, 0); af::connectivity conn = AF_CONNECTIVITY_4; af::dtype dtype = f32; if (args.Length() > 1) conn = (af::connectivity)args[1]->Uint32Value(); if (args.Length() > 2) dtype = GetDTypeInfo(args[2]).first; Guard(); ArrayWrapper::New(af::regions(*pArray, conn, dtype)); } FIRE_CATCH; } NAN_METHOD(Bilateral) { NanScope(); try { ARGS_LEN(3); auto pArray = ArrayWrapper::GetArrayAt(args, 0); float spatialSigma = args[1]->NumberValue(); float chromaticSigma = args[2]->NumberValue(); bool isColor = false; if (args.Length() > 3) isColor = args[3]->BooleanValue(); Guard(); ArrayWrapper::New(af::bilateral(*pArray, spatialSigma, chromaticSigma, isColor)); } FIRE_CATCH; } #define FIRE_FILT_METHOD(F, f)\ NAN_METHOD(F)\ {\ NanScope();\ try\ {\ ARGS_LEN(1);\ auto pArray = ArrayWrapper::GetArrayAt(args, 0);\ dim_t windLength = 3;\ dim_t windWidth = 3;\ af::borderType edgePad = AF_PAD_ZERO;\ if (args.Length() > 1) windLength = args[1]->Uint32Value();\ if (args.Length() > 2) windWidth = args[2]->Uint32Value();\ if (args.Length() > 3) edgePad = (af::borderType)args[3]->Uint32Value();\ Guard();\ ArrayWrapper::New(af::f(*pArray, windLength, windWidth, edgePad));\ }\ FIRE_CATCH;\ } FIRE_FILT_METHOD(MaxFilt, maxfilt) FIRE_FILT_METHOD(MinFilt, minfilt) FIRE_FILT_METHOD(MedFilt, medfilt) #undef FIRE_FILT_METHOD NAN_METHOD(MeanShift) { NanScope(); try { ARGS_LEN(4); auto pArray = ArrayWrapper::GetArrayAt(args, 0); float spatialSigma = args[1]->NumberValue(); float chromaticSigma = args[2]->NumberValue(); unsigned iter = args[3]->Uint32Value(); bool isColor = false; if (args.Length() > 4) isColor = args[4]->BooleanValue(); Guard(); ArrayWrapper::New(af::meanShift(*pArray, spatialSigma, chromaticSigma, iter, isColor)); } FIRE_CATCH; } NAN_METHOD(Sobel) { NanScope(); try { ARGS_LEN(1); auto pArray = ArrayWrapper::GetArrayAt(args, 0); unsigned kerSize = 3; if (args.Length() > 1) kerSize = args[1]->Uint32Value(); Guard(); af::array dx, dy; af::sobel(dx, dy, *pArray, kerSize); auto result = NanNew<Object>(); result->Set(NanNew(Symbols::DX), ArrayWrapper::New(dx)); result->Set(NanNew(Symbols::DY), ArrayWrapper::New(dy)); NanReturnValue(result); } FIRE_CATCH; } FIRE_SYNC_METHOD_ARR_ARR(HistEqual, histEqual) NAN_METHOD(Histogram) { NanScope(); try { ARGS_LEN(2); auto pArray = ArrayWrapper::GetArrayAt(args, 0); unsigned nbins = args[1]->Uint32Value(); double minval = numeric_limits<double>::min(); double maxval = numeric_limits<double>::max(); if (args.Length() > 2) minval = args[2]->NumberValue(); if (args.Length() > 3) maxval = args[3]->NumberValue(); Guard(); ArrayWrapper::New(af::histogram(*pArray, nbins, minval, maxval)); } FIRE_CATCH; } NAN_METHOD(Resize) { NanScope(); try { ARGS_LEN(2); auto pIn = ArrayWrapper::TryGetArrayAt(args, 0); af::interpType method = AF_INTERP_NEAREST; if (pIn) { dim_t odim0 = args[1]->Uint32Value(); dim_t odim1 = args[2]->Uint32Value(); if (args.Length() > 3) method = (af::interpType)args[3]->Uint32Value(); Guard(); ArrayWrapper::New(af::resize(*pIn, odim0, odim1, method)); } else { pIn = ArrayWrapper::TryGetArrayAt(args, 1); if (pIn) { float scale = args[0]->NumberValue(); if (args.Length() > 2) method = (af::interpType)args[2]->Uint32Value(); Guard(); ArrayWrapper::New(af::resize(scale, *pIn, method)); } else { float scale0 = args[0]->NumberValue(); float scale1 = args[1]->NumberValue(); pIn = ArrayWrapper::GetArrayAt(args, 2); if (args.Length() > 3) method = (af::interpType)args[3]->Uint32Value(); Guard(); ArrayWrapper::New(af::resize(scale0, scale1, *pIn, method)); } } } FIRE_CATCH; } NAN_METHOD(Rotate) { NanScope(); try { ARGS_LEN(2); auto pArray = ArrayWrapper::GetArrayAt(args, 0); float theta = args[1]->NumberValue(); bool crop = true; af::interpType method = AF_INTERP_NEAREST; if (args.Length() > 2) crop = args[2]->BooleanValue(); if (args.Length() > 3) method = (af::interpType)args[3]->Uint32Value(); Guard(); ArrayWrapper::New(af::rotate(*pArray, theta, crop, method)); } FIRE_CATCH; } NAN_METHOD(Scale) { NanScope(); try { ARGS_LEN(3); auto pArray = ArrayWrapper::GetArrayAt(args, 0); float scale0 = args[1]->NumberValue(); float scale1 = args[2]->NumberValue(); dim_t odim0 = 0; dim_t odim1 = 0; af::interpType method = AF_INTERP_NEAREST; if (args.Length() > 3) odim0 = args[3]->Uint32Value(); if (args.Length() > 4) odim1 = args[4]->Uint32Value(); if (args.Length() > 5) method = (af::interpType)args[5]->Uint32Value(); Guard(); ArrayWrapper::New(af::scale(*pArray, scale0, scale1, odim0, odim1, method)); } FIRE_CATCH; } NAN_METHOD(Skew) { NanScope(); try { ARGS_LEN(3); auto pArray = ArrayWrapper::GetArrayAt(args, 0); float skew0 = args[1]->NumberValue(); float skew1 = args[2]->NumberValue(); dim_t odim0 = 0; dim_t odim1 = 0; bool inverse = true; af::interpType method = AF_INTERP_NEAREST; if (args.Length() > 3) odim0 = args[3]->Uint32Value(); if (args.Length() > 4) odim1 = args[4]->Uint32Value(); if (args.Length() > 5) inverse = args[5]->BooleanValue(); if (args.Length() > 6) method = (af::interpType)args[6]->Uint32Value(); Guard(); ArrayWrapper::New(af::skew(*pArray, skew0, skew1, odim0, odim1, inverse, method)); } FIRE_CATCH; } NAN_METHOD(Transform) { NanScope(); try { ARGS_LEN(2); auto pArray1 = ArrayWrapper::GetArrayAt(args, 0); auto pArray2 = ArrayWrapper::GetArrayAt(args, 1); dim_t odim0 = 0; dim_t odim1 = 0; bool inverse = true; af::interpType method = AF_INTERP_NEAREST; if (args.Length() > 2) odim0 = args[2]->Uint32Value(); if (args.Length() > 3) odim1 = args[3]->Uint32Value(); if (args.Length() > 4) inverse = args[4]->BooleanValue(); if (args.Length() > 5) method = (af::interpType)args[5]->Uint32Value(); Guard(); ArrayWrapper::New(af::transform(*pArray1, *pArray2, odim0, odim1, method, inverse)); } FIRE_CATCH; } NAN_METHOD(Translate) { NanScope(); try { ARGS_LEN(3); auto pArray = ArrayWrapper::GetArrayAt(args, 0); float trans0 = args[1]->NumberValue(); float trans1 = args[2]->NumberValue(); dim_t odim0 = 0; dim_t odim1 = 0; af::interpType method = AF_INTERP_NEAREST; if (args.Length() > 3) odim0 = args[3]->Uint32Value(); if (args.Length() > 4) odim1 = args[4]->Uint32Value(); if (args.Length() > 5) method = (af::interpType)args[5]->Uint32Value(); Guard(); ArrayWrapper::New(af::translate(*pArray, trans0, trans1, odim0, odim1, method)); } FIRE_CATCH; } FIRE_SYNC_METHOD_ARR_ARR(Dilate, dilate) FIRE_SYNC_METHOD_ARR_ARR(Dilate3, dilate3) FIRE_SYNC_METHOD_ARR_ARR(Erode, erode) FIRE_SYNC_METHOD_ARR_ARR(Erode3, erode3) NAN_METHOD(GaussianKernel) { NanScope(); try { ARGS_LEN(2); int rows = args[0]->Int32Value(); int cols = args[1]->Int32Value(); double sigR = 0; double sigC = 0; if (args.Length() > 2) sigR = args[2]->NumberValue(); if (args.Length() > 3) sigC = args[3]->NumberValue(); Guard(); ArrayWrapper::New(af::gaussianKernel(rows, cols, sigR, sigC)); } FIRE_CATCH; } void InitImageProcessing(v8::Handle<v8::Object> exports) { exports->Set(NanNew("loadImage"), NanNew<FunctionTemplate>(LoadImage)->GetFunction()); exports->Set(NanNew("saveImage"), NanNew<FunctionTemplate>(SaveImage)->GetFunction()); exports->Set(NanNew("colorSpace"), NanNew<FunctionTemplate>(ColorSpace)->GetFunction()); exports->Set(NanNew("gray2rgb"), NanNew<FunctionTemplate>(Gray2RGB)->GetFunction()); exports->Set(NanNew("rgb2gray"), NanNew<FunctionTemplate>(RGB2Gray)->GetFunction()); exports->Set(NanNew("hsv2rgb"), NanNew<FunctionTemplate>(HSV2RGB)->GetFunction()); exports->Set(NanNew("rgb2hsv"), NanNew<FunctionTemplate>(RGB2HSV)->GetFunction()); exports->Set(NanNew("regions"), NanNew<FunctionTemplate>(Regions)->GetFunction()); exports->Set(NanNew("bilateral"), NanNew<FunctionTemplate>(Bilateral)->GetFunction()); exports->Set(NanNew("maxFilt"), NanNew<FunctionTemplate>(MaxFilt)->GetFunction()); exports->Set(NanNew("minFilt"), NanNew<FunctionTemplate>(MinFilt)->GetFunction()); exports->Set(NanNew("medFilt"), NanNew<FunctionTemplate>(MedFilt)->GetFunction()); exports->Set(NanNew("meanShift"), NanNew<FunctionTemplate>(MeanShift)->GetFunction()); exports->Set(NanNew("sobel"), NanNew<FunctionTemplate>(Sobel)->GetFunction()); exports->Set(NanNew("histEqual"), NanNew<FunctionTemplate>(HistEqual)->GetFunction()); exports->Set(NanNew("histogram"), NanNew<FunctionTemplate>(Histogram)->GetFunction()); exports->Set(NanNew("resize"), NanNew<FunctionTemplate>(Resize)->GetFunction()); exports->Set(NanNew("rotate"), NanNew<FunctionTemplate>(Rotate)->GetFunction()); exports->Set(NanNew("scale"), NanNew<FunctionTemplate>(Scale)->GetFunction()); exports->Set(NanNew("skew"), NanNew<FunctionTemplate>(Skew)->GetFunction()); exports->Set(NanNew("transform"), NanNew<FunctionTemplate>(Transform)->GetFunction()); exports->Set(NanNew("translate"), NanNew<FunctionTemplate>(Translate)->GetFunction()); exports->Set(NanNew("dilate"), NanNew<FunctionTemplate>(Dilate)->GetFunction()); exports->Set(NanNew("dilate3"), NanNew<FunctionTemplate>(Dilate3)->GetFunction()); exports->Set(NanNew("erode"), NanNew<FunctionTemplate>(Erode)->GetFunction()); exports->Set(NanNew("erode3"), NanNew<FunctionTemplate>(Erode3)->GetFunction()); exports->Set(NanNew("gaussianKernel"), NanNew<FunctionTemplate>(GaussianKernel)->GetFunction()); } <|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 "GrGLPath.h" #include "GrGLPathRendering.h" #include "GrGLGpu.h" namespace { inline GrGLubyte verb_to_gl_path_cmd(SkPath::Verb verb) { static const GrGLubyte gTable[] = { GR_GL_MOVE_TO, GR_GL_LINE_TO, GR_GL_QUADRATIC_CURVE_TO, GR_GL_CONIC_CURVE_TO, GR_GL_CUBIC_CURVE_TO, GR_GL_CLOSE_PATH, }; GR_STATIC_ASSERT(0 == SkPath::kMove_Verb); GR_STATIC_ASSERT(1 == SkPath::kLine_Verb); GR_STATIC_ASSERT(2 == SkPath::kQuad_Verb); GR_STATIC_ASSERT(3 == SkPath::kConic_Verb); GR_STATIC_ASSERT(4 == SkPath::kCubic_Verb); GR_STATIC_ASSERT(5 == SkPath::kClose_Verb); SkASSERT(verb >= 0 && (size_t)verb < SK_ARRAY_COUNT(gTable)); return gTable[verb]; } #ifdef SK_DEBUG inline int num_coords(SkPath::Verb verb) { static const int gTable[] = { 2, // move 2, // line 4, // quad 5, // conic 6, // cubic 0, // close }; GR_STATIC_ASSERT(0 == SkPath::kMove_Verb); GR_STATIC_ASSERT(1 == SkPath::kLine_Verb); GR_STATIC_ASSERT(2 == SkPath::kQuad_Verb); GR_STATIC_ASSERT(3 == SkPath::kConic_Verb); GR_STATIC_ASSERT(4 == SkPath::kCubic_Verb); GR_STATIC_ASSERT(5 == SkPath::kClose_Verb); SkASSERT(verb >= 0 && (size_t)verb < SK_ARRAY_COUNT(gTable)); return gTable[verb]; } #endif inline GrGLenum join_to_gl_join(SkPaint::Join join) { static GrGLenum gSkJoinsToGrGLJoins[] = { GR_GL_MITER_REVERT, GR_GL_ROUND, GR_GL_BEVEL }; return gSkJoinsToGrGLJoins[join]; GR_STATIC_ASSERT(0 == SkPaint::kMiter_Join); GR_STATIC_ASSERT(1 == SkPaint::kRound_Join); GR_STATIC_ASSERT(2 == SkPaint::kBevel_Join); GR_STATIC_ASSERT(SK_ARRAY_COUNT(gSkJoinsToGrGLJoins) == SkPaint::kJoinCount); } inline GrGLenum cap_to_gl_cap(SkPaint::Cap cap) { static GrGLenum gSkCapsToGrGLCaps[] = { GR_GL_FLAT, GR_GL_ROUND, GR_GL_SQUARE }; return gSkCapsToGrGLCaps[cap]; GR_STATIC_ASSERT(0 == SkPaint::kButt_Cap); GR_STATIC_ASSERT(1 == SkPaint::kRound_Cap); GR_STATIC_ASSERT(2 == SkPaint::kSquare_Cap); GR_STATIC_ASSERT(SK_ARRAY_COUNT(gSkCapsToGrGLCaps) == SkPaint::kCapCount); } #ifdef SK_DEBUG inline void verify_floats(const float* floats, int count) { for (int i = 0; i < count; ++i) { SkASSERT(!SkScalarIsNaN(SkFloatToScalar(floats[i]))); } } #endif inline void points_to_coords(const SkPoint points[], size_t first_point, size_t amount, GrGLfloat coords[]) { for (size_t i = 0; i < amount; ++i) { coords[i * 2] = SkScalarToFloat(points[first_point + i].fX); coords[i * 2 + 1] = SkScalarToFloat(points[first_point + i].fY); } } template<bool checkForDegenerates> inline bool init_path_object_for_general_path(GrGLGpu* gpu, GrGLuint pathID, const SkPath& skPath) { SkDEBUGCODE(int numCoords = 0); int verbCnt = skPath.countVerbs(); int pointCnt = skPath.countPoints(); int minCoordCnt = pointCnt * 2; SkSTArray<16, GrGLubyte, true> pathCommands(verbCnt); SkSTArray<16, GrGLfloat, true> pathCoords(minCoordCnt); bool lastVerbWasMove = true; // A path with just "close;" means "moveto(0,0); close;" SkPoint points[4]; SkPath::RawIter iter(skPath); SkPath::Verb verb; while ((verb = iter.next(points)) != SkPath::kDone_Verb) { pathCommands.push_back(verb_to_gl_path_cmd(verb)); GrGLfloat coords[6]; int coordsForVerb; switch (verb) { case SkPath::kMove_Verb: if (checkForDegenerates) { lastVerbWasMove = true; } points_to_coords(points, 0, 1, coords); coordsForVerb = 2; break; case SkPath::kLine_Verb: if (checkForDegenerates) { if (SkPath::IsLineDegenerate(points[0], points[1], true)) { return false; } lastVerbWasMove = false; } points_to_coords(points, 1, 1, coords); coordsForVerb = 2; break; case SkPath::kConic_Verb: if (checkForDegenerates) { if (SkPath::IsQuadDegenerate(points[0], points[1], points[2], true)) { return false; } lastVerbWasMove = false; } points_to_coords(points, 1, 2, coords); coords[4] = SkScalarToFloat(iter.conicWeight()); coordsForVerb = 5; break; case SkPath::kQuad_Verb: if (checkForDegenerates) { if (SkPath::IsQuadDegenerate(points[0], points[1], points[2], true)) { return false; } lastVerbWasMove = false; } points_to_coords(points, 1, 2, coords); coordsForVerb = 4; break; case SkPath::kCubic_Verb: if (checkForDegenerates) { if (SkPath::IsCubicDegenerate(points[0], points[1], points[2], points[3], true)) { return false; } lastVerbWasMove = false; } points_to_coords(points, 1, 3, coords); coordsForVerb = 6; break; case SkPath::kClose_Verb: if (checkForDegenerates) { if (lastVerbWasMove) { // Interpret "move(x,y);close;" as "move(x,y);lineto(x,y);close;". // which produces a degenerate segment. return false; } } continue; default: SkASSERT(false); // Not reached. continue; } SkDEBUGCODE(numCoords += num_coords(verb)); SkDEBUGCODE(verify_floats(coords, coordsForVerb)); pathCoords.push_back_n(coordsForVerb, coords); } SkASSERT(verbCnt == pathCommands.count()); SkASSERT(numCoords == pathCoords.count()); GR_GL_CALL(gpu->glInterface(), PathCommands(pathID, pathCommands.count(), &pathCommands[0], pathCoords.count(), GR_GL_FLOAT, &pathCoords[0])); return true; } /* * For now paths only natively support winding and even odd fill types */ static GrPathRendering::FillType convert_skpath_filltype(SkPath::FillType fill) { switch (fill) { default: SkFAIL("Incomplete Switch\n"); case SkPath::kWinding_FillType: case SkPath::kInverseWinding_FillType: return GrPathRendering::kWinding_FillType; case SkPath::kEvenOdd_FillType: case SkPath::kInverseEvenOdd_FillType: return GrPathRendering::kEvenOdd_FillType; } } } // namespace bool GrGLPath::InitPathObjectPathDataCheckingDegenerates(GrGLGpu* gpu, GrGLuint pathID, const SkPath& skPath) { return init_path_object_for_general_path<true>(gpu, pathID, skPath); } void GrGLPath::InitPathObjectPathData(GrGLGpu* gpu, GrGLuint pathID, const SkPath& skPath) { SkASSERT(!skPath.isEmpty()); #ifdef SK_SCALAR_IS_FLOAT // This branch does type punning, converting SkPoint* to GrGLfloat*. if ((skPath.getSegmentMasks() & SkPath::kConic_SegmentMask) == 0) { int verbCnt = skPath.countVerbs(); int pointCnt = skPath.countPoints(); int coordCnt = pointCnt * 2; SkSTArray<16, GrGLubyte, true> pathCommands(verbCnt); SkSTArray<16, GrGLfloat, true> pathCoords(coordCnt); static_assert(sizeof(SkPoint) == sizeof(GrGLfloat) * 2, "sk_point_not_two_floats"); pathCommands.resize_back(verbCnt); pathCoords.resize_back(coordCnt); skPath.getPoints(reinterpret_cast<SkPoint*>(&pathCoords[0]), pointCnt); skPath.getVerbs(&pathCommands[0], verbCnt); SkDEBUGCODE(int verbCoordCnt = 0); for (int i = 0; i < verbCnt; ++i) { SkPath::Verb v = static_cast<SkPath::Verb>(pathCommands[i]); pathCommands[i] = verb_to_gl_path_cmd(v); SkDEBUGCODE(verbCoordCnt += num_coords(v)); } SkASSERT(verbCnt == pathCommands.count()); SkASSERT(verbCoordCnt == pathCoords.count()); SkDEBUGCODE(verify_floats(&pathCoords[0], pathCoords.count())); GR_GL_CALL(gpu->glInterface(), PathCommands(pathID, pathCommands.count(), &pathCommands[0], pathCoords.count(), GR_GL_FLOAT, &pathCoords[0])); return; } #endif SkAssertResult(init_path_object_for_general_path<false>(gpu, pathID, skPath)); } void GrGLPath::InitPathObjectStroke(GrGLGpu* gpu, GrGLuint pathID, const GrStrokeInfo& stroke) { SkASSERT(stroke.needToApply()); SkASSERT(!stroke.isDashed()); SkASSERT(!stroke.isHairlineStyle()); GR_GL_CALL(gpu->glInterface(), PathParameterf(pathID, GR_GL_PATH_STROKE_WIDTH, SkScalarToFloat(stroke.getWidth()))); GR_GL_CALL(gpu->glInterface(), PathParameterf(pathID, GR_GL_PATH_MITER_LIMIT, SkScalarToFloat(stroke.getMiter()))); GrGLenum join = join_to_gl_join(stroke.getJoin()); GR_GL_CALL(gpu->glInterface(), PathParameteri(pathID, GR_GL_PATH_JOIN_STYLE, join)); GrGLenum cap = cap_to_gl_cap(stroke.getCap()); GR_GL_CALL(gpu->glInterface(), PathParameteri(pathID, GR_GL_PATH_END_CAPS, cap)); GR_GL_CALL(gpu->glInterface(), PathParameterf(pathID, GR_GL_PATH_STROKE_BOUND, 0.02f)); } void GrGLPath::InitPathObjectEmptyPath(GrGLGpu* gpu, GrGLuint pathID) { GR_GL_CALL(gpu->glInterface(), PathCommands(pathID, 0, nullptr, 0, GR_GL_FLOAT, nullptr)); } GrGLPath::GrGLPath(GrGLGpu* gpu, const SkPath& origSkPath, const GrStrokeInfo& origStroke) : INHERITED(gpu, origSkPath, origStroke), fPathID(gpu->glPathRendering()->genPaths(1)) { if (origSkPath.isEmpty()) { InitPathObjectEmptyPath(gpu, fPathID); fShouldStroke = false; fShouldFill = false; } else { const SkPath* skPath = &origSkPath; SkTLazy<SkPath> tmpPath; const GrStrokeInfo* stroke = &origStroke; GrStrokeInfo tmpStroke(SkStrokeRec::kFill_InitStyle); if (stroke->isDashed()) { // Skia stroking and NVPR stroking differ with respect to dashing // pattern. // Convert a dashing to either a stroke or a fill. if (stroke->applyDashToPath(tmpPath.init(), &tmpStroke, *skPath)) { skPath = tmpPath.get(); stroke = &tmpStroke; } } bool didInit = false; if (stroke->needToApply() && stroke->getCap() != SkPaint::kButt_Cap) { // Skia stroking and NVPR stroking differ with respect to stroking // end caps of empty subpaths. // Convert stroke to fill if path contains empty subpaths. didInit = InitPathObjectPathDataCheckingDegenerates(gpu, fPathID, *skPath); if (!didInit) { if (!tmpPath.isValid()) { tmpPath.init(); } SkAssertResult(stroke->applyToPath(tmpPath.get(), *skPath)); skPath = tmpPath.get(); tmpStroke.setFillStyle(); stroke = &tmpStroke; } } if (!didInit) { InitPathObjectPathData(gpu, fPathID, *skPath); } fShouldStroke = stroke->needToApply(); fShouldFill = stroke->isFillStyle() || stroke->getStyle() == SkStrokeRec::kStrokeAndFill_Style; fFillType = convert_skpath_filltype(skPath->getFillType()); fBounds = skPath->getBounds(); if (fShouldStroke) { InitPathObjectStroke(gpu, fPathID, *stroke); // FIXME: try to account for stroking, without rasterizing the stroke. fBounds.outset(stroke->getWidth(), stroke->getWidth()); } } this->registerWithCache(); } void GrGLPath::onRelease() { if (0 != fPathID && this->shouldFreeResources()) { static_cast<GrGLGpu*>(this->getGpu())->glPathRendering()->deletePaths(fPathID, 1); fPathID = 0; } INHERITED::onRelease(); } void GrGLPath::onAbandon() { fPathID = 0; INHERITED::onAbandon(); } <commit_msg>Use sktarray.begin() instead of &sktarray[0].<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 "GrGLPath.h" #include "GrGLPathRendering.h" #include "GrGLGpu.h" namespace { inline GrGLubyte verb_to_gl_path_cmd(SkPath::Verb verb) { static const GrGLubyte gTable[] = { GR_GL_MOVE_TO, GR_GL_LINE_TO, GR_GL_QUADRATIC_CURVE_TO, GR_GL_CONIC_CURVE_TO, GR_GL_CUBIC_CURVE_TO, GR_GL_CLOSE_PATH, }; GR_STATIC_ASSERT(0 == SkPath::kMove_Verb); GR_STATIC_ASSERT(1 == SkPath::kLine_Verb); GR_STATIC_ASSERT(2 == SkPath::kQuad_Verb); GR_STATIC_ASSERT(3 == SkPath::kConic_Verb); GR_STATIC_ASSERT(4 == SkPath::kCubic_Verb); GR_STATIC_ASSERT(5 == SkPath::kClose_Verb); SkASSERT(verb >= 0 && (size_t)verb < SK_ARRAY_COUNT(gTable)); return gTable[verb]; } #ifdef SK_DEBUG inline int num_coords(SkPath::Verb verb) { static const int gTable[] = { 2, // move 2, // line 4, // quad 5, // conic 6, // cubic 0, // close }; GR_STATIC_ASSERT(0 == SkPath::kMove_Verb); GR_STATIC_ASSERT(1 == SkPath::kLine_Verb); GR_STATIC_ASSERT(2 == SkPath::kQuad_Verb); GR_STATIC_ASSERT(3 == SkPath::kConic_Verb); GR_STATIC_ASSERT(4 == SkPath::kCubic_Verb); GR_STATIC_ASSERT(5 == SkPath::kClose_Verb); SkASSERT(verb >= 0 && (size_t)verb < SK_ARRAY_COUNT(gTable)); return gTable[verb]; } #endif inline GrGLenum join_to_gl_join(SkPaint::Join join) { static GrGLenum gSkJoinsToGrGLJoins[] = { GR_GL_MITER_REVERT, GR_GL_ROUND, GR_GL_BEVEL }; return gSkJoinsToGrGLJoins[join]; GR_STATIC_ASSERT(0 == SkPaint::kMiter_Join); GR_STATIC_ASSERT(1 == SkPaint::kRound_Join); GR_STATIC_ASSERT(2 == SkPaint::kBevel_Join); GR_STATIC_ASSERT(SK_ARRAY_COUNT(gSkJoinsToGrGLJoins) == SkPaint::kJoinCount); } inline GrGLenum cap_to_gl_cap(SkPaint::Cap cap) { static GrGLenum gSkCapsToGrGLCaps[] = { GR_GL_FLAT, GR_GL_ROUND, GR_GL_SQUARE }; return gSkCapsToGrGLCaps[cap]; GR_STATIC_ASSERT(0 == SkPaint::kButt_Cap); GR_STATIC_ASSERT(1 == SkPaint::kRound_Cap); GR_STATIC_ASSERT(2 == SkPaint::kSquare_Cap); GR_STATIC_ASSERT(SK_ARRAY_COUNT(gSkCapsToGrGLCaps) == SkPaint::kCapCount); } #ifdef SK_DEBUG inline void verify_floats(const float* floats, int count) { for (int i = 0; i < count; ++i) { SkASSERT(!SkScalarIsNaN(SkFloatToScalar(floats[i]))); } } #endif inline void points_to_coords(const SkPoint points[], size_t first_point, size_t amount, GrGLfloat coords[]) { for (size_t i = 0; i < amount; ++i) { coords[i * 2] = SkScalarToFloat(points[first_point + i].fX); coords[i * 2 + 1] = SkScalarToFloat(points[first_point + i].fY); } } template<bool checkForDegenerates> inline bool init_path_object_for_general_path(GrGLGpu* gpu, GrGLuint pathID, const SkPath& skPath) { SkDEBUGCODE(int numCoords = 0); int verbCnt = skPath.countVerbs(); int pointCnt = skPath.countPoints(); int minCoordCnt = pointCnt * 2; SkSTArray<16, GrGLubyte, true> pathCommands(verbCnt); SkSTArray<16, GrGLfloat, true> pathCoords(minCoordCnt); bool lastVerbWasMove = true; // A path with just "close;" means "moveto(0,0); close;" SkPoint points[4]; SkPath::RawIter iter(skPath); SkPath::Verb verb; while ((verb = iter.next(points)) != SkPath::kDone_Verb) { pathCommands.push_back(verb_to_gl_path_cmd(verb)); GrGLfloat coords[6]; int coordsForVerb; switch (verb) { case SkPath::kMove_Verb: if (checkForDegenerates) { lastVerbWasMove = true; } points_to_coords(points, 0, 1, coords); coordsForVerb = 2; break; case SkPath::kLine_Verb: if (checkForDegenerates) { if (SkPath::IsLineDegenerate(points[0], points[1], true)) { return false; } lastVerbWasMove = false; } points_to_coords(points, 1, 1, coords); coordsForVerb = 2; break; case SkPath::kConic_Verb: if (checkForDegenerates) { if (SkPath::IsQuadDegenerate(points[0], points[1], points[2], true)) { return false; } lastVerbWasMove = false; } points_to_coords(points, 1, 2, coords); coords[4] = SkScalarToFloat(iter.conicWeight()); coordsForVerb = 5; break; case SkPath::kQuad_Verb: if (checkForDegenerates) { if (SkPath::IsQuadDegenerate(points[0], points[1], points[2], true)) { return false; } lastVerbWasMove = false; } points_to_coords(points, 1, 2, coords); coordsForVerb = 4; break; case SkPath::kCubic_Verb: if (checkForDegenerates) { if (SkPath::IsCubicDegenerate(points[0], points[1], points[2], points[3], true)) { return false; } lastVerbWasMove = false; } points_to_coords(points, 1, 3, coords); coordsForVerb = 6; break; case SkPath::kClose_Verb: if (checkForDegenerates) { if (lastVerbWasMove) { // Interpret "move(x,y);close;" as "move(x,y);lineto(x,y);close;". // which produces a degenerate segment. return false; } } continue; default: SkASSERT(false); // Not reached. continue; } SkDEBUGCODE(numCoords += num_coords(verb)); SkDEBUGCODE(verify_floats(coords, coordsForVerb)); pathCoords.push_back_n(coordsForVerb, coords); } SkASSERT(verbCnt == pathCommands.count()); SkASSERT(numCoords == pathCoords.count()); GR_GL_CALL(gpu->glInterface(), PathCommands(pathID, pathCommands.count(), pathCommands.begin(), pathCoords.count(), GR_GL_FLOAT, pathCoords.begin())); return true; } /* * For now paths only natively support winding and even odd fill types */ static GrPathRendering::FillType convert_skpath_filltype(SkPath::FillType fill) { switch (fill) { default: SkFAIL("Incomplete Switch\n"); case SkPath::kWinding_FillType: case SkPath::kInverseWinding_FillType: return GrPathRendering::kWinding_FillType; case SkPath::kEvenOdd_FillType: case SkPath::kInverseEvenOdd_FillType: return GrPathRendering::kEvenOdd_FillType; } } } // namespace bool GrGLPath::InitPathObjectPathDataCheckingDegenerates(GrGLGpu* gpu, GrGLuint pathID, const SkPath& skPath) { return init_path_object_for_general_path<true>(gpu, pathID, skPath); } void GrGLPath::InitPathObjectPathData(GrGLGpu* gpu, GrGLuint pathID, const SkPath& skPath) { SkASSERT(!skPath.isEmpty()); #ifdef SK_SCALAR_IS_FLOAT // This branch does type punning, converting SkPoint* to GrGLfloat*. if ((skPath.getSegmentMasks() & SkPath::kConic_SegmentMask) == 0) { int verbCnt = skPath.countVerbs(); int pointCnt = skPath.countPoints(); int coordCnt = pointCnt * 2; SkSTArray<16, GrGLubyte, true> pathCommands(verbCnt); SkSTArray<16, GrGLfloat, true> pathCoords(coordCnt); static_assert(sizeof(SkPoint) == sizeof(GrGLfloat) * 2, "sk_point_not_two_floats"); pathCommands.resize_back(verbCnt); pathCoords.resize_back(coordCnt); skPath.getPoints(reinterpret_cast<SkPoint*>(&pathCoords[0]), pointCnt); skPath.getVerbs(&pathCommands[0], verbCnt); SkDEBUGCODE(int verbCoordCnt = 0); for (int i = 0; i < verbCnt; ++i) { SkPath::Verb v = static_cast<SkPath::Verb>(pathCommands[i]); pathCommands[i] = verb_to_gl_path_cmd(v); SkDEBUGCODE(verbCoordCnt += num_coords(v)); } SkASSERT(verbCnt == pathCommands.count()); SkASSERT(verbCoordCnt == pathCoords.count()); SkDEBUGCODE(verify_floats(&pathCoords[0], pathCoords.count())); GR_GL_CALL(gpu->glInterface(), PathCommands(pathID, pathCommands.count(), &pathCommands[0], pathCoords.count(), GR_GL_FLOAT, &pathCoords[0])); return; } #endif SkAssertResult(init_path_object_for_general_path<false>(gpu, pathID, skPath)); } void GrGLPath::InitPathObjectStroke(GrGLGpu* gpu, GrGLuint pathID, const GrStrokeInfo& stroke) { SkASSERT(stroke.needToApply()); SkASSERT(!stroke.isDashed()); SkASSERT(!stroke.isHairlineStyle()); GR_GL_CALL(gpu->glInterface(), PathParameterf(pathID, GR_GL_PATH_STROKE_WIDTH, SkScalarToFloat(stroke.getWidth()))); GR_GL_CALL(gpu->glInterface(), PathParameterf(pathID, GR_GL_PATH_MITER_LIMIT, SkScalarToFloat(stroke.getMiter()))); GrGLenum join = join_to_gl_join(stroke.getJoin()); GR_GL_CALL(gpu->glInterface(), PathParameteri(pathID, GR_GL_PATH_JOIN_STYLE, join)); GrGLenum cap = cap_to_gl_cap(stroke.getCap()); GR_GL_CALL(gpu->glInterface(), PathParameteri(pathID, GR_GL_PATH_END_CAPS, cap)); GR_GL_CALL(gpu->glInterface(), PathParameterf(pathID, GR_GL_PATH_STROKE_BOUND, 0.02f)); } void GrGLPath::InitPathObjectEmptyPath(GrGLGpu* gpu, GrGLuint pathID) { GR_GL_CALL(gpu->glInterface(), PathCommands(pathID, 0, nullptr, 0, GR_GL_FLOAT, nullptr)); } GrGLPath::GrGLPath(GrGLGpu* gpu, const SkPath& origSkPath, const GrStrokeInfo& origStroke) : INHERITED(gpu, origSkPath, origStroke), fPathID(gpu->glPathRendering()->genPaths(1)) { if (origSkPath.isEmpty()) { InitPathObjectEmptyPath(gpu, fPathID); fShouldStroke = false; fShouldFill = false; } else { const SkPath* skPath = &origSkPath; SkTLazy<SkPath> tmpPath; const GrStrokeInfo* stroke = &origStroke; GrStrokeInfo tmpStroke(SkStrokeRec::kFill_InitStyle); if (stroke->isDashed()) { // Skia stroking and NVPR stroking differ with respect to dashing // pattern. // Convert a dashing to either a stroke or a fill. if (stroke->applyDashToPath(tmpPath.init(), &tmpStroke, *skPath)) { skPath = tmpPath.get(); stroke = &tmpStroke; } } bool didInit = false; if (stroke->needToApply() && stroke->getCap() != SkPaint::kButt_Cap) { // Skia stroking and NVPR stroking differ with respect to stroking // end caps of empty subpaths. // Convert stroke to fill if path contains empty subpaths. didInit = InitPathObjectPathDataCheckingDegenerates(gpu, fPathID, *skPath); if (!didInit) { if (!tmpPath.isValid()) { tmpPath.init(); } SkAssertResult(stroke->applyToPath(tmpPath.get(), *skPath)); skPath = tmpPath.get(); tmpStroke.setFillStyle(); stroke = &tmpStroke; } } if (!didInit) { InitPathObjectPathData(gpu, fPathID, *skPath); } fShouldStroke = stroke->needToApply(); fShouldFill = stroke->isFillStyle() || stroke->getStyle() == SkStrokeRec::kStrokeAndFill_Style; fFillType = convert_skpath_filltype(skPath->getFillType()); fBounds = skPath->getBounds(); if (fShouldStroke) { InitPathObjectStroke(gpu, fPathID, *stroke); // FIXME: try to account for stroking, without rasterizing the stroke. fBounds.outset(stroke->getWidth(), stroke->getWidth()); } } this->registerWithCache(); } void GrGLPath::onRelease() { if (0 != fPathID && this->shouldFreeResources()) { static_cast<GrGLGpu*>(this->getGpu())->glPathRendering()->deletePaths(fPathID, 1); fPathID = 0; } INHERITED::onRelease(); } void GrGLPath::onAbandon() { fPathID = 0; INHERITED::onAbandon(); } <|endoftext|>
<commit_before>/*! * Copyright (c) 2019 by Contributors * \file src/lang/data_layout.cc * \brief Data Layout expression. */ #include <tvm/data_layout.h> #include <tvm/ir_pass.h> namespace tvm { TVM_REGISTER_NODE_TYPE(LayoutNode); TVM_REGISTER_NODE_TYPE(BijectiveLayoutNode); const LayoutAxis LayoutAxis::UPPER_CASE[] = { LayoutAxis('A'), LayoutAxis('B'), LayoutAxis('C'), LayoutAxis('D'), LayoutAxis('E'), LayoutAxis('F'), LayoutAxis('G'), LayoutAxis('H'), LayoutAxis('I'), LayoutAxis('J'), LayoutAxis('K'), LayoutAxis('L'), LayoutAxis('M'), LayoutAxis('N'), LayoutAxis('O'), LayoutAxis('P'), LayoutAxis('Q'), LayoutAxis('R'), LayoutAxis('S'), LayoutAxis('T'), LayoutAxis('U'), LayoutAxis('V'), LayoutAxis('W'), LayoutAxis('X'), LayoutAxis('Y'), LayoutAxis('Z') }; const LayoutAxis LayoutAxis::LOWER_CASE[] = { LayoutAxis('a'), LayoutAxis('b'), LayoutAxis('c'), LayoutAxis('d'), LayoutAxis('e'), LayoutAxis('f'), LayoutAxis('g'), LayoutAxis('h'), LayoutAxis('i'), LayoutAxis('j'), LayoutAxis('k'), LayoutAxis('l'), LayoutAxis('m'), LayoutAxis('n'), LayoutAxis('o'), LayoutAxis('p'), LayoutAxis('q'), LayoutAxis('r'), LayoutAxis('s'), LayoutAxis('t'), LayoutAxis('u'), LayoutAxis('v'), LayoutAxis('w'), LayoutAxis('x'), LayoutAxis('y'), LayoutAxis('z') }; const LayoutAxis& LayoutAxis::Get(const char name) { CHECK((name >= 'A' && name <= 'Z') || (name >= 'a' && name <= 'z')) << "Invalid layout axis name: " << name << ". Has to be A-Z or a-z."; return (name >= 'A' && name <= 'Z') ? LayoutAxis::UPPER_CASE[name-'A'] : LayoutAxis::LOWER_CASE[name-'a']; } const LayoutAxis& LayoutAxis::Get(const IterVar& itvar) { const std::string axis = itvar->var.get()->name_hint; CHECK_EQ(axis.size(), 1) << "Invalid layout axis " << axis; return LayoutAxis::Get(axis[0]); } const LayoutAxis& LayoutAxis::make(const std::string& name) { CHECK_EQ(name.length(), 1) << "Invalid axis " << name; return LayoutAxis::Get(name[0]); } Layout::Layout(const Array<IterVar>& axes) { node_ = make_node<LayoutNode>(); LayoutNode *node = operator->(); node->axes = axes; std::ostringstream repr; for (const IterVar& axis : axes) { if (const auto* factor = axis->dom->extent.as<IntImm>()) { CHECK_GT(factor->value, 0); repr << factor->value; } CHECK_EQ(axis->var.get()->name_hint.size(), 1) << "Invalid layout axis " << axis->var.get()->name_hint; char c = axis->var.get()->name_hint[0]; CHECK((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) << "Invalid layout axis " << c; repr << axis->var.get()->name_hint; } node->name = repr.str(); } Layout::Layout(const std::string& name) { // NOLINT(*) if (name.empty() || name == "__undef__") return; node_ = make_node<LayoutNode>(); LayoutNode *node = operator->(); node->name = name; // parse layout string int32_t factor = 0; for (char c : name) { if (c >= 'A' && c <= 'Z') { CHECK_EQ(factor, 0) << "Invalid layout " << name << ": invalid factor size " << factor << " before dimension " << c; std::string shape_name("_shape"); shape_name.insert(0, 1, c); IterVar axis = IterVarNode::make(Range(Expr(0), Var(shape_name)), Var(std::string(1, c)), kDataPar); node->axes.push_back(axis); } else if (c >= 'a' && c <= 'z') { CHECK_GT(factor, 0) << "Invalid layout " << name << ": invalid factor size " << factor << " for dimension " << c; IterVar axis = IterVarNode::make(Range(Expr(0), Expr(factor)), Var(std::string(1, c)), kDataPar); node->axes.push_back(axis); factor = 0; } else if (c >= '0' && c <= '9') { CHECK(factor >= 0) << "Invalid layout " << name << ": _ is adjacent to a number."; factor = factor * 10 + c - '0'; } else { LOG(FATAL) << "Invalid layout " << name; } } // validate layout std::vector<bool> exist_axis(256, false); for (const IterVar& v : node->axes) { auto axis_str = v->var.get()->name_hint; CHECK_EQ(axis_str.size(), 1); char axis = axis_str[0]; CHECK((axis >= 'a' && axis <= 'z') || (axis >= 'A' && axis <= 'Z')); CHECK(!exist_axis[axis]) << "Invalid layout " << name << ": duplicate axis " << axis; exist_axis[axis] = true; } for (const IterVar& v : node->axes) { char axis = v->var.get()->name_hint[0]; if (axis >= 'a' && axis <= 'z') { CHECK(exist_axis[axis-'a'+'A']) << "Invalid layout " << name << ": missing axis " << axis - 'a' + 'A'; } } } Layout LayoutNode::make(const std::string& layout) { return Layout(layout); } Layout Layout::SubLayout(size_t pos, size_t len) const { if (!defined() || pos > ndim()) return Layout::Undef(); if (pos + len > ndim()) len = ndim() - pos; Array<IterVar> new_layout; const auto axes = operator->()->axes; for (size_t i = pos; i < pos + len; ++i) { new_layout.push_back(axes[i]); } return Layout(new_layout); } Layout Layout::Split(const LayoutAxis &axis, size_t target_pos, int32_t factor) const { if (!defined()) return Layout::Undef(); const std::string& name = operator->()->name; const auto axes = operator->()->axes; CHECK(target_pos <= this->ndim()) << "Invalid split position " << target_pos << " for layout " << name; CHECK(axis.IsPrimal()) << "Cannot split a subordinate axis " << axis; CHECK(this->Contains(axis)) << "Axis " << axis << " does not exist in " << name; CHECK(!this->Contains(axis.ToSubordinate())) << "Axis " << axis << " has already been split in " << name; CHECK(factor > 0) << "Invalid split size " << factor; Array<IterVar> new_layout; for (size_t i = 0; i <= this->ndim(); ++i) { if (i == target_pos) { new_layout.push_back(IterVarNode::make(Range(Expr(0), Expr(factor)), Var(axis.ToSubordinate().name()), kDataPar)); } if (i == this->ndim()) break; new_layout.push_back(axes[i]); } return Layout(new_layout); } int32_t Layout::FactorOf(const LayoutAxis& axis) const { if (!defined()) return -1; const LayoutAxis& sub = axis.ToSubordinate(); if (!this->defined()) return -1; for (const IterVar& itvar : operator->()->axes) { if (sub == LayoutAxis::Get(itvar)) { const auto* factor = itvar->dom->extent.as<IntImm>(); CHECK(factor); return factor->value; } } return -1; } inline bool GetStoreRule(Array<Expr>* rule, const Layout& src_layout, const Layout& dst_layout) { for (size_t i = 0; i < dst_layout.ndim(); ++i) { const auto& store_axis = dst_layout[i]; const IterVar& store_axis_impl = dst_layout->axes[i]; Expr store(0); for (size_t j = 0; j < src_layout.ndim(); ++j) { const auto& orig_axis = src_layout[j]; const IterVar& orig_axis_impl = src_layout->axes[j]; if (store_axis.ToPrimal() == orig_axis.ToPrimal()) { if (orig_axis.IsPrimal()) { Expr orig_var = orig_axis_impl->var; const int32_t factor = src_layout.FactorOf(orig_axis); if (factor > 0) { orig_var = orig_var * Expr(factor); } store = store + orig_var; } else { store = store + orig_axis_impl->var; } } } if (is_zero(store)) { // Not convertible return false; } if (store_axis.IsPrimal()) { const int32_t factor = dst_layout.FactorOf(store_axis); if (factor > 0) { store = store / Expr(factor); } } else { store = store % store_axis_impl->dom->extent; } rule->push_back(store); } return true; } inline Array<Expr> TransformIndex(const Array<Expr>& src_index, const Array<IterVar>& src_axis, const Array<Expr>& transform_rule) { Array<Expr> result; std::unordered_map<const Variable*, Expr> bind_map; for (size_t i = 0; i < src_index.size(); ++i) { bind_map[src_axis[i]->var.get()] = src_index[i]; } for (Expr rule : transform_rule) { result.push_back(ir::Simplify(ir::Substitute(rule, bind_map))); } return result; } Array<Expr> BijectiveLayout::ForwardIndex(const Array<Expr>& src_index) const { CHECK(defined()) << "Cannot operate on an undefined bijective layout."; const BijectiveLayoutNode* self = operator->(); CHECK_EQ(src_index.size(), self->src_layout->axes.size()) << "Input mismatch with layout " << self->src_layout; return TransformIndex(src_index, self->src_layout->axes, self->forward_rule); } Array<Expr> BijectiveLayout::BackwardIndex(const Array<Expr>& dst_index) const { CHECK(defined()) << "Cannot operate on an undefined bijective layout."; const BijectiveLayoutNode* self = operator->(); CHECK_EQ(dst_index.size(), self->dst_layout->axes.size()) << "Output mismatch with layout " << self->dst_layout; return TransformIndex(dst_index, self->dst_layout->axes, self->backward_rule); } inline Array<Expr> TransformShape(const Array<Expr>& src_shape, const Array<IterVar>& src_axis, const Array<IterVar>& target_axis, const Array<Expr>& transform_rule) { CHECK_EQ(src_shape.size(), src_axis.size()); // bind variables for original axes // for major-axis, bind the corresponding size // for minor-axis, simply bind it as 0, so that we can reuse forward/backward_rule, // e.g., (C * 16 + c) / 32 std::unordered_map<const Variable*, Expr> bind_map; for (size_t i = 0; i < src_shape.size(); ++i) { Expr orig_shape = src_shape[i]; IterVar orig_axis = src_axis[i]; if (!LayoutAxis::Get(orig_axis).IsPrimal()) { if (orig_shape.defined()) { const auto* orig_shape_const = orig_shape.as<IntImm>(); const auto* orig_axis_extent = orig_axis->dom->extent.as<IntImm>(); CHECK_EQ(orig_shape_const->value, orig_axis_extent->value) << "Input shape mismatch at index " << i << ". Expected " << orig_axis->dom->extent << ", get " << orig_shape; } bind_map[orig_axis->var.get()] = Expr(0); } else { bind_map[orig_axis->var.get()] = orig_shape; } } // infer the target shape, // for major-axis, use the forward/backward_rule directly, // for minor-axis, simply use the extent. Array<Expr> result; CHECK_EQ(transform_rule.size(), target_axis.size()); for (size_t i = 0; i < transform_rule.size(); ++i) { Expr rule = transform_rule[i]; IterVar axis = target_axis[i]; if (!LayoutAxis::Get(axis).IsPrimal()) { result.push_back(axis->dom->extent); } else { result.push_back(ir::Simplify(ir::Substitute(rule, bind_map))); } } return result; } Array<Expr> BijectiveLayout::ForwardShape(const Array<Expr>& shape) const { CHECK(defined()) << "Cannot operate on an undefined bijective layout."; const BijectiveLayoutNode* self = operator->(); return TransformShape(shape, self->src_layout->axes, self->dst_layout->axes, self->forward_rule); } Array<Expr> BijectiveLayout::BackwardShape(const Array<Expr>& shape) const { CHECK(defined()) << "Cannot operate on an undefined bijective layout."; const BijectiveLayoutNode* self = operator->(); return TransformShape(shape, self->dst_layout->axes, self->src_layout->axes, self->backward_rule); } BijectiveLayout BijectiveLayoutNode::make(const Layout& src_layout, const Layout& dst_layout) { auto n = make_node<BijectiveLayoutNode>(); n->src_layout = src_layout; n->dst_layout = dst_layout; if (!GetStoreRule(&n->forward_rule, n->src_layout, n->dst_layout)) { // not convertible return BijectiveLayout(); } CHECK(GetStoreRule(&n->backward_rule, n->dst_layout, n->src_layout)); return BijectiveLayout(n); } } // namespace tvm <commit_msg>Fix error reporting for missing axis (#2835)<commit_after>/*! * Copyright (c) 2019 by Contributors * \file src/lang/data_layout.cc * \brief Data Layout expression. */ #include <tvm/data_layout.h> #include <tvm/ir_pass.h> #include <cctype> namespace tvm { TVM_REGISTER_NODE_TYPE(LayoutNode); TVM_REGISTER_NODE_TYPE(BijectiveLayoutNode); const LayoutAxis LayoutAxis::UPPER_CASE[] = { LayoutAxis('A'), LayoutAxis('B'), LayoutAxis('C'), LayoutAxis('D'), LayoutAxis('E'), LayoutAxis('F'), LayoutAxis('G'), LayoutAxis('H'), LayoutAxis('I'), LayoutAxis('J'), LayoutAxis('K'), LayoutAxis('L'), LayoutAxis('M'), LayoutAxis('N'), LayoutAxis('O'), LayoutAxis('P'), LayoutAxis('Q'), LayoutAxis('R'), LayoutAxis('S'), LayoutAxis('T'), LayoutAxis('U'), LayoutAxis('V'), LayoutAxis('W'), LayoutAxis('X'), LayoutAxis('Y'), LayoutAxis('Z') }; const LayoutAxis LayoutAxis::LOWER_CASE[] = { LayoutAxis('a'), LayoutAxis('b'), LayoutAxis('c'), LayoutAxis('d'), LayoutAxis('e'), LayoutAxis('f'), LayoutAxis('g'), LayoutAxis('h'), LayoutAxis('i'), LayoutAxis('j'), LayoutAxis('k'), LayoutAxis('l'), LayoutAxis('m'), LayoutAxis('n'), LayoutAxis('o'), LayoutAxis('p'), LayoutAxis('q'), LayoutAxis('r'), LayoutAxis('s'), LayoutAxis('t'), LayoutAxis('u'), LayoutAxis('v'), LayoutAxis('w'), LayoutAxis('x'), LayoutAxis('y'), LayoutAxis('z') }; const LayoutAxis& LayoutAxis::Get(const char name) { CHECK((name >= 'A' && name <= 'Z') || (name >= 'a' && name <= 'z')) << "Invalid layout axis name: " << name << ". Has to be A-Z or a-z."; return (name >= 'A' && name <= 'Z') ? LayoutAxis::UPPER_CASE[name-'A'] : LayoutAxis::LOWER_CASE[name-'a']; } const LayoutAxis& LayoutAxis::Get(const IterVar& itvar) { const std::string axis = itvar->var.get()->name_hint; CHECK_EQ(axis.size(), 1) << "Invalid layout axis " << axis; return LayoutAxis::Get(axis[0]); } const LayoutAxis& LayoutAxis::make(const std::string& name) { CHECK_EQ(name.length(), 1) << "Invalid axis " << name; return LayoutAxis::Get(name[0]); } Layout::Layout(const Array<IterVar>& axes) { node_ = make_node<LayoutNode>(); LayoutNode *node = operator->(); node->axes = axes; std::ostringstream repr; for (const IterVar& axis : axes) { if (const auto* factor = axis->dom->extent.as<IntImm>()) { CHECK_GT(factor->value, 0); repr << factor->value; } CHECK_EQ(axis->var.get()->name_hint.size(), 1) << "Invalid layout axis " << axis->var.get()->name_hint; char c = axis->var.get()->name_hint[0]; CHECK((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) << "Invalid layout axis " << c; repr << axis->var.get()->name_hint; } node->name = repr.str(); } Layout::Layout(const std::string& name) { // NOLINT(*) if (name.empty() || name == "__undef__") return; node_ = make_node<LayoutNode>(); LayoutNode *node = operator->(); node->name = name; // parse layout string int32_t factor = 0; for (char c : name) { if (c >= 'A' && c <= 'Z') { CHECK_EQ(factor, 0) << "Invalid layout " << name << ": invalid factor size " << factor << " before dimension " << c; std::string shape_name("_shape"); shape_name.insert(0, 1, c); IterVar axis = IterVarNode::make(Range(Expr(0), Var(shape_name)), Var(std::string(1, c)), kDataPar); node->axes.push_back(axis); } else if (c >= 'a' && c <= 'z') { CHECK_GT(factor, 0) << "Invalid layout " << name << ": invalid factor size " << factor << " for dimension " << c; IterVar axis = IterVarNode::make(Range(Expr(0), Expr(factor)), Var(std::string(1, c)), kDataPar); node->axes.push_back(axis); factor = 0; } else if (c >= '0' && c <= '9') { CHECK(factor >= 0) << "Invalid layout " << name << ": _ is adjacent to a number."; factor = factor * 10 + c - '0'; } else { LOG(FATAL) << "Invalid layout " << name; } } // validate layout std::vector<bool> exist_axis(256, false); for (const IterVar& v : node->axes) { auto axis_str = v->var.get()->name_hint; CHECK_EQ(axis_str.size(), 1); char axis = axis_str[0]; CHECK((axis >= 'a' && axis <= 'z') || (axis >= 'A' && axis <= 'Z')); CHECK(!exist_axis[axis]) << "Invalid layout " << name << ": duplicate axis " << axis; exist_axis[axis] = true; } for (const IterVar& v : node->axes) { char axis = v->var.get()->name_hint[0]; if (axis >= 'a' && axis <= 'z') { CHECK(exist_axis[axis-'a'+'A']) << "Invalid layout " << name << ": missing axis " << std::toupper(axis); } } } Layout LayoutNode::make(const std::string& layout) { return Layout(layout); } Layout Layout::SubLayout(size_t pos, size_t len) const { if (!defined() || pos > ndim()) return Layout::Undef(); if (pos + len > ndim()) len = ndim() - pos; Array<IterVar> new_layout; const auto axes = operator->()->axes; for (size_t i = pos; i < pos + len; ++i) { new_layout.push_back(axes[i]); } return Layout(new_layout); } Layout Layout::Split(const LayoutAxis &axis, size_t target_pos, int32_t factor) const { if (!defined()) return Layout::Undef(); const std::string& name = operator->()->name; const auto axes = operator->()->axes; CHECK(target_pos <= this->ndim()) << "Invalid split position " << target_pos << " for layout " << name; CHECK(axis.IsPrimal()) << "Cannot split a subordinate axis " << axis; CHECK(this->Contains(axis)) << "Axis " << axis << " does not exist in " << name; CHECK(!this->Contains(axis.ToSubordinate())) << "Axis " << axis << " has already been split in " << name; CHECK(factor > 0) << "Invalid split size " << factor; Array<IterVar> new_layout; for (size_t i = 0; i <= this->ndim(); ++i) { if (i == target_pos) { new_layout.push_back(IterVarNode::make(Range(Expr(0), Expr(factor)), Var(axis.ToSubordinate().name()), kDataPar)); } if (i == this->ndim()) break; new_layout.push_back(axes[i]); } return Layout(new_layout); } int32_t Layout::FactorOf(const LayoutAxis& axis) const { if (!defined()) return -1; const LayoutAxis& sub = axis.ToSubordinate(); if (!this->defined()) return -1; for (const IterVar& itvar : operator->()->axes) { if (sub == LayoutAxis::Get(itvar)) { const auto* factor = itvar->dom->extent.as<IntImm>(); CHECK(factor); return factor->value; } } return -1; } inline bool GetStoreRule(Array<Expr>* rule, const Layout& src_layout, const Layout& dst_layout) { for (size_t i = 0; i < dst_layout.ndim(); ++i) { const auto& store_axis = dst_layout[i]; const IterVar& store_axis_impl = dst_layout->axes[i]; Expr store(0); for (size_t j = 0; j < src_layout.ndim(); ++j) { const auto& orig_axis = src_layout[j]; const IterVar& orig_axis_impl = src_layout->axes[j]; if (store_axis.ToPrimal() == orig_axis.ToPrimal()) { if (orig_axis.IsPrimal()) { Expr orig_var = orig_axis_impl->var; const int32_t factor = src_layout.FactorOf(orig_axis); if (factor > 0) { orig_var = orig_var * Expr(factor); } store = store + orig_var; } else { store = store + orig_axis_impl->var; } } } if (is_zero(store)) { // Not convertible return false; } if (store_axis.IsPrimal()) { const int32_t factor = dst_layout.FactorOf(store_axis); if (factor > 0) { store = store / Expr(factor); } } else { store = store % store_axis_impl->dom->extent; } rule->push_back(store); } return true; } inline Array<Expr> TransformIndex(const Array<Expr>& src_index, const Array<IterVar>& src_axis, const Array<Expr>& transform_rule) { Array<Expr> result; std::unordered_map<const Variable*, Expr> bind_map; for (size_t i = 0; i < src_index.size(); ++i) { bind_map[src_axis[i]->var.get()] = src_index[i]; } for (Expr rule : transform_rule) { result.push_back(ir::Simplify(ir::Substitute(rule, bind_map))); } return result; } Array<Expr> BijectiveLayout::ForwardIndex(const Array<Expr>& src_index) const { CHECK(defined()) << "Cannot operate on an undefined bijective layout."; const BijectiveLayoutNode* self = operator->(); CHECK_EQ(src_index.size(), self->src_layout->axes.size()) << "Input mismatch with layout " << self->src_layout; return TransformIndex(src_index, self->src_layout->axes, self->forward_rule); } Array<Expr> BijectiveLayout::BackwardIndex(const Array<Expr>& dst_index) const { CHECK(defined()) << "Cannot operate on an undefined bijective layout."; const BijectiveLayoutNode* self = operator->(); CHECK_EQ(dst_index.size(), self->dst_layout->axes.size()) << "Output mismatch with layout " << self->dst_layout; return TransformIndex(dst_index, self->dst_layout->axes, self->backward_rule); } inline Array<Expr> TransformShape(const Array<Expr>& src_shape, const Array<IterVar>& src_axis, const Array<IterVar>& target_axis, const Array<Expr>& transform_rule) { CHECK_EQ(src_shape.size(), src_axis.size()); // bind variables for original axes // for major-axis, bind the corresponding size // for minor-axis, simply bind it as 0, so that we can reuse forward/backward_rule, // e.g., (C * 16 + c) / 32 std::unordered_map<const Variable*, Expr> bind_map; for (size_t i = 0; i < src_shape.size(); ++i) { Expr orig_shape = src_shape[i]; IterVar orig_axis = src_axis[i]; if (!LayoutAxis::Get(orig_axis).IsPrimal()) { if (orig_shape.defined()) { const auto* orig_shape_const = orig_shape.as<IntImm>(); const auto* orig_axis_extent = orig_axis->dom->extent.as<IntImm>(); CHECK_EQ(orig_shape_const->value, orig_axis_extent->value) << "Input shape mismatch at index " << i << ". Expected " << orig_axis->dom->extent << ", get " << orig_shape; } bind_map[orig_axis->var.get()] = Expr(0); } else { bind_map[orig_axis->var.get()] = orig_shape; } } // infer the target shape, // for major-axis, use the forward/backward_rule directly, // for minor-axis, simply use the extent. Array<Expr> result; CHECK_EQ(transform_rule.size(), target_axis.size()); for (size_t i = 0; i < transform_rule.size(); ++i) { Expr rule = transform_rule[i]; IterVar axis = target_axis[i]; if (!LayoutAxis::Get(axis).IsPrimal()) { result.push_back(axis->dom->extent); } else { result.push_back(ir::Simplify(ir::Substitute(rule, bind_map))); } } return result; } Array<Expr> BijectiveLayout::ForwardShape(const Array<Expr>& shape) const { CHECK(defined()) << "Cannot operate on an undefined bijective layout."; const BijectiveLayoutNode* self = operator->(); return TransformShape(shape, self->src_layout->axes, self->dst_layout->axes, self->forward_rule); } Array<Expr> BijectiveLayout::BackwardShape(const Array<Expr>& shape) const { CHECK(defined()) << "Cannot operate on an undefined bijective layout."; const BijectiveLayoutNode* self = operator->(); return TransformShape(shape, self->dst_layout->axes, self->src_layout->axes, self->backward_rule); } BijectiveLayout BijectiveLayoutNode::make(const Layout& src_layout, const Layout& dst_layout) { auto n = make_node<BijectiveLayoutNode>(); n->src_layout = src_layout; n->dst_layout = dst_layout; if (!GetStoreRule(&n->forward_rule, n->src_layout, n->dst_layout)) { // not convertible return BijectiveLayout(); } CHECK(GetStoreRule(&n->backward_rule, n->dst_layout, n->src_layout)); return BijectiveLayout(n); } } // namespace tvm <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ /* libwpd * Copyright (C) 2002 William Lachance (wrlach@gmail.com) * Copyright (C) 2002 Marc Maurer (uwog@uwog.net) * Copyright (C) 2006-2007 Fridrich Strba (fridrich.strba@bluewin.ch) * * 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; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * For further information visit http://libwpd.sourceforge.net */ /* "This product is not manufactured, approved, or supported by * Corel Corporation or Corel Corporation Limited." */ #include <math.h> #include <algorithm> #include "WPXPageSpan.h" #include "libwpd_internal.h" const double WPX_DEFAULT_PAGE_MARGIN_TOP = 1.0; const double WPX_DEFAULT_PAGE_MARGIN_BOTTOM = 1.0; const uint8_t DUMMY_INTERNAL_HEADER_FOOTER = 16; // precondition: 0 <= headerFooterType <= 3 (i.e.: we don't handle watermarks here) WPXHeaderFooter::WPXHeaderFooter(const WPXHeaderFooterType headerFooterType, const WPXHeaderFooterOccurence occurence, const uint8_t internalType, const WPXSubDocument *subDocument, WPXTableList tableList) : m_type(headerFooterType), m_occurence(occurence), m_internalType(internalType), m_subDocument(subDocument), m_tableList(tableList) { } WPXHeaderFooter::WPXHeaderFooter(const WPXHeaderFooterType headerFooterType, const WPXHeaderFooterOccurence occurence, const uint8_t internalType, const WPXSubDocument *subDocument) : m_type(headerFooterType), m_occurence(occurence), m_internalType(internalType), m_subDocument(subDocument), m_tableList() { } WPXHeaderFooter::WPXHeaderFooter(const WPXHeaderFooter &headerFooter) : m_type(headerFooter.getType()), m_occurence(headerFooter.getOccurence()), m_internalType(headerFooter.getInternalType()), m_subDocument(headerFooter.getSubDocument()), m_tableList(headerFooter.getTableList()) { } WPXHeaderFooter &WPXHeaderFooter::operator=(const WPXHeaderFooter &headerFooter) { m_type = headerFooter.getType(); m_occurence = headerFooter.getOccurence(); m_internalType = headerFooter.getInternalType(); m_subDocument = headerFooter.getSubDocument(); m_tableList = headerFooter.getTableList(); return *this; } WPXHeaderFooter::~WPXHeaderFooter() { // delete m_subDocument; } WPXPageSpan::WPXPageSpan() : m_isPageNumberSuppressed(false), m_formLength(11.0), m_formWidth(8.5f), m_formOrientation(PORTRAIT), m_marginLeft(1.0), m_marginRight(1.0), m_marginTop(WPX_DEFAULT_PAGE_MARGIN_TOP), m_marginBottom(WPX_DEFAULT_PAGE_MARGIN_BOTTOM), m_pageNumberPosition(PAGENUMBER_POSITION_NONE), m_isPageNumberOverridden(false), m_pageNumberOverride(0), m_pageNumberingType(ARABIC), m_pageNumberingFontName(/*WP6_DEFAULT_FONT_NAME*/"Times New Roman"), // EN PAS DEFAULT FONT AAN VOOR WP5/6/etc m_pageNumberingFontSize(12.0/*WP6_DEFAULT_FONT_SIZE*/), // FIXME ME!!!!!!!!!!!!!!!!!!! HELP WP6_DEFAULT_FONT_SIZE m_headerFooterList(), m_pageSpan(1) { for (int i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) m_isHeaderFooterSuppressed[i]=false; } // NB: this is not a literal "clone" function: it is contingent on the side margins that are passed, // and suppression and override variables are not copied WPXPageSpan::WPXPageSpan(const WPXPageSpan &page, double paragraphMarginLeft, double paragraphMarginRight) : m_isPageNumberSuppressed(false), m_formLength(page.getFormLength()), m_formWidth(page.getFormWidth()), m_formOrientation(page.getFormOrientation()), m_marginLeft(page.getMarginLeft()+paragraphMarginLeft), m_marginRight(page.getMarginRight()+paragraphMarginRight), m_marginTop(page.getMarginTop()), m_marginBottom(page.getMarginBottom()), m_pageNumberPosition(page.getPageNumberPosition()), m_isPageNumberOverridden(false), m_pageNumberOverride(0), m_pageNumberingType(page.getPageNumberingType()), m_pageNumberingFontName(page.getPageNumberingFontName()), m_pageNumberingFontSize(page.getPageNumberingFontSize()), m_headerFooterList(page.getHeaderFooterList()), m_pageSpan(page.getPageSpan()) { for (int i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) m_isHeaderFooterSuppressed[i] = false; } WPXPageSpan::~WPXPageSpan() { } void WPXPageSpan::setHeaderFooter(const WPXHeaderFooterType type, const uint8_t headerFooterType, const WPXHeaderFooterOccurence occurence, const WPXSubDocument *subDocument, WPXTableList tableList) { WPXHeaderFooter headerFooter(type, occurence, headerFooterType, subDocument, tableList); switch (occurence) { case ALL: case NEVER: _removeHeaderFooter(type, ODD); _removeHeaderFooter(type, EVEN); _removeHeaderFooter(type, ALL); break; case ODD: _removeHeaderFooter(type, ODD); _removeHeaderFooter(type, ALL); break; case EVEN: _removeHeaderFooter(type, EVEN); _removeHeaderFooter(type, ALL); break; } if ((occurence != NEVER) && (subDocument)) m_headerFooterList.push_back(headerFooter); bool containsHFLeft = _containsHeaderFooter(type, ODD); bool containsHFRight = _containsHeaderFooter(type, EVEN); WPD_DEBUG_MSG(("Contains HFL: %i HFR: %i\n", containsHFLeft, containsHFRight)); if (containsHFLeft && !containsHFRight) { WPD_DEBUG_MSG(("Inserting dummy header right\n")); WPXHeaderFooter dummyHeader(type, EVEN, DUMMY_INTERNAL_HEADER_FOOTER, 0); m_headerFooterList.push_back(dummyHeader); } else if (!containsHFLeft && containsHFRight) { WPD_DEBUG_MSG(("Inserting dummy header left\n")); WPXHeaderFooter dummyHeader(type, ODD, DUMMY_INTERNAL_HEADER_FOOTER, 0); m_headerFooterList.push_back(dummyHeader); } } void WPXPageSpan::_removeHeaderFooter(WPXHeaderFooterType type, WPXHeaderFooterOccurence occurence) { for (std::vector<WPXHeaderFooter>::iterator iter = m_headerFooterList.begin(); iter != m_headerFooterList.end(); iter++) { if ((*iter).getType() == type && (*iter).getOccurence() == occurence) { WPD_DEBUG_MSG(("WordPerfect: Removing header/footer element of type: %i since it is identical to %i\n",(*iter).getType(), type)); m_headerFooterList.erase(iter); return; } } } bool WPXPageSpan::_containsHeaderFooter(WPXHeaderFooterType type, WPXHeaderFooterOccurence occurence) { for (std::vector<WPXHeaderFooter>::iterator iter = m_headerFooterList.begin(); iter != m_headerFooterList.end(); iter++) { if ((*iter).getType()==type && (*iter).getOccurence()==occurence) return true; } return false; } inline bool operator==(const WPXHeaderFooter &headerFooter1, const WPXHeaderFooter &headerFooter2) { return ((headerFooter1.getType() == headerFooter2.getType()) && (headerFooter1.getSubDocument() == headerFooter2.getSubDocument()) && (headerFooter1.getOccurence() == headerFooter2.getOccurence()) && (headerFooter1.getInternalType() == headerFooter2.getInternalType()) ); } bool operator==(const WPXPageSpan &page1, const WPXPageSpan &page2) { if ((page1.getMarginLeft() != page2.getMarginLeft()) || (page1.getMarginRight() != page2.getMarginRight()) || (page1.getMarginTop() != page2.getMarginTop())|| (page1.getMarginBottom() != page2.getMarginBottom())) return false; if (page1.getPageNumberPosition() != page2.getPageNumberPosition()) return false; if (page1.getPageNumberSuppression() != page2.getPageNumberSuppression()) return false; if (page1.getPageNumberOverriden() != page2.getPageNumberOverriden() || page1.getPageNumberOverride() != page2.getPageNumberOverride()) return false; if (page1.getPageNumberingType() != page2.getPageNumberingType()) return false; if (page1.getPageNumberingFontName() != page2.getPageNumberingFontName() || page1.getPageNumberingFontSize() != page2.getPageNumberingFontSize()) return false; for (uint8_t i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) { if (page1.getHeaderFooterSuppression(i) != page2.getHeaderFooterSuppression(i)) return false; } // NOTE: yes this is O(n^2): so what? n=4 at most const std::vector<WPXHeaderFooter> headerFooterList1 = page1.getHeaderFooterList(); const std::vector<WPXHeaderFooter> headerFooterList2 = page2.getHeaderFooterList(); std::vector<WPXHeaderFooter>::const_iterator iter1; std::vector<WPXHeaderFooter>::const_iterator iter2; for (iter1 = headerFooterList1.begin(); iter1 != headerFooterList1.end(); iter1++) { if (std::find(headerFooterList2.begin(), headerFooterList2.end(), (*iter1)) == headerFooterList2.end()) return false; } // If we came here, we know that every header/footer that is found in the first page span is in the second too. // But this is not enought for us to know whether the page spans are equal. Now we have to check in addition // whether every header/footer that is in the second one is in the first too. If someone wants to optimize this, // (s)he is most welcome :-) for (iter2 = headerFooterList2.begin(); iter2 != headerFooterList2.end(); iter2++) { if (std::find(headerFooterList1.begin(), headerFooterList1.end(), (*iter2)) == headerFooterList1.end()) return false; } WPD_DEBUG_MSG(("WordPerfect: WPXPageSpan == comparison finished, found no differences\n")); return true; } /* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */ <commit_msg>coverity: protect against self-assignment<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ /* libwpd * Copyright (C) 2002 William Lachance (wrlach@gmail.com) * Copyright (C) 2002 Marc Maurer (uwog@uwog.net) * Copyright (C) 2006-2007 Fridrich Strba (fridrich.strba@bluewin.ch) * * 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; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * For further information visit http://libwpd.sourceforge.net */ /* "This product is not manufactured, approved, or supported by * Corel Corporation or Corel Corporation Limited." */ #include <math.h> #include <algorithm> #include "WPXPageSpan.h" #include "libwpd_internal.h" const double WPX_DEFAULT_PAGE_MARGIN_TOP = 1.0; const double WPX_DEFAULT_PAGE_MARGIN_BOTTOM = 1.0; const uint8_t DUMMY_INTERNAL_HEADER_FOOTER = 16; // precondition: 0 <= headerFooterType <= 3 (i.e.: we don't handle watermarks here) WPXHeaderFooter::WPXHeaderFooter(const WPXHeaderFooterType headerFooterType, const WPXHeaderFooterOccurence occurence, const uint8_t internalType, const WPXSubDocument *subDocument, WPXTableList tableList) : m_type(headerFooterType), m_occurence(occurence), m_internalType(internalType), m_subDocument(subDocument), m_tableList(tableList) { } WPXHeaderFooter::WPXHeaderFooter(const WPXHeaderFooterType headerFooterType, const WPXHeaderFooterOccurence occurence, const uint8_t internalType, const WPXSubDocument *subDocument) : m_type(headerFooterType), m_occurence(occurence), m_internalType(internalType), m_subDocument(subDocument), m_tableList() { } WPXHeaderFooter::WPXHeaderFooter(const WPXHeaderFooter &headerFooter) : m_type(headerFooter.getType()), m_occurence(headerFooter.getOccurence()), m_internalType(headerFooter.getInternalType()), m_subDocument(headerFooter.getSubDocument()), m_tableList(headerFooter.getTableList()) { } WPXHeaderFooter &WPXHeaderFooter::operator=(const WPXHeaderFooter &headerFooter) { if (this != &headerFooter) { m_type = headerFooter.getType(); m_occurence = headerFooter.getOccurence(); m_internalType = headerFooter.getInternalType(); m_subDocument = headerFooter.getSubDocument(); m_tableList = headerFooter.getTableList(); } return *this; } WPXHeaderFooter::~WPXHeaderFooter() { // delete m_subDocument; } WPXPageSpan::WPXPageSpan() : m_isPageNumberSuppressed(false), m_formLength(11.0), m_formWidth(8.5f), m_formOrientation(PORTRAIT), m_marginLeft(1.0), m_marginRight(1.0), m_marginTop(WPX_DEFAULT_PAGE_MARGIN_TOP), m_marginBottom(WPX_DEFAULT_PAGE_MARGIN_BOTTOM), m_pageNumberPosition(PAGENUMBER_POSITION_NONE), m_isPageNumberOverridden(false), m_pageNumberOverride(0), m_pageNumberingType(ARABIC), m_pageNumberingFontName(/*WP6_DEFAULT_FONT_NAME*/"Times New Roman"), // EN PAS DEFAULT FONT AAN VOOR WP5/6/etc m_pageNumberingFontSize(12.0/*WP6_DEFAULT_FONT_SIZE*/), // FIXME ME!!!!!!!!!!!!!!!!!!! HELP WP6_DEFAULT_FONT_SIZE m_headerFooterList(), m_pageSpan(1) { for (int i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) m_isHeaderFooterSuppressed[i]=false; } // NB: this is not a literal "clone" function: it is contingent on the side margins that are passed, // and suppression and override variables are not copied WPXPageSpan::WPXPageSpan(const WPXPageSpan &page, double paragraphMarginLeft, double paragraphMarginRight) : m_isPageNumberSuppressed(false), m_formLength(page.getFormLength()), m_formWidth(page.getFormWidth()), m_formOrientation(page.getFormOrientation()), m_marginLeft(page.getMarginLeft()+paragraphMarginLeft), m_marginRight(page.getMarginRight()+paragraphMarginRight), m_marginTop(page.getMarginTop()), m_marginBottom(page.getMarginBottom()), m_pageNumberPosition(page.getPageNumberPosition()), m_isPageNumberOverridden(false), m_pageNumberOverride(0), m_pageNumberingType(page.getPageNumberingType()), m_pageNumberingFontName(page.getPageNumberingFontName()), m_pageNumberingFontSize(page.getPageNumberingFontSize()), m_headerFooterList(page.getHeaderFooterList()), m_pageSpan(page.getPageSpan()) { for (int i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) m_isHeaderFooterSuppressed[i] = false; } WPXPageSpan::~WPXPageSpan() { } void WPXPageSpan::setHeaderFooter(const WPXHeaderFooterType type, const uint8_t headerFooterType, const WPXHeaderFooterOccurence occurence, const WPXSubDocument *subDocument, WPXTableList tableList) { WPXHeaderFooter headerFooter(type, occurence, headerFooterType, subDocument, tableList); switch (occurence) { case ALL: case NEVER: _removeHeaderFooter(type, ODD); _removeHeaderFooter(type, EVEN); _removeHeaderFooter(type, ALL); break; case ODD: _removeHeaderFooter(type, ODD); _removeHeaderFooter(type, ALL); break; case EVEN: _removeHeaderFooter(type, EVEN); _removeHeaderFooter(type, ALL); break; } if ((occurence != NEVER) && (subDocument)) m_headerFooterList.push_back(headerFooter); bool containsHFLeft = _containsHeaderFooter(type, ODD); bool containsHFRight = _containsHeaderFooter(type, EVEN); WPD_DEBUG_MSG(("Contains HFL: %i HFR: %i\n", containsHFLeft, containsHFRight)); if (containsHFLeft && !containsHFRight) { WPD_DEBUG_MSG(("Inserting dummy header right\n")); WPXHeaderFooter dummyHeader(type, EVEN, DUMMY_INTERNAL_HEADER_FOOTER, 0); m_headerFooterList.push_back(dummyHeader); } else if (!containsHFLeft && containsHFRight) { WPD_DEBUG_MSG(("Inserting dummy header left\n")); WPXHeaderFooter dummyHeader(type, ODD, DUMMY_INTERNAL_HEADER_FOOTER, 0); m_headerFooterList.push_back(dummyHeader); } } void WPXPageSpan::_removeHeaderFooter(WPXHeaderFooterType type, WPXHeaderFooterOccurence occurence) { for (std::vector<WPXHeaderFooter>::iterator iter = m_headerFooterList.begin(); iter != m_headerFooterList.end(); iter++) { if ((*iter).getType() == type && (*iter).getOccurence() == occurence) { WPD_DEBUG_MSG(("WordPerfect: Removing header/footer element of type: %i since it is identical to %i\n",(*iter).getType(), type)); m_headerFooterList.erase(iter); return; } } } bool WPXPageSpan::_containsHeaderFooter(WPXHeaderFooterType type, WPXHeaderFooterOccurence occurence) { for (std::vector<WPXHeaderFooter>::iterator iter = m_headerFooterList.begin(); iter != m_headerFooterList.end(); iter++) { if ((*iter).getType()==type && (*iter).getOccurence()==occurence) return true; } return false; } inline bool operator==(const WPXHeaderFooter &headerFooter1, const WPXHeaderFooter &headerFooter2) { return ((headerFooter1.getType() == headerFooter2.getType()) && (headerFooter1.getSubDocument() == headerFooter2.getSubDocument()) && (headerFooter1.getOccurence() == headerFooter2.getOccurence()) && (headerFooter1.getInternalType() == headerFooter2.getInternalType()) ); } bool operator==(const WPXPageSpan &page1, const WPXPageSpan &page2) { if ((page1.getMarginLeft() != page2.getMarginLeft()) || (page1.getMarginRight() != page2.getMarginRight()) || (page1.getMarginTop() != page2.getMarginTop())|| (page1.getMarginBottom() != page2.getMarginBottom())) return false; if (page1.getPageNumberPosition() != page2.getPageNumberPosition()) return false; if (page1.getPageNumberSuppression() != page2.getPageNumberSuppression()) return false; if (page1.getPageNumberOverriden() != page2.getPageNumberOverriden() || page1.getPageNumberOverride() != page2.getPageNumberOverride()) return false; if (page1.getPageNumberingType() != page2.getPageNumberingType()) return false; if (page1.getPageNumberingFontName() != page2.getPageNumberingFontName() || page1.getPageNumberingFontSize() != page2.getPageNumberingFontSize()) return false; for (uint8_t i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) { if (page1.getHeaderFooterSuppression(i) != page2.getHeaderFooterSuppression(i)) return false; } // NOTE: yes this is O(n^2): so what? n=4 at most const std::vector<WPXHeaderFooter> headerFooterList1 = page1.getHeaderFooterList(); const std::vector<WPXHeaderFooter> headerFooterList2 = page2.getHeaderFooterList(); std::vector<WPXHeaderFooter>::const_iterator iter1; std::vector<WPXHeaderFooter>::const_iterator iter2; for (iter1 = headerFooterList1.begin(); iter1 != headerFooterList1.end(); iter1++) { if (std::find(headerFooterList2.begin(), headerFooterList2.end(), (*iter1)) == headerFooterList2.end()) return false; } // If we came here, we know that every header/footer that is found in the first page span is in the second too. // But this is not enought for us to know whether the page spans are equal. Now we have to check in addition // whether every header/footer that is in the second one is in the first too. If someone wants to optimize this, // (s)he is most welcome :-) for (iter2 = headerFooterList2.begin(); iter2 != headerFooterList2.end(); iter2++) { if (std::find(headerFooterList1.begin(), headerFooterList1.end(), (*iter2)) == headerFooterList1.end()) return false; } WPD_DEBUG_MSG(("WordPerfect: WPXPageSpan == comparison finished, found no differences\n")); return true; } /* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */ <|endoftext|>
<commit_before>/* libwpd * Copyright (C) 2002 William Lachance (wrlach@gmail.com) * Copyright (C) 2002 Marc Maurer (uwog@uwog.net) * Copyright (C) 2006-2007 Fridrich Strba (fridrich.strba@bluewin.ch) * * 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; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * For further information visit http://libwpd.sourceforge.net */ /* "This product is not manufactured, approved, or supported by * Corel Corporation or Corel Corporation Limited." */ #include <math.h> #include <algorithm> #include "WPXPageSpan.h" #include "libwpd_internal.h" const double WPX_DEFAULT_PAGE_MARGIN_TOP = 1.0; const double WPX_DEFAULT_PAGE_MARGIN_BOTTOM = 1.0; const uint8_t DUMMY_INTERNAL_HEADER_FOOTER = 16; // precondition: 0 <= headerFooterType <= 3 (i.e.: we don't handle watermarks here) WPXHeaderFooter::WPXHeaderFooter(const WPXHeaderFooterType headerFooterType, const WPXHeaderFooterOccurence occurence, const uint8_t internalType, const WPXSubDocument * subDocument, WPXTableList tableList) : m_type(headerFooterType), m_occurence(occurence), m_internalType(internalType), m_subDocument(subDocument), m_tableList(tableList) { } WPXHeaderFooter::WPXHeaderFooter(const WPXHeaderFooterType headerFooterType, const WPXHeaderFooterOccurence occurence, const uint8_t internalType, const WPXSubDocument * subDocument) : m_type(headerFooterType), m_occurence(occurence), m_internalType(internalType), m_subDocument(subDocument), m_tableList() { } WPXHeaderFooter::WPXHeaderFooter(const WPXHeaderFooter &headerFooter) : m_type(headerFooter.getType()), m_occurence(headerFooter.getOccurence()), m_internalType(headerFooter.getInternalType()), m_subDocument(headerFooter.getSubDocument()), m_tableList(headerFooter.getTableList()) { } WPXHeaderFooter& WPXHeaderFooter::operator=(const WPXHeaderFooter &headerFooter) { m_type = headerFooter.getType(); m_occurence = headerFooter.getOccurence(); m_internalType = headerFooter.getInternalType(); m_subDocument = headerFooter.getSubDocument(); m_tableList = headerFooter.getTableList(); return *this; } WPXHeaderFooter::~WPXHeaderFooter() { // delete m_subDocument; } WPXPageSpan::WPXPageSpan() : m_isPageNumberSuppressed(false), m_formLength(11.0), m_formWidth(8.5f), m_formOrientation(PORTRAIT), m_marginLeft(1.0), m_marginRight(1.0), m_marginTop(WPX_DEFAULT_PAGE_MARGIN_TOP), m_marginBottom(WPX_DEFAULT_PAGE_MARGIN_BOTTOM), m_pageNumberPosition(PAGENUMBER_POSITION_NONE), m_isPageNumberOverridden(false), m_pageNumberOverride(0), m_pageNumberingType(ARABIC), m_pageNumberingFontName(/*WP6_DEFAULT_FONT_NAME*/"Times New Roman"), // EN PAS DEFAULT FONT AAN VOOR WP5/6/etc m_pageNumberingFontSize(12.0/*WP6_DEFAULT_FONT_SIZE*/), // FIXME ME!!!!!!!!!!!!!!!!!!! HELP WP6_DEFAULT_FONT_SIZE m_headerFooterList(), m_pageSpan(1) { for (int i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) m_isHeaderFooterSuppressed[i]=false; } WPXPageSpan::WPXPageSpan(const WPXPageSpan &page) : m_isPageNumberSuppressed(page.getPageNumberSuppression()), m_formLength(page.getFormLength()), m_formWidth(page.getFormWidth()), m_formOrientation(page.getFormOrientation()), m_marginLeft(page.getMarginLeft()), m_marginRight(page.getMarginRight()), m_marginTop(page.getMarginTop()), m_marginBottom(page.getMarginBottom()), m_pageNumberPosition(page.getPageNumberPosition()), m_isPageNumberOverridden(page.getPageNumberOverriden()), m_pageNumberOverride(page.getPageNumberOverride()), m_pageNumberingType(page.getPageNumberingType()), m_pageNumberingFontName(page.getPageNumberingFontName()), m_pageNumberingFontSize(page.getPageNumberingFontSize()), m_headerFooterList(page.getHeaderFooterList()), m_pageSpan(page.getPageSpan()) { for (uint8_t i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) m_isHeaderFooterSuppressed[i] = page.getHeaderFooterSuppression(i); } // NB: this is not a literal "clone" function: it is contingent on the side margins that are passed, // and suppression and override variables are not copied WPXPageSpan::WPXPageSpan(const WPXPageSpan &page, double paragraphMarginLeft, double paragraphMarginRight) : m_isPageNumberSuppressed(false), m_formLength(page.getFormLength()), m_formWidth(page.getFormWidth()), m_formOrientation(page.getFormOrientation()), m_marginLeft(page.getMarginLeft()+paragraphMarginLeft), m_marginRight(page.getMarginRight()+paragraphMarginRight), m_marginTop(page.getMarginTop()), m_marginBottom(page.getMarginBottom()), m_pageNumberPosition(page.getPageNumberPosition()), m_isPageNumberOverridden(false), m_pageNumberOverride(0), m_pageNumberingType(page.getPageNumberingType()), m_pageNumberingFontName(page.getPageNumberingFontName()), m_pageNumberingFontSize(page.getPageNumberingFontSize()), m_headerFooterList(page.getHeaderFooterList()), m_pageSpan(page.getPageSpan()) { for (int i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) m_isHeaderFooterSuppressed[i] = false; } WPXPageSpan::~WPXPageSpan() { } void WPXPageSpan::setHeaderFooter(const WPXHeaderFooterType type, const uint8_t headerFooterType, const WPXHeaderFooterOccurence occurence, const WPXSubDocument * subDocument, WPXTableList tableList) { WPXHeaderFooter headerFooter(type, occurence, headerFooterType, subDocument, tableList); switch (occurence) { case ALL: case NEVER: _removeHeaderFooter(type, ODD); _removeHeaderFooter(type, EVEN); _removeHeaderFooter(type, ALL); break; case ODD: _removeHeaderFooter(type, ODD); _removeHeaderFooter(type, ALL); break; case EVEN: _removeHeaderFooter(type, EVEN); _removeHeaderFooter(type, ALL); break; } if ((occurence != NEVER) && (subDocument)) m_headerFooterList.push_back(headerFooter); bool containsHFLeft = _containsHeaderFooter(type, ODD); bool containsHFRight = _containsHeaderFooter(type, EVEN); WPD_DEBUG_MSG(("Contains HFL: %i HFR: %i\n", containsHFLeft, containsHFRight)); if (containsHFLeft && !containsHFRight) { WPD_DEBUG_MSG(("Inserting dummy header right\n")); WPXHeaderFooter dummyHeader(type, EVEN, DUMMY_INTERNAL_HEADER_FOOTER, 0); m_headerFooterList.push_back(dummyHeader); } else if (!containsHFLeft && containsHFRight) { WPD_DEBUG_MSG(("Inserting dummy header left\n")); WPXHeaderFooter dummyHeader(type, ODD, DUMMY_INTERNAL_HEADER_FOOTER, 0); m_headerFooterList.push_back(dummyHeader); } } void WPXPageSpan::_removeHeaderFooter(WPXHeaderFooterType type, WPXHeaderFooterOccurence occurence) { for (std::vector<WPXHeaderFooter>::iterator iter = m_headerFooterList.begin(); iter != m_headerFooterList.end(); iter++) { if ((*iter).getType() == type && (*iter).getOccurence() == occurence) { WPD_DEBUG_MSG(("WordPerfect: Removing header/footer element of type: %i since it is identical to %i\n",(*iter).getType(), type)); m_headerFooterList.erase(iter); return; } } } bool WPXPageSpan::_containsHeaderFooter(WPXHeaderFooterType type, WPXHeaderFooterOccurence occurence) { for (std::vector<WPXHeaderFooter>::iterator iter = m_headerFooterList.begin(); iter != m_headerFooterList.end(); iter++) { if ((*iter).getType()==type && (*iter).getOccurence()==occurence) return true; } return false; } inline bool operator==(const WPXHeaderFooter &headerFooter1, const WPXHeaderFooter &headerFooter2) { return ((headerFooter1.getType() == headerFooter2.getType()) && (headerFooter1.getSubDocument() == headerFooter2.getSubDocument()) && (headerFooter1.getOccurence() == headerFooter2.getOccurence()) && (headerFooter1.getInternalType() == headerFooter2.getInternalType()) ); } bool operator==(const WPXPageSpan &page1, const WPXPageSpan &page2) { if ((page1.getMarginLeft() != page2.getMarginLeft()) || (page1.getMarginRight() != page2.getMarginRight()) || (page1.getMarginTop() != page2.getMarginTop())|| (page1.getMarginBottom() != page2.getMarginBottom())) return false; if (page1.getPageNumberPosition() != page2.getPageNumberPosition()) return false; if (page1.getPageNumberSuppression() != page2.getPageNumberSuppression()) return false; if (page1.getPageNumberOverriden() != page2.getPageNumberOverriden() || page1.getPageNumberOverride() != page2.getPageNumberOverride()) return false; if (page1.getPageNumberingType() != page2.getPageNumberingType()) return false; if (page1.getPageNumberingFontName() != page2.getPageNumberingFontName() || page1.getPageNumberingFontSize() != page2.getPageNumberingFontSize()) return false; for (uint8_t i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) { if (page1.getHeaderFooterSuppression(i) != page2.getHeaderFooterSuppression(i)) return false; } // NOTE: yes this is O(n^2): so what? n=4 at most const std::vector<WPXHeaderFooter> headerFooterList1 = page1.getHeaderFooterList(); const std::vector<WPXHeaderFooter> headerFooterList2 = page2.getHeaderFooterList(); std::vector<WPXHeaderFooter>::const_iterator iter1; std::vector<WPXHeaderFooter>::const_iterator iter2; for (iter1 = headerFooterList1.begin(); iter1 != headerFooterList1.end(); iter1++) { if (std::find(headerFooterList2.begin(), headerFooterList2.end(), (*iter1)) == headerFooterList2.end()) return false; } // If we came here, we know that every header/footer that is found in the first page span is in the second too. // But this is not enought for us to know whether the page spans are equal. Now we have to check in addition // whether every header/footer that is in the second one is in the first too. If someone wants to optimize this, // (s)he is most welcome :-) for (iter2 = headerFooterList2.begin(); iter2 != headerFooterList2.end(); iter2++) { if (std::find(headerFooterList1.begin(), headerFooterList1.end(), (*iter2)) == headerFooterList1.end()) return false; } WPD_DEBUG_MSG(("WordPerfect: WPXPageSpan == comparison finished, found no differences\n")); return true; } <commit_msg>A whitespace change<commit_after>/* libwpd * Copyright (C) 2002 William Lachance (wrlach@gmail.com) * Copyright (C) 2002 Marc Maurer (uwog@uwog.net) * Copyright (C) 2006-2007 Fridrich Strba (fridrich.strba@bluewin.ch) * * 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; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * For further information visit http://libwpd.sourceforge.net */ /* "This product is not manufactured, approved, or supported by * Corel Corporation or Corel Corporation Limited." */ #include <math.h> #include <algorithm> #include "WPXPageSpan.h" #include "libwpd_internal.h" const double WPX_DEFAULT_PAGE_MARGIN_TOP = 1.0; const double WPX_DEFAULT_PAGE_MARGIN_BOTTOM = 1.0; const uint8_t DUMMY_INTERNAL_HEADER_FOOTER = 16; // precondition: 0 <= headerFooterType <= 3 (i.e.: we don't handle watermarks here) WPXHeaderFooter::WPXHeaderFooter(const WPXHeaderFooterType headerFooterType, const WPXHeaderFooterOccurence occurence, const uint8_t internalType, const WPXSubDocument * subDocument, WPXTableList tableList) : m_type(headerFooterType), m_occurence(occurence), m_internalType(internalType), m_subDocument(subDocument), m_tableList(tableList) { } WPXHeaderFooter::WPXHeaderFooter(const WPXHeaderFooterType headerFooterType, const WPXHeaderFooterOccurence occurence, const uint8_t internalType, const WPXSubDocument * subDocument) : m_type(headerFooterType), m_occurence(occurence), m_internalType(internalType), m_subDocument(subDocument), m_tableList() { } WPXHeaderFooter::WPXHeaderFooter(const WPXHeaderFooter &headerFooter) : m_type(headerFooter.getType()), m_occurence(headerFooter.getOccurence()), m_internalType(headerFooter.getInternalType()), m_subDocument(headerFooter.getSubDocument()), m_tableList(headerFooter.getTableList()) { } WPXHeaderFooter& WPXHeaderFooter::operator=(const WPXHeaderFooter &headerFooter) { m_type = headerFooter.getType(); m_occurence = headerFooter.getOccurence(); m_internalType = headerFooter.getInternalType(); m_subDocument = headerFooter.getSubDocument(); m_tableList = headerFooter.getTableList(); return *this; } WPXHeaderFooter::~WPXHeaderFooter() { // delete m_subDocument; } WPXPageSpan::WPXPageSpan() : m_isPageNumberSuppressed(false), m_formLength(11.0), m_formWidth(8.5f), m_formOrientation(PORTRAIT), m_marginLeft(1.0), m_marginRight(1.0), m_marginTop(WPX_DEFAULT_PAGE_MARGIN_TOP), m_marginBottom(WPX_DEFAULT_PAGE_MARGIN_BOTTOM), m_pageNumberPosition(PAGENUMBER_POSITION_NONE), m_isPageNumberOverridden(false), m_pageNumberOverride(0), m_pageNumberingType(ARABIC), m_pageNumberingFontName(/*WP6_DEFAULT_FONT_NAME*/"Times New Roman"), // EN PAS DEFAULT FONT AAN VOOR WP5/6/etc m_pageNumberingFontSize(12.0/*WP6_DEFAULT_FONT_SIZE*/), // FIXME ME!!!!!!!!!!!!!!!!!!! HELP WP6_DEFAULT_FONT_SIZE m_headerFooterList(), m_pageSpan(1) { for (int i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) m_isHeaderFooterSuppressed[i]=false; } WPXPageSpan::WPXPageSpan(const WPXPageSpan &page) : m_isPageNumberSuppressed(page.getPageNumberSuppression()), m_formLength(page.getFormLength()), m_formWidth(page.getFormWidth()), m_formOrientation(page.getFormOrientation()), m_marginLeft(page.getMarginLeft()), m_marginRight(page.getMarginRight()), m_marginTop(page.getMarginTop()), m_marginBottom(page.getMarginBottom()), m_pageNumberPosition(page.getPageNumberPosition()), m_isPageNumberOverridden(page.getPageNumberOverriden()), m_pageNumberOverride(page.getPageNumberOverride()), m_pageNumberingType(page.getPageNumberingType()), m_pageNumberingFontName(page.getPageNumberingFontName()), m_pageNumberingFontSize(page.getPageNumberingFontSize()), m_headerFooterList(page.getHeaderFooterList()), m_pageSpan(page.getPageSpan()) { for (uint8_t i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) m_isHeaderFooterSuppressed[i] = page.getHeaderFooterSuppression(i); } // NB: this is not a literal "clone" function: it is contingent on the side margins that are passed, // and suppression and override variables are not copied WPXPageSpan::WPXPageSpan(const WPXPageSpan &page, double paragraphMarginLeft, double paragraphMarginRight) : m_isPageNumberSuppressed(false), m_formLength(page.getFormLength()), m_formWidth(page.getFormWidth()), m_formOrientation(page.getFormOrientation()), m_marginLeft(page.getMarginLeft()+paragraphMarginLeft), m_marginRight(page.getMarginRight()+paragraphMarginRight), m_marginTop(page.getMarginTop()), m_marginBottom(page.getMarginBottom()), m_pageNumberPosition(page.getPageNumberPosition()), m_isPageNumberOverridden(false), m_pageNumberOverride(0), m_pageNumberingType(page.getPageNumberingType()), m_pageNumberingFontName(page.getPageNumberingFontName()), m_pageNumberingFontSize(page.getPageNumberingFontSize()), m_headerFooterList(page.getHeaderFooterList()), m_pageSpan(page.getPageSpan()) { for (int i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) m_isHeaderFooterSuppressed[i] = false; } WPXPageSpan::~WPXPageSpan() { } void WPXPageSpan::setHeaderFooter(const WPXHeaderFooterType type, const uint8_t headerFooterType, const WPXHeaderFooterOccurence occurence, const WPXSubDocument * subDocument, WPXTableList tableList) { WPXHeaderFooter headerFooter(type, occurence, headerFooterType, subDocument, tableList); switch (occurence) { case ALL: case NEVER: _removeHeaderFooter(type, ODD); _removeHeaderFooter(type, EVEN); _removeHeaderFooter(type, ALL); break; case ODD: _removeHeaderFooter(type, ODD); _removeHeaderFooter(type, ALL); break; case EVEN: _removeHeaderFooter(type, EVEN); _removeHeaderFooter(type, ALL); break; } if ((occurence != NEVER) && (subDocument)) m_headerFooterList.push_back(headerFooter); bool containsHFLeft = _containsHeaderFooter(type, ODD); bool containsHFRight = _containsHeaderFooter(type, EVEN); WPD_DEBUG_MSG(("Contains HFL: %i HFR: %i\n", containsHFLeft, containsHFRight)); if (containsHFLeft && !containsHFRight) { WPD_DEBUG_MSG(("Inserting dummy header right\n")); WPXHeaderFooter dummyHeader(type, EVEN, DUMMY_INTERNAL_HEADER_FOOTER, 0); m_headerFooterList.push_back(dummyHeader); } else if (!containsHFLeft && containsHFRight) { WPD_DEBUG_MSG(("Inserting dummy header left\n")); WPXHeaderFooter dummyHeader(type, ODD, DUMMY_INTERNAL_HEADER_FOOTER, 0); m_headerFooterList.push_back(dummyHeader); } } void WPXPageSpan::_removeHeaderFooter(WPXHeaderFooterType type, WPXHeaderFooterOccurence occurence) { for (std::vector<WPXHeaderFooter>::iterator iter = m_headerFooterList.begin(); iter != m_headerFooterList.end(); iter++) { if ((*iter).getType() == type && (*iter).getOccurence() == occurence) { WPD_DEBUG_MSG(("WordPerfect: Removing header/footer element of type: %i since it is identical to %i\n",(*iter).getType(), type)); m_headerFooterList.erase(iter); return; } } } bool WPXPageSpan::_containsHeaderFooter(WPXHeaderFooterType type, WPXHeaderFooterOccurence occurence) { for (std::vector<WPXHeaderFooter>::iterator iter = m_headerFooterList.begin(); iter != m_headerFooterList.end(); iter++) { if ((*iter).getType()==type && (*iter).getOccurence()==occurence) return true; } return false; } inline bool operator==(const WPXHeaderFooter &headerFooter1, const WPXHeaderFooter &headerFooter2) { return ((headerFooter1.getType() == headerFooter2.getType()) && (headerFooter1.getSubDocument() == headerFooter2.getSubDocument()) && (headerFooter1.getOccurence() == headerFooter2.getOccurence()) && (headerFooter1.getInternalType() == headerFooter2.getInternalType()) ); } bool operator==(const WPXPageSpan &page1, const WPXPageSpan &page2) { if ((page1.getMarginLeft() != page2.getMarginLeft()) || (page1.getMarginRight() != page2.getMarginRight()) || (page1.getMarginTop() != page2.getMarginTop())|| (page1.getMarginBottom() != page2.getMarginBottom())) return false; if (page1.getPageNumberPosition() != page2.getPageNumberPosition()) return false; if (page1.getPageNumberSuppression() != page2.getPageNumberSuppression()) return false; if (page1.getPageNumberOverriden() != page2.getPageNumberOverriden() || page1.getPageNumberOverride() != page2.getPageNumberOverride()) return false; if (page1.getPageNumberingType() != page2.getPageNumberingType()) return false; if (page1.getPageNumberingFontName() != page2.getPageNumberingFontName() || page1.getPageNumberingFontSize() != page2.getPageNumberingFontSize()) return false; for (uint8_t i=0; i<WPX_NUM_HEADER_FOOTER_TYPES; i++) { if (page1.getHeaderFooterSuppression(i) != page2.getHeaderFooterSuppression(i)) return false; } // NOTE: yes this is O(n^2): so what? n=4 at most const std::vector<WPXHeaderFooter> headerFooterList1 = page1.getHeaderFooterList(); const std::vector<WPXHeaderFooter> headerFooterList2 = page2.getHeaderFooterList(); std::vector<WPXHeaderFooter>::const_iterator iter1; std::vector<WPXHeaderFooter>::const_iterator iter2; for (iter1 = headerFooterList1.begin(); iter1 != headerFooterList1.end(); iter1++) { if (std::find(headerFooterList2.begin(), headerFooterList2.end(), (*iter1)) == headerFooterList2.end()) return false; } // If we came here, we know that every header/footer that is found in the first page span is in the second too. // But this is not enought for us to know whether the page spans are equal. Now we have to check in addition // whether every header/footer that is in the second one is in the first too. If someone wants to optimize this, // (s)he is most welcome :-) for (iter2 = headerFooterList2.begin(); iter2 != headerFooterList2.end(); iter2++) { if (std::find(headerFooterList1.begin(), headerFooterList1.end(), (*iter2)) == headerFooterList1.end()) return false; } WPD_DEBUG_MSG(("WordPerfect: WPXPageSpan == comparison finished, found no differences\n")); return true; } <|endoftext|>
<commit_before>//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include <iostream> #include <fstream> #include "LinuxUtils.h" #include "Utils.h" #include "PrintVar.h" #include "Capture.h" #include "Callstack.h" #include "CoreApp.h" #include "SamplingProfiler.h" #include "EventBuffer.h" #include "Capture.h" #include "ScopeTimer.h" #include "OrbitProcess.h" #include "OrbitModule.h" #include "ConnectionManager.h" #include "TcpServer.h" #include "EventBuffer.h" #include "EventTracer.h" #if __linux__ #include <unistd.h> #include <sys/types.h> #include <sys/syscall.h> #include <linux/types.h> #include <linux/perf_event.h> #include <asm/unistd.h> #include <sys/mman.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <string.h> #include <iomanip> #include <signal.h> #include <sys/wait.h> #include <sstream> #include <string> #include <cstdlib> #include <memory> #include <cxxabi.h> #endif //----------------------------------------------------------------------------- LinuxPerf::LinuxPerf( uint32_t a_PID, uint32_t a_Freq ) : m_PID(a_PID) , m_Frequency(a_Freq) { m_Callback = [this](const std::string& a_Buffer) { HandleLine( a_Buffer ); }; m_PerfCommand = Format("perf record -k monotonic -F %u -p %u -g --no-buffering -o - | perf script -i -", m_Frequency, m_PID); } //----------------------------------------------------------------------------- void LinuxPerf::Start() { PRINT_FUNC; #if __linux__ m_ExitRequested = false; m_PerfData.Clear(); m_Thread = std::make_shared<std::thread> ( &LinuxUtils::StreamCommandOutput , m_PerfCommand.c_str() , m_Callback , &m_ExitRequested ); m_Thread->detach(); #endif } //----------------------------------------------------------------------------- void LinuxPerf::Stop() { PRINT_FUNC; #if __linux__ m_ExitRequested = true; #endif } //----------------------------------------------------------------------------- bool ParseStackLine( const std::string& a_Line, uint64_t& o_Address, std::string& o_Name, std::string& o_Module ) { // Module std::size_t moduleBegin = a_Line.find_last_of("("); if( moduleBegin == std::string::npos ) return false; o_Module = Replace(a_Line.substr(moduleBegin+1), ")", ""); // Function name std::string line = LTrim(a_Line.substr(0, moduleBegin)); std::size_t nameBegin = line.find_first_of(" "); if( nameBegin == std::string::npos ) return false; o_Name = line.substr(nameBegin); // Address std::string address = line.substr(0, nameBegin); o_Address = std::stoull(address, nullptr, 16); return true; } void LinuxPerf::HandleLine( const std::string& a_Line ) { bool isEmptyLine = (a_Line.empty() || a_Line == "\n"); bool isHeader = !isEmptyLine && !StartsWith(a_Line, "\t"); bool isStackLine = !isHeader && !isEmptyLine; bool isEndBlock = !isStackLine && isEmptyLine && !m_PerfData.m_header.empty(); if(isHeader) { m_PerfData.m_header = a_Line; auto tokens = Tokenize(a_Line); m_PerfData.m_time = tokens.size() > 2 ? GetMicros(tokens[2])*1000 : 0; m_PerfData.m_tid = tokens.size() > 1 ? atoi(tokens[1].c_str()) : 0; } else if(isStackLine) { std::string module; std::string function; uint64_t address; if( !ParseStackLine( a_Line, address, function, module ) ) { PRINT_VAR("ParseStackLine error"); PRINT_VAR(a_Line); return; } std::wstring moduleName = ToLower(Path::GetFileName(s2ws(module))); std::shared_ptr<Module> moduleFromName = Capture::GTargetProcess->GetModuleFromName( ws2s(moduleName) ); if( moduleFromName ) { uint64_t new_address = moduleFromName->ValidateAddress(address); address = new_address; } m_PerfData.m_CS.m_Data.push_back(address); if( Capture::GTargetProcess && !Capture::GTargetProcess->HasSymbol(address)) { GCoreApp->AddSymbol(address, module, function); } } else if(isEndBlock) { CallStack& CS = m_PerfData.m_CS; if( CS.m_Data.size() ) { CS.m_Depth = (uint32_t)CS.m_Data.size(); CS.m_ThreadId = m_PerfData.m_tid; CallstackID hash = CS.Hash(); GCoreApp->ProcessSamplingCallStack(m_PerfData); ++m_PerfData.m_numCallstacks; HashedCallStack hashedCallStack; hashedCallStack.m_Depth = CS.m_Depth; hashedCallStack.m_Hash = hash; hashedCallStack.m_ThreadId = m_PerfData.m_tid; Capture::GSamplingProfiler->AddHashedCallStack( hashedCallStack ); GEventTracer.GetEventBuffer().AddCallstackEvent( m_PerfData.m_time, hash, m_PerfData.m_tid ); } m_PerfData.Clear(); } } //----------------------------------------------------------------------------- void LinuxPerf::LoadPerfData( std::istream& a_Stream ) { m_PerfData.Clear(); for (std::string line; std::getline(a_Stream, line); ) { HandleLine(line); } PRINT_VAR(m_PerfData.m_numCallstacks); PRINT_FUNC; }<commit_msg>Fixed module resolution in LinuxPerf callstack parsing.<commit_after>//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include <iostream> #include <fstream> #include "LinuxUtils.h" #include "Utils.h" #include "PrintVar.h" #include "Capture.h" #include "Callstack.h" #include "CoreApp.h" #include "SamplingProfiler.h" #include "EventBuffer.h" #include "Capture.h" #include "ScopeTimer.h" #include "OrbitProcess.h" #include "OrbitModule.h" #include "ConnectionManager.h" #include "TcpServer.h" #include "EventBuffer.h" #include "EventTracer.h" #if __linux__ #include <unistd.h> #include <sys/types.h> #include <sys/syscall.h> #include <linux/types.h> #include <linux/perf_event.h> #include <asm/unistd.h> #include <sys/mman.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <string.h> #include <iomanip> #include <signal.h> #include <sys/wait.h> #include <sstream> #include <string> #include <cstdlib> #include <memory> #include <cxxabi.h> #endif //----------------------------------------------------------------------------- LinuxPerf::LinuxPerf( uint32_t a_PID, uint32_t a_Freq ) : m_PID(a_PID) , m_Frequency(a_Freq) { m_Callback = [this](const std::string& a_Buffer) { HandleLine( a_Buffer ); }; m_PerfCommand = Format("perf record -k monotonic -F %u -p %u -g --no-buffering -o - | perf script -i -", m_Frequency, m_PID); } //----------------------------------------------------------------------------- void LinuxPerf::Start() { PRINT_FUNC; #if __linux__ m_ExitRequested = false; m_PerfData.Clear(); m_Thread = std::make_shared<std::thread> ( &LinuxUtils::StreamCommandOutput , m_PerfCommand.c_str() , m_Callback , &m_ExitRequested ); m_Thread->detach(); #endif } //----------------------------------------------------------------------------- void LinuxPerf::Stop() { PRINT_FUNC; #if __linux__ m_ExitRequested = true; #endif } //----------------------------------------------------------------------------- bool ParseStackLine( const std::string& a_Line, uint64_t& o_Address, std::string& o_Name, std::string& o_Module ) { // Module std::size_t moduleBegin = a_Line.find_last_of("("); if( moduleBegin == std::string::npos ) return false; o_Module = RTrim(Replace(a_Line.substr(moduleBegin+1), ")", "")); // Function name std::string line = LTrim(a_Line.substr(0, moduleBegin)); std::size_t nameBegin = line.find_first_of(" "); if( nameBegin == std::string::npos ) return false; o_Name = line.substr(nameBegin); // Address std::string address = line.substr(0, nameBegin); o_Address = std::stoull(address, nullptr, 16); return true; } void LinuxPerf::HandleLine( const std::string& a_Line ) { bool isEmptyLine = (a_Line.empty() || a_Line == "\n"); bool isHeader = !isEmptyLine && !StartsWith(a_Line, "\t"); bool isStackLine = !isHeader && !isEmptyLine; bool isEndBlock = !isStackLine && isEmptyLine && !m_PerfData.m_header.empty(); if(isHeader) { m_PerfData.m_header = a_Line; auto tokens = Tokenize(a_Line); m_PerfData.m_time = tokens.size() > 2 ? GetMicros(tokens[2])*1000 : 0; m_PerfData.m_tid = tokens.size() > 1 ? atoi(tokens[1].c_str()) : 0; } else if(isStackLine) { std::string module; std::string function; uint64_t address; if( !ParseStackLine( a_Line, address, function, module ) ) { PRINT_VAR("ParseStackLine error"); PRINT_VAR(a_Line); return; } std::wstring moduleName = ToLower(Path::GetFileName(s2ws(module))); std::shared_ptr<Module> moduleFromName = Capture::GTargetProcess->GetModuleFromName( ws2s(moduleName) ); if( moduleFromName ) { uint64_t new_address = moduleFromName->ValidateAddress(address); address = new_address; } m_PerfData.m_CS.m_Data.push_back(address); if( Capture::GTargetProcess && !Capture::GTargetProcess->HasSymbol(address)) { GCoreApp->AddSymbol(address, module, function); } } else if(isEndBlock) { CallStack& CS = m_PerfData.m_CS; if( CS.m_Data.size() ) { CS.m_Depth = (uint32_t)CS.m_Data.size(); CS.m_ThreadId = m_PerfData.m_tid; CallstackID hash = CS.Hash(); GCoreApp->ProcessSamplingCallStack(m_PerfData); ++m_PerfData.m_numCallstacks; HashedCallStack hashedCallStack; hashedCallStack.m_Depth = CS.m_Depth; hashedCallStack.m_Hash = hash; hashedCallStack.m_ThreadId = m_PerfData.m_tid; Capture::GSamplingProfiler->AddHashedCallStack( hashedCallStack ); GEventTracer.GetEventBuffer().AddCallstackEvent( m_PerfData.m_time, hash, m_PerfData.m_tid ); } m_PerfData.Clear(); } } //----------------------------------------------------------------------------- void LinuxPerf::LoadPerfData( std::istream& a_Stream ) { m_PerfData.Clear(); for (std::string line; std::getline(a_Stream, line); ) { HandleLine(line); } PRINT_VAR(m_PerfData.m_numCallstacks); PRINT_FUNC; } <|endoftext|>
<commit_before>/* * Copyright 2009-2019 The VOTCA Development Team * (http://www.votca.org) * * 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 <votca/xtp/eigencuda.h> namespace votca { namespace xtp { /* * Deallocate memory from the device */ void free_mem_in_gpu(double *x) { checkCuda(cudaFree(x)); }; EigenCuda::~EigenCuda() { // destroy handle cublasDestroy(_handle); // destroy stream cudaStreamDestroy(_stream); } /* * Check if the available memory is enough to compute the system */ void EigenCuda::check_available_memory_in_gpu(size_t requested_memory) const { // Use Unified memory size_t *free, *total; cudaMallocManaged(&free, sizeof(size_t)); cudaMallocManaged(&total, sizeof(size_t)); checkCuda(cudaMemGetInfo(free, total)); std::ostringstream oss; oss << "There were requested : " << requested_memory << "bytes int the device\n"; oss << "Device Free memory (bytes): " << *free << "\nDevice total Memory (bytes): " << *total << "\n"; // Raise an error if there is not enough total or free memory in the device if (requested_memory > *free) { oss << "There is not enough memory in the Device!\n"; throw std::runtime_error(oss.str()); } // Release memory cudaFree(free); cudaFree(total); } /* * Allocate memory in the device for matrix A. */ uniq_double EigenCuda::alloc_matrix_in_gpu(size_t size_matrix) const { // Pointer in the device double *dmatrix; checkCuda(cudaMalloc(&dmatrix, size_matrix)); uniq_double dev_ptr(dmatrix, free_mem_in_gpu); return dev_ptr; } uniq_double EigenCuda::copy_matrix_to_gpu(const Eigen::MatrixXd &matrix) const { // allocate memory in the device size_t size_matrix = matrix.size() * sizeof(double); uniq_double dev_ptr = alloc_matrix_in_gpu(size_matrix); // Transfer data to the GPU const double *hmatrix = matrix.data(); // Pointers at the host cudaError_t err = cudaMemcpyAsync(dev_ptr.get(), hmatrix, size_matrix, cudaMemcpyHostToDevice, _stream); if (err != 0) { throw std::runtime_error("Error copy arrays to device"); } return dev_ptr; } /* * Call the gemm function from cublas, resulting in the multiplication of the * two matrices. */ void EigenCuda::gemm(const CudaMatrix &A, const CudaMatrix &B, CudaMatrix &C) const { // Scalar constanst for calling blas double alpha = 1.; double beta = 0.; const double *palpha = &alpha; const double *pbeta = &beta; cublasDgemm(_handle, CUBLAS_OP_N, CUBLAS_OP_N, A.rows(), B.cols(), A.cols(), palpha, A.ptr(), A.rows(), B.ptr(), B.rows(), pbeta, C.ptr(), C.rows()); } /* * \brief Perform a Tensor3D matrix multiplication */ void EigenCuda::right_matrix_tensor_mult(std::vector<Eigen::MatrixXd> &&tensor, const Eigen::MatrixXd &B) const { int batchCount = tensor.size(); // First submatrix from the tensor const Eigen::MatrixXd &submatrix = tensor[0]; // sizes of the matrices to allocated in the device size_t size_A = submatrix.size() * sizeof(double); size_t size_B = B.size() * sizeof(double); size_t size_C = submatrix.rows() * B.cols() * sizeof(double); check_available_memory_in_gpu(size_A + size_B + size_C); // Matrix in the Cuda device uniq_double dA = alloc_matrix_in_gpu(size_A); uniq_double dC = alloc_matrix_in_gpu(size_C); uniq_double dB = copy_matrix_to_gpu(B); CudaMatrix matrixA{std::move(dA), submatrix.rows(), submatrix.cols()}; CudaMatrix matrixB{std::move(dB), B.rows(), B.cols()}; CudaMatrix matrixC{std::move(dC), submatrix.rows(), B.cols()}; std::vector<Eigen::MatrixXd> result( batchCount, Eigen::MatrixXd::Zero(submatrix.rows(), B.cols())); // Call tensor matrix multiplication for (auto i = 0; i < batchCount; i++) { // Copy tensor component to the device checkCuda(cudaMemcpyAsync(matrixA.ptr(), tensor[i].data(), size_C, cudaMemcpyHostToDevice, _stream)); // matrix multiplication gemm(matrixA, matrixB, matrixC); // Copy the result to the host // double *hout = result[i].data(); double *hout = tensor[i].data(); checkCuda(cudaMemcpyAsync(hout, matrixC.ptr(), size_C, cudaMemcpyDeviceToHost, _stream)); } } /* * \brief performs a matrix_1 * matrix2 * matrix_2 multiplication */ Eigen::MatrixXd EigenCuda::triple_matrix_mult(const CudaMatrix &A, const Eigen::MatrixXd &matrix, const CudaMatrix &C) const { // sizes of the matrices to allocated in the device size_t size_A = A.size() * sizeof(double); size_t size_B = matrix.size() * sizeof(double); size_t size_C = C.size() * sizeof(double); std::size_t size_W = A.rows() * matrix.cols() * sizeof(double); std::size_t size_Z = A.rows() * C.cols() * sizeof(double); // Check if there is enough available memory check_available_memory_in_gpu(size_A + size_B + size_C + size_W + size_Z); // Intermediate Matrices CudaMatrix B{copy_matrix_to_gpu(matrix), matrix.rows(), matrix.cols()}; CudaMatrix W{alloc_matrix_in_gpu(size_W), A.rows(), matrix.cols()}; CudaMatrix Z{alloc_matrix_in_gpu(size_Z), A.rows(), C.cols()}; Eigen::MatrixXd result = Eigen::MatrixXd::Zero(A.rows(), C.cols()); // Call the first tensor matrix multiplication gemm(A, B, W); // Call the second tensor matrix multiplication gemm(W, C, Z); // Copy the result Array back to the device checkCuda(cudaMemcpyAsync(result.data(), Z.ptr(), size_Z, cudaMemcpyDeviceToHost, _stream)); return result; } } // namespace xtp } // namespace votca <commit_msg>fixed check of available mem in CUDA device<commit_after>/* * Copyright 2009-2019 The VOTCA Development Team * (http://www.votca.org) * * 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 <votca/xtp/eigencuda.h> namespace votca { namespace xtp { /* * Deallocate memory from the device */ void free_mem_in_gpu(double *x) { checkCuda(cudaFree(x)); }; EigenCuda::~EigenCuda() { // destroy handle cublasDestroy(_handle); // destroy stream cudaStreamDestroy(_stream); } /* * Check if the available memory is enough to compute the system */ void EigenCuda::check_available_memory_in_gpu(size_t requested_memory) const { size_t free, total; checkCuda(cudaMemGetInfo(&free, &total)); std::ostringstream oss; oss << "There were requested : " << requested_memory << "bytes int the device\n"; oss << "Device Free memory (bytes): " << free << "\nDevice total Memory (bytes): " << total << "\n"; // Raise an error if there is not enough total or free memory in the device if (requested_memory > free) { oss << "There is not enough memory in the Device!\n"; throw std::runtime_error(oss.str()); } } /* * Allocate memory in the device for matrix A. */ uniq_double EigenCuda::alloc_matrix_in_gpu(size_t size_matrix) const { // Pointer in the device double *dmatrix; checkCuda(cudaMalloc(&dmatrix, size_matrix)); uniq_double dev_ptr(dmatrix, free_mem_in_gpu); return dev_ptr; } uniq_double EigenCuda::copy_matrix_to_gpu(const Eigen::MatrixXd &matrix) const { // allocate memory in the device size_t size_matrix = matrix.size() * sizeof(double); uniq_double dev_ptr = alloc_matrix_in_gpu(size_matrix); // Transfer data to the GPU const double *hmatrix = matrix.data(); // Pointers at the host cudaError_t err = cudaMemcpyAsync(dev_ptr.get(), hmatrix, size_matrix, cudaMemcpyHostToDevice, _stream); if (err != 0) { throw std::runtime_error("Error copy arrays to device"); } return dev_ptr; } /* * Call the gemm function from cublas, resulting in the multiplication of the * two matrices. */ void EigenCuda::gemm(const CudaMatrix &A, const CudaMatrix &B, CudaMatrix &C) const { // Scalar constanst for calling blas double alpha = 1.; double beta = 0.; const double *palpha = &alpha; const double *pbeta = &beta; cublasDgemm(_handle, CUBLAS_OP_N, CUBLAS_OP_N, A.rows(), B.cols(), A.cols(), palpha, A.ptr(), A.rows(), B.ptr(), B.rows(), pbeta, C.ptr(), C.rows()); } /* * \brief Perform a Tensor3D matrix multiplication */ void EigenCuda::right_matrix_tensor_mult(std::vector<Eigen::MatrixXd> &&tensor, const Eigen::MatrixXd &B) const { int batchCount = tensor.size(); // First submatrix from the tensor const Eigen::MatrixXd &submatrix = tensor[0]; // sizes of the matrices to allocated in the device size_t size_A = submatrix.size() * sizeof(double); size_t size_B = B.size() * sizeof(double); size_t size_C = submatrix.rows() * B.cols() * sizeof(double); check_available_memory_in_gpu(size_A + size_B + size_C); // Matrix in the Cuda device uniq_double dA = alloc_matrix_in_gpu(size_A); uniq_double dC = alloc_matrix_in_gpu(size_C); uniq_double dB = copy_matrix_to_gpu(B); CudaMatrix matrixA{std::move(dA), submatrix.rows(), submatrix.cols()}; CudaMatrix matrixB{std::move(dB), B.rows(), B.cols()}; CudaMatrix matrixC{std::move(dC), submatrix.rows(), B.cols()}; std::vector<Eigen::MatrixXd> result( batchCount, Eigen::MatrixXd::Zero(submatrix.rows(), B.cols())); // Call tensor matrix multiplication for (auto i = 0; i < batchCount; i++) { // Copy tensor component to the device checkCuda(cudaMemcpyAsync(matrixA.ptr(), tensor[i].data(), size_C, cudaMemcpyHostToDevice, _stream)); // matrix multiplication gemm(matrixA, matrixB, matrixC); // Copy the result to the host // double *hout = result[i].data(); double *hout = tensor[i].data(); checkCuda(cudaMemcpyAsync(hout, matrixC.ptr(), size_C, cudaMemcpyDeviceToHost, _stream)); } } /* * \brief performs a matrix_1 * matrix2 * matrix_2 multiplication */ Eigen::MatrixXd EigenCuda::triple_matrix_mult(const CudaMatrix &A, const Eigen::MatrixXd &matrix, const CudaMatrix &C) const { // sizes of the matrices to allocated in the device size_t size_A = A.size() * sizeof(double); size_t size_B = matrix.size() * sizeof(double); size_t size_C = C.size() * sizeof(double); std::size_t size_W = A.rows() * matrix.cols() * sizeof(double); std::size_t size_Z = A.rows() * C.cols() * sizeof(double); // Check if there is enough available memory check_available_memory_in_gpu(size_A + size_B + size_C + size_W + size_Z); // Intermediate Matrices CudaMatrix B{copy_matrix_to_gpu(matrix), matrix.rows(), matrix.cols()}; CudaMatrix W{alloc_matrix_in_gpu(size_W), A.rows(), matrix.cols()}; CudaMatrix Z{alloc_matrix_in_gpu(size_Z), A.rows(), C.cols()}; Eigen::MatrixXd result = Eigen::MatrixXd::Zero(A.rows(), C.cols()); // Call the first tensor matrix multiplication gemm(A, B, W); // Call the second tensor matrix multiplication gemm(W, C, Z); // Copy the result Array back to the device checkCuda(cudaMemcpyAsync(result.data(), Z.ptr(), size_Z, cudaMemcpyDeviceToHost, _stream)); return result; } } // namespace xtp } // namespace votca <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // Copyright (c) 2016 by contributors. 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. //------------------------------------------------------------------------------ /* Author: Chao Ma (mctt90@gmail.com) This file tests the Metric class. */ #include "gtest/gtest.h" #include <vector> #include "src/base/common.h" #include "src/data/data_structure.h" #include "src/loss/metric.h" namespace xLearn { TEST(AccMetricTest, acc_test) { std::vector<real_t> Y; Y.push_back(1.0); Y.push_back(1.0); Y.push_back(-1.0); Y.push_back(-1.0); std::vector<real_t> pred; pred.push_back(100); pred.push_back(32); pred.push_back(12); pred.push_back(-21); AccMetric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (3.0 / 4.0)); metric.Reset(); Y[0] = 1.0; Y[1] = -1.0; Y[2] = -1.0; Y[3] = 1.0; pred[0] = 12; pred[1] = 12; pred[2] = 12; pred[3] = -12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (1.0 / 4.0)); EXPECT_EQ(metric.metric_type(), "Accuarcy"); } TEST(PrecMetricTest, prec_test) { std::vector<real_t> Y; Y.push_back(1.0); Y.push_back(1.0); Y.push_back(-1.0); Y.push_back(-1.0); std::vector<real_t> pred; pred.push_back(100); pred.push_back(32); pred.push_back(12); pred.push_back(-21); PrecMetric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (2.0 / 3.0)); metric.Reset(); Y[0] = 1.0; Y[1] = -1.0; Y[2] = -1.0; Y[3] = -1.0; pred[0] = 12; pred[1] = 12; pred[2] = 12; pred[3] = -12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (1.0 / 3.0)); EXPECT_EQ(metric.metric_type(), "Precision"); } TEST(RecallMetricTest, recall_test) { std::vector<real_t> Y; Y.push_back(1.0); Y.push_back(1.0); Y.push_back(-1.0); Y.push_back(-1.0); std::vector<real_t> pred; pred.push_back(100); pred.push_back(32); pred.push_back(12); pred.push_back(-21); RecallMetric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (2.0 / 2.0)); metric.Reset(); Y[0] = 1.0; Y[1] = -1.0; Y[2] = 1.0; Y[3] = -1.0; pred[0] = 12; pred[1] = 12; pred[2] = -12; pred[3] = -12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (1.0 / 2.0)); EXPECT_EQ(metric.metric_type(), "Recall"); } TEST(F1MetricTest, f1_test) { std::vector<real_t> Y; Y.push_back(1.0); Y.push_back(1.0); Y.push_back(-1.0); Y.push_back(-1.0); std::vector<real_t> pred; pred.push_back(100); pred.push_back(32); pred.push_back(12); pred.push_back(-21); F1Metric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (4.0 / 5.0)); metric.Reset(); Y[0] = 1.0; Y[1] = -1.0; Y[2] = 1.0; Y[3] = -1.0; pred[0] = 12; pred[1] = 12; pred[2] = -12; pred[3] = -12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (2.0 / 4.0)); EXPECT_EQ(metric.metric_type(), "F1"); } TEST(MAEMetricTest, mae_test) { std::vector<real_t> Y; Y.push_back(12); Y.push_back(13); Y.push_back(14); Y.push_back(15); std::vector<real_t> pred; pred.push_back(11); pred.push_back(12); pred.push_back(13); pred.push_back(14); MAEMetric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, 1.0); metric.Reset(); Y[0] = 23; Y[1] = 24; Y[2] = 25; Y[3] = 26; pred[0] = 12; pred[1] = 12; pred[2] = 12; pred[3] = 12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, 12.5); EXPECT_EQ(metric.metric_type(), "MAE"); } TEST(MAPEMetricTest, mape_test) { std::vector<real_t> Y; Y.push_back(12); Y.push_back(12); Y.push_back(12); Y.push_back(12); std::vector<real_t> pred; pred.push_back(11); pred.push_back(11); pred.push_back(11); pred.push_back(11); MAPEMetric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, 0.0833333333); metric.Reset(); Y[0] = 23; Y[1] = 23; Y[2] = 23; Y[3] = 23; pred[0] = 12; pred[1] = 12; pred[2] = 12; pred[3] = 12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, 0.478260869); EXPECT_EQ(metric.metric_type(), "MAPE"); } TEST(RMSDMetricTest, rsmd_test) { std::vector<real_t> Y; Y.push_back(2); Y.push_back(2); Y.push_back(2); Y.push_back(2); std::vector<real_t> pred; pred.push_back(1); pred.push_back(1); pred.push_back(1); pred.push_back(1); RMSDMetric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, 1.0); metric.Reset(); Y[0] = 23; Y[1] = 23; Y[2] = 23; Y[3] = 23; pred[0] = 12; pred[1] = 12; pred[2] = 12; pred[3] = 12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, sqrt(121)); EXPECT_EQ(metric.metric_type(), "RMSD"); } Metric* CreateMetric(const char* format_name) { return CREATE_METRIC(format_name); } TEST(MetricTest, Create_Metric) { EXPECT_TRUE(CreateMetric("acc") != NULL); EXPECT_TRUE(CreateMetric("prec") != NULL); EXPECT_TRUE(CreateMetric("recall") != NULL); EXPECT_TRUE(CreateMetric("f1") != NULL); EXPECT_TRUE(CreateMetric("mae") != NULL); EXPECT_TRUE(CreateMetric("mape") != NULL); EXPECT_TRUE(CreateMetric("rmsd") != NULL); EXPECT_TRUE(CreateMetric("") == NULL); EXPECT_TRUE(CreateMetric("unknow_name") == NULL); } } // namespace xLearn<commit_msg>ADD: AUC MetricTest<commit_after>//------------------------------------------------------------------------------ // Copyright (c) 2016 by contributors. 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. //------------------------------------------------------------------------------ /* Author: Chao Ma (mctt90@gmail.com) This file tests the Metric class. */ #include "gtest/gtest.h" #include <vector> #include "src/base/common.h" #include "src/data/data_structure.h" #include "src/loss/metric.h" namespace xLearn { TEST(AccMetricTest, acc_test) { std::vector<real_t> Y; Y.push_back(1.0); Y.push_back(1.0); Y.push_back(-1.0); Y.push_back(-1.0); std::vector<real_t> pred; pred.push_back(100); pred.push_back(32); pred.push_back(12); pred.push_back(-21); AccMetric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (3.0 / 4.0)); metric.Reset(); Y[0] = 1.0; Y[1] = -1.0; Y[2] = -1.0; Y[3] = 1.0; pred[0] = 12; pred[1] = 12; pred[2] = 12; pred[3] = -12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (1.0 / 4.0)); EXPECT_EQ(metric.metric_type(), "Accuarcy"); } TEST(PrecMetricTest, prec_test) { std::vector<real_t> Y; Y.push_back(1.0); Y.push_back(1.0); Y.push_back(-1.0); Y.push_back(-1.0); std::vector<real_t> pred; pred.push_back(100); pred.push_back(32); pred.push_back(12); pred.push_back(-21); PrecMetric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (2.0 / 3.0)); metric.Reset(); Y[0] = 1.0; Y[1] = -1.0; Y[2] = -1.0; Y[3] = -1.0; pred[0] = 12; pred[1] = 12; pred[2] = 12; pred[3] = -12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (1.0 / 3.0)); EXPECT_EQ(metric.metric_type(), "Precision"); } TEST(RecallMetricTest, recall_test) { std::vector<real_t> Y; Y.push_back(1.0); Y.push_back(1.0); Y.push_back(-1.0); Y.push_back(-1.0); std::vector<real_t> pred; pred.push_back(100); pred.push_back(32); pred.push_back(12); pred.push_back(-21); RecallMetric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (2.0 / 2.0)); metric.Reset(); Y[0] = 1.0; Y[1] = -1.0; Y[2] = 1.0; Y[3] = -1.0; pred[0] = 12; pred[1] = 12; pred[2] = -12; pred[3] = -12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (1.0 / 2.0)); EXPECT_EQ(metric.metric_type(), "Recall"); } TEST(F1MetricTest, f1_test) { std::vector<real_t> Y; Y.push_back(1.0); Y.push_back(1.0); Y.push_back(-1.0); Y.push_back(-1.0); std::vector<real_t> pred; pred.push_back(100); pred.push_back(32); pred.push_back(12); pred.push_back(-21); F1Metric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (4.0 / 5.0)); metric.Reset(); Y[0] = 1.0; Y[1] = -1.0; Y[2] = 1.0; Y[3] = -1.0; pred[0] = 12; pred[1] = 12; pred[2] = -12; pred[3] = -12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, (2.0 / 4.0)); EXPECT_EQ(metric.metric_type(), "F1"); } TEST(AUCMetricTest, auc_test) { std::vector<real_t> Y = {-1.0, -1.0, 1.0, 1.0}; std::vector<real_t> pred = {0.1, 0.4, 0.35, 0.8}; AUCMetric metric; //size_t threadNumber = std::thread::hardware_concurrency(); size_t threadNumber = 2; ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, 0.75); } TEST(MAEMetricTest, mae_test) { std::vector<real_t> Y; Y.push_back(12); Y.push_back(13); Y.push_back(14); Y.push_back(15); std::vector<real_t> pred; pred.push_back(11); pred.push_back(12); pred.push_back(13); pred.push_back(14); MAEMetric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, 1.0); metric.Reset(); Y[0] = 23; Y[1] = 24; Y[2] = 25; Y[3] = 26; pred[0] = 12; pred[1] = 12; pred[2] = 12; pred[3] = 12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, 12.5); EXPECT_EQ(metric.metric_type(), "MAE"); } TEST(MAPEMetricTest, mape_test) { std::vector<real_t> Y; Y.push_back(12); Y.push_back(12); Y.push_back(12); Y.push_back(12); std::vector<real_t> pred; pred.push_back(11); pred.push_back(11); pred.push_back(11); pred.push_back(11); MAPEMetric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, 0.0833333333); metric.Reset(); Y[0] = 23; Y[1] = 23; Y[2] = 23; Y[3] = 23; pred[0] = 12; pred[1] = 12; pred[2] = 12; pred[3] = 12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, 0.478260869); EXPECT_EQ(metric.metric_type(), "MAPE"); } TEST(RMSDMetricTest, rsmd_test) { std::vector<real_t> Y; Y.push_back(2); Y.push_back(2); Y.push_back(2); Y.push_back(2); std::vector<real_t> pred; pred.push_back(1); pred.push_back(1); pred.push_back(1); pred.push_back(1); RMSDMetric metric; size_t threadNumber = std::thread::hardware_concurrency(); ThreadPool* pool = new ThreadPool(threadNumber); metric.Initialize(pool); metric.Accumulate(Y, pred); real_t metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, 1.0); metric.Reset(); Y[0] = 23; Y[1] = 23; Y[2] = 23; Y[3] = 23; pred[0] = 12; pred[1] = 12; pred[2] = 12; pred[3] = 12; metric.Accumulate(Y, pred); metric_val = metric.GetMetric(); EXPECT_FLOAT_EQ(metric_val, sqrt(121)); EXPECT_EQ(metric.metric_type(), "RMSD"); } Metric* CreateMetric(const char* format_name) { return CREATE_METRIC(format_name); } TEST(MetricTest, Create_Metric) { EXPECT_TRUE(CreateMetric("acc") != NULL); EXPECT_TRUE(CreateMetric("prec") != NULL); EXPECT_TRUE(CreateMetric("recall") != NULL); EXPECT_TRUE(CreateMetric("f1") != NULL); EXPECT_TRUE(CreateMetric("mae") != NULL); EXPECT_TRUE(CreateMetric("mape") != NULL); EXPECT_TRUE(CreateMetric("rmsd") != NULL); EXPECT_TRUE(CreateMetric("") == NULL); EXPECT_TRUE(CreateMetric("unknow_name") == NULL); } } // namespace xLearn <|endoftext|>
<commit_before>#include <class_loader/class_loader.h> #include <utexas_guidance/mdp/guidance_model.h> #include <utexas_guidance/mdp/pdpt_solver.h> #include <utexas_planning/common/exceptions.h> namespace utexas_guidance { class ActionEquals { public: explicit ActionEquals(const Action& a) : a_(a) {} inline bool operator() (const utexas_planning::Action::ConstPtr& action_base) const { Action::ConstPtr action = boost::dynamic_pointer_cast<const Action>(action_base); if (!action) { throw utexas_planning::DowncastException("utexas_planning::Action", "utexas_guidance::Action"); } return (*action == a_); } private: Action a_; }; PDPTSolver::~PDPTSolver() {} void PDPTSolver::init(const utexas_planning::GenerativeModel::ConstPtr& model_base, const YAML::Node& params, const std::string& output_directory, const boost::shared_ptr<RNG>& rng, bool verbose) { model_ = boost::dynamic_pointer_cast<const GuidanceModel>(model_base); if (!model_) { throw utexas_planning::DowncastException("utexas_planning::GenerativeModel", "utexas_guidance::GuidanceModel"); } model_->getUnderlyingGraph(graph_); motion_model_ = model_->getUnderlyingMotionModel(); task_model_ = model_->getUnderlyingTaskModel(); rng_ = rng; getAllAdjacentVertices(adjacent_vertices_map_, graph_); getAllShortestPaths(shortest_distances_, shortest_paths_, graph_); } void PDPTSolver::performEpisodeStartProcessing(const utexas_planning::State::ConstPtr& start_state, float timeout) {} utexas_planning::Action::ConstPtr PDPTSolver::getBestAction(const utexas_planning::State::ConstPtr& state_base) const { State::ConstPtr state = boost::dynamic_pointer_cast<const State>(state_base); if (!state) { throw utexas_planning::DowncastException("utexas_planning::State", "utexas_guidance::State"); } float robot_speed = motion_model_->getRobotSpeed(); std::vector<std::vector<std::pair<int, float> > > future_robot_locations(state->robots.size()); for (unsigned int robot_idx = 0; robot_idx < state->robots.size(); ++robot_idx) { const RobotState& robot = state->robots[robot_idx]; std::vector<std::pair<int, float> >& future_robot_location = future_robot_locations[robot_idx]; if (robot.help_destination == NONE) { float total_robot_time = 0.0f; int current_loc = robot.loc_u; RobotState current_task(robot); current_task.tau_total_task_time -= current_task.tau_t; if (!isRobotExactlyAt(robot, robot.tau_d)) { float current_edge_distance = shortest_distances_[robot.loc_u][robot.loc_v]; float distance_to_u = robot.loc_p * current_edge_distance; float distance_to_v = current_edge_distance - distance_to_u; float distance_from_u = shortest_distances_[robot.loc_u][robot.tau_d] + distance_to_u; float distance_from_v = shortest_distances_[robot.loc_v][robot.tau_d] + distance_to_v; if (distance_from_u < distance_from_v) { total_robot_time += distance_to_u / robot_speed; } else { current_loc = robot.loc_v; total_robot_time += distance_to_v / robot_speed; } } else { current_loc = robot.tau_d; } // TODO parametrize this time. while (total_robot_time < 150.0f) { future_robot_location.push_back(std::make_pair<int, float>(current_loc, total_robot_time)); if (current_loc == current_task.tau_d) { total_robot_time += current_task.tau_total_task_time; RNG unused_rng(0); task_model_->generateNewTaskForRobot(robot_idx, current_task, unused_rng); // Fixed task only. } int next_loc = shortest_paths_[current_loc][current_task.tau_d][0]; total_robot_time += shortest_distances_[current_loc][next_loc] / robot_speed; current_loc = next_loc; } // std::cout << "For robot idx " << robot_idx << ":-" << std::endl; // for (int future_location_idx = 0; future_location_idx < future_robot_location.size(); ++future_location_idx) { // std::cout << " " << future_robot_location[future_location_idx].first << "@" << // future_robot_location[future_location_idx].second << std::endl; // } } } /* Step 2 - For every request, calculate the intersection between the current request path, and each robot's path. * Make a special consideration for elevators. If there is an intersection, calculate how well would it do with a * transfer. If transfer is better, go for it, otherwise continue leading the robot yourself. */ std::vector<utexas_planning::Action::ConstPtr> actions; model_->getActionsAtState(state, actions); // Lead via shortest path. std::vector<std::pair<int, int> > robot_request_ids; getColocatedRobotRequestIds(*state, robot_request_ids); for (unsigned int idx_num = 0; idx_num < robot_request_ids.size(); ++idx_num) { int robot_id = robot_request_ids[idx_num].first; int request_id = robot_request_ids[idx_num].second; const RequestState& request = state->requests[request_id]; // Get shortest path to goal for this request, and see if swapping will help. Action a(LEAD_PERSON, robot_id, shortest_paths_[request.loc_node][request.goal][0], request_id); std::vector<utexas_planning::Action::ConstPtr>::const_iterator it = std::find_if(actions.begin(), actions.end(), ActionEquals(a)); if (it != actions.end()) { return *it; } } int num_assigned_robots = 0; for (unsigned int robot_idx = 0; robot_idx < state->robots.size(); ++robot_idx) { if (state->robots[robot_idx].help_destination != NONE) { ++num_assigned_robots; } } /* This logic isn't the best as the default policy, but better than nothing to prevent unnecessary robots. */ if (num_assigned_robots > state->requests.size()) { for (unsigned int robot_idx = 0; robot_idx < state->robots.size(); ++robot_idx) { if (state->robots[robot_idx].help_destination != NONE && !(state->robots[robot_idx].is_leading_person)) { Action a(RELEASE_ROBOT, robot_idx); std::vector<utexas_planning::Action::ConstPtr>::const_iterator it = std::find_if(actions.begin(), actions.end(), ActionEquals(a)); if (it != actions.end()) { return *it; } } } } return Action::ConstPtr(new Action(WAIT)); } void PDPTSolver::performPreActionProcessing(const utexas_planning::State::ConstPtr& state, const utexas_planning::Action::ConstPtr& prev_action, float timeout) { boost::this_thread::sleep(boost::posix_time::milliseconds(timeout * 1000.0f)); } void PDPTSolver::performPostActionProcessing(const utexas_planning::State::ConstPtr& state, const utexas_planning::Action::ConstPtr& action, float timeout) { boost::this_thread::sleep(boost::posix_time::milliseconds(timeout * 1000.0f)); } std::string PDPTSolver::getName() const { return std::string("SingleRobot"); } } /* utexas_guidance */ CLASS_LOADER_REGISTER_CLASS(utexas_guidance::PDPTSolver, utexas_planning::AbstractPlanner) <commit_msg>getting closer with the pdpt solver.<commit_after>#include <class_loader/class_loader.h> #include <utexas_guidance/mdp/guidance_model.h> #include <utexas_guidance/mdp/pdpt_solver.h> #include <utexas_planning/common/exceptions.h> namespace utexas_guidance { class ActionEquals { public: explicit ActionEquals(const Action& a) : a_(a) {} inline bool operator() (const utexas_planning::Action::ConstPtr& action_base) const { Action::ConstPtr action = boost::dynamic_pointer_cast<const Action>(action_base); if (!action) { throw utexas_planning::DowncastException("utexas_planning::Action", "utexas_guidance::Action"); } return (*action == a_); } private: Action a_; }; PDPTSolver::~PDPTSolver() {} void PDPTSolver::init(const utexas_planning::GenerativeModel::ConstPtr& model_base, const YAML::Node& params, const std::string& output_directory, const boost::shared_ptr<RNG>& rng, bool verbose) { model_ = boost::dynamic_pointer_cast<const GuidanceModel>(model_base); if (!model_) { throw utexas_planning::DowncastException("utexas_planning::GenerativeModel", "utexas_guidance::GuidanceModel"); } model_->getUnderlyingGraph(graph_); motion_model_ = model_->getUnderlyingMotionModel(); task_model_ = model_->getUnderlyingTaskModel(); rng_ = rng; getAllAdjacentVertices(adjacent_vertices_map_, graph_); getAllShortestPaths(shortest_distances_, shortest_paths_, graph_); } void PDPTSolver::performEpisodeStartProcessing(const utexas_planning::State::ConstPtr& start_state, float timeout) {} utexas_planning::Action::ConstPtr PDPTSolver::getBestAction(const utexas_planning::State::ConstPtr& state_base) const { State::ConstPtr state = boost::dynamic_pointer_cast<const State>(state_base); if (!state) { throw utexas_planning::DowncastException("utexas_planning::State", "utexas_guidance::State"); } float robot_speed = motion_model_->getRobotSpeed(); std::vector<std::vector<std::pair<int, float> > > future_robot_locations(state->robots.size()); for (unsigned int robot_idx = 0; robot_idx < state->robots.size(); ++robot_idx) { const RobotState& robot = state->robots[robot_idx]; std::vector<std::pair<int, float> >& future_robot_location = future_robot_locations[robot_idx]; if (robot.help_destination == NONE) { float total_robot_time = 0.0f; int current_loc = robot.loc_u; RobotState current_task(robot); current_task.tau_total_task_time -= current_task.tau_t; if (!isRobotExactlyAt(robot, robot.tau_d)) { float current_edge_distance = shortest_distances_[robot.loc_u][robot.loc_v]; float distance_to_u = robot.loc_p * current_edge_distance; float distance_to_v = current_edge_distance - distance_to_u; float distance_from_u = shortest_distances_[robot.loc_u][robot.tau_d] + distance_to_u; float distance_from_v = shortest_distances_[robot.loc_v][robot.tau_d] + distance_to_v; if (distance_from_u < distance_from_v) { total_robot_time += distance_to_u / robot_speed; } else { current_loc = robot.loc_v; total_robot_time += distance_to_v / robot_speed; } } else { current_loc = robot.tau_d; } // TODO this time needs to be computed as longest edge distance / robot speed. while (total_robot_time <= 150.0f) { future_robot_location.push_back(std::make_pair<int, float>(current_loc, total_robot_time)); if (current_loc == current_task.tau_d) { total_robot_time += current_task.tau_total_task_time; RNG unused_rng(0); task_model_->generateNewTaskForRobot(robot_idx, current_task, unused_rng); // Fixed task only. } int next_loc = shortest_paths_[current_loc][current_task.tau_d][0]; total_robot_time += shortest_distances_[current_loc][next_loc] / robot_speed; current_loc = next_loc; } // std::cout << "For robot idx " << robot_idx << ":-" << std::endl; // for (int future_location_idx = 0; future_location_idx < future_robot_location.size(); ++future_location_idx) { // std::cout << " " << future_robot_location[future_location_idx].first << "@" << // future_robot_location[future_location_idx].second << std::endl; // } } } /* Step 2 - For every request, calculate the intersection between the current request path, and each robot's path. * Make a special consideration for elevators. If there is an intersection, calculate how well would it do with a * transfer. If transfer is better, go for it, otherwise continue leading the robot yourself. */ std::vector<utexas_planning::Action::ConstPtr> actions; model_->getActionsAtState(state, actions); // Lead via shortest path. std::vector<std::pair<int, int> > robot_request_ids; getColocatedRobotRequestIds(*state, robot_request_ids); for (unsigned int idx_num = 0; idx_num < robot_request_ids.size(); ++idx_num) { int lead_robot_idx = robot_request_ids[idx_num].first; int request_id = robot_request_ids[idx_num].second; const RequestState& request = state->requests[request_id]; // Figure out if you need to: // - lead person to the goal. // OR // - assign robot at future position. // - and/or wait at current position, // First calculate intersection point. If intersection is past one step of the request, or it does not exist, LEAD PERSON. // Once intersection point has been calculated - call assign robot if robot will get there first/leave it prior to // next call. // TODO: add some code to handle elevators as well. // Calculate time to which we're interested, which is the time until the next lead action will be executed, and // see if some assignments need to take place in that time. float max_time = 150.0f; std::vector<int> first_intersection(state->robots.size(), -1); float max_relative_reward = 0.0f; int exchange_idx = -1; for (unsigned int robot_idx = 0; robot_idx < state->robots.size(); ++robot_idx) { std::vector<std::pair<int, float> >& future_robot_location = future_robot_locations[robot_idx]; int interesection_idx = -1; float robot_time_to_intersection = 0.0f; float reward = 0.0f; for (int future_location_idx = 0; future_location_idx < future_robot_location.size(); ++future_location_idx) { if (future_robot_location[future_location_idx].second > max_time) { break; } if (std::find(shortest_paths_[request.loc_node][request.goal].begin(), shortest_paths_[request.loc_node][request.goal].end(), future_robot_location[future_location_idx].first) != shortest_paths_[request.loc_node][request.goal].end()) { intersection_idx = future_robot_location[future_location_idx].first; robot_time_to_intersection = future_robot_location[future_location_idx].second; break; } } if (intersection_idx != -1) { // First calculate the reward loss due to wait at the intersection point. float lead_time_to_intersection = robot_speed * shortest_distances_[request_.loc_node][intersection_idx]; if (lead_time_to_intersection > robot_time_to_intersection) { // TODO: This is buggy, since the robot can do work during this time. You need the to know if they're gonna // wait at each location they visit as well. // TODO: This assumes the task utility is same across all background tasks. You need to store the task // utility per task as well. Overall it's starting to look like you need a better data structure than pair. reward -= state->robots[robot_idx].tau_u * (lead_time_to_intersection - robot_time_to_intersection); } else { // TODO: This assumes the task utility is same across all background tasks. You need to store the task // utility per task as well. Overall it's starting to look like you need a better data structure than pair. reward -= (1.0f + state->robots[lead_robot_idx].tau_u) * (lead_time_to_intersection - robot_time_to_intersection); } // Next, calculate the reward loss by assigning the new robot. You need the destination of the robot at the // time of intersection. // TODO: This is buggy. You don't have that destination yet. float time_to_service_destination_before_action = robot_speed * shortest_distances_[intersection_idx][destination_at_time_of_intersection]; float time_to_service_destination_after_action = robot_speed * shortest_distances_[request->goal][destination_at_time_of_intersection]; float leading_time = robot_speed * shortest_distances_[intersection_idx][request->goal]; float extra_time_to_service_destination = leading_time + time_to_service_destination_after_action - time_to_service_destination_before_action; reward -= state->robots[robot_idx].tau_u * extra_time_to_service_destination; // Next calculate the reward gain by early relief of the original leading robot. float time_to_service_destination_before_action = robot_speed * shortest_distances_[request->goal][state->robots[lead_robot_idx].tau_d]; float time_to_service_destination_after_action = robot_speed * shortest_distances_[intersection_idx][state->robots[lead_robot_idx].tau_d]; float time_not_spent_leading = robot_speed * shortest_distances_[intersection_idx][request->goal]; float time_saved = time_not_spent_leading + time_to_service_destination_before_action - time_to_service_destination_before_action; reward += state->robots[lead_robot_idx].tau_u * extra_time_to_service_destination; } if (reward > max_relative_reward) { max_relative_reward = reward; exchange_idx = robot_idx; } } // Next, figure out when the exchange will happen, should it happen. If the current location is the exchange // location, see if wait (/and assign needs to be called - assign might need to be called to prevent the robot // from moving ahead before the wait terminates. // If the current location is not the wait location, see if assignment needs to be called to prevent the robot // from moving past the intersection point. This might be merged with the last condition. // For each intersection, see which exchange will produce the best action, and then see if what action is // necessary to take. // How would an exchange work - figure out who gets there first, no loss in reward until then. If human has to // wait, then the reward is (1 + \tau_u) * time, if other robot has to wait, it is \tau_u * time. If transition // has to happen, calculate the reward gain by starting robot, and the reward loss by final robot. Pick a // transition if any. if more than the next lead action away, do nothing and drop down to the next request. for // Get shortest path to goal for this request, and see if swapping will help. Action a(LEAD_PERSON, lead_robot_idx, shortest_paths_[request.loc_node][request.goal][0], request_id); std::vector<utexas_planning::Action::ConstPtr>::const_iterator it = std::find_if(actions.begin(), actions.end(), ActionEquals(a)); if (it != actions.end()) { return *it; } } int num_assigned_robots = 0; for (unsigned int robot_idx = 0; robot_idx < state->robots.size(); ++robot_idx) { if (state->robots[robot_idx].help_destination != NONE) { ++num_assigned_robots; } } /* This logic isn't the best as the default policy, but better than nothing to prevent unnecessary robots. */ if (num_assigned_robots > state->requests.size()) { for (unsigned int robot_idx = 0; robot_idx < state->robots.size(); ++robot_idx) { if (state->robots[robot_idx].help_destination != NONE && !(state->robots[robot_idx].is_leading_person)) { Action a(RELEASE_ROBOT, robot_idx); std::vector<utexas_planning::Action::ConstPtr>::const_iterator it = std::find_if(actions.begin(), actions.end(), ActionEquals(a)); if (it != actions.end()) { return *it; } } } } return Action::ConstPtr(new Action(WAIT)); } void PDPTSolver::performPreActionProcessing(const utexas_planning::State::ConstPtr& state, const utexas_planning::Action::ConstPtr& prev_action, float timeout) { boost::this_thread::sleep(boost::posix_time::milliseconds(timeout * 1000.0f)); } void PDPTSolver::performPostActionProcessing(const utexas_planning::State::ConstPtr& state, const utexas_planning::Action::ConstPtr& action, float timeout) { boost::this_thread::sleep(boost::posix_time::milliseconds(timeout * 1000.0f)); } std::string PDPTSolver::getName() const { return std::string("SingleRobot"); } } /* utexas_guidance */ CLASS_LOADER_REGISTER_CLASS(utexas_guidance::PDPTSolver, utexas_planning::AbstractPlanner) <|endoftext|>
<commit_before>/* * Copyright (c) 2013 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Stephan Diestelhorst <stephan.diestelhorst@arm.com> */ /** * @file * Definition of a snoop filter. */ #include "base/misc.hh" #include "base/trace.hh" #include "debug/SnoopFilter.hh" #include "mem/snoop_filter.hh" #include "sim/system.hh" std::pair<SnoopFilter::SnoopList, Cycles> SnoopFilter::lookupRequest(const Packet* cpkt, const SlavePort& slave_port) { DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n", __func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopMask req_port = portToMask(slave_port); auto sf_it = cachedLocations.find(line_addr); bool is_hit = (sf_it != cachedLocations.end()); // Create a new element through operator[] and modify in-place SnoopItem& sf_item = is_hit ? sf_it->second : cachedLocations[line_addr]; SnoopMask interested = sf_item.holder | sf_item.requested; totRequests++; if (is_hit) { // Single bit set -> value is a power of two if (isPow2(interested)) hitSingleRequests++; else hitMultiRequests++; } DPRINTF(SnoopFilter, "%s: SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); if (!cpkt->req->isUncacheable() && cpkt->needsResponse()) { if (!cpkt->memInhibitAsserted()) { // Max one request per address per port panic_if(sf_item.requested & req_port, "double request :( "\ "SF value %x.%x\n", sf_item.requested, sf_item.holder); // Mark in-flight requests to distinguish later on sf_item.requested |= req_port; } else { // NOTE: The memInhibit might have been asserted by a cache closer // to the CPU, already -> the response will not be seen by this // filter -> we do not need to keep the in-flight request, but make // sure that we know that that cluster has a copy panic_if(!(sf_item.holder & req_port), "Need to hold the value!"); DPRINTF(SnoopFilter, "%s: not marking request. SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } return snoopSelected(maskToPortList(interested & ~req_port), lookupLatency); } void SnoopFilter::updateRequest(const Packet* cpkt, const SlavePort& slave_port, bool will_retry) { DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n", __func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString()); if (cpkt->req->isUncacheable()) return; Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopMask req_port = portToMask(slave_port); SnoopItem& sf_item = cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x retry: %i\n", __func__, sf_item.requested, sf_item.holder, will_retry); if (will_retry) { // Unmark a request that will come again. sf_item.requested &= ~req_port; return; } // will_retry == false if (!cpkt->needsResponse()) { // Packets that will not evoke a response but still need updates of the // snoop filter; WRITEBACKs for now only if (cpkt->cmd == MemCmd::Writeback) { // make sure that the sender actually had the line panic_if(sf_item.requested & req_port, "double request :( "\ "SF value %x.%x\n", sf_item.requested, sf_item.holder); panic_if(!(sf_item.holder & req_port), "requester %x is not a "\ "holder :( SF value %x.%x\n", req_port, sf_item.requested, sf_item.holder); // Writebacks -> the sender does not have the line anymore sf_item.holder &= ~req_port; } else { // @todo Add CleanEvicts assert(cpkt->cmd == MemCmd::CleanEvict); } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } } std::pair<SnoopFilter::SnoopList, Cycles> SnoopFilter::lookupSnoop(const Packet* cpkt) { DPRINTF(SnoopFilter, "%s: packet addr 0x%x cmd %s\n", __func__, cpkt->getAddr(), cpkt->cmdString()); assert(cpkt->isRequest()); // Broadcast / filter upward snoops const bool filter_upward = true; // @todo: Make configurable if (!filter_upward) return snoopAll(lookupLatency); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); auto sf_it = cachedLocations.find(line_addr); bool is_hit = (sf_it != cachedLocations.end()); // Create a new element through operator[] and modify in-place SnoopItem& sf_item = is_hit ? sf_it->second : cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); SnoopMask interested = (sf_item.holder | sf_item.requested); totSnoops++; if (is_hit) { // Single bit set -> value is a power of two if (isPow2(interested)) hitSingleSnoops++; else hitMultiSnoops++; } // ReadEx and Writes require both invalidation and exlusivity, while reads // require neither. Writebacks on the other hand require exclusivity but // not the invalidation. Previously Writebacks did not generate upward // snoops so this was never an aissue. Now that Writebacks generate snoops // we need to special case for Writebacks. assert(cpkt->cmd == MemCmd::Writeback || (cpkt->isInvalidate() == cpkt->needsExclusive())); if (cpkt->isInvalidate() && !sf_item.requested) { // Early clear of the holder, if no other request is currently going on // @todo: This should possibly be updated even though we do not filter // upward snoops sf_item.holder = 0; } DPRINTF(SnoopFilter, "%s: new SF value %x.%x interest: %x \n", __func__, sf_item.requested, sf_item.holder, interested); return snoopSelected(maskToPortList(interested), lookupLatency); } void SnoopFilter::updateSnoopResponse(const Packet* cpkt, const SlavePort& rsp_port, const SlavePort& req_port) { DPRINTF(SnoopFilter, "%s: packet rsp %s req %s addr 0x%x cmd %s\n", __func__, rsp_port.name(), req_port.name(), cpkt->getAddr(), cpkt->cmdString()); assert(cpkt->isResponse()); assert(cpkt->memInhibitAsserted()); if (cpkt->req->isUncacheable()) return; Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopMask rsp_mask = portToMask(rsp_port); SnoopMask req_mask = portToMask(req_port); SnoopItem& sf_item = cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // The source should have the line panic_if(!(sf_item.holder & rsp_mask), "SF value %x.%x does not have "\ "the line\n", sf_item.requested, sf_item.holder); // The destination should have had a request in panic_if(!(sf_item.requested & req_mask), "SF value %x.%x missing "\ "the original request\n", sf_item.requested, sf_item.holder); // Update the residency of the cache line. if (cpkt->needsExclusive() || !cpkt->sharedAsserted()) { DPRINTF(SnoopFilter, "%s: dropping %x because needs: %i shared: %i "\ "SF val: %x.%x\n", __func__, rsp_mask, cpkt->needsExclusive(), cpkt->sharedAsserted(), sf_item.requested, sf_item.holder); sf_item.holder &= ~rsp_mask; // The snoop filter does not see any ACKs from non-responding sharers // that have been invalidated :( So below assert would be nice, but.. //assert(sf_item.holder == 0); sf_item.holder = 0; } assert(cpkt->cmd != MemCmd::Writeback); sf_item.holder |= req_mask; sf_item.requested &= ~req_mask; DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::updateSnoopForward(const Packet* cpkt, const SlavePort& rsp_port, const MasterPort& req_port) { DPRINTF(SnoopFilter, "%s: packet rsp %s req %s addr 0x%x cmd %s\n", __func__, rsp_port.name(), req_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopItem& sf_item = cachedLocations[line_addr]; SnoopMask rsp_mask M5_VAR_USED = portToMask(rsp_port); assert(cpkt->isResponse()); assert(cpkt->memInhibitAsserted()); DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // Remote (to this snoop filter) snoops update the filter already when they // arrive from below, because we may not see any response. if (cpkt->needsExclusive()) { // If the request to this snoop response hit an in-flight transaction, // the holder was not reset -> no assertion & do that here, now! //assert(sf_item.holder == 0); sf_item.holder = 0; } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::updateResponse(const Packet* cpkt, const SlavePort& slave_port) { DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n", __func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString()); assert(cpkt->isResponse()); if (cpkt->req->isUncacheable()) return; Addr line_addr = cpkt->getAddr() & ~(linesize - 1); SnoopMask slave_mask = portToMask(slave_port); SnoopItem& sf_item = cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // Make sure we have seen the actual request, too panic_if(!(sf_item.requested & slave_mask), "SF value %x.%x missing "\ "request bit\n", sf_item.requested, sf_item.holder); // Update the residency of the cache line. if (cpkt->needsExclusive() || !cpkt->sharedAsserted()) sf_item.holder = 0; sf_item.holder |= slave_mask; sf_item.requested &= ~slave_mask; DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::regStats() { totRequests .name(name() + ".tot_requests") .desc("Total number of requests made to the snoop filter."); hitSingleRequests .name(name() + ".hit_single_requests") .desc("Number of requests hitting in the snoop filter with a single "\ "holder of the requested data."); hitMultiRequests .name(name() + ".hit_multi_requests") .desc("Number of requests hitting in the snoop filter with multiple "\ "(>1) holders of the requested data."); totSnoops .name(name() + ".tot_snoops") .desc("Total number of snoops made to the snoop filter."); hitSingleSnoops .name(name() + ".hit_single_snoops") .desc("Number of snoops hitting in the snoop filter with a single "\ "holder of the requested data."); hitMultiSnoops .name(name() + ".hit_multi_snoops") .desc("Number of snoops hitting in the snoop filter with multiple "\ "(>1) holders of the requested data."); } SnoopFilter * SnoopFilterParams::create() { return new SnoopFilter(this); } <commit_msg>mem: Add check for snooping ports in the snoop filter<commit_after>/* * Copyright (c) 2013-2015 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Stephan Diestelhorst <stephan.diestelhorst@arm.com> */ /** * @file * Definition of a snoop filter. */ #include "base/misc.hh" #include "base/trace.hh" #include "debug/SnoopFilter.hh" #include "mem/snoop_filter.hh" #include "sim/system.hh" std::pair<SnoopFilter::SnoopList, Cycles> SnoopFilter::lookupRequest(const Packet* cpkt, const SlavePort& slave_port) { DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n", __func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString()); // Ultimately we should check if the packet came from an // allocating source, not just if the port is snooping bool allocate = !cpkt->req->isUncacheable() && slave_port.isSnooping(); Addr line_addr = cpkt->getBlockAddr(linesize); SnoopMask req_port = portToMask(slave_port); auto sf_it = cachedLocations.find(line_addr); bool is_hit = (sf_it != cachedLocations.end()); // If the snoop filter has no entry, and we should not allocate, // do not create a new snoop filter entry, simply return a NULL // portlist. if (!is_hit && !allocate) return snoopDown(lookupLatency); // Create a new element through operator[] and modify in-place SnoopItem& sf_item = is_hit ? sf_it->second : cachedLocations[line_addr]; SnoopMask interested = sf_item.holder | sf_item.requested; totRequests++; if (is_hit) { // Single bit set -> value is a power of two if (isPow2(interested)) hitSingleRequests++; else hitMultiRequests++; } DPRINTF(SnoopFilter, "%s: SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); if (allocate && cpkt->needsResponse()) { if (!cpkt->memInhibitAsserted()) { // Max one request per address per port panic_if(sf_item.requested & req_port, "double request :( "\ "SF value %x.%x\n", sf_item.requested, sf_item.holder); // Mark in-flight requests to distinguish later on sf_item.requested |= req_port; } else { // NOTE: The memInhibit might have been asserted by a cache closer // to the CPU, already -> the response will not be seen by this // filter -> we do not need to keep the in-flight request, but make // sure that we know that that cluster has a copy panic_if(!(sf_item.holder & req_port), "Need to hold the value!"); DPRINTF(SnoopFilter, "%s: not marking request. SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } return snoopSelected(maskToPortList(interested & ~req_port), lookupLatency); } void SnoopFilter::updateRequest(const Packet* cpkt, const SlavePort& slave_port, bool will_retry) { DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n", __func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString()); // Ultimately we should check if the packet came from an // allocating source, not just if the port is snooping bool allocate = !cpkt->req->isUncacheable() && slave_port.isSnooping(); if (!allocate) return; Addr line_addr = cpkt->getBlockAddr(linesize); SnoopMask req_port = portToMask(slave_port); SnoopItem& sf_item = cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x retry: %i\n", __func__, sf_item.requested, sf_item.holder, will_retry); if (will_retry) { // Unmark a request that will come again. sf_item.requested &= ~req_port; return; } // will_retry == false if (!cpkt->needsResponse()) { // Packets that will not evoke a response but still need updates of the // snoop filter; WRITEBACKs for now only if (cpkt->cmd == MemCmd::Writeback) { // make sure that the sender actually had the line panic_if(sf_item.requested & req_port, "double request :( "\ "SF value %x.%x\n", sf_item.requested, sf_item.holder); panic_if(!(sf_item.holder & req_port), "requester %x is not a "\ "holder :( SF value %x.%x\n", req_port, sf_item.requested, sf_item.holder); // Writebacks -> the sender does not have the line anymore sf_item.holder &= ~req_port; } else { // @todo Add CleanEvicts assert(cpkt->cmd == MemCmd::CleanEvict); } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } } std::pair<SnoopFilter::SnoopList, Cycles> SnoopFilter::lookupSnoop(const Packet* cpkt) { DPRINTF(SnoopFilter, "%s: packet addr 0x%x cmd %s\n", __func__, cpkt->getAddr(), cpkt->cmdString()); assert(cpkt->isRequest()); // Broadcast / filter upward snoops const bool filter_upward = true; // @todo: Make configurable if (!filter_upward) return snoopAll(lookupLatency); Addr line_addr = cpkt->getBlockAddr(linesize); auto sf_it = cachedLocations.find(line_addr); bool is_hit = (sf_it != cachedLocations.end()); // Create a new element through operator[] and modify in-place SnoopItem& sf_item = is_hit ? sf_it->second : cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); SnoopMask interested = (sf_item.holder | sf_item.requested); totSnoops++; if (is_hit) { // Single bit set -> value is a power of two if (isPow2(interested)) hitSingleSnoops++; else hitMultiSnoops++; } // ReadEx and Writes require both invalidation and exlusivity, while reads // require neither. Writebacks on the other hand require exclusivity but // not the invalidation. Previously Writebacks did not generate upward // snoops so this was never an aissue. Now that Writebacks generate snoops // we need to special case for Writebacks. assert(cpkt->cmd == MemCmd::Writeback || (cpkt->isInvalidate() == cpkt->needsExclusive())); if (cpkt->isInvalidate() && !sf_item.requested) { // Early clear of the holder, if no other request is currently going on // @todo: This should possibly be updated even though we do not filter // upward snoops sf_item.holder = 0; } DPRINTF(SnoopFilter, "%s: new SF value %x.%x interest: %x \n", __func__, sf_item.requested, sf_item.holder, interested); return snoopSelected(maskToPortList(interested), lookupLatency); } void SnoopFilter::updateSnoopResponse(const Packet* cpkt, const SlavePort& rsp_port, const SlavePort& req_port) { DPRINTF(SnoopFilter, "%s: packet rsp %s req %s addr 0x%x cmd %s\n", __func__, rsp_port.name(), req_port.name(), cpkt->getAddr(), cpkt->cmdString()); assert(cpkt->isResponse()); assert(cpkt->memInhibitAsserted()); // Ultimately we should check if the packet came from an // allocating source, not just if the port is snooping bool allocate = !cpkt->req->isUncacheable() && req_port.isSnooping(); if (!allocate) return; Addr line_addr = cpkt->getBlockAddr(linesize); SnoopMask rsp_mask = portToMask(rsp_port); SnoopMask req_mask = portToMask(req_port); SnoopItem& sf_item = cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // The source should have the line panic_if(!(sf_item.holder & rsp_mask), "SF value %x.%x does not have "\ "the line\n", sf_item.requested, sf_item.holder); // The destination should have had a request in panic_if(!(sf_item.requested & req_mask), "SF value %x.%x missing "\ "the original request\n", sf_item.requested, sf_item.holder); // Update the residency of the cache line. if (cpkt->needsExclusive() || !cpkt->sharedAsserted()) { DPRINTF(SnoopFilter, "%s: dropping %x because needs: %i shared: %i "\ "SF val: %x.%x\n", __func__, rsp_mask, cpkt->needsExclusive(), cpkt->sharedAsserted(), sf_item.requested, sf_item.holder); sf_item.holder &= ~rsp_mask; // The snoop filter does not see any ACKs from non-responding sharers // that have been invalidated :( So below assert would be nice, but.. //assert(sf_item.holder == 0); sf_item.holder = 0; } assert(cpkt->cmd != MemCmd::Writeback); sf_item.holder |= req_mask; sf_item.requested &= ~req_mask; DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::updateSnoopForward(const Packet* cpkt, const SlavePort& rsp_port, const MasterPort& req_port) { DPRINTF(SnoopFilter, "%s: packet rsp %s req %s addr 0x%x cmd %s\n", __func__, rsp_port.name(), req_port.name(), cpkt->getAddr(), cpkt->cmdString()); Addr line_addr = cpkt->getBlockAddr(linesize); SnoopItem& sf_item = cachedLocations[line_addr]; SnoopMask rsp_mask M5_VAR_USED = portToMask(rsp_port); assert(cpkt->isResponse()); assert(cpkt->memInhibitAsserted()); DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // Remote (to this snoop filter) snoops update the filter already when they // arrive from below, because we may not see any response. if (cpkt->needsExclusive()) { // If the request to this snoop response hit an in-flight transaction, // the holder was not reset -> no assertion & do that here, now! //assert(sf_item.holder == 0); sf_item.holder = 0; } DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::updateResponse(const Packet* cpkt, const SlavePort& slave_port) { DPRINTF(SnoopFilter, "%s: packet src %s addr 0x%x cmd %s\n", __func__, slave_port.name(), cpkt->getAddr(), cpkt->cmdString()); assert(cpkt->isResponse()); // Ultimately we should check if the packet came from an // allocating source, not just if the port is snooping bool allocate = !cpkt->req->isUncacheable() && slave_port.isSnooping(); if (!allocate) return; Addr line_addr = cpkt->getBlockAddr(linesize); SnoopMask slave_mask = portToMask(slave_port); SnoopItem& sf_item = cachedLocations[line_addr]; DPRINTF(SnoopFilter, "%s: old SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); // Make sure we have seen the actual request, too panic_if(!(sf_item.requested & slave_mask), "SF value %x.%x missing "\ "request bit\n", sf_item.requested, sf_item.holder); // Update the residency of the cache line. if (cpkt->needsExclusive() || !cpkt->sharedAsserted()) sf_item.holder = 0; sf_item.holder |= slave_mask; sf_item.requested &= ~slave_mask; DPRINTF(SnoopFilter, "%s: new SF value %x.%x\n", __func__, sf_item.requested, sf_item.holder); } void SnoopFilter::regStats() { totRequests .name(name() + ".tot_requests") .desc("Total number of requests made to the snoop filter."); hitSingleRequests .name(name() + ".hit_single_requests") .desc("Number of requests hitting in the snoop filter with a single "\ "holder of the requested data."); hitMultiRequests .name(name() + ".hit_multi_requests") .desc("Number of requests hitting in the snoop filter with multiple "\ "(>1) holders of the requested data."); totSnoops .name(name() + ".tot_snoops") .desc("Total number of snoops made to the snoop filter."); hitSingleSnoops .name(name() + ".hit_single_snoops") .desc("Number of snoops hitting in the snoop filter with a single "\ "holder of the requested data."); hitMultiSnoops .name(name() + ".hit_multi_snoops") .desc("Number of snoops hitting in the snoop filter with multiple "\ "(>1) holders of the requested data."); } SnoopFilter * SnoopFilterParams::create() { return new SnoopFilter(this); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: collectchanges.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: ihi $ $Date: 2007-11-23 14:39:16 $ * * 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_configmgr.hxx" #include <string.h> #include "collectchanges.hxx" #include "nodechangeinfo.hxx" #include <osl/diagnose.h> namespace configmgr { namespace configuration { //----------------------------------------------------------------------------- // conversion helper function //----------------------------------------------------------------------------- bool convertNodeChange(NodeChangeData& aData_, ValueChange const& aChange_) { switch(aChange_.getMode()) { case ValueChange::wasDefault: case ValueChange::changeValue: aData_.type = NodeChangeData::eSetValue; break; case ValueChange::setToDefault: aData_.type = NodeChangeData::eSetDefault; break; case ValueChange::changeDefault: aData_.type = NodeChangeData::eNoChange; // ?? break; default: OSL_ENSURE(false,"Unknown change type found"); return false; } aData_.unoData.newValue = aChange_.getNewValue(); aData_.unoData.oldValue = aChange_.getOldValue(); return true; } //----------------------------------------------------------------------------- bool convertNodeChange(NodeChangeData& aData_, AddNode const& aChange_) { aData_.type = aChange_.isReplacing() ? NodeChangeData::eReplaceElement : NodeChangeData::eInsertElement; return true; } //----------------------------------------------------------------------------- bool convertNodeChange(NodeChangeData& aData_, RemoveNode const& /*aChange_*/) { aData_.type = NodeChangeData::eRemoveElement; return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // CollectChanges visitor class //----------------------------------------------------------------------------- CollectChanges::CollectChanges( NodeChangesInformation& rTargetList_, TreeImpl& rStartTree_, NodeOffset nStartNode_, TemplateHolder aElementTemplate_, TreeDepth nMaxDepth) : m_rTargetList(rTargetList_) , m_aAccessor() , m_aContextTypeName() , m_pBaseTree(&rStartTree_) , m_nBaseNode(nStartNode_) , m_nDepthLeft( nMaxDepth ) { if (aElementTemplate_.is()) m_aContextTypeName = aElementTemplate_->getName(); } //----------------------------------------------------------------------------- CollectChanges::CollectChanges( CollectChanges const& rBase, Path::Component const& rChildName, Name const& aSubTypeName_) : m_rTargetList(rBase.m_rTargetList) , m_aAccessor(rBase.m_aAccessor.compose(rChildName)) , m_aContextTypeName(aSubTypeName_) , m_pBaseTree(rBase.m_pBaseTree) , m_nBaseNode(rBase.m_nBaseNode) , m_nDepthLeft(childDepth(rBase.m_nDepthLeft)) { OSL_ASSERT(rBase.m_nDepthLeft > 0); } //----------------------------------------------------------------------------- inline Path::Component CollectChanges::implGetNodeName(Change const& aChange_) const { Name aSimpleNodeName = makeName( aChange_.getNodeName(), Name::NoValidate() ); if (m_aContextTypeName.isEmpty()) { OSL_ENSURE(isSimpleName(aSimpleNodeName),"Unexpected: Found non-simple name without a type"); return Path::wrapSafeName(aSimpleNodeName); } else return Path::makeCompositeName(aSimpleNodeName, m_aContextTypeName); } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(ValueChange const& aChange_) { NodeChangeInformation aInfo; if ( convertNodeChange( aInfo.change, aChange_ ) && implSetLocation( aInfo.location, aChange_, false ) ) { implAdd( aInfo ); } } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(AddNode const& aChange_) { NodeChangeInformation aInfo; if ( convertNodeChange( aInfo.change, aChange_ ) && implSetLocation( aInfo.location, aChange_, true ) ) { implAdd( aInfo ); } } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(RemoveNode const& aChange_) { NodeChangeInformation aInfo; if ( convertNodeChange( aInfo.change, aChange_ ) && implSetLocation( aInfo.location, aChange_, true ) ) { implAdd( aInfo ); } } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(SubtreeChange const& aChanges_) { if (m_nDepthLeft > 0) { Name aSubTypeName = makeName( aChanges_.getElementTemplateName(), Name::NoValidate() ); CollectChanges aSubcollector( *this, implGetNodeName(aChanges_), aSubTypeName ); aSubcollector.applyToChildren(aChanges_); } } //----------------------------------------------------------------------------- void CollectChanges::implAdd(NodeChangeInformation const& aChangeInfo_) { m_rTargetList.push_back(aChangeInfo_); } //----------------------------------------------------------------------------- bool CollectChanges::implSetLocation(NodeChangeLocation& rLocation_, Change const& aOriginal_, bool bSet_) const { NodeID aBaseID(m_pBaseTree,m_nBaseNode); if (aBaseID.isEmpty()) return false; rLocation_.setBase( aBaseID ); if (bSet_ && m_aAccessor.isEmpty()) // It is a set change affecting the base ... rLocation_.setAffected( aBaseID ); Path::Component aChangeName = implGetNodeName( aOriginal_ ); rLocation_.setAccessor( m_aAccessor.compose( aChangeName ) ); return true; } // ChangeTreeAction implementations //----------------------------------------------------------------------------- void CollectChanges::handle(ValueChange const& aValueNode_) { collectFrom(aValueNode_); } //----------------------------------------------------------------------------- void CollectChanges::handle(AddNode const& aAddNode_) { collectFrom(aAddNode_); } //----------------------------------------------------------------------------- void CollectChanges::handle(RemoveNode const& aRemoveNode_) { collectFrom(aRemoveNode_); } //----------------------------------------------------------------------------- void CollectChanges::handle(SubtreeChange const& aSubtree_) { collectFrom( aSubtree_ ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- } } <commit_msg>INTEGRATION: CWS changefileheader (1.10.16); FILE MERGED 2008/03/31 12:22:55 rt 1.10.16.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: collectchanges.cxx,v $ * $Revision: 1.11 $ * * 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_configmgr.hxx" #include <string.h> #include "collectchanges.hxx" #include "nodechangeinfo.hxx" #include <osl/diagnose.h> namespace configmgr { namespace configuration { //----------------------------------------------------------------------------- // conversion helper function //----------------------------------------------------------------------------- bool convertNodeChange(NodeChangeData& aData_, ValueChange const& aChange_) { switch(aChange_.getMode()) { case ValueChange::wasDefault: case ValueChange::changeValue: aData_.type = NodeChangeData::eSetValue; break; case ValueChange::setToDefault: aData_.type = NodeChangeData::eSetDefault; break; case ValueChange::changeDefault: aData_.type = NodeChangeData::eNoChange; // ?? break; default: OSL_ENSURE(false,"Unknown change type found"); return false; } aData_.unoData.newValue = aChange_.getNewValue(); aData_.unoData.oldValue = aChange_.getOldValue(); return true; } //----------------------------------------------------------------------------- bool convertNodeChange(NodeChangeData& aData_, AddNode const& aChange_) { aData_.type = aChange_.isReplacing() ? NodeChangeData::eReplaceElement : NodeChangeData::eInsertElement; return true; } //----------------------------------------------------------------------------- bool convertNodeChange(NodeChangeData& aData_, RemoveNode const& /*aChange_*/) { aData_.type = NodeChangeData::eRemoveElement; return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // CollectChanges visitor class //----------------------------------------------------------------------------- CollectChanges::CollectChanges( NodeChangesInformation& rTargetList_, TreeImpl& rStartTree_, NodeOffset nStartNode_, TemplateHolder aElementTemplate_, TreeDepth nMaxDepth) : m_rTargetList(rTargetList_) , m_aAccessor() , m_aContextTypeName() , m_pBaseTree(&rStartTree_) , m_nBaseNode(nStartNode_) , m_nDepthLeft( nMaxDepth ) { if (aElementTemplate_.is()) m_aContextTypeName = aElementTemplate_->getName(); } //----------------------------------------------------------------------------- CollectChanges::CollectChanges( CollectChanges const& rBase, Path::Component const& rChildName, Name const& aSubTypeName_) : m_rTargetList(rBase.m_rTargetList) , m_aAccessor(rBase.m_aAccessor.compose(rChildName)) , m_aContextTypeName(aSubTypeName_) , m_pBaseTree(rBase.m_pBaseTree) , m_nBaseNode(rBase.m_nBaseNode) , m_nDepthLeft(childDepth(rBase.m_nDepthLeft)) { OSL_ASSERT(rBase.m_nDepthLeft > 0); } //----------------------------------------------------------------------------- inline Path::Component CollectChanges::implGetNodeName(Change const& aChange_) const { Name aSimpleNodeName = makeName( aChange_.getNodeName(), Name::NoValidate() ); if (m_aContextTypeName.isEmpty()) { OSL_ENSURE(isSimpleName(aSimpleNodeName),"Unexpected: Found non-simple name without a type"); return Path::wrapSafeName(aSimpleNodeName); } else return Path::makeCompositeName(aSimpleNodeName, m_aContextTypeName); } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(ValueChange const& aChange_) { NodeChangeInformation aInfo; if ( convertNodeChange( aInfo.change, aChange_ ) && implSetLocation( aInfo.location, aChange_, false ) ) { implAdd( aInfo ); } } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(AddNode const& aChange_) { NodeChangeInformation aInfo; if ( convertNodeChange( aInfo.change, aChange_ ) && implSetLocation( aInfo.location, aChange_, true ) ) { implAdd( aInfo ); } } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(RemoveNode const& aChange_) { NodeChangeInformation aInfo; if ( convertNodeChange( aInfo.change, aChange_ ) && implSetLocation( aInfo.location, aChange_, true ) ) { implAdd( aInfo ); } } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(SubtreeChange const& aChanges_) { if (m_nDepthLeft > 0) { Name aSubTypeName = makeName( aChanges_.getElementTemplateName(), Name::NoValidate() ); CollectChanges aSubcollector( *this, implGetNodeName(aChanges_), aSubTypeName ); aSubcollector.applyToChildren(aChanges_); } } //----------------------------------------------------------------------------- void CollectChanges::implAdd(NodeChangeInformation const& aChangeInfo_) { m_rTargetList.push_back(aChangeInfo_); } //----------------------------------------------------------------------------- bool CollectChanges::implSetLocation(NodeChangeLocation& rLocation_, Change const& aOriginal_, bool bSet_) const { NodeID aBaseID(m_pBaseTree,m_nBaseNode); if (aBaseID.isEmpty()) return false; rLocation_.setBase( aBaseID ); if (bSet_ && m_aAccessor.isEmpty()) // It is a set change affecting the base ... rLocation_.setAffected( aBaseID ); Path::Component aChangeName = implGetNodeName( aOriginal_ ); rLocation_.setAccessor( m_aAccessor.compose( aChangeName ) ); return true; } // ChangeTreeAction implementations //----------------------------------------------------------------------------- void CollectChanges::handle(ValueChange const& aValueNode_) { collectFrom(aValueNode_); } //----------------------------------------------------------------------------- void CollectChanges::handle(AddNode const& aAddNode_) { collectFrom(aAddNode_); } //----------------------------------------------------------------------------- void CollectChanges::handle(RemoveNode const& aRemoveNode_) { collectFrom(aRemoveNode_); } //----------------------------------------------------------------------------- void CollectChanges::handle(SubtreeChange const& aSubtree_) { collectFrom( aSubtree_ ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: collectchanges.cxx,v $ * * $Revision: 1.1 $ * * last change: $Author: jb $ $Date: 2001-02-13 17:22:35 $ * * 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 "collectchanges.hxx" #include "nodechangeinfo.hxx" #include <osl/diagnose.h> namespace configmgr { namespace configuration { //----------------------------------------------------------------------------- // conversion helper function //----------------------------------------------------------------------------- bool convertNodeChange(NodeChangeData& aData_, ValueChange const& aChange_) { switch(aChange_.getMode()) { case ValueChange::wasDefault: case ValueChange::typeIsAny: case ValueChange::changeValue: aData_.type = NodeChangeData::eSetValue; break; case ValueChange::setToDefault: aData_.type = NodeChangeData::eSetDefault; break; case ValueChange::changeDefault: aData_.type = NodeChangeData::eNoChange; // ?? break; default: OSL_ENSURE(false,"Unknown change type found"); return false; } aData_.unoData.newValue = aChange_.getNewValue(); aData_.unoData.oldValue = aChange_.getOldValue(); return true; } //----------------------------------------------------------------------------- bool convertNodeChange(NodeChangeData& aData_, AddNode const& aChange_) { aData_.type = aChange_.isReplacing() ? NodeChangeData::eReplaceElement : NodeChangeData::eInsertElement; return true; } //----------------------------------------------------------------------------- bool convertNodeChange(NodeChangeData& aData_, RemoveNode const& aChange_) { aData_.type = NodeChangeData::eRemoveElement; return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // CollectChanges visitor class //----------------------------------------------------------------------------- CollectChanges::CollectChanges( NodeChangesInformation& rTargetList_, TreeImpl& rStartTree_, NodeOffset nStartNode_, TreeDepth nMaxDepth) : m_rTargetList(rTargetList_) , m_aAccessor() , m_pBaseTree(&rStartTree_) , m_nBaseNode(nStartNode_) , m_nDepthLeft( nMaxDepth ) { } //----------------------------------------------------------------------------- CollectChanges::CollectChanges( CollectChanges const& rBase, Name const& rChildName) : m_rTargetList(rBase.m_rTargetList) , m_aAccessor(rBase.m_aAccessor.child(rChildName)) , m_pBaseTree(rBase.m_pBaseTree) , m_nBaseNode(rBase.m_nBaseNode) , m_nDepthLeft(childDepth(rBase.m_nDepthLeft)) { OSL_ASSERT(rBase.m_nDepthLeft > 0); } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(ValueChange const& aChange_) { NodeChangeInformation aInfo; if ( convertNodeChange( aInfo.change, aChange_ ) && implSetLocation( aInfo.location, aChange_, false ) ) { implAdd( aInfo ); } } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(AddNode const& aChange_) { NodeChangeInformation aInfo; if ( convertNodeChange( aInfo.change, aChange_ ) && implSetLocation( aInfo.location, aChange_, true ) ) { implAdd( aInfo ); } } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(RemoveNode const& aChange_) { NodeChangeInformation aInfo; if ( convertNodeChange( aInfo.change, aChange_ ) && implSetLocation( aInfo.location, aChange_, true ) ) { implAdd( aInfo ); } } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(SubtreeChange const& aChanges_) { if (m_nDepthLeft > 0) { Name aNodeName( aChanges_.getNodeName(), Name::NoValidate() ); CollectChanges aSubcollector( *this, aNodeName ); aSubcollector.applyToChildren(aChanges_); } } //----------------------------------------------------------------------------- void CollectChanges::implAdd(NodeChangeInformation const& aChangeInfo_) { m_rTargetList.push_back(aChangeInfo_); } //----------------------------------------------------------------------------- bool CollectChanges::implSetLocation(NodeChangeLocation& rLocation_, Change const& aOriginal_, bool bSet_) const { NodeID aBaseID(m_pBaseTree,m_nBaseNode); if (aBaseID.isEmpty()) return false; rLocation_.setBase( aBaseID ); if (bSet_ && m_aAccessor.isEmpty()) // It is a set change affecting the base ... rLocation_.setTarget( aBaseID ); Name aChangeName( aOriginal_.getNodeName(), Name::NoValidate() ); rLocation_.setAccessor( m_aAccessor.child( aChangeName ) ); return true; } // ChangeTreeAction implementations //----------------------------------------------------------------------------- void CollectChanges::handle(ValueChange const& aValueNode_) { collectFrom(aValueNode_); } //----------------------------------------------------------------------------- void CollectChanges::handle(AddNode const& aAddNode_) { collectFrom(aAddNode_); } //----------------------------------------------------------------------------- void CollectChanges::handle(RemoveNode const& aRemoveNode_) { collectFrom(aRemoveNode_); } //----------------------------------------------------------------------------- void CollectChanges::handle(SubtreeChange const& aSubtree_) { collectFrom( aSubtree_ ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- } } <commit_msg>#88036# Adjusted to NodeVisitor change<commit_after>/************************************************************************* * * $RCSfile: collectchanges.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: jb $ $Date: 2001-06-20 20:35:06 $ * * 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 "collectchanges.hxx" #include "nodechangeinfo.hxx" #include <osl/diagnose.h> namespace configmgr { namespace configuration { //----------------------------------------------------------------------------- // conversion helper function //----------------------------------------------------------------------------- bool convertNodeChange(NodeChangeData& aData_, ValueChange const& aChange_) { switch(aChange_.getMode()) { case ValueChange::wasDefault: case ValueChange::typeIsAny: case ValueChange::changeValue: aData_.type = NodeChangeData::eSetValue; break; case ValueChange::setToDefault: aData_.type = NodeChangeData::eSetDefault; break; case ValueChange::changeDefault: aData_.type = NodeChangeData::eNoChange; // ?? break; default: OSL_ENSURE(false,"Unknown change type found"); return false; } aData_.unoData.newValue = aChange_.getNewValue(); aData_.unoData.oldValue = aChange_.getOldValue(); return true; } //----------------------------------------------------------------------------- bool convertNodeChange(NodeChangeData& aData_, AddNode const& aChange_) { aData_.type = aChange_.isReplacing() ? NodeChangeData::eReplaceElement : NodeChangeData::eInsertElement; return true; } //----------------------------------------------------------------------------- bool convertNodeChange(NodeChangeData& aData_, RemoveNode const& aChange_) { aData_.type = NodeChangeData::eRemoveElement; return true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // CollectChanges visitor class //----------------------------------------------------------------------------- CollectChanges::CollectChanges( NodeChangesInformation& rTargetList_, TreeImpl& rStartTree_, NodeOffset nStartNode_, TreeDepth nMaxDepth) : m_rTargetList(rTargetList_) , m_aAccessor() , m_pBaseTree(&rStartTree_) , m_nBaseNode(nStartNode_) , m_nDepthLeft( nMaxDepth ) { } //----------------------------------------------------------------------------- CollectChanges::CollectChanges( CollectChanges const& rBase, Name const& rChildName) : m_rTargetList(rBase.m_rTargetList) , m_aAccessor(rBase.m_aAccessor.child(rChildName)) , m_pBaseTree(rBase.m_pBaseTree) , m_nBaseNode(rBase.m_nBaseNode) , m_nDepthLeft(childDepth(rBase.m_nDepthLeft)) { OSL_ASSERT(rBase.m_nDepthLeft > 0); } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(ValueChange const& aChange_) { NodeChangeInformation aInfo; if ( convertNodeChange( aInfo.change, aChange_ ) && implSetLocation( aInfo.location, aChange_, false ) ) { implAdd( aInfo ); } } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(AddNode const& aChange_) { NodeChangeInformation aInfo; if ( convertNodeChange( aInfo.change, aChange_ ) && implSetLocation( aInfo.location, aChange_, true ) ) { implAdd( aInfo ); } } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(RemoveNode const& aChange_) { NodeChangeInformation aInfo; if ( convertNodeChange( aInfo.change, aChange_ ) && implSetLocation( aInfo.location, aChange_, true ) ) { implAdd( aInfo ); } } //----------------------------------------------------------------------------- void CollectChanges::collectFrom(SubtreeChange const& aChanges_) { if (m_nDepthLeft > 0) { Name aNodeName( aChanges_.getNodeName(), Name::NoValidate() ); CollectChanges aSubcollector( *this, aNodeName ); aSubcollector.applyToChildren(aChanges_); } } //----------------------------------------------------------------------------- void CollectChanges::implAdd(NodeChangeInformation const& aChangeInfo_) { m_rTargetList.push_back(aChangeInfo_); } //----------------------------------------------------------------------------- bool CollectChanges::implSetLocation(NodeChangeLocation& rLocation_, Change const& aOriginal_, bool bSet_) const { NodeID aBaseID(m_pBaseTree,m_nBaseNode); if (aBaseID.isEmpty()) return false; rLocation_.setBase( aBaseID ); if (bSet_ && m_aAccessor.isEmpty()) // It is a set change affecting the base ... rLocation_.setAffected( aBaseID ); Name aChangeName( aOriginal_.getNodeName(), Name::NoValidate() ); rLocation_.setAccessor( m_aAccessor.child( aChangeName ) ); return true; } // ChangeTreeAction implementations //----------------------------------------------------------------------------- void CollectChanges::handle(ValueChange const& aValueNode_) { collectFrom(aValueNode_); } //----------------------------------------------------------------------------- void CollectChanges::handle(AddNode const& aAddNode_) { collectFrom(aAddNode_); } //----------------------------------------------------------------------------- void CollectChanges::handle(RemoveNode const& aRemoveNode_) { collectFrom(aRemoveNode_); } //----------------------------------------------------------------------------- void CollectChanges::handle(SubtreeChange const& aSubtree_) { collectFrom( aSubtree_ ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- } } <|endoftext|>
<commit_before><commit_msg>removed debugging code<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: intercept.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-06-20 02:45:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _COM_SUN_STAR_EMBED_EMBEDSTATES_HPP_ #include <com/sun/star/embed/EmbedStates.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTBROADCASTER_HPP_ #include <com/sun/star/document/XEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XMODIFIABLE_HPP_ #include <com/sun/star/util/XModifiable.hpp> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef DBA_INTERCEPT_HXX #include "intercept.hxx" #endif #include "dbastrings.hrc" #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif namespace dbaccess { using namespace ::com::sun::star::uno; using namespace ::com::sun::star::util; using namespace ::com::sun::star::ucb; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::io; using namespace ::com::sun::star::embed; using namespace ::com::sun::star::container; using namespace ::comphelper; using namespace ::cppu; #define DISPATCH_SAVEAS 0 #define DISPATCH_SAVE 1 #define DISPATCH_CLOSEDOC 2 #define DISPATCH_CLOSEWIN 3 #define DISPATCH_CLOSEFRAME 4 #define DISPATCH_RELOAD 5 // the OSL_ENSURE in CTOR has to be changed too, when adding new defines void SAL_CALL OInterceptor::dispose() throw( RuntimeException ) { EventObject aEvt( *this ); osl::MutexGuard aGuard(m_aMutex); if ( m_pDisposeEventListeners && m_pDisposeEventListeners->getLength() ) m_pDisposeEventListeners->disposeAndClear( aEvt ); if ( m_pStatCL ) m_pStatCL->disposeAndClear( aEvt ); m_xSlaveDispatchProvider.clear(); m_xMasterDispatchProvider.clear(); m_pContentHolder = NULL; } DBG_NAME(OInterceptor) OInterceptor::OInterceptor( ODocumentDefinition* _pContentHolder,sal_Bool _bAllowEditDoc ) :m_pContentHolder( _pContentHolder ) ,m_aInterceptedURL(7) ,m_pDisposeEventListeners(0) ,m_pStatCL(0) ,m_bAllowEditDoc(_bAllowEditDoc) { DBG_CTOR(OInterceptor,NULL); OSL_ENSURE(DISPATCH_RELOAD < m_aInterceptedURL.getLength(),"Illegal size."); m_aInterceptedURL[DISPATCH_SAVEAS] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:SaveAs")); m_aInterceptedURL[DISPATCH_SAVE] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:Save")); m_aInterceptedURL[DISPATCH_CLOSEDOC] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:CloseDoc")); m_aInterceptedURL[DISPATCH_CLOSEWIN] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:CloseWin")); m_aInterceptedURL[DISPATCH_CLOSEFRAME] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:CloseFrame")); m_aInterceptedURL[DISPATCH_RELOAD] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:Reload")); } OInterceptor::~OInterceptor() { if( m_pDisposeEventListeners ) delete m_pDisposeEventListeners; if(m_pStatCL) delete m_pStatCL; DBG_DTOR(OInterceptor,NULL); } //XDispatch void SAL_CALL OInterceptor::dispatch( const URL& _URL, const Sequence< PropertyValue >& Arguments ) throw (RuntimeException) { osl::MutexGuard aGuard(m_aMutex); if( m_pContentHolder ) if( _URL.Complete == m_aInterceptedURL[DISPATCH_SAVE] ) { m_pContentHolder->save(sal_False); } else if( _URL.Complete == m_aInterceptedURL[DISPATCH_RELOAD] ) { m_pContentHolder->fillReportData(); } else if( _URL.Complete == m_aInterceptedURL[DISPATCH_SAVEAS] ) { Sequence< PropertyValue > aNewArgs = Arguments; sal_Int32 nInd = 0; while( nInd < aNewArgs.getLength() ) { if ( aNewArgs[nInd].Name.equalsAscii( "SaveTo" ) ) { aNewArgs[nInd].Value <<= sal_True; break; } nInd++; } if ( nInd == aNewArgs.getLength() ) { aNewArgs.realloc( nInd + 1 ); aNewArgs[nInd].Name = ::rtl::OUString::createFromAscii( "SaveTo" ); aNewArgs[nInd].Value <<= sal_True; } Reference< XDispatch > xDispatch = m_xSlaveDispatchProvider->queryDispatch( _URL, ::rtl::OUString::createFromAscii( "_self" ), 0 ); if ( xDispatch.is() ) xDispatch->dispatch( _URL, aNewArgs ); } else if ( _URL.Complete == m_aInterceptedURL[DISPATCH_CLOSEDOC] || _URL.Complete == m_aInterceptedURL[DISPATCH_CLOSEWIN] || _URL.Complete == m_aInterceptedURL[DISPATCH_CLOSEFRAME] ) { if ( m_pContentHolder->prepareClose() ) { Reference< XDispatch > xDispatch = m_xSlaveDispatchProvider->queryDispatch( _URL, ::rtl::OUString::createFromAscii( "_self" ), 0 ); if ( xDispatch.is() ) { Reference< ::com::sun::star::document::XEventBroadcaster> xEvtB(m_pContentHolder->getComponent(),UNO_QUERY); if ( xEvtB.is() ) xEvtB->removeEventListener(this); Reference< XInterface > xKeepContentHolderAlive( *m_pContentHolder ); xDispatch->dispatch( _URL, Arguments ); } } } } void SAL_CALL OInterceptor::addStatusListener( const Reference< XStatusListener >& Control, const URL& _URL ) throw ( RuntimeException ) { if(!Control.is()) return; if ( m_pContentHolder && _URL.Complete == m_aInterceptedURL[DISPATCH_SAVEAS] ) { // SaveAs FeatureStateEvent aStateEvent; aStateEvent.FeatureURL.Complete = m_aInterceptedURL[DISPATCH_SAVEAS]; aStateEvent.FeatureDescriptor = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SaveCopyTo")); aStateEvent.IsEnabled = sal_True; aStateEvent.Requery = sal_False; aStateEvent.State <<= (rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("($3)"))); Control->statusChanged(aStateEvent); { osl::MutexGuard aGuard(m_aMutex); if(!m_pStatCL) m_pStatCL = new PropertyChangeListenerContainer(m_aMutex); } m_pStatCL->addInterface(_URL.Complete,Control); } else if ( m_pContentHolder && _URL.Complete == m_aInterceptedURL[DISPATCH_SAVE] ) { // Save FeatureStateEvent aStateEvent; aStateEvent.FeatureURL.Complete = m_aInterceptedURL[DISPATCH_SAVE]; aStateEvent.FeatureDescriptor = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Update")); aStateEvent.IsEnabled = m_pContentHolder != NULL && m_pContentHolder->isModified(); aStateEvent.Requery = sal_False; Control->statusChanged(aStateEvent); { osl::MutexGuard aGuard(m_aMutex); if(!m_pStatCL) m_pStatCL = new PropertyChangeListenerContainer(m_aMutex); } m_pStatCL->addInterface(_URL.Complete,Control); Reference< ::com::sun::star::document::XEventBroadcaster> xEvtB(m_pContentHolder->getComponent(),UNO_QUERY); if ( xEvtB.is() ) xEvtB->addEventListener(this); } else { sal_Int32 i = 2; if(_URL.Complete == m_aInterceptedURL[i] || _URL.Complete == m_aInterceptedURL[++i] || _URL.Complete == m_aInterceptedURL[++i] || _URL.Complete == m_aInterceptedURL[i = DISPATCH_RELOAD] ) { // Close and return FeatureStateEvent aStateEvent; aStateEvent.FeatureURL.Complete = m_aInterceptedURL[i]; aStateEvent.FeatureDescriptor = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Close and Return")); aStateEvent.IsEnabled = sal_True; aStateEvent.Requery = sal_False; Control->statusChanged(aStateEvent); { osl::MutexGuard aGuard(m_aMutex); if(!m_pStatCL) m_pStatCL = new PropertyChangeListenerContainer(m_aMutex); } m_pStatCL->addInterface(_URL.Complete,Control); return; } } } void SAL_CALL OInterceptor::removeStatusListener( const Reference< XStatusListener >& Control, const URL& _URL ) throw ( RuntimeException ) { if(!(Control.is() && m_pStatCL)) return; else { m_pStatCL->removeInterface(_URL.Complete,Control); return; } } //XInterceptorInfo Sequence< ::rtl::OUString > SAL_CALL OInterceptor::getInterceptedURLs( ) throw ( RuntimeException ) { // now implemented as update return m_aInterceptedURL; } // XDispatchProvider Reference< XDispatch > SAL_CALL OInterceptor::queryDispatch( const URL& _URL, const ::rtl::OUString& TargetFrameName, sal_Int32 SearchFlags ) throw ( RuntimeException ) { osl::MutexGuard aGuard(m_aMutex); const ::rtl::OUString* pIter = m_aInterceptedURL.getConstArray(); const ::rtl::OUString* pEnd = pIter + m_aInterceptedURL.getLength(); for(;pIter != pEnd;++pIter) { if ( _URL.Complete == *pIter ) return (XDispatch*)this; } if(m_xSlaveDispatchProvider.is()) return m_xSlaveDispatchProvider->queryDispatch(_URL,TargetFrameName,SearchFlags); else return Reference<XDispatch>(); } Sequence< Reference< XDispatch > > SAL_CALL OInterceptor::queryDispatches( const Sequence<DispatchDescriptor >& Requests ) throw ( RuntimeException ) { Sequence< Reference< XDispatch > > aRet; osl::MutexGuard aGuard(m_aMutex); if(m_xSlaveDispatchProvider.is()) aRet = m_xSlaveDispatchProvider->queryDispatches(Requests); else aRet.realloc(Requests.getLength()); for(sal_Int32 i = 0; i < Requests.getLength(); ++i) { const ::rtl::OUString* pIter = m_aInterceptedURL.getConstArray(); const ::rtl::OUString* pEnd = pIter + m_aInterceptedURL.getLength(); for(;pIter != pEnd;++pIter) { if ( Requests[i].FeatureURL.Complete == *pIter ) { aRet[i] = (XDispatch*) this; break; } } } return aRet; } //XDispatchProviderInterceptor Reference< XDispatchProvider > SAL_CALL OInterceptor::getSlaveDispatchProvider( ) throw ( RuntimeException ) { osl::MutexGuard aGuard(m_aMutex); return m_xSlaveDispatchProvider; } void SAL_CALL OInterceptor::setSlaveDispatchProvider( const Reference< XDispatchProvider >& NewDispatchProvider ) throw ( RuntimeException ) { osl::MutexGuard aGuard(m_aMutex); m_xSlaveDispatchProvider = NewDispatchProvider; } Reference< XDispatchProvider > SAL_CALL OInterceptor::getMasterDispatchProvider( ) throw ( RuntimeException ) { osl::MutexGuard aGuard(m_aMutex); return m_xMasterDispatchProvider; } void SAL_CALL OInterceptor::setMasterDispatchProvider( const Reference< XDispatchProvider >& NewSupplier ) throw ( RuntimeException ) { osl::MutexGuard aGuard(m_aMutex); m_xMasterDispatchProvider = NewSupplier; } // ----------------------------------------------------------------------------- void SAL_CALL OInterceptor::notifyEvent( const ::com::sun::star::document::EventObject& Event ) throw (::com::sun::star::uno::RuntimeException) { osl::ResettableMutexGuard _rGuard(m_aMutex); if ( m_pStatCL && Event.EventName == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("OnModifyChanged")) ) { OInterfaceContainerHelper* pListener = m_pStatCL->getContainer(m_aInterceptedURL[DISPATCH_SAVE]); if ( pListener ) { FeatureStateEvent aEvt; aEvt.FeatureURL.Complete = m_aInterceptedURL[DISPATCH_SAVE]; aEvt.FeatureDescriptor = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Update")); Reference<XModifiable> xModel(Event.Source,UNO_QUERY); aEvt.IsEnabled = xModel.is() && xModel->isModified(); aEvt.Requery = sal_False; NOTIFY_LISTERNERS((*pListener),XStatusListener,statusChanged) } } } // ----------------------------------------------------------------------------- void SAL_CALL OInterceptor::disposing( const ::com::sun::star::lang::EventObject& /*Source*/ ) throw (::com::sun::star::uno::RuntimeException) { } //........................................................................ } // namespace dbaccess //........................................................................ <commit_msg>INTEGRATION: CWS pchfix02 (1.7.52); FILE MERGED 2006/09/01 17:24:09 kaib 1.7.52.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: intercept.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: obo $ $Date: 2006-09-17 06:40:38 $ * * 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_dbaccess.hxx" #ifndef _COM_SUN_STAR_EMBED_EMBEDSTATES_HPP_ #include <com/sun/star/embed/EmbedStates.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEVENTBROADCASTER_HPP_ #include <com/sun/star/document/XEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XMODIFIABLE_HPP_ #include <com/sun/star/util/XModifiable.hpp> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef DBA_INTERCEPT_HXX #include "intercept.hxx" #endif #include "dbastrings.hrc" #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif namespace dbaccess { using namespace ::com::sun::star::uno; using namespace ::com::sun::star::util; using namespace ::com::sun::star::ucb; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::io; using namespace ::com::sun::star::embed; using namespace ::com::sun::star::container; using namespace ::comphelper; using namespace ::cppu; #define DISPATCH_SAVEAS 0 #define DISPATCH_SAVE 1 #define DISPATCH_CLOSEDOC 2 #define DISPATCH_CLOSEWIN 3 #define DISPATCH_CLOSEFRAME 4 #define DISPATCH_RELOAD 5 // the OSL_ENSURE in CTOR has to be changed too, when adding new defines void SAL_CALL OInterceptor::dispose() throw( RuntimeException ) { EventObject aEvt( *this ); osl::MutexGuard aGuard(m_aMutex); if ( m_pDisposeEventListeners && m_pDisposeEventListeners->getLength() ) m_pDisposeEventListeners->disposeAndClear( aEvt ); if ( m_pStatCL ) m_pStatCL->disposeAndClear( aEvt ); m_xSlaveDispatchProvider.clear(); m_xMasterDispatchProvider.clear(); m_pContentHolder = NULL; } DBG_NAME(OInterceptor) OInterceptor::OInterceptor( ODocumentDefinition* _pContentHolder,sal_Bool _bAllowEditDoc ) :m_pContentHolder( _pContentHolder ) ,m_aInterceptedURL(7) ,m_pDisposeEventListeners(0) ,m_pStatCL(0) ,m_bAllowEditDoc(_bAllowEditDoc) { DBG_CTOR(OInterceptor,NULL); OSL_ENSURE(DISPATCH_RELOAD < m_aInterceptedURL.getLength(),"Illegal size."); m_aInterceptedURL[DISPATCH_SAVEAS] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:SaveAs")); m_aInterceptedURL[DISPATCH_SAVE] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:Save")); m_aInterceptedURL[DISPATCH_CLOSEDOC] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:CloseDoc")); m_aInterceptedURL[DISPATCH_CLOSEWIN] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:CloseWin")); m_aInterceptedURL[DISPATCH_CLOSEFRAME] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:CloseFrame")); m_aInterceptedURL[DISPATCH_RELOAD] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".uno:Reload")); } OInterceptor::~OInterceptor() { if( m_pDisposeEventListeners ) delete m_pDisposeEventListeners; if(m_pStatCL) delete m_pStatCL; DBG_DTOR(OInterceptor,NULL); } //XDispatch void SAL_CALL OInterceptor::dispatch( const URL& _URL, const Sequence< PropertyValue >& Arguments ) throw (RuntimeException) { osl::MutexGuard aGuard(m_aMutex); if( m_pContentHolder ) if( _URL.Complete == m_aInterceptedURL[DISPATCH_SAVE] ) { m_pContentHolder->save(sal_False); } else if( _URL.Complete == m_aInterceptedURL[DISPATCH_RELOAD] ) { m_pContentHolder->fillReportData(); } else if( _URL.Complete == m_aInterceptedURL[DISPATCH_SAVEAS] ) { Sequence< PropertyValue > aNewArgs = Arguments; sal_Int32 nInd = 0; while( nInd < aNewArgs.getLength() ) { if ( aNewArgs[nInd].Name.equalsAscii( "SaveTo" ) ) { aNewArgs[nInd].Value <<= sal_True; break; } nInd++; } if ( nInd == aNewArgs.getLength() ) { aNewArgs.realloc( nInd + 1 ); aNewArgs[nInd].Name = ::rtl::OUString::createFromAscii( "SaveTo" ); aNewArgs[nInd].Value <<= sal_True; } Reference< XDispatch > xDispatch = m_xSlaveDispatchProvider->queryDispatch( _URL, ::rtl::OUString::createFromAscii( "_self" ), 0 ); if ( xDispatch.is() ) xDispatch->dispatch( _URL, aNewArgs ); } else if ( _URL.Complete == m_aInterceptedURL[DISPATCH_CLOSEDOC] || _URL.Complete == m_aInterceptedURL[DISPATCH_CLOSEWIN] || _URL.Complete == m_aInterceptedURL[DISPATCH_CLOSEFRAME] ) { if ( m_pContentHolder->prepareClose() ) { Reference< XDispatch > xDispatch = m_xSlaveDispatchProvider->queryDispatch( _URL, ::rtl::OUString::createFromAscii( "_self" ), 0 ); if ( xDispatch.is() ) { Reference< ::com::sun::star::document::XEventBroadcaster> xEvtB(m_pContentHolder->getComponent(),UNO_QUERY); if ( xEvtB.is() ) xEvtB->removeEventListener(this); Reference< XInterface > xKeepContentHolderAlive( *m_pContentHolder ); xDispatch->dispatch( _URL, Arguments ); } } } } void SAL_CALL OInterceptor::addStatusListener( const Reference< XStatusListener >& Control, const URL& _URL ) throw ( RuntimeException ) { if(!Control.is()) return; if ( m_pContentHolder && _URL.Complete == m_aInterceptedURL[DISPATCH_SAVEAS] ) { // SaveAs FeatureStateEvent aStateEvent; aStateEvent.FeatureURL.Complete = m_aInterceptedURL[DISPATCH_SAVEAS]; aStateEvent.FeatureDescriptor = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SaveCopyTo")); aStateEvent.IsEnabled = sal_True; aStateEvent.Requery = sal_False; aStateEvent.State <<= (rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("($3)"))); Control->statusChanged(aStateEvent); { osl::MutexGuard aGuard(m_aMutex); if(!m_pStatCL) m_pStatCL = new PropertyChangeListenerContainer(m_aMutex); } m_pStatCL->addInterface(_URL.Complete,Control); } else if ( m_pContentHolder && _URL.Complete == m_aInterceptedURL[DISPATCH_SAVE] ) { // Save FeatureStateEvent aStateEvent; aStateEvent.FeatureURL.Complete = m_aInterceptedURL[DISPATCH_SAVE]; aStateEvent.FeatureDescriptor = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Update")); aStateEvent.IsEnabled = m_pContentHolder != NULL && m_pContentHolder->isModified(); aStateEvent.Requery = sal_False; Control->statusChanged(aStateEvent); { osl::MutexGuard aGuard(m_aMutex); if(!m_pStatCL) m_pStatCL = new PropertyChangeListenerContainer(m_aMutex); } m_pStatCL->addInterface(_URL.Complete,Control); Reference< ::com::sun::star::document::XEventBroadcaster> xEvtB(m_pContentHolder->getComponent(),UNO_QUERY); if ( xEvtB.is() ) xEvtB->addEventListener(this); } else { sal_Int32 i = 2; if(_URL.Complete == m_aInterceptedURL[i] || _URL.Complete == m_aInterceptedURL[++i] || _URL.Complete == m_aInterceptedURL[++i] || _URL.Complete == m_aInterceptedURL[i = DISPATCH_RELOAD] ) { // Close and return FeatureStateEvent aStateEvent; aStateEvent.FeatureURL.Complete = m_aInterceptedURL[i]; aStateEvent.FeatureDescriptor = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Close and Return")); aStateEvent.IsEnabled = sal_True; aStateEvent.Requery = sal_False; Control->statusChanged(aStateEvent); { osl::MutexGuard aGuard(m_aMutex); if(!m_pStatCL) m_pStatCL = new PropertyChangeListenerContainer(m_aMutex); } m_pStatCL->addInterface(_URL.Complete,Control); return; } } } void SAL_CALL OInterceptor::removeStatusListener( const Reference< XStatusListener >& Control, const URL& _URL ) throw ( RuntimeException ) { if(!(Control.is() && m_pStatCL)) return; else { m_pStatCL->removeInterface(_URL.Complete,Control); return; } } //XInterceptorInfo Sequence< ::rtl::OUString > SAL_CALL OInterceptor::getInterceptedURLs( ) throw ( RuntimeException ) { // now implemented as update return m_aInterceptedURL; } // XDispatchProvider Reference< XDispatch > SAL_CALL OInterceptor::queryDispatch( const URL& _URL, const ::rtl::OUString& TargetFrameName, sal_Int32 SearchFlags ) throw ( RuntimeException ) { osl::MutexGuard aGuard(m_aMutex); const ::rtl::OUString* pIter = m_aInterceptedURL.getConstArray(); const ::rtl::OUString* pEnd = pIter + m_aInterceptedURL.getLength(); for(;pIter != pEnd;++pIter) { if ( _URL.Complete == *pIter ) return (XDispatch*)this; } if(m_xSlaveDispatchProvider.is()) return m_xSlaveDispatchProvider->queryDispatch(_URL,TargetFrameName,SearchFlags); else return Reference<XDispatch>(); } Sequence< Reference< XDispatch > > SAL_CALL OInterceptor::queryDispatches( const Sequence<DispatchDescriptor >& Requests ) throw ( RuntimeException ) { Sequence< Reference< XDispatch > > aRet; osl::MutexGuard aGuard(m_aMutex); if(m_xSlaveDispatchProvider.is()) aRet = m_xSlaveDispatchProvider->queryDispatches(Requests); else aRet.realloc(Requests.getLength()); for(sal_Int32 i = 0; i < Requests.getLength(); ++i) { const ::rtl::OUString* pIter = m_aInterceptedURL.getConstArray(); const ::rtl::OUString* pEnd = pIter + m_aInterceptedURL.getLength(); for(;pIter != pEnd;++pIter) { if ( Requests[i].FeatureURL.Complete == *pIter ) { aRet[i] = (XDispatch*) this; break; } } } return aRet; } //XDispatchProviderInterceptor Reference< XDispatchProvider > SAL_CALL OInterceptor::getSlaveDispatchProvider( ) throw ( RuntimeException ) { osl::MutexGuard aGuard(m_aMutex); return m_xSlaveDispatchProvider; } void SAL_CALL OInterceptor::setSlaveDispatchProvider( const Reference< XDispatchProvider >& NewDispatchProvider ) throw ( RuntimeException ) { osl::MutexGuard aGuard(m_aMutex); m_xSlaveDispatchProvider = NewDispatchProvider; } Reference< XDispatchProvider > SAL_CALL OInterceptor::getMasterDispatchProvider( ) throw ( RuntimeException ) { osl::MutexGuard aGuard(m_aMutex); return m_xMasterDispatchProvider; } void SAL_CALL OInterceptor::setMasterDispatchProvider( const Reference< XDispatchProvider >& NewSupplier ) throw ( RuntimeException ) { osl::MutexGuard aGuard(m_aMutex); m_xMasterDispatchProvider = NewSupplier; } // ----------------------------------------------------------------------------- void SAL_CALL OInterceptor::notifyEvent( const ::com::sun::star::document::EventObject& Event ) throw (::com::sun::star::uno::RuntimeException) { osl::ResettableMutexGuard _rGuard(m_aMutex); if ( m_pStatCL && Event.EventName == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("OnModifyChanged")) ) { OInterfaceContainerHelper* pListener = m_pStatCL->getContainer(m_aInterceptedURL[DISPATCH_SAVE]); if ( pListener ) { FeatureStateEvent aEvt; aEvt.FeatureURL.Complete = m_aInterceptedURL[DISPATCH_SAVE]; aEvt.FeatureDescriptor = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Update")); Reference<XModifiable> xModel(Event.Source,UNO_QUERY); aEvt.IsEnabled = xModel.is() && xModel->isModified(); aEvt.Requery = sal_False; NOTIFY_LISTERNERS((*pListener),XStatusListener,statusChanged) } } } // ----------------------------------------------------------------------------- void SAL_CALL OInterceptor::disposing( const ::com::sun::star::lang::EventObject& /*Source*/ ) throw (::com::sun::star::uno::RuntimeException) { } //........................................................................ } // namespace dbaccess //........................................................................ <|endoftext|>
<commit_before><commit_msg>Cleans up commenting.<commit_after><|endoftext|>
<commit_before>// matrixMultiplication.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <stdlib.h> int main() { printf("Pierwszy program w tym roku xD\n"); system("pause"); return 0; } <commit_msg>First part of reading from files.<commit_after>// matrixMultiplication.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <stdlib.h> int main() { //Czytanie z pliku //Deklaracja plikw FILE *firstMatrixFile, *secondMatrixFile, *outputFile; //Zmienne do danych z plikw {FM - FirstMatrix | SM - SecondMatrix} int FMRowLenght, FMColumnLenght, SMRowLenght, SMColumnLenght; char test[5]; //Otwarcie plikw do odczytu if ((firstMatrixFile = fopen("firstMatrixFile.txt", "r")) == NULL) { printf("Nie mog otworzy pliku firstMatrixFile.txt!\n"); exit(1); } else if ((firstMatrixFile = fopen("secondMatrixFile.txt", "r")) == NULL) { printf("Nie mog otworzy pliku secondMatrixFile.txt!\n"); exit(1); } //Czytanie po caych plikach while (fscanf(firstMatrixFile, "%s", test)!=EOF) { printf("%s", test); } //fprintf(fp, "%s", tekst); /* zapisz nasz acuch w pliku */ fclose(firstMatrixFile); /* zamknij plik */ printf("Pierwszy program w tym roku xD\n"); system("pause"); return 0; } <|endoftext|>
<commit_before>/* * SegmentInformation.cpp ***************************************************************************** * Copyright (C) 2014 - VideoLAN Authors * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "SegmentInformation.hpp" #include "Segment.h" #include "SegmentBase.h" #include "SegmentList.h" #include "SegmentTemplate.h" using namespace dash::mpd; using namespace std; SegmentInformation::SegmentInformation(SegmentInformation *parent_) : ICanonicalUrl( parent_ ) { parent = parent_; segmentBase = NULL; segmentList = NULL; for(int i=0; i<InfoTypeCount; i++) segmentTemplate[i] = NULL; bitswitch_policy = BITSWITCH_INHERIT; timescale.Set(0); } SegmentInformation::SegmentInformation(ICanonicalUrl * parent_) : ICanonicalUrl( parent_ ) { parent = NULL; segmentBase = NULL; segmentList = NULL; for(int i=0; i<InfoTypeCount; i++) segmentTemplate[i] = NULL; bitswitch_policy = BITSWITCH_INHERIT; timescale.Set(0); } SegmentInformation::~SegmentInformation() { delete segmentBase; delete segmentList; for(int i=0; i<InfoTypeCount; i++) delete segmentTemplate[i]; } vector<ISegment *> SegmentInformation::getSegments(SegmentInfoType type) const { vector<ISegment *> retSegments; switch (type) { case INFOTYPE_INIT: { /* init segments are always single segment */ ISegment *segment = getSegment( INFOTYPE_INIT ); if( segment ) retSegments.push_back( segment ); } break; case INFOTYPE_MEDIA: { SegmentList *segList = inheritSegmentList(); if( inheritSegmentTemplate(INFOTYPE_MEDIA) ) { retSegments.push_back( inheritSegmentTemplate(INFOTYPE_MEDIA) ); } else if ( segList && !segList->getSegments().empty() ) { std::vector<Segment *>::const_iterator it; for(it=segList->getSegments().begin(); it!=segList->getSegments().end(); it++) { std::vector<ISegment *> list = (*it)->subSegments(); retSegments.insert( retSegments.end(), list.begin(), list.end() ); } } } default: break; } return retSegments; } vector<ISegment *> SegmentInformation::getSegments() const { vector<ISegment *> retSegments; for(int i=0; i<InfoTypeCount; i++) { vector<ISegment *> segs = getSegments(static_cast<SegmentInfoType>(i)); retSegments.insert( retSegments.end(), segs.begin(), segs.end() ); } return retSegments; } ISegment * SegmentInformation::getSegment(SegmentInfoType type, uint64_t pos) const { SegmentBase *segBase = inheritSegmentBase(); SegmentList *segList = inheritSegmentList(); ISegment *segment = NULL; switch(type) { case INFOTYPE_INIT: if( segBase && segBase->initialisationSegment.Get() ) { segment = segBase->initialisationSegment.Get(); } else if( segList && segList->initialisationSegment.Get() ) { segment = segList->initialisationSegment.Get(); } else if( inheritSegmentTemplate(INFOTYPE_INIT) ) { segment = inheritSegmentTemplate(INFOTYPE_INIT); } break; case INFOTYPE_MEDIA: if( inheritSegmentTemplate(INFOTYPE_MEDIA) ) { segment = inheritSegmentTemplate(INFOTYPE_MEDIA); } else if ( segList && !segList->getSegments().empty() ) { std::vector<Segment *> list = segList->getSegments(); if(pos < list.size()) segment = list.at(pos); } break; case INFOTYPE_INDEX: //returned with media for now; default: break; } return segment; } bool SegmentInformation::getSegmentNumberByTime(mtime_t time, uint64_t *ret) const { SegmentList *segList = inheritSegmentList(); if ( segList->getDuration() ) { uint64_t timescale = segList->timescale.Get(); if(!timescale) timescale = getTimescale(); *ret = time / (CLOCK_FREQ * segList->getDuration() / timescale); return true; } return false; } bool SegmentInformation::canBitswitch() const { if(bitswitch_policy == BITSWITCH_INHERIT) return (parent) ? parent->canBitswitch() : false; else return (bitswitch_policy == BITSWITCH_YES); } uint64_t SegmentInformation::getTimescale() const { if (timescale.Get()) return timescale.Get(); else if (parent) return parent->getTimescale(); else return 1; } mtime_t SegmentInformation::getPeriodStart() const { if(parent) return parent->getPeriodStart(); else return 0; } void SegmentInformation::setSegmentList(SegmentList *list) { segmentList = list; } void SegmentInformation::setSegmentBase(SegmentBase *base) { segmentBase = base; } void SegmentInformation::setSegmentTemplate(SegmentTemplate *templ, SegmentInfoType type) { segmentTemplate[type] = templ; } static void insertIntoSegment(std::vector<Segment *> &seglist, size_t start, size_t end, mtime_t time) { std::vector<Segment *>::iterator segIt; for(segIt = seglist.begin(); segIt < seglist.end(); segIt++) { Segment *segment = *segIt; if(segment->getClassId() == Segment::CLASSID_SEGMENT && segment->contains(end + segment->getOffset())) { SubSegment *subsegment = new SubSegment(segment, start + segment->getOffset(), end + segment->getOffset()); segment->addSubSegment(subsegment); segment->startTime.Set(time); break; } } } void SegmentInformation::SplitUsingIndex(std::vector<SplitPoint> &splitlist) { std::vector<Segment *> seglist = segmentList->getSegments(); std::vector<SplitPoint>::const_iterator splitIt; size_t start = 0, end = 0; mtime_t time = 0; for(splitIt = splitlist.begin(); splitIt < splitlist.end(); splitIt++) { start = end; SplitPoint split = *splitIt; end = split.offset; if(splitIt == splitlist.begin() && split.offset == 0) continue; time = split.time; insertIntoSegment(seglist, start, end, time); end++; } if(start != 0) { start = end; end = 0; insertIntoSegment(seglist, start, end, time); } } void SegmentInformation::setBitstreamSwitching(bool bitswitch) { bitswitch_policy = (bitswitch) ? BITSWITCH_YES : BITSWITCH_NO; } SegmentBase * SegmentInformation::inheritSegmentBase() const { if(segmentBase) return segmentBase; else if (parent) return parent->inheritSegmentBase(); else return NULL; } SegmentList * SegmentInformation::inheritSegmentList() const { if(segmentList) return segmentList; else if (parent) return parent->inheritSegmentList(); else return NULL; } SegmentTemplate * SegmentInformation::inheritSegmentTemplate(SegmentInfoType type) const { if(segmentTemplate[type]) return segmentTemplate[type]; else if (parent) return parent->inheritSegmentTemplate(type); else return NULL; } <commit_msg>demux: dash: enable passive seek for templates as well<commit_after>/* * SegmentInformation.cpp ***************************************************************************** * Copyright (C) 2014 - VideoLAN Authors * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "SegmentInformation.hpp" #include "Segment.h" #include "SegmentBase.h" #include "SegmentList.h" #include "SegmentTemplate.h" using namespace dash::mpd; using namespace std; SegmentInformation::SegmentInformation(SegmentInformation *parent_) : ICanonicalUrl( parent_ ) { parent = parent_; segmentBase = NULL; segmentList = NULL; for(int i=0; i<InfoTypeCount; i++) segmentTemplate[i] = NULL; bitswitch_policy = BITSWITCH_INHERIT; timescale.Set(0); } SegmentInformation::SegmentInformation(ICanonicalUrl * parent_) : ICanonicalUrl( parent_ ) { parent = NULL; segmentBase = NULL; segmentList = NULL; for(int i=0; i<InfoTypeCount; i++) segmentTemplate[i] = NULL; bitswitch_policy = BITSWITCH_INHERIT; timescale.Set(0); } SegmentInformation::~SegmentInformation() { delete segmentBase; delete segmentList; for(int i=0; i<InfoTypeCount; i++) delete segmentTemplate[i]; } vector<ISegment *> SegmentInformation::getSegments(SegmentInfoType type) const { vector<ISegment *> retSegments; switch (type) { case INFOTYPE_INIT: { /* init segments are always single segment */ ISegment *segment = getSegment( INFOTYPE_INIT ); if( segment ) retSegments.push_back( segment ); } break; case INFOTYPE_MEDIA: { SegmentList *segList = inheritSegmentList(); if( inheritSegmentTemplate(INFOTYPE_MEDIA) ) { retSegments.push_back( inheritSegmentTemplate(INFOTYPE_MEDIA) ); } else if ( segList && !segList->getSegments().empty() ) { std::vector<Segment *>::const_iterator it; for(it=segList->getSegments().begin(); it!=segList->getSegments().end(); it++) { std::vector<ISegment *> list = (*it)->subSegments(); retSegments.insert( retSegments.end(), list.begin(), list.end() ); } } } default: break; } return retSegments; } vector<ISegment *> SegmentInformation::getSegments() const { vector<ISegment *> retSegments; for(int i=0; i<InfoTypeCount; i++) { vector<ISegment *> segs = getSegments(static_cast<SegmentInfoType>(i)); retSegments.insert( retSegments.end(), segs.begin(), segs.end() ); } return retSegments; } ISegment * SegmentInformation::getSegment(SegmentInfoType type, uint64_t pos) const { SegmentBase *segBase = inheritSegmentBase(); SegmentList *segList = inheritSegmentList(); ISegment *segment = NULL; switch(type) { case INFOTYPE_INIT: if( segBase && segBase->initialisationSegment.Get() ) { segment = segBase->initialisationSegment.Get(); } else if( segList && segList->initialisationSegment.Get() ) { segment = segList->initialisationSegment.Get(); } else if( inheritSegmentTemplate(INFOTYPE_INIT) ) { segment = inheritSegmentTemplate(INFOTYPE_INIT); } break; case INFOTYPE_MEDIA: if( inheritSegmentTemplate(INFOTYPE_MEDIA) ) { segment = inheritSegmentTemplate(INFOTYPE_MEDIA); } else if ( segList && !segList->getSegments().empty() ) { std::vector<Segment *> list = segList->getSegments(); if(pos < list.size()) segment = list.at(pos); } break; case INFOTYPE_INDEX: //returned with media for now; default: break; } return segment; } bool SegmentInformation::getSegmentNumberByTime(mtime_t time, uint64_t *ret) const { SegmentList *segList; SegmentTemplate *segTemplate; uint64_t timescale; mtime_t duration = 0; if ( (segList = inheritSegmentList()) ) { timescale = segList->timescale.Get(); duration = segList->getDuration(); } else if( (segTemplate = inheritSegmentTemplate(INFOTYPE_MEDIA)) ) { timescale = segTemplate->timescale.Get(); duration = segTemplate->duration.Get(); } if(duration) { if(!timescale) timescale = getTimescale(); /* inherit */ *ret = time / (CLOCK_FREQ * duration / timescale); return true; } return false; } bool SegmentInformation::canBitswitch() const { if(bitswitch_policy == BITSWITCH_INHERIT) return (parent) ? parent->canBitswitch() : false; else return (bitswitch_policy == BITSWITCH_YES); } uint64_t SegmentInformation::getTimescale() const { if (timescale.Get()) return timescale.Get(); else if (parent) return parent->getTimescale(); else return 1; } mtime_t SegmentInformation::getPeriodStart() const { if(parent) return parent->getPeriodStart(); else return 0; } void SegmentInformation::setSegmentList(SegmentList *list) { segmentList = list; } void SegmentInformation::setSegmentBase(SegmentBase *base) { segmentBase = base; } void SegmentInformation::setSegmentTemplate(SegmentTemplate *templ, SegmentInfoType type) { segmentTemplate[type] = templ; } static void insertIntoSegment(std::vector<Segment *> &seglist, size_t start, size_t end, mtime_t time) { std::vector<Segment *>::iterator segIt; for(segIt = seglist.begin(); segIt < seglist.end(); segIt++) { Segment *segment = *segIt; if(segment->getClassId() == Segment::CLASSID_SEGMENT && segment->contains(end + segment->getOffset())) { SubSegment *subsegment = new SubSegment(segment, start + segment->getOffset(), end + segment->getOffset()); segment->addSubSegment(subsegment); segment->startTime.Set(time); break; } } } void SegmentInformation::SplitUsingIndex(std::vector<SplitPoint> &splitlist) { std::vector<Segment *> seglist = segmentList->getSegments(); std::vector<SplitPoint>::const_iterator splitIt; size_t start = 0, end = 0; mtime_t time = 0; for(splitIt = splitlist.begin(); splitIt < splitlist.end(); splitIt++) { start = end; SplitPoint split = *splitIt; end = split.offset; if(splitIt == splitlist.begin() && split.offset == 0) continue; time = split.time; insertIntoSegment(seglist, start, end, time); end++; } if(start != 0) { start = end; end = 0; insertIntoSegment(seglist, start, end, time); } } void SegmentInformation::setBitstreamSwitching(bool bitswitch) { bitswitch_policy = (bitswitch) ? BITSWITCH_YES : BITSWITCH_NO; } SegmentBase * SegmentInformation::inheritSegmentBase() const { if(segmentBase) return segmentBase; else if (parent) return parent->inheritSegmentBase(); else return NULL; } SegmentList * SegmentInformation::inheritSegmentList() const { if(segmentList) return segmentList; else if (parent) return parent->inheritSegmentList(); else return NULL; } SegmentTemplate * SegmentInformation::inheritSegmentTemplate(SegmentInfoType type) const { if(segmentTemplate[type]) return segmentTemplate[type]; else if (parent) return parent->inheritSegmentTemplate(type); else return NULL; } <|endoftext|>
<commit_before>#include <iostream> #include <stdio.h> #include <stdlib.h> #include <mpi.h> #include "doTheMath.cpp" #include <fstream> using namespace std; int main(int argc, char *argv[]) { int numprocessors, rank, namelen, i,limit,slaves; char processor_name[MPI_MAX_PROCESSOR_NAME]; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numprocessors); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Get_processor_name(processor_name, &namelen); i=0; p_drop(); if ( rank == 0 ) { std::cout << "Master core: " << processor_name << " : " << rank <<"\n"; // std::cout << "master (" << rank << "/" << numprocessors << ")\n"; } else { // std::cout << "slave (" << rank << "/" << numprocessors << ")\n"; slaves=(numprocessors-1); while(i<(img_s/slaves)){ int slice=rank+i*slaves; doTheMath(slice); //char c[10]; //sprintf(c, "%d", slice); //ofstream myfile; //myfile.open(c); //riga=my_ext_function(slice) //myfile << riga; //myfile.close(); i++; } } if(rank <= (img_s%slaves)) { int slice=rank+i*slaves; doTheMath(slice); } MPI_Finalize(); if ( rank == 0) { std::cout << "Master core: " << processor_name << " : " << rank <<"\n"; // printf("%d",i); // ofstream myfile; // myfile.open("200"); // myfile << 15; // myfile.close(); //char output[200000] = system("ls"); } return 0; } <commit_msg>Delete MPI_base.cpp<commit_after><|endoftext|>
<commit_before>#include "delta.h" #include "../utils.h" #include "../exception.h" #include "binarybuffer.h" #include <sstream> #include <cassert> #include <limits> using namespace dariadb::compression; const uint16_t delta_64_mask = 512; //10 0000 0000 const uint16_t delta_64_mask_inv = 127; //00 1111 111 const uint16_t delta_256_mask = 3072; //1100 0000 0000 const uint16_t delta_256_mask_inv = 511; //0001 1111 1111 const uint16_t delta_2047_mask = 57344; //1110 0000 0000 0000 const uint16_t delta_2047_mask_inv = 4095; //0000 1111 1111 1111 const uint64_t delta_big_mask = 64424509440; //1111 [0000 0000] [0000 0000][0000 0000] [0000 0000] const uint64_t delta_big_mask_inv = 4294967295;//0000 1111 1111 1111 1111 1111 1111 1111 1111 DeltaCompressor::DeltaCompressor(const BinaryBuffer &bw): BaseCompressor(bw), _is_first(true), _first(0), _prev_delta(0), _prev_time(0) { } DeltaCompressor::~DeltaCompressor(){ } bool DeltaCompressor::append(dariadb::Time t){ if(_is_first){ _first=t; _is_first=false; _prev_time=t; return true; } int64_t D=(t-_prev_time) - _prev_delta; if(D==0){ if (_bw.free_size() == 1) { return false; } _bw.clrbit().incbit(); }else{ if ((-63<D)&&(D<64)){ if (_bw.free_size() <2) { return false; } auto d=DeltaCompressor::get_delta_64(D); _bw.write(d,9); }else{ if ((-255<D)&&(D<256)){ if (_bw.free_size() <2) { return false; } auto d=DeltaCompressor::get_delta_256(D); _bw.write(d,11); }else{ if ((-2047<D)&&(D<2048)){ if (_bw.free_size() <3) { return false; } auto d=DeltaCompressor::get_delta_2048(D); _bw.write(d,15); }else{ if (_bw.free_size() <6) { return false; } auto d=DeltaCompressor::get_delta_big(D); _bw.write(d,35); } } } } _prev_delta=D; _prev_time=t; return true; } uint16_t DeltaCompressor::get_delta_64(int64_t D) { return delta_64_mask | (delta_64_mask_inv & static_cast<uint16_t>(D)); } uint16_t DeltaCompressor::get_delta_256(int64_t D) { return delta_256_mask| (delta_256_mask_inv &static_cast<uint16_t>(D)); } uint16_t DeltaCompressor::get_delta_2048(int64_t D) { return delta_2047_mask | (delta_2047_mask_inv &static_cast<uint16_t>(D)); } uint64_t DeltaCompressor::get_delta_big(int64_t D) { return delta_big_mask | (delta_big_mask_inv & D); } DeltaDeCompressor::DeltaDeCompressor(const BinaryBuffer &bw, dariadb::Time first): BaseCompressor(bw), _prev_delta(0), _prev_time(first) { } DeltaDeCompressor::~DeltaDeCompressor(){ } dariadb::Time DeltaDeCompressor::read(){ auto b0=_bw.getbit(); _bw.incbit(); if(b0==0){ return _prev_time+_prev_delta; } auto b1=_bw.getbit(); _bw.incbit(); if((b0==1) && (b1==0)){//64 int8_t result=static_cast<int8_t>(_bw.read(7)); if (result>64) { //is negative result = (-128) | result; } auto ret=_prev_time+result+_prev_delta; _prev_delta=result; _prev_time=ret; return ret; } auto b2=_bw.getbit(); _bw.incbit(); if((b0==1) && (b1==1)&& (b2==0)){//256 int16_t result=static_cast<int16_t>(_bw.read(8)); if (result > 256) { //is negative result = (-256) | result; } auto ret=_prev_time+result+_prev_delta; _prev_delta=result; _prev_time=ret; return ret; } auto b3=_bw.getbit(); _bw.incbit(); if((b0==1) && (b1==1)&& (b2==1)&& (b3==0)){//2048 int16_t result=static_cast<int16_t>(_bw.read(11)); if (result > 2048) { //is negative result = (-2048) | result; } auto ret=_prev_time+result+_prev_delta; _prev_delta=result; _prev_time=ret; return ret; } int64_t result=_bw.read(31); if (result > std::numeric_limits<int32_t>::max()) { result = (-4294967296) | result; } auto ret=_prev_time+result+_prev_delta; _prev_delta=result; _prev_time=ret; return ret; } <commit_msg>delt: cons refact.<commit_after>#include "delta.h" #include "../utils.h" #include "../exception.h" #include "binarybuffer.h" #include <sstream> #include <cassert> #include <limits> using namespace dariadb::compression; const uint16_t delta_64_mask = 0x200; //10 0000 0000 const uint16_t delta_64_mask_inv = 0x7F; //00 1111 111 const uint16_t delta_256_mask = 0xC00; //1100 0000 0000 const uint16_t delta_256_mask_inv = 0x1FF; //0001 1111 1111 const uint16_t delta_2047_mask = 0xE000; //1110 0000 0000 0000 const uint16_t delta_2047_mask_inv = 0xFFF; //0000 1111 1111 1111 const uint64_t delta_big_mask = 0xF00000000; //1111 [0000 0000] [0000 0000][0000 0000] [0000 0000] const uint64_t delta_big_mask_inv = 0xFFFFFFFF;//0000 1111 1111 1111 1111 1111 1111 1111 1111 DeltaCompressor::DeltaCompressor(const BinaryBuffer &bw): BaseCompressor(bw), _is_first(true), _first(0), _prev_delta(0), _prev_time(0) { } DeltaCompressor::~DeltaCompressor(){ } bool DeltaCompressor::append(dariadb::Time t){ if(_is_first){ _first=t; _is_first=false; _prev_time=t; return true; } int64_t D=(t-_prev_time) - _prev_delta; if(D==0){ if (_bw.free_size() == 1) { return false; } _bw.clrbit().incbit(); }else{ if ((-63<D)&&(D<64)){ if (_bw.free_size() <2) { return false; } auto d=DeltaCompressor::get_delta_64(D); _bw.write(d,9); }else{ if ((-255<D)&&(D<256)){ if (_bw.free_size() <2) { return false; } auto d=DeltaCompressor::get_delta_256(D); _bw.write(d,11); }else{ if ((-2047<D)&&(D<2048)){ if (_bw.free_size() <3) { return false; } auto d=DeltaCompressor::get_delta_2048(D); _bw.write(d,15); }else{ if (_bw.free_size() <6) { return false; } auto d=DeltaCompressor::get_delta_big(D); _bw.write(d,35); } } } } _prev_delta=D; _prev_time=t; return true; } uint16_t DeltaCompressor::get_delta_64(int64_t D) { return delta_64_mask | (delta_64_mask_inv & static_cast<uint16_t>(D)); } uint16_t DeltaCompressor::get_delta_256(int64_t D) { return delta_256_mask| (delta_256_mask_inv &static_cast<uint16_t>(D)); } uint16_t DeltaCompressor::get_delta_2048(int64_t D) { return delta_2047_mask | (delta_2047_mask_inv &static_cast<uint16_t>(D)); } uint64_t DeltaCompressor::get_delta_big(int64_t D) { return delta_big_mask | (delta_big_mask_inv & D); } DeltaDeCompressor::DeltaDeCompressor(const BinaryBuffer &bw, dariadb::Time first): BaseCompressor(bw), _prev_delta(0), _prev_time(first) { } DeltaDeCompressor::~DeltaDeCompressor(){ } dariadb::Time DeltaDeCompressor::read(){ auto b0=_bw.getbit(); _bw.incbit(); if(b0==0){ return _prev_time+_prev_delta; } auto b1=_bw.getbit(); _bw.incbit(); if((b0==1) && (b1==0)){//64 int8_t result=static_cast<int8_t>(_bw.read(7)); if (result>64) { //is negative result = (-128) | result; } auto ret=_prev_time+result+_prev_delta; _prev_delta=result; _prev_time=ret; return ret; } auto b2=_bw.getbit(); _bw.incbit(); if((b0==1) && (b1==1)&& (b2==0)){//256 int16_t result=static_cast<int16_t>(_bw.read(8)); if (result > 256) { //is negative result = (-256) | result; } auto ret=_prev_time+result+_prev_delta; _prev_delta=result; _prev_time=ret; return ret; } auto b3=_bw.getbit(); _bw.incbit(); if((b0==1) && (b1==1)&& (b2==1)&& (b3==0)){//2048 int16_t result=static_cast<int16_t>(_bw.read(11)); if (result > 2048) { //is negative result = (-2048) | result; } auto ret=_prev_time+result+_prev_delta; _prev_delta=result; _prev_time=ret; return ret; } int64_t result=_bw.read(31); if (result > std::numeric_limits<int32_t>::max()) { result = (-4294967296) | result; } auto ret=_prev_time+result+_prev_delta; _prev_delta=result; _prev_time=ret; return ret; } <|endoftext|>
<commit_before>/* kopetestdaction.cpp - Kopete Standard Actionds Copyright (c) 2001-2002 by Ryan Cumming. <bodnar42@phalynx.dhs.org> Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kaction.h> #include <klocale.h> #include <kdebug.h> #include "kopete.h" #include "kopetestdaction.h" #include "kopetecontactlist.h" #include "kopetecontactlistview.h" #include "kopeteprotocol.h" #include "pluginloader.h" /** KopeteGroupList **/ KopeteGroupList::KopeteGroupList(const QString& text, const QString& pix, const KShortcut& cut, const QObject* receiver, const char* slot, QObject* parent, const char* name) : KListAction(text, pix, cut, parent, name) { connect( this, SIGNAL( activated() ), receiver, slot ); connect(KopeteContactList::contactList(), SIGNAL(groupAdded(const QString &)), this, SLOT(slotUpdateList())); connect(KopeteContactList::contactList(), SIGNAL(groupRemoved(const QString &)), this, SLOT(slotUpdateList())); slotUpdateList(); } KopeteGroupList::~KopeteGroupList() { } void KopeteGroupList::slotUpdateList() { m_groupList = QStringList(); m_groupList << "Top Level"; m_groupList += KopeteContactList::contactList()->groups(); setItems( m_groupList ); } KAction* KopeteStdAction::chat( const QObject *recvr, const char *slot, QObject* parent, const char *name ) { return new KAction( i18n("Start &Chat..."), "mail_generic", 0, recvr, slot, parent, name ); } KAction* KopeteStdAction::sendMessage(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("&Send Message..."), "mail_generic", 0, recvr, slot, parent, name ); } KAction* KopeteStdAction::contactInfo(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("User &Info..."), "identity", 0, recvr, slot, parent, name ); } KAction* KopeteStdAction::viewHistory(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("View &History..."), "history", 0, recvr, slot, parent, name ); } KAction* KopeteStdAction::addGroup(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("&Add Group..."), "folder", 0, recvr, slot, parent, name ); } KAction* KopeteStdAction::changeMetaContact(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("Cha&nge MetaContact..."), "move", 0, recvr, slot, parent, name ); } KListAction *KopeteStdAction::moveContact(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KopeteGroupList( i18n("&Move Contact"), "editcut", 0, recvr, slot, parent, name ); } KListAction *KopeteStdAction::copyContact( const QObject *recvr, const char *slot, QObject* parent, const char *name ) { return new KopeteGroupList( i18n("Cop&y Contact"), "editcopy", 0, recvr, slot, parent, name ); } KAction* KopeteStdAction::deleteContact(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("&Delete Contact..."), "edittrash", 0, recvr, slot, parent, name ); } KListAction *KopeteStdAction::addContact(const QObject *recvr, const char *slot, QObject* parent, const char *name) { KListAction *a=new KListAction( i18n("&Add Contact"), "bookmark_add", 0, recvr, slot, parent, name ); QStringList protocolList; QValueList<KopeteLibraryInfo> l = kopeteapp->libraryLoader()->loaded(); for (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i) { KopetePlugin *tmpprot = (kopeteapp->libraryLoader())->mLibHash[(*i).specfile]->plugin; KopeteProtocol *prot = dynamic_cast<KopeteProtocol*>( tmpprot ); if (prot) { protocolList.append((*i).name); } } a->setItems( protocolList ); return a; } KAction* KopeteStdAction::changeAlias(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("Change A&lias..."), "signature", 0, recvr, slot, parent, name ); } #include "kopetestdaction.moc" /* * Local variables: * c-indentation-style: k&r * c-basic-offset: 8 * indent-tabs-mode: t * End: */ // vim: set noet ts=4 sts=4 sw=4: <commit_msg>Style-guide fix<commit_after>/* kopetestdaction.cpp - Kopete Standard Actionds Copyright (c) 2001-2002 by Ryan Cumming. <bodnar42@phalynx.dhs.org> Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kaction.h> #include <klocale.h> #include <kdebug.h> #include "kopete.h" #include "kopetestdaction.h" #include "kopetecontactlist.h" #include "kopetecontactlistview.h" #include "kopeteprotocol.h" #include "pluginloader.h" /** KopeteGroupList **/ KopeteGroupList::KopeteGroupList(const QString& text, const QString& pix, const KShortcut& cut, const QObject* receiver, const char* slot, QObject* parent, const char* name) : KListAction(text, pix, cut, parent, name) { connect( this, SIGNAL( activated() ), receiver, slot ); connect(KopeteContactList::contactList(), SIGNAL(groupAdded(const QString &)), this, SLOT(slotUpdateList())); connect(KopeteContactList::contactList(), SIGNAL(groupRemoved(const QString &)), this, SLOT(slotUpdateList())); slotUpdateList(); } KopeteGroupList::~KopeteGroupList() { } void KopeteGroupList::slotUpdateList() { m_groupList = QStringList(); m_groupList << "Top Level"; m_groupList += KopeteContactList::contactList()->groups(); setItems( m_groupList ); } KAction* KopeteStdAction::chat( const QObject *recvr, const char *slot, QObject* parent, const char *name ) { return new KAction( i18n("Start &Chat..."), "mail_generic", 0, recvr, slot, parent, name ); } KAction* KopeteStdAction::sendMessage(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("&Send Message..."), "mail_generic", 0, recvr, slot, parent, name ); } KAction* KopeteStdAction::contactInfo(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("User &Info..."), "identity", 0, recvr, slot, parent, name ); } KAction* KopeteStdAction::viewHistory(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("View &History..."), "history", 0, recvr, slot, parent, name ); } KAction* KopeteStdAction::addGroup(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("&Add Group..."), "folder", 0, recvr, slot, parent, name ); } KAction* KopeteStdAction::changeMetaContact(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("Cha&nge MetaContact..."), "move", 0, recvr, slot, parent, name ); } KListAction *KopeteStdAction::moveContact(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KopeteGroupList( i18n("&Move Contact"), "editcut", 0, recvr, slot, parent, name ); } KListAction *KopeteStdAction::copyContact( const QObject *recvr, const char *slot, QObject* parent, const char *name ) { return new KopeteGroupList( i18n("Cop&y Contact"), "editcopy", 0, recvr, slot, parent, name ); } KAction* KopeteStdAction::deleteContact(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("&Delete Contact"), "edittrash", 0, recvr, slot, parent, name ); } KListAction *KopeteStdAction::addContact(const QObject *recvr, const char *slot, QObject* parent, const char *name) { KListAction *a=new KListAction( i18n("&Add Contact"), "bookmark_add", 0, recvr, slot, parent, name ); QStringList protocolList; QValueList<KopeteLibraryInfo> l = kopeteapp->libraryLoader()->loaded(); for (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i) { KopetePlugin *tmpprot = (kopeteapp->libraryLoader())->mLibHash[(*i).specfile]->plugin; KopeteProtocol *prot = dynamic_cast<KopeteProtocol*>( tmpprot ); if (prot) { protocolList.append((*i).name); } } a->setItems( protocolList ); return a; } KAction* KopeteStdAction::changeAlias(const QObject *recvr, const char *slot, QObject* parent, const char *name) { return new KAction( i18n("Change A&lias..."), "signature", 0, recvr, slot, parent, name ); } #include "kopetestdaction.moc" /* * Local variables: * c-indentation-style: k&r * c-basic-offset: 8 * indent-tabs-mode: t * End: */ // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/* The MIT License (MIT) * * Copyright (c) 2014-2018 David Medina and Tim Warburton * * 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 */ #include <occa/defines.hpp> #if OCCA_HIP_ENABLED #include <occa/mode/hip/kernel.hpp> #include <occa/mode/hip/device.hpp> #include <occa/mode/hip/utils.hpp> #include <occa/tools/env.hpp> #include <occa/io.hpp> #include <occa/base.hpp> namespace occa { namespace hip { kernel::kernel(modeDevice_t *modeDevice_, const std::string &name_, const std::string &sourceFilename_, const occa::properties &properties_) : occa::modeKernel_t(modeDevice_, name_, sourceFilename_, properties_), hipModule(NULL), hipFunction(NULL), launcherKernel(NULL) {} kernel::kernel(modeDevice_t *modeDevice_, const std::string &name_, const std::string &sourceFilename_, hipModule_t hipModule_, hipFunction_t hipFunction_, const occa::properties &properties_) : occa::modeKernel_t(modeDevice_, name_, sourceFilename_, properties_), hipModule(hipModule_), hipFunction(hipFunction_), launcherKernel(NULL) {} kernel::~kernel() {} int kernel::maxDims() const { return 3; } dim kernel::maxOuterDims() const { return dim(-1, -1, -1); } dim kernel::maxInnerDims() const { static dim innerDims(0); if (innerDims.x == 0) { int maxSize; int deviceID = properties["device_id"]; hipDeviceProp_t props; OCCA_HIP_ERROR("Getting device properties", hipGetDeviceProperties(&props, deviceID )); maxSize = props.maxThreadsPerBlock; innerDims.x = maxSize; } return innerDims; } void kernel::run() const { if (launcherKernel) { return launcherRun(); } const int totalArgCount = kernelArg::argumentCount(arguments); if (!totalArgCount) { vArgs.resize(1); } else if ((int) vArgs.size() < totalArgCount) { vArgs.resize(totalArgCount); } const int kArgCount = (int) arguments.size(); int argc = 0; for (int i = 0; i < kArgCount; ++i) { const kArgVector &iArgs = arguments[i].args; const int argCount = (int) iArgs.size(); if (!argCount) { continue; } for (int ai = 0; ai < argCount; ++ai) { memcpy(vArgs.data() + argc++,&(iArgs[ai].data.int64_), sizeof(void*)); } } size_t size = vArgs.size()*sizeof(vArgs[0]); void* config[] = {HIP_LAUNCH_PARAM_BUFFER_POINTER, &(vArgs[0]), HIP_LAUNCH_PARAM_BUFFER_SIZE, &size, HIP_LAUNCH_PARAM_END}; OCCA_HIP_ERROR("Launching Kernel", hipModuleLaunchKernel(hipFunction, outerDims.x, outerDims.y, outerDims.z, innerDims.x, innerDims.y, innerDims.z, 0, *((hipStream_t*) modeDevice->currentStream), NULL, (void**)&config)); } void kernel::launcherRun() const { launcherKernel->arguments = arguments; launcherKernel->arguments.insert( launcherKernel->arguments.begin(), &(hipKernels[0]) ); int kernelCount = (int) hipKernels.size(); for (int i = 0; i < kernelCount; ++i) { hipKernels[i]->arguments = arguments; } launcherKernel->run(); } void kernel::free() { if (!launcherKernel) { if (hipModule) { OCCA_HIP_ERROR("Kernel (" + name + ") : Unloading Module", hipModuleUnload(hipModule)); hipModule = NULL; } return; } launcherKernel->free(); delete launcherKernel; launcherKernel = NULL; int kernelCount = (int) hipKernels.size(); for (int i = 0; i < kernelCount; ++i) { hipKernels[i]->free(); delete hipKernels[i]; } hipKernels.clear(); } } } #endif <commit_msg>[HIP] Fixed a subtle bug regarding how HIP expects kernel arguments to be byte-align and packed.<commit_after>/* The MIT License (MIT) * * Copyright (c) 2014-2018 David Medina and Tim Warburton * * 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 */ #include <occa/defines.hpp> #if OCCA_HIP_ENABLED #include <occa/mode/hip/kernel.hpp> #include <occa/mode/hip/device.hpp> #include <occa/mode/hip/utils.hpp> #include <occa/tools/env.hpp> #include <occa/io.hpp> #include <occa/base.hpp> namespace occa { namespace hip { kernel::kernel(modeDevice_t *modeDevice_, const std::string &name_, const std::string &sourceFilename_, const occa::properties &properties_) : occa::modeKernel_t(modeDevice_, name_, sourceFilename_, properties_), hipModule(NULL), hipFunction(NULL), launcherKernel(NULL) {} kernel::kernel(modeDevice_t *modeDevice_, const std::string &name_, const std::string &sourceFilename_, hipModule_t hipModule_, hipFunction_t hipFunction_, const occa::properties &properties_) : occa::modeKernel_t(modeDevice_, name_, sourceFilename_, properties_), hipModule(hipModule_), hipFunction(hipFunction_), launcherKernel(NULL) {} kernel::~kernel() {} int kernel::maxDims() const { return 3; } dim kernel::maxOuterDims() const { return dim(-1, -1, -1); } dim kernel::maxInnerDims() const { static dim innerDims(0); if (innerDims.x == 0) { int maxSize; int deviceID = properties["device_id"]; hipDeviceProp_t props; OCCA_HIP_ERROR("Getting device properties", hipGetDeviceProperties(&props, deviceID )); maxSize = props.maxThreadsPerBlock; innerDims.x = maxSize; } return innerDims; } void kernel::run() const { if (launcherKernel) { return launcherRun(); } const int totalArgCount = kernelArg::argumentCount(arguments); if (!totalArgCount) { vArgs.resize(1); } else if ((int) vArgs.size() < totalArgCount) { vArgs.resize(totalArgCount); } const int kArgCount = (int) arguments.size(); int argc = 0; int rem = 0; for (int i = 0; i < kArgCount; ++i) { const kArgVector &iArgs = arguments[i].args; const int argCount = (int) iArgs.size(); if (!argCount) { continue; } for (int ai = 0; ai < argCount; ++ai) { size_t Nbytes; if (rem+iArgs[ai].size<=sizeof(void*)) { Nbytes = iArgs[ai].size; rem = sizeof(void*) - rem - iArgs[ai].size; } else { Nbytes = sizeof(void*); argc+=rem; rem = 0; } memcpy((char*) vArgs.data() + argc,&(iArgs[ai].data.int64_), Nbytes); argc += Nbytes; } } size_t size = vArgs.size()*sizeof(vArgs[0]); void* config[] = {HIP_LAUNCH_PARAM_BUFFER_POINTER, &(vArgs[0]), HIP_LAUNCH_PARAM_BUFFER_SIZE, &size, HIP_LAUNCH_PARAM_END}; OCCA_HIP_ERROR("Launching Kernel", hipModuleLaunchKernel(hipFunction, outerDims.x, outerDims.y, outerDims.z, innerDims.x, innerDims.y, innerDims.z, 0, *((hipStream_t*) modeDevice->currentStream), NULL, (void**)&config)); } void kernel::launcherRun() const { launcherKernel->arguments = arguments; launcherKernel->arguments.insert( launcherKernel->arguments.begin(), &(hipKernels[0]) ); int kernelCount = (int) hipKernels.size(); for (int i = 0; i < kernelCount; ++i) { hipKernels[i]->arguments = arguments; } launcherKernel->run(); } void kernel::free() { if (!launcherKernel) { if (hipModule) { OCCA_HIP_ERROR("Kernel (" + name + ") : Unloading Module", hipModuleUnload(hipModule)); hipModule = NULL; } return; } launcherKernel->free(); delete launcherKernel; launcherKernel = NULL; int kernelCount = (int) hipKernels.size(); for (int i = 0; i < kernelCount; ++i) { hipKernels[i]->free(); delete hipKernels[i]; } hipKernels.clear(); } } } #endif <|endoftext|>
<commit_before>#ifndef NETWORK_MANAGER_HPP #define NETWORK_MANAGER_HPP #include <stdexcept> #include <string> #include <map> #include <functional> #include <SFML/Network.hpp> #include <SFML/System.hpp> class NetworkManager { private: unsigned short mPort; sf::UdpSocket mSocket; public: // Use similar structure to sf::Event class Event { public: struct NopEvent { sf::IpAddress sender; }; struct ConnectEvent { sf::IpAddress sender; sf::Uint8 gameId; // Game connecting to sf::Uint8 charId; // Which character slot they are }; struct DisconnectEvent { sf::IpAddress sender; sf::Uint8 gameId; // Game they were connected to sf::Uint8 charId; // Which slot they were in }; enum EventType { Nop, // No request Connect, // A player has connected Disconnect, // A player has disconnected Move, // Creature is moving }; EventType type; union { NopEvent nop; ConnectEvent connect; DisconnectEvent disconnect; }; }; NetworkManager() : mPort(49518) {} NetworkManager(unsigned short port) : mPort(port) { // Open UDP socket sf::UdpSocket mSocket; if(mSocket.bind(mPort) != sf::Socket::Done) { throw std::runtime_error("Failed to open socket on port " + std::to_string(mPort)); } } }; #endif /* NETWORK_MANAGER_HPP */ <commit_msg>Added event polling to NetworkManager<commit_after>#ifndef NETWORK_MANAGER_HPP #define NETWORK_MANAGER_HPP #include <stdexcept> #include <string> #include <map> #include <queue> #include <SFML/Network.hpp> #include <SFML/System.hpp> class NetworkManager { private: unsigned short mPort; sf::UdpSocket mSocket; public: // Use similar structure to sf::Event class Event { public: struct NopEvent { sf::IpAddress sender; }; struct ConnectEvent { sf::IpAddress sender; sf::Uint8 gameId; // Game connecting to sf::Uint8 charId; // Which character slot they are }; struct DisconnectEvent { sf::IpAddress sender; sf::Uint8 gameId; // Game they were connected to sf::Uint8 charId; // Which slot they were in }; enum EventType { Nop, // No request Connect, // A player has connected Disconnect, // A player has disconnected Move, // Creature is moving Count }; EventType type; union { NopEvent nop; ConnectEvent connect; DisconnectEvent disconnect; }; }; private: std::queue<Event> mEventQueue; public: NetworkManager() : mPort(49518) {} NetworkManager(unsigned short port) : mPort(port) { // Open UDP socket sf::UdpSocket mSocket; if(mSocket.bind(mPort) != sf::Socket::Done) { throw std::runtime_error("Failed to open socket on port " + std::to_string(mPort)); } } // Take the next event out of the event queue bool pollEvent(Event& event) { if(mEventQueue.empty()) return false; event = mEventQueue.front(); mEventQueue.pop(); return true; } // Wait for an incoming connect and parse it as an event. If it // was a valid event, add it to the event queue and return true bool waitEvent() { sf::Packet packet; sf::IpAddress sender; unsigned short port; // Wait for an incoming connection mSocket.receive(packet, sender, port); // Extract event type. Can't send and receive enums directly // so force them into something we know the size of sf::Uint16 t = 0; packet >> t; if(t == 0 || t >= static_cast<sf::Uint8>(Event::Count)) { // Invalid packet return false; } auto type = static_cast<Event::EventType>(t); // Depending on the type of the packet, we extract different // data switch(type) { case Event::Nop: { Event e = { .nop = { .sender = sender }, .type = Event::Nop }; mEventQueue.push(e); return true; } case Event::Connect: { sf::Uint8 gameId = 0; sf::Uint8 charId = 0; if(!(packet >> gameId >> charId)) return false; Event e = { .connect = { .sender = sender, .gameId = gameId, .charId = charId }, .type = Event::Connect }; mEventQueue.push(e); return true; } case Event::Disconnect: { sf::Uint8 gameId = 0; sf::Uint8 charId = 0; if(!(packet >> gameId >> charId)) return false; Event e = { .disconnect = { .sender = sender, .gameId = gameId, .charId = charId }, .type = Event::Disconnect }; mEventQueue.push(e); return true; } default: return false; } } }; #endif /* NETWORK_MANAGER_HPP */ <|endoftext|>
<commit_before>#include <boost/filesystem.hpp> #include <boost/format.hpp> #include <libport/detect-win32.h> #include <object/directory.hh> #include <object/path.hh> #include <runner/raise.hh> namespace object { using boost::format; /*------------. | C++ methods | `------------*/ Directory::value_type Directory::value_get() { return path_; } /*-------------. | Urbi methods | `-------------*/ // Construction Directory::Directory() : path_(new Path("/")) { proto_add(proto); } Directory::Directory(rDirectory model) : path_(model.get()->path_) { proto_add(model); } Directory::Directory(const std::string& value) : path_(new Path(value)) { proto_add(proto ? proto : object_class); } void Directory::init(rPath path) { if (!path->is_dir()) runner::raise_primitive_error(str(format("Not a directory: '%s'") % path->as_string())); path_ = path; } void Directory::init(const std::string& path) { init(new Path(path)); } // Conversions std::string Directory::as_string() { return path_->as_string(); } std::string Directory::as_printable() { return "Directory " + path_->as_printable(); } // Stat template <rObject (*F) (Directory& d, const std::string& entry)> rList Directory::list() { using boost::filesystem::directory_iterator; List::value_type res; directory_iterator end; for (directory_iterator it (path_->value_get().to_string()); it != end; ++it) res << F(*this, it->path().string()); return new List(res); } /*--------. | Details | `--------*/ namespace details { rObject mk_string(Directory&, const std::string&); rObject mk_path(Directory&, const std::string&); rObject mk_string(Directory&, const std::string& entry) { return new String(entry); } rObject mk_path(Directory& d, const std::string& entry) { return new Path(d.value_get()->value_get() / entry); } } OVERLOAD_TYPE(init_bouncer, init, Path, (void (Directory::*)(rPath)) &Directory::init, String, (void (Directory::*)(const std::string&)) &Directory::init); /*---------------. | Binding system | `---------------*/ void Directory::initialize(CxxObject::Binder<Directory>& bind) { bind(SYMBOL(asPrintable), &Directory::as_printable); bind(SYMBOL(asString), &Directory::as_string); bind(SYMBOL(content), &Directory::list<&details::mk_path>); bind(SYMBOL(list), &Directory::list<&details::mk_string>); proto->slot_set(SYMBOL(init), new Primitive(&init_bouncer)); } rObject Directory::proto_make() { #ifdef WIN32 return new Directory("C:\\"); #else return new Directory("/"); #endif } URBI_CXX_OBJECT_REGISTER(Directory); } <commit_msg>Fix Directory.asPrintable: use Type(values) convention.<commit_after>#include <boost/filesystem.hpp> #include <boost/format.hpp> #include <libport/detect-win32.h> #include <object/directory.hh> #include <object/path.hh> #include <runner/raise.hh> namespace object { using boost::format; /*------------. | C++ methods | `------------*/ Directory::value_type Directory::value_get() { return path_; } /*-------------. | Urbi methods | `-------------*/ // Construction Directory::Directory() : path_(new Path("/")) { proto_add(proto); } Directory::Directory(rDirectory model) : path_(model.get()->path_) { proto_add(model); } Directory::Directory(const std::string& value) : path_(new Path(value)) { proto_add(proto ? proto : object_class); } void Directory::init(rPath path) { if (!path->is_dir()) runner::raise_primitive_error(str(format("Not a directory: '%s'") % path->as_string())); path_ = path; } void Directory::init(const std::string& path) { init(new Path(path)); } // Conversions std::string Directory::as_string() { return path_->as_string(); } std::string Directory::as_printable() { return (boost::format("Directory(\"%s\")") % path_->as_string()).str(); } // Stat template <rObject (*F) (Directory& d, const std::string& entry)> rList Directory::list() { using boost::filesystem::directory_iterator; List::value_type res; directory_iterator end; for (directory_iterator it (path_->value_get().to_string()); it != end; ++it) res << F(*this, it->path().string()); return new List(res); } /*--------. | Details | `--------*/ namespace details { rObject mk_string(Directory&, const std::string&); rObject mk_path(Directory&, const std::string&); rObject mk_string(Directory&, const std::string& entry) { return new String(entry); } rObject mk_path(Directory& d, const std::string& entry) { return new Path(d.value_get()->value_get() / entry); } } OVERLOAD_TYPE(init_bouncer, init, Path, (void (Directory::*)(rPath)) &Directory::init, String, (void (Directory::*)(const std::string&)) &Directory::init); /*---------------. | Binding system | `---------------*/ void Directory::initialize(CxxObject::Binder<Directory>& bind) { bind(SYMBOL(asPrintable), &Directory::as_printable); bind(SYMBOL(asString), &Directory::as_string); bind(SYMBOL(content), &Directory::list<&details::mk_path>); bind(SYMBOL(list), &Directory::list<&details::mk_string>); proto->slot_set(SYMBOL(init), new Primitive(&init_bouncer)); } rObject Directory::proto_make() { #ifdef WIN32 return new Directory("C:\\"); #else return new Directory("/"); #endif } URBI_CXX_OBJECT_REGISTER(Directory); } <|endoftext|>
<commit_before>//Ejercicio Productor - Consumirdor //Autor: Javier Aranda Izquierdo #include <iostream> #include <cassert> #include <pthread.h> #include <semaphore.h> using namespace std ; // --------------------------------------------------------------------- // constantes const unsigned num_items = 40 , // Numero de items a Consumirdor tam_vector = 10 ; // Tamaño del vector sem_t consumir, producir, mutex; // --------------------------------------------------------------------- // Funcion para profucir datos unsigned producir_dato() { static int contador = 0 ; cout << "Producido: " << contador << endl << flush ; return contador++ ; } // --------------------------------------------------------------------- // Funcion para consumir datos void consumir_dato( int dato ) { cout << "Dato recibido: " << dato << endl ; } // --------------------------------------------------------------------- void * productor( void * ) { for( unsigned i = 0 ; i < num_items ; i++ ) { int dato = producir_dato() ; // falta: insertar "dato" en el vector // ................ } return NULL ; } // --------------------------------------------------------------------- void * consumidor( void * ) { for( unsigned i = 0 ; i < num_items ; i++ ) { int dato ; // falta: leer "dato" desde el vector intermedio // ................. consumir_dato( dato ) ; } return NULL ; } //---------------------------------------------------------------------- int main() { pthread_t hebraConsumidor, hebraProductor; return 0 ; } <commit_msg>Implementado el metodo del productor<commit_after>//Ejercicio Productor - Consumirdor //Autor: Javier Aranda Izquierdo #include <iostream> #include <cassert> #include <pthread.h> #include <semaphore.h> using namespace std ; // --------------------------------------------------------------------- // constantes const unsigned num_items = 40 , // Numero de items a Consumirdor tam_vector = 10 ; // Tamaño del vector int buffer [tam_vector]; sem_t consumir, producir, mutex; // --------------------------------------------------------------------- // Funcion para profucir datos unsigned producir_dato() { static int contador = 0 ; cout << "Producido: " << contador << endl << flush ; return contador++ ; } // --------------------------------------------------------------------- // Funcion para consumir datos void consumir_dato( int dato ) { cout << "Dato recibido: " << dato << endl ; } // --------------------------------------------------------------------- void * productor( void * ) { for( unsigned i = 0 ; i < num_items ; i++ ) { int dato = producir_dato(); // Producimos un nuevo dato sem_wait (&producir); // Semaforo del productor sem_wait (&mutex); // Ya que nos encontramos ante una seccion critica buffer[i] = dato; // Escribe el dato en la posicion i del buffer i++; // Incrementa la posicion del buffer sem_post (&mutex); // Decrementamos la seccion critica para que otro proceso pueda entrar sem_post (&consumir); // Decrementamos el consumidor } return NULL ; } // --------------------------------------------------------------------- void * consumidor( void * ) { for( unsigned i = 0 ; i < num_items ; i++ ) { int dato ; // falta: leer "dato" desde el vector intermedio // ................. consumir_dato( dato ) ; } return NULL ; } //---------------------------------------------------------------------- int main() { pthread_t hebraConsumidor, hebraProductor; return 0 ; } <|endoftext|>
<commit_before>//******************************************************************* // // Program: Rogue Game // // Author: Gus Oberdick // Email: go125412@ohio.edu // // // Description: // Fill int // // Date: November 14, 2016 // //******************************************************************* // TO DO: // - Watch thebennybox - Intro to Modern OpenGL Tutorial #6: Camera and Perspective // - There's also a guy name Jamie King who does good opengl tutorials // #include <iostream> #include "Angel.h" #include <vector> #include <fstream> #include <string> #include <sstream> #include <cstring> #include <typeinfo> #include "src/objloader.h" #include "src/mesh.h" #include "src/camera.h" using namespace std; typedef Angel::vec4 point4; typedef Angel::vec4 color4; // // GLOBAL CONSTANTS // // OBJECTS IN SCENE // Mesh Cube("models/cube.obj"); // Mesh Pipe("models/pipe.obj"); // Window dimension constants int win_w = 1024; int win_h = 768; GLfloat incr =0.06; // Array of rotation angles (in degrees) for each coordinate axis enum {Xaxis = 0, Yaxis = 1, Zaxis = 2, NumAxes = 3}; int Axis = Xaxis; GLfloat Theta[NumAxes] = {0.0, 0.0, 0.0}; vector<vec4> vertices; vector<vec2> uvs; vector<vec4> normals; GLuint program; GLuint loc; GLint matrix_loc, projection_loc; point4 at = vec4(0.0, 0.0, 0.0, 1.0); point4 eye = vec4(0.0, 0.0, 2.0, 1.0); vec4 up = vec4(0.0, 1.0, 0.0, 0.0); GLfloat l= -2.0, r=2.0, top=2.0, bottom= -2.0, near= -100.0, far=100.0; // Declaring the projection and model view mat4 model_view; mat4 projection; // Initialize the camera Camera camera(vec4(0.0f, 0.0f, -2.0f, 0.0f), 70.0f, (float)win_w/(float)win_h, 0.1f, 100.0f); float camera_speed = 0.5f; // // CALLBACKS // extern "C" void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Generate tha model-view matrixn const vec3 viewer_pos(0.0, 0.0, 1.0); model_view = (Translate(-viewer_pos)* RotateX(Theta[Xaxis]) * RotateY(Theta[Yaxis]) * RotateZ(Theta[Zaxis])); projection = camera.GetViewProjection(); glUniformMatrix4fv(matrix_loc, 1, GL_TRUE, model_view); glUniformMatrix4fv(projection_loc, 1, GL_TRUE, projection); // For wireframe rendering for(int i = 0; i<vertices.size(); i+=3) glDrawArrays(GL_LINE_LOOP, i, 3); // for(int i = 0; i<Pipe.GetVertices().size(); i+=3) glDrawArrays(GL_LINE_LOOP, i, 3); // For solid rendering // glDrawArrays(GL_TRIANGLES, 0, vertices.size()); glutSwapBuffers(); } extern "C" void key(unsigned char k, int nx, int ny) { switch (k) { case 'q': case 'Q': exit(0); break; case 'w': case 'W': camera.MoveForward(camera_speed); break; case 's': case 'S': camera.MoveForward(-camera_speed); break; case 'd': case 'D': camera.MoveRight(-camera_speed); break; case 'a': case 'A': camera.MoveRight(camera_speed); break; case 'r': camera.RotateYaw(-0.02); break; case 'e': camera.RotateYaw(0.02); break; default: // Anything else. break; } // Something might have changed requiring redisplay glutPostRedisplay(); } extern "C" void mouse(int button, int state, int x, int y) { if (state == GLUT_DOWN) { switch(button) { case GLUT_LEFT_BUTTON: Axis = Xaxis; break; case GLUT_MIDDLE_BUTTON: Axis = Yaxis; break; case GLUT_RIGHT_BUTTON: Axis = Zaxis; break; } } } extern "C" void idle() { static GLint time=glutGet(GLUT_ELAPSED_TIME); Theta[Axis] += incr*(glutGet(GLUT_ELAPSED_TIME)-time); time = glutGet(GLUT_ELAPSED_TIME); if (Theta[Axis] > 360.0) { Theta[Axis] -= 360.0; } glutPostRedisplay(); } void GLUTinit() { glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(win_w, win_h); glutInitWindowPosition(20,20); glutCreateWindow("Rogue Game"); glClearColor(0.0, 0.0, 0.0, 1.0); // Clear screen to black /* CALLBACKS */ glutDisplayFunc(display); glutIdleFunc(idle); glutMouseFunc (mouse); // glutMotionFunc (motion); // glutPassiveMotionFunc (passivemotion); glutKeyboardFunc(key); // glutReshapeFunc (myReshape); } void init() { GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(vec4), &vertices[0], GL_STATIC_DRAW); // glBindBuffer(GL_ARRAY_BUFFER, buffer[1]); // glBufferData(GL_ARRAY_BUFFER, Pipe.GetVertices().size()*sizeof(vec4), &Pipe.GetVertices()[0], GL_STATIC_DRAW); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, 0, 0); // get shader program program = InitShader("vshader.glsl", "fshader.glsl"); glUseProgram(program); loc = glGetAttribLocation(program, "vPosition"); matrix_loc = glGetUniformLocation(program, "model_view"); projection_loc = glGetUniformLocation(program, "projection"); glClearColor(0.0, 0.0, 0.0, 1.0); // white background } int main(int argc, char **argv) { glutInit(&argc, argv); load_obj("models/pipe.obj", vertices, uvs, normals); // Initializes the GLUT and callbacks GLUTinit(); glewInit(); // Initializes the buffers and vao init(); glEnable(GL_DEPTH_TEST); glutMainLoop(); // enter event loop return (EXIT_SUCCESS); }<commit_msg>adjust the camera speed<commit_after>//******************************************************************* // // Program: Rogue Game // // Author: Gus Oberdick // Email: go125412@ohio.edu // // // Description: // Fill int // // Date: November 14, 2016 // //******************************************************************* // TO DO: // - Watch thebennybox - Intro to Modern OpenGL Tutorial #6: Camera and Perspective // - There's also a guy name Jamie King who does good opengl tutorials // #include <iostream> #include "Angel.h" #include <vector> #include <fstream> #include <string> #include <sstream> #include <cstring> #include <typeinfo> #include "src/objloader.h" #include "src/mesh.h" #include "src/camera.h" using namespace std; typedef Angel::vec4 point4; typedef Angel::vec4 color4; // // GLOBAL CONSTANTS // // OBJECTS IN SCENE Mesh Cube("models/cube.obj"); // Mesh Pipe("models/pipe.obj"); // Window dimension constants int win_w = 1024; int win_h = 768; GLfloat incr =0.06; // Array of rotation angles (in degrees) for each coordinate axis enum {Xaxis = 0, Yaxis = 1, Zaxis = 2, NumAxes = 3}; int Axis = Xaxis; GLfloat Theta[NumAxes] = {0.0, 0.0, 0.0}; vector<vec4> vertices; vector<vec2> uvs; vector<vec4> normals; GLuint program; GLuint loc; GLint matrix_loc, projection_loc; point4 at = vec4(0.0, 0.0, 0.0, 1.0); point4 eye = vec4(0.0, 0.0, 2.0, 1.0); vec4 up = vec4(0.0, 1.0, 0.0, 0.0); GLfloat l= -2.0, r=2.0, top=2.0, bottom= -2.0, near= -100.0, far=100.0; // Declaring the projection and model view mat4 model_view; mat4 projection; // Initialize the camera Camera camera(vec4(0.0f, 0.0f, -2.0f, 0.0f), 70.0f, (float)win_w/(float)win_h, 0.1f, 100.0f); float camera_speed = 0.5f; // // CALLBACKS // extern "C" void display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Generate tha model-view matrixn const vec3 viewer_pos(0.0, 0.0, 1.0); model_view = (Translate(-viewer_pos)* RotateX(Theta[Xaxis]) * RotateY(Theta[Yaxis]) * RotateZ(Theta[Zaxis])); projection = camera.GetViewProjection(); glUniformMatrix4fv(matrix_loc, 1, GL_TRUE, model_view); glUniformMatrix4fv(projection_loc, 1, GL_TRUE, projection); // For wireframe rendering for(int i = 0; i<vertices.size(); i+=3) glDrawArrays(GL_LINE_LOOP, i, 3); // for(int i = 0; i<Pipe.GetVertices().size(); i+=3) glDrawArrays(GL_LINE_LOOP, i, 3); // For solid rendering // glDrawArrays(GL_TRIANGLES, 0, vertices.size()); glutSwapBuffers(); } extern "C" void key(unsigned char k, int nx, int ny) { switch (k) { case 'q': case 'Q': exit(0); break; case 'w': case 'W': camera.MoveForward(camera_speed); break; case 's': case 'S': camera.MoveForward(-camera_speed); break; case 'd': case 'D': camera.MoveRight(-camera_speed); break; case 'a': case 'A': camera.MoveRight(camera_speed); break; case 'r': camera.RotateYaw(-0.5); break; case 'e': camera.RotateYaw(0.5); break; default: // Anything else. break; } // Something might have changed requiring redisplay glutPostRedisplay(); } extern "C" void mouse(int button, int state, int x, int y) { if (state == GLUT_DOWN) { switch(button) { case GLUT_LEFT_BUTTON: Axis = Xaxis; break; case GLUT_MIDDLE_BUTTON: Axis = Yaxis; break; case GLUT_RIGHT_BUTTON: Axis = Zaxis; break; } } } extern "C" void idle() { static GLint time=glutGet(GLUT_ELAPSED_TIME); Theta[Axis] += incr*(glutGet(GLUT_ELAPSED_TIME)-time); time = glutGet(GLUT_ELAPSED_TIME); if (Theta[Axis] > 360.0) { Theta[Axis] -= 360.0; } glutPostRedisplay(); } void GLUTinit() { glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(win_w, win_h); glutInitWindowPosition(20,20); glutCreateWindow("Rogue Game"); glClearColor(0.0, 0.0, 0.0, 1.0); // Clear screen to black /* CALLBACKS */ glutDisplayFunc(display); glutIdleFunc(idle); glutMouseFunc (mouse); // glutMotionFunc (motion); // glutPassiveMotionFunc (passivemotion); glutKeyboardFunc(key); // glutReshapeFunc (myReshape); } void init() { GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); // Cube data glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(vec4), &vertices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(loc); glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, 0, 0); // get shader program program = InitShader("vshader.glsl", "fshader.glsl"); glUseProgram(program); loc = glGetAttribLocation(program, "vPosition"); matrix_loc = glGetUniformLocation(program, "model_view"); projection_loc = glGetUniformLocation(program, "projection"); glClearColor(0.0, 0.0, 0.0, 1.0); // white background } int main(int argc, char **argv) { glutInit(&argc, argv); // load_obj("models/pipe.obj", vertices, uvs, normals); // Initializes the GLUT and callbacks GLUTinit(); glewInit(); // Initializes the buffers and vao init(); glEnable(GL_DEPTH_TEST); glutMainLoop(); // enter event loop return (EXIT_SUCCESS); }<|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #include <boost/python.hpp> #include <mapnik/datasource_cache.hpp> void export_datasource_cache() { using mapnik::datasource_cache; using mapnik::singleton; using mapnik::CreateStatic; using namespace boost::python; class_<singleton<datasource_cache,CreateStatic>,boost::noncopyable>("Singleton",no_init) .def("instance",&singleton<datasource_cache,CreateStatic>::instance, return_value_policy<reference_existing_object>()) .staticmethod("instance") ; class_<datasource_cache,bases<singleton<datasource_cache,CreateStatic> >, boost::noncopyable>("DatasourceCache",no_init) .def("create",&datasource_cache::create) .staticmethod("create") .def("register_datasources",&datasource_cache::register_datasources) .staticmethod("register_datasources") ; } <commit_msg>+reflect 'plugin_names()' method in python<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #include <boost/python.hpp> #include <mapnik/datasource_cache.hpp> void export_datasource_cache() { using mapnik::datasource_cache; using mapnik::singleton; using mapnik::CreateStatic; using namespace boost::python; class_<singleton<datasource_cache,CreateStatic>,boost::noncopyable>("Singleton",no_init) .def("instance",&singleton<datasource_cache,CreateStatic>::instance, return_value_policy<reference_existing_object>()) .staticmethod("instance") ; class_<datasource_cache,bases<singleton<datasource_cache,CreateStatic> >, boost::noncopyable>("DatasourceCache",no_init) .def("create",&datasource_cache::create) .staticmethod("create") .def("register_datasources",&datasource_cache::register_datasources) .staticmethod("register_datasources") .def("plugin_names",&datasource_cache::plugin_names) .staticmethod("plugin_names") ; } <|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <mutex> // NOLINT #include "bindings/python/pyiree/binding.h" #include "bindings/python/pyiree/compiler.h" #include "bindings/python/pyiree/hal.h" #include "bindings/python/pyiree/rt.h" #include "bindings/python/pyiree/status_utils.h" #include "bindings/python/pyiree/tf_interop/register_tensorflow.h" #include "bindings/python/pyiree/vm.h" #include "iree/base/initializer.h" #include "iree/base/tracing.h" #include "wtf/event.h" #include "wtf/macros.h" namespace iree { namespace python { namespace { // Wrapper around wtf::ScopedEvent to make it usable as a python context // object. class PyScopedEvent { public: PyScopedEvent(std::string name_spec) : scoped_event_(InternEvent(std::move(name_spec))) {} bool Enter() { if (scoped_event_) { scoped_event_->Enter(); return true; } return false; } void Exit(py::args args) { if (scoped_event_) scoped_event_->Leave(); } private: static ::wtf::ScopedEvent<>* InternEvent(std::string name_spec) { if (!::wtf::kMasterEnable) return nullptr; std::lock_guard<std::mutex> lock(mu_); auto it = scoped_event_intern_.find(name_spec); if (it == scoped_event_intern_.end()) { // Name spec must live forever. std::string* dup_name_spec = new std::string(std::move(name_spec)); // So must the event. auto scoped_event = new ::wtf::ScopedEvent<>(dup_name_spec->c_str()); scoped_event_intern_.insert(std::make_pair(*dup_name_spec, scoped_event)); return scoped_event; } else { return it->second; } } static std::mutex mu_; static std::unordered_map<std::string, ::wtf::ScopedEvent<>*> scoped_event_intern_; ::wtf::ScopedEvent<>* scoped_event_; }; std::mutex PyScopedEvent::mu_; std::unordered_map<std::string, ::wtf::ScopedEvent<>*> PyScopedEvent::scoped_event_intern_; void SetupTracingBindings(pybind11::module m) { m.def("enable_thread", []() { WTF_AUTO_THREAD_ENABLE(); }); m.def("is_available", []() { return IsTracingAvailable(); }); m.def( "flush", [](absl::optional<std::string> explicit_trace_path) { absl::optional<absl::string_view> sv_path; if (explicit_trace_path) sv_path = explicit_trace_path; FlushTrace(explicit_trace_path); }, py::arg("explicit_trace_path") = absl::optional<absl::string_view>()); m.def( "autoflush", [](float period) { StartTracingAutoFlush(absl::Seconds(period)); }, py::arg("period") = 5.0f); m.def("stop", []() { StopTracing(); }); py::class_<PyScopedEvent>(m, "ScopedEvent") .def(py::init<std::string>()) .def("__enter__", &PyScopedEvent::Enter) .def("__exit__", &PyScopedEvent::Exit); } } // namespace PYBIND11_MODULE(binding, m) { IREE_RUN_MODULE_INITIALIZERS(); m.doc() = "IREE Binding Backend Helpers"; py::class_<OpaqueBlob, std::shared_ptr<OpaqueBlob>>(m, "OpaqueBlob"); auto compiler_m = m.def_submodule("compiler", "IREE compiler support"); SetupCompilerBindings(compiler_m); auto hal_m = m.def_submodule("hal", "IREE HAL support"); SetupHalBindings(hal_m); auto rt_m = m.def_submodule("rt", "IREE RT api"); SetupRtBindings(rt_m); auto vm_m = m.def_submodule("vm", "IREE VM api"); SetupVmBindings(vm_m); auto tracing_m = m.def_submodule("tracing", "IREE tracing api"); SetupTracingBindings(tracing_m); // TensorFlow. #if defined(IREE_TENSORFLOW_ENABLED) auto tf_m = m.def_submodule("tf_interop", "IREE TensorFlow interop"); SetupTensorFlowBindings(tf_m); #endif } } // namespace python } // namespace iree <commit_msg>Add a method to get the blob contents.<commit_after>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <mutex> // NOLINT #include "bindings/python/pyiree/binding.h" #include "bindings/python/pyiree/compiler.h" #include "bindings/python/pyiree/hal.h" #include "bindings/python/pyiree/rt.h" #include "bindings/python/pyiree/status_utils.h" #include "bindings/python/pyiree/tf_interop/register_tensorflow.h" #include "bindings/python/pyiree/vm.h" #include "iree/base/initializer.h" #include "iree/base/tracing.h" #include "wtf/event.h" #include "wtf/macros.h" namespace iree { namespace python { namespace { // Wrapper around wtf::ScopedEvent to make it usable as a python context // object. class PyScopedEvent { public: PyScopedEvent(std::string name_spec) : scoped_event_(InternEvent(std::move(name_spec))) {} bool Enter() { if (scoped_event_) { scoped_event_->Enter(); return true; } return false; } void Exit(py::args args) { if (scoped_event_) scoped_event_->Leave(); } private: static ::wtf::ScopedEvent<>* InternEvent(std::string name_spec) { if (!::wtf::kMasterEnable) return nullptr; std::lock_guard<std::mutex> lock(mu_); auto it = scoped_event_intern_.find(name_spec); if (it == scoped_event_intern_.end()) { // Name spec must live forever. std::string* dup_name_spec = new std::string(std::move(name_spec)); // So must the event. auto scoped_event = new ::wtf::ScopedEvent<>(dup_name_spec->c_str()); scoped_event_intern_.insert(std::make_pair(*dup_name_spec, scoped_event)); return scoped_event; } else { return it->second; } } static std::mutex mu_; static std::unordered_map<std::string, ::wtf::ScopedEvent<>*> scoped_event_intern_; ::wtf::ScopedEvent<>* scoped_event_; }; std::mutex PyScopedEvent::mu_; std::unordered_map<std::string, ::wtf::ScopedEvent<>*> PyScopedEvent::scoped_event_intern_; void SetupTracingBindings(pybind11::module m) { m.def("enable_thread", []() { WTF_AUTO_THREAD_ENABLE(); }); m.def("is_available", []() { return IsTracingAvailable(); }); m.def( "flush", [](absl::optional<std::string> explicit_trace_path) { absl::optional<absl::string_view> sv_path; if (explicit_trace_path) sv_path = explicit_trace_path; FlushTrace(explicit_trace_path); }, py::arg("explicit_trace_path") = absl::optional<absl::string_view>()); m.def( "autoflush", [](float period) { StartTracingAutoFlush(absl::Seconds(period)); }, py::arg("period") = 5.0f); m.def("stop", []() { StopTracing(); }); py::class_<PyScopedEvent>(m, "ScopedEvent") .def(py::init<std::string>()) .def("__enter__", &PyScopedEvent::Enter) .def("__exit__", &PyScopedEvent::Exit); } } // namespace PYBIND11_MODULE(binding, m) { IREE_RUN_MODULE_INITIALIZERS(); m.doc() = "IREE Binding Backend Helpers"; py::class_<OpaqueBlob, std::shared_ptr<OpaqueBlob>>(m, "OpaqueBlob") .def_property_readonly("bytes", [](OpaqueBlob* self) -> py::bytes { return py::bytes(static_cast<const char*>(self->data()), self->size()); }); auto compiler_m = m.def_submodule("compiler", "IREE compiler support"); SetupCompilerBindings(compiler_m); auto hal_m = m.def_submodule("hal", "IREE HAL support"); SetupHalBindings(hal_m); auto rt_m = m.def_submodule("rt", "IREE RT api"); SetupRtBindings(rt_m); auto vm_m = m.def_submodule("vm", "IREE VM api"); SetupVmBindings(vm_m); auto tracing_m = m.def_submodule("tracing", "IREE tracing api"); SetupTracingBindings(tracing_m); // TensorFlow. #if defined(IREE_TENSORFLOW_ENABLED) auto tf_m = m.def_submodule("tf_interop", "IREE TensorFlow interop"); SetupTensorFlowBindings(tf_m); #endif } } // namespace python } // namespace iree <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file QFunctionDefinition.cpp * @author Yann yann@ethdev.com * @date 2014 */ #include <libsolidity/AST.h> #include <libdevcrypto/SHA3.h> #include <libdevcore/Exceptions.h> #include "QVariableDeclaration.h" #include "QFunctionDefinition.h" using namespace dev::solidity; using namespace dev::mix; QFunctionDefinition::QFunctionDefinition(dev::solidity::FunctionTypePointer const& _f): QBasicNodeDefinition(_f->getDeclaration()), m_hash(dev::sha3(_f->getCanonicalSignature())) { auto paramNames = _f->getParameterNames(); auto paramTypes = _f->getParameterTypeNames(); auto returnNames = _f->getReturnParameterNames(); auto returnTypes = _f->getReturnParameterTypeNames(); for (unsigned i = 0; i < paramNames.size(); ++i) m_parameters.append(new QVariableDeclaration(paramNames[i], paramTypes[i])); for (unsigned i = 0; i < returnNames.size(); ++i) m_returnParameters.append(new QVariableDeclaration(returnNames[i], returnTypes[i])); } <commit_msg>FunctionType now returns const ref for Declaration<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file QFunctionDefinition.cpp * @author Yann yann@ethdev.com * @date 2014 */ #include <libsolidity/AST.h> #include <libdevcrypto/SHA3.h> #include <libdevcore/Exceptions.h> #include "QVariableDeclaration.h" #include "QFunctionDefinition.h" using namespace dev::solidity; using namespace dev::mix; QFunctionDefinition::QFunctionDefinition(dev::solidity::FunctionTypePointer const& _f): QBasicNodeDefinition(&_f->getDeclaration()), m_hash(dev::sha3(_f->getCanonicalSignature())) { auto paramNames = _f->getParameterNames(); auto paramTypes = _f->getParameterTypeNames(); auto returnNames = _f->getReturnParameterNames(); auto returnTypes = _f->getReturnParameterTypeNames(); for (unsigned i = 0; i < paramNames.size(); ++i) m_parameters.append(new QVariableDeclaration(paramNames[i], paramTypes[i])); for (unsigned i = 0; i < returnNames.size(); ++i) m_returnParameters.append(new QVariableDeclaration(returnNames[i], returnTypes[i])); } <|endoftext|>
<commit_before>#include "ovasCAcquisitionServerGUI.h" #include <openvibe/ov_all.h> #include <openvibe-toolkit/ovtk_all.h> #include <gtk/gtk.h> #include <iostream> using namespace OpenViBE; using namespace OpenViBE::Kernel; using namespace std; int main(int argc, char ** argv) { //___________________________________________________________________// // // CKernelLoader l_oKernelLoader; cout<<"[ INF ] Created kernel loader, trying to load kernel module"<<endl; CString m_sError; #if defined OVAS_OS_Windows if(!l_oKernelLoader.load(OpenViBE::Directories::getLibDir() + "/OpenViBE-kernel-dynamic.dll", &m_sError)) #else if(!l_oKernelLoader.load(OpenViBE::Directories::getLibDir() + "/libOpenViBE-kernel-dynamic.so", &m_sError)) #endif { cout<<"[ FAILED ] Error loading kernel ("<<m_sError<<")"<<endl; } else { cout<<"[ INF ] Kernel module loaded, trying to get kernel descriptor"<<endl; IKernelDesc* l_pKernelDesc=NULL; IKernelContext* l_pKernelContext=NULL; l_oKernelLoader.initialize(); l_oKernelLoader.getKernelDesc(l_pKernelDesc); if(!l_pKernelDesc) { cout<<"[ FAILED ] No kernel descriptor"<<endl; } else { cout<<"[ INF ] Got kernel descriptor, trying to create kernel"<<endl; l_pKernelContext=l_pKernelDesc->createKernel("acquisition-server", OpenViBE::Directories::getDataDir() + "/openvibe.conf"); if(!l_pKernelContext) { cout<<"[ FAILED ] No kernel created by kernel descriptor"<<endl; } else { OpenViBEToolkit::initialize(*l_pKernelContext); // For Mister Vincent ! #ifdef OVAS_OS_Windows #ifndef NDEBUG //_asm int 3; #endif #endif IConfigurationManager& l_rConfigurationManager=l_pKernelContext->getConfigurationManager(); l_pKernelContext->getPluginManager().addPluginsFromFiles(l_rConfigurationManager.expand("${Kernel_Plugins}")); //initialise Gtk before 3D context #if (GTK_MAJOR_VERSION == 2) && (GTK_MINOR_VERSION < 32) // although deprecated in newer GTKs, we need to use this on Windows with the older GTK, or acquisition server will crash on startup g_thread_init(NULL); #endif gdk_threads_init(); gtk_init(&argc, &argv); // gtk_rc_parse(OpenViBE::Directories::getDataDir() + "/openvibe-applications/designer/interface.gtkrc"); #if 0 // This is not needed in the acquisition server if(l_rConfigurationManager.expandAsBoolean("${Kernel_3DVisualisationEnabled}")) { l_pKernelContext->getVisualisationManager().initialize3DContext(); } #endif { // If this is encapsulated by gdk_threads_enter() and gdk_threads_exit(), m_pThread->join() can hang when gtk_main() returns before destructor of app has been called. OpenViBEAcquisitionServer::CAcquisitionServerGUI app(*l_pKernelContext); try { gdk_threads_enter(); gtk_main(); gdk_threads_leave(); } catch(...) { l_pKernelContext->getLogManager() << LogLevel_Fatal << "Catched top level exception\n"; } } cout<<"[ INF ] Application terminated, releasing allocated objects"<<endl; OpenViBEToolkit::uninitialize(*l_pKernelContext); l_pKernelDesc->releaseKernel(l_pKernelContext); } } l_oKernelLoader.uninitialize(); l_oKernelLoader.unload(); } return 0; } <commit_msg>Ajust GTK version test to fix warnings in Ubuntu 12.10<commit_after>#include "ovasCAcquisitionServerGUI.h" #include <openvibe/ov_all.h> #include <openvibe-toolkit/ovtk_all.h> #include <gtk/gtk.h> #include <iostream> using namespace OpenViBE; using namespace OpenViBE::Kernel; using namespace std; int main(int argc, char ** argv) { //___________________________________________________________________// // // CKernelLoader l_oKernelLoader; cout<<"[ INF ] Created kernel loader, trying to load kernel module"<<endl; CString m_sError; #if defined OVAS_OS_Windows if(!l_oKernelLoader.load(OpenViBE::Directories::getLibDir() + "/OpenViBE-kernel-dynamic.dll", &m_sError)) #else if(!l_oKernelLoader.load(OpenViBE::Directories::getLibDir() + "/libOpenViBE-kernel-dynamic.so", &m_sError)) #endif { cout<<"[ FAILED ] Error loading kernel ("<<m_sError<<")"<<endl; } else { cout<<"[ INF ] Kernel module loaded, trying to get kernel descriptor"<<endl; IKernelDesc* l_pKernelDesc=NULL; IKernelContext* l_pKernelContext=NULL; l_oKernelLoader.initialize(); l_oKernelLoader.getKernelDesc(l_pKernelDesc); if(!l_pKernelDesc) { cout<<"[ FAILED ] No kernel descriptor"<<endl; } else { cout<<"[ INF ] Got kernel descriptor, trying to create kernel"<<endl; l_pKernelContext=l_pKernelDesc->createKernel("acquisition-server", OpenViBE::Directories::getDataDir() + "/openvibe.conf"); if(!l_pKernelContext) { cout<<"[ FAILED ] No kernel created by kernel descriptor"<<endl; } else { OpenViBEToolkit::initialize(*l_pKernelContext); // For Mister Vincent ! #ifdef OVAS_OS_Windows #ifndef NDEBUG //_asm int 3; #endif #endif IConfigurationManager& l_rConfigurationManager=l_pKernelContext->getConfigurationManager(); l_pKernelContext->getPluginManager().addPluginsFromFiles(l_rConfigurationManager.expand("${Kernel_Plugins}")); //initialise Gtk before 3D context #if (GTK_BINARY_AGE < 2413) // although deprecated in newer GTKs (no more needed after (at least) 2.24.13, deprecated in 2.32), we need to use this on Windows with the older GTK (2.22.1), or acquisition server will crash on startup g_thread_init(NULL); #endif gdk_threads_init(); gtk_init(&argc, &argv); // gtk_rc_parse(OpenViBE::Directories::getDataDir() + "/openvibe-applications/designer/interface.gtkrc"); #if 0 // This is not needed in the acquisition server if(l_rConfigurationManager.expandAsBoolean("${Kernel_3DVisualisationEnabled}")) { l_pKernelContext->getVisualisationManager().initialize3DContext(); } #endif { // If this is encapsulated by gdk_threads_enter() and gdk_threads_exit(), m_pThread->join() can hang when gtk_main() returns before destructor of app has been called. OpenViBEAcquisitionServer::CAcquisitionServerGUI app(*l_pKernelContext); try { gdk_threads_enter(); gtk_main(); gdk_threads_leave(); } catch(...) { l_pKernelContext->getLogManager() << LogLevel_Fatal << "Catched top level exception\n"; } } cout<<"[ INF ] Application terminated, releasing allocated objects"<<endl; OpenViBEToolkit::uninitialize(*l_pKernelContext); l_pKernelDesc->releaseKernel(l_pKernelContext); } } l_oKernelLoader.uninitialize(); l_oKernelLoader.unload(); } return 0; } <|endoftext|>
<commit_before>#include "StdAfx.h" #include "SrwDecoder.h" #include "TiffParserOlympus.h" #include "ByteStreamSwap.h" #if defined(__unix__) || defined(__APPLE__) #include <stdlib.h> #endif /* RawSpeed - RAW file decoder. Copyright (C) 2009-2010 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { SrwDecoder::SrwDecoder(TiffIFD *rootIFD, FileMap* file): RawDecoder(file), mRootIFD(rootIFD) { decoderVersion = 3; b = NULL; } SrwDecoder::~SrwDecoder(void) { if (mRootIFD) delete mRootIFD; mRootIFD = NULL; if (NULL != b) delete b; b = NULL; } RawImage SrwDecoder::decodeRawInternal() { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(STRIPOFFSETS); if (data.empty()) ThrowRDE("Srw Decoder: No image data found"); TiffIFD* raw = data[0]; int compression = raw->getEntry(COMPRESSION)->getInt(); int bits = raw->getEntry(BITSPERSAMPLE)->getInt(); if (32769 != compression && 32770 != compression && 32772 != compression) ThrowRDE("Srw Decoder: Unsupported compression"); if (32769 == compression) { bool bit_order = false; // Default guess map<string,string>::iterator msb_hint = hints.find("msb_override"); if (msb_hint != hints.end()) bit_order = (0 == (msb_hint->second).compare("true")); this->decodeUncompressed(raw, bit_order ? BitOrder_Jpeg : BitOrder_Plain); return mRaw; } if (32770 == compression) { if (!raw->hasEntry ((TiffTag)40976)) { bool bit_order = (bits == 12); // Default guess map<string,string>::iterator msb_hint = hints.find("msb_override"); if (msb_hint != hints.end()) bit_order = (0 == (msb_hint->second).compare("true")); this->decodeUncompressed(raw, bit_order ? BitOrder_Jpeg : BitOrder_Plain); return mRaw; } else { uint32 nslices = raw->getEntry(STRIPOFFSETS)->count; if (nslices != 1) ThrowRDE("Srw Decoder: Only one slice supported, found %u", nslices); try { decodeCompressed(raw); } catch (RawDecoderException& e) { mRaw->setError(e.what()); } return mRaw; } } if (32772 == compression) { uint32 nslices = raw->getEntry(STRIPOFFSETS)->count; if (nslices != 1) ThrowRDE("Srw Decoder: Only one slice supported, found %u", nslices); try { decodeCompressed2(raw, bits); } catch (RawDecoderException& e) { mRaw->setError(e.what()); } return mRaw; } ThrowRDE("Srw Decoder: Unsupported compression"); return mRaw; } // Decoder for compressed srw files (NX300 and later) void SrwDecoder::decodeCompressed( TiffIFD* raw ) { uint32 width = raw->getEntry(IMAGEWIDTH)->getInt(); uint32 height = raw->getEntry(IMAGELENGTH)->getInt(); mRaw->dim = iPoint2D(width, height); mRaw->createData(); const uint32 offset = raw->getEntry(STRIPOFFSETS)->getInt(); uint32 compressed_offset = raw->getEntry((TiffTag)40976)->getInt(); if (NULL != b) delete b; if (getHostEndianness() == little) b = new ByteStream(mFile->getData(0), mFile->getSize()); else b = new ByteStreamSwap(mFile->getData(0), mFile->getSize()); b->setAbsoluteOffset(compressed_offset); for (uint32 y = 0; y < height; y++) { uint32 line_offset = offset + b->getInt(); if (line_offset >= mFile->getSize()) ThrowRDE("Srw decoder: Offset outside image file, file probably truncated."); int len[4]; for (int i = 0; i < 4; i++) len[i] = y < 2 ? 7 : 4; BitPumpMSB32 bits(mFile->getData(line_offset),mFile->getSize() - line_offset); int op[4]; ushort16* img = (ushort16*)mRaw->getData(0, y); ushort16* img_up = (ushort16*)mRaw->getData(0, max(0, (int)y - 1)); ushort16* img_up2 = (ushort16*)mRaw->getData(0, max(0, (int)y - 2)); // Image is arranged in groups of 16 pixels horizontally for (uint32 x = 0; x < width; x += 16) { bits.fill(); bool dir = !!bits.getBitNoFill(); for (int i = 0; i < 4; i++) op[i] = bits.getBitsNoFill(2); for (int i = 0; i < 4; i++) { switch (op[i]) { case 3: len[i] = bits.getBits(4); break; case 2: len[i]--; break; case 1: len[i]++; } if (len[i] < 0) ThrowRDE("Srw Decompressor: Bit length less than 0."); if (len[i] > 16) ThrowRDE("Srw Decompressor: Bit Length more than 16."); } if (dir) { // Upward prediction // First we decode even pixels for (int c = 0; c < 16; c += 2) { int b = len[(c >> 3)]; int32 adj = ((int32) bits.getBits(b) << (32-b) >> (32-b)); img[c] = adj + img_up[c]; } // Now we decode odd pixels // Why on earth upward prediction only looks up 1 line above // is beyond me, it will hurt compression a deal. for (int c = 1; c < 16; c += 2) { int b = len[2 | (c >> 3)]; int32 adj = ((int32) bits.getBits(b) << (32-b) >> (32-b)); img[c] = adj + img_up2[c]; } } else { // Left to right prediction // First we decode even pixels int pred_left = x ? img[-2] : 128; for (int c = 0; c < 16; c += 2) { int b = len[(c >> 3)]; int32 adj = ((int32) bits.getBits(b) << (32-b) >> (32-b)); img[c] = adj + pred_left; } // Now we decode odd pixels pred_left = x ? img[-1] : 128; for (int c = 1; c < 16; c += 2) { int b = len[2 | (c >> 3)]; int32 adj = ((int32) bits.getBits(b) << (32-b) >> (32-b)); img[c] = adj + pred_left; } } bits.checkPos(); img += 16; img_up += 16; img_up2 += 16; } } // Swap red and blue pixels to get the final CFA pattern for (uint32 y = 0; y < height-1; y+=2) { ushort16* topline = (ushort16*)mRaw->getData(0, y); ushort16* bottomline = (ushort16*)mRaw->getData(0, y+1); for (uint32 x = 0; x < width-1; x += 2) { ushort16 temp = topline[1]; topline[1] = bottomline[0]; bottomline[0] = temp; topline += 2; bottomline += 2; } } } // Decoder for compressed srw files (NX3000 and later) void SrwDecoder::decodeCompressed2( TiffIFD* raw, int bits) { uint32 width = raw->getEntry(IMAGEWIDTH)->getInt(); uint32 height = raw->getEntry(IMAGELENGTH)->getInt(); uint32 offset = raw->getEntry(STRIPOFFSETS)->getInt(); mRaw->dim = iPoint2D(width, height); mRaw->createData(); // This format has a variable length encoding of how many bits are needed // to encode the difference between pixels, we use a table to process it // that has two values, the first the number of bits that were used to // encode, the second the number of bits that come after with the difference // The table has 14 entries because the difference can have between 0 (no // difference) and 13 bits (differences between 12 bits numbers can need 13) const ushort16 tab[14][2] = {{3,4}, {3,7}, {2,6}, {2,5}, {4,3}, {6,0}, {7,9}, {8,10}, {9,11}, {10,12}, {10,13}, {5,1}, {4,8}, {4,2}}; encTableItem tbl[1024]; ushort16 vpred[2][2] = {{0,0},{0,0}}, hpred[2]; // We generate a 1024 entry table (to be addressed by reading 10 bits) by // consecutively filling in 2^(10-N) positions where N is the variable number of // bits of the encoding. So for example 4 is encoded with 3 bits so the first // 2^(10-3)=128 positions are set with 3,4 so that any time we read 000 we // know the next 4 bits are the difference. We read 10 bits because that is // the maximum number of bits used in the variable encoding (for the 12 and // 13 cases) uint32 n = 0; for (uint32 i=0; i < 14; i++) { for(int32 c = 0; c < (1024 >> tab[i][0]); c++) { tbl[n ].encLen = tab[i][0]; tbl[n++].diffLen = tab[i][1]; } } BitPumpMSB pump(mFile->getData(offset),mFile->getSize() - offset); for (uint32 y = 0; y < height; y++) { ushort16* img = (ushort16*)mRaw->getData(0, y); for (uint32 x = 0; x < width; x++) { int32 diff = samsungDiff(pump, tbl); if (x < 2) hpred[x] = vpred[y & 1][x] += diff; else hpred[x & 1] += diff; img[x] = hpred[x & 1]; if (img[x] >> bits) ThrowRDE("SRW: Error: decoded value out of bounds at %d:%d", x, y); } } } int32 SrwDecoder::samsungDiff (BitPumpMSB &pump, encTableItem *tbl) { // We read 10 bits to index into our table uint32 c = pump.peekBits(10); // Skip the bits that were used to encode this case pump.getBitsSafe(tbl[c].encLen); // Read the number of bits the table tells me int32 len = tbl[c].diffLen; int32 diff = pump.getBitsSafe(len); // If the first bit is 0 we need to turn this into a negative number if (len && (diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; return diff; } void SrwDecoder::checkSupportInternal(CameraMetaData *meta) { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("Srw Support check: Model name found"); if (!data[0]->hasEntry(MAKE)) ThrowRDE("SRW Support: Make name not found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); this->checkCameraSupported(meta, make, model, ""); } void SrwDecoder::decodeMetaDataInternal(CameraMetaData *meta) { mRaw->cfa.setCFA(iPoint2D(2,2), CFA_RED, CFA_GREEN, CFA_GREEN2, CFA_BLUE); vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("SRW Meta Decoder: Model name found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); data = mRootIFD->getIFDsWithTag(CFAPATTERN); if (!this->checkCameraSupported(meta, make, model, "") && !data.empty() && data[0]->hasEntry(CFAREPEATPATTERNDIM)) { const unsigned short* pDim = data[0]->getEntry(CFAREPEATPATTERNDIM)->getShortArray(); iPoint2D cfaSize(pDim[1], pDim[0]); if (cfaSize.x != 2 && cfaSize.y != 2) ThrowRDE("SRW Decoder: Unsupported CFA pattern size"); const uchar8* cPat = data[0]->getEntry(CFAPATTERN)->getData(); if (cfaSize.area() != data[0]->getEntry(CFAPATTERN)->count) ThrowRDE("SRW Decoder: CFA pattern dimension and pattern count does not match: %d."); for (int y = 0; y < cfaSize.y; y++) { for (int x = 0; x < cfaSize.x; x++) { uint32 c1 = cPat[x+y*cfaSize.x]; CFAColor c2; switch (c1) { case 0: c2 = CFA_RED; break; case 1: c2 = CFA_GREEN; break; case 2: c2 = CFA_BLUE; break; default: c2 = CFA_UNKNOWN; ThrowRDE("SRW Decoder: Unsupported CFA Color."); } mRaw->cfa.setColorAt(iPoint2D(x, y), c2); } } //printf("Camera CFA: %s\n", mRaw->cfa.asString().c_str()); } int iso = 0; if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS)) iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getInt(); setMetaData(meta, make, model, "", iso); } } // namespace RawSpeed <commit_msg>Make table uchar 8 - fixes warning.<commit_after>#include "StdAfx.h" #include "SrwDecoder.h" #include "TiffParserOlympus.h" #include "ByteStreamSwap.h" #if defined(__unix__) || defined(__APPLE__) #include <stdlib.h> #endif /* RawSpeed - RAW file decoder. Copyright (C) 2009-2010 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ namespace RawSpeed { SrwDecoder::SrwDecoder(TiffIFD *rootIFD, FileMap* file): RawDecoder(file), mRootIFD(rootIFD) { decoderVersion = 3; b = NULL; } SrwDecoder::~SrwDecoder(void) { if (mRootIFD) delete mRootIFD; mRootIFD = NULL; if (NULL != b) delete b; b = NULL; } RawImage SrwDecoder::decodeRawInternal() { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(STRIPOFFSETS); if (data.empty()) ThrowRDE("Srw Decoder: No image data found"); TiffIFD* raw = data[0]; int compression = raw->getEntry(COMPRESSION)->getInt(); int bits = raw->getEntry(BITSPERSAMPLE)->getInt(); if (32769 != compression && 32770 != compression && 32772 != compression) ThrowRDE("Srw Decoder: Unsupported compression"); if (32769 == compression) { bool bit_order = false; // Default guess map<string,string>::iterator msb_hint = hints.find("msb_override"); if (msb_hint != hints.end()) bit_order = (0 == (msb_hint->second).compare("true")); this->decodeUncompressed(raw, bit_order ? BitOrder_Jpeg : BitOrder_Plain); return mRaw; } if (32770 == compression) { if (!raw->hasEntry ((TiffTag)40976)) { bool bit_order = (bits == 12); // Default guess map<string,string>::iterator msb_hint = hints.find("msb_override"); if (msb_hint != hints.end()) bit_order = (0 == (msb_hint->second).compare("true")); this->decodeUncompressed(raw, bit_order ? BitOrder_Jpeg : BitOrder_Plain); return mRaw; } else { uint32 nslices = raw->getEntry(STRIPOFFSETS)->count; if (nslices != 1) ThrowRDE("Srw Decoder: Only one slice supported, found %u", nslices); try { decodeCompressed(raw); } catch (RawDecoderException& e) { mRaw->setError(e.what()); } return mRaw; } } if (32772 == compression) { uint32 nslices = raw->getEntry(STRIPOFFSETS)->count; if (nslices != 1) ThrowRDE("Srw Decoder: Only one slice supported, found %u", nslices); try { decodeCompressed2(raw, bits); } catch (RawDecoderException& e) { mRaw->setError(e.what()); } return mRaw; } ThrowRDE("Srw Decoder: Unsupported compression"); return mRaw; } // Decoder for compressed srw files (NX300 and later) void SrwDecoder::decodeCompressed( TiffIFD* raw ) { uint32 width = raw->getEntry(IMAGEWIDTH)->getInt(); uint32 height = raw->getEntry(IMAGELENGTH)->getInt(); mRaw->dim = iPoint2D(width, height); mRaw->createData(); const uint32 offset = raw->getEntry(STRIPOFFSETS)->getInt(); uint32 compressed_offset = raw->getEntry((TiffTag)40976)->getInt(); if (NULL != b) delete b; if (getHostEndianness() == little) b = new ByteStream(mFile->getData(0), mFile->getSize()); else b = new ByteStreamSwap(mFile->getData(0), mFile->getSize()); b->setAbsoluteOffset(compressed_offset); for (uint32 y = 0; y < height; y++) { uint32 line_offset = offset + b->getInt(); if (line_offset >= mFile->getSize()) ThrowRDE("Srw decoder: Offset outside image file, file probably truncated."); int len[4]; for (int i = 0; i < 4; i++) len[i] = y < 2 ? 7 : 4; BitPumpMSB32 bits(mFile->getData(line_offset),mFile->getSize() - line_offset); int op[4]; ushort16* img = (ushort16*)mRaw->getData(0, y); ushort16* img_up = (ushort16*)mRaw->getData(0, max(0, (int)y - 1)); ushort16* img_up2 = (ushort16*)mRaw->getData(0, max(0, (int)y - 2)); // Image is arranged in groups of 16 pixels horizontally for (uint32 x = 0; x < width; x += 16) { bits.fill(); bool dir = !!bits.getBitNoFill(); for (int i = 0; i < 4; i++) op[i] = bits.getBitsNoFill(2); for (int i = 0; i < 4; i++) { switch (op[i]) { case 3: len[i] = bits.getBits(4); break; case 2: len[i]--; break; case 1: len[i]++; } if (len[i] < 0) ThrowRDE("Srw Decompressor: Bit length less than 0."); if (len[i] > 16) ThrowRDE("Srw Decompressor: Bit Length more than 16."); } if (dir) { // Upward prediction // First we decode even pixels for (int c = 0; c < 16; c += 2) { int b = len[(c >> 3)]; int32 adj = ((int32) bits.getBits(b) << (32-b) >> (32-b)); img[c] = adj + img_up[c]; } // Now we decode odd pixels // Why on earth upward prediction only looks up 1 line above // is beyond me, it will hurt compression a deal. for (int c = 1; c < 16; c += 2) { int b = len[2 | (c >> 3)]; int32 adj = ((int32) bits.getBits(b) << (32-b) >> (32-b)); img[c] = adj + img_up2[c]; } } else { // Left to right prediction // First we decode even pixels int pred_left = x ? img[-2] : 128; for (int c = 0; c < 16; c += 2) { int b = len[(c >> 3)]; int32 adj = ((int32) bits.getBits(b) << (32-b) >> (32-b)); img[c] = adj + pred_left; } // Now we decode odd pixels pred_left = x ? img[-1] : 128; for (int c = 1; c < 16; c += 2) { int b = len[2 | (c >> 3)]; int32 adj = ((int32) bits.getBits(b) << (32-b) >> (32-b)); img[c] = adj + pred_left; } } bits.checkPos(); img += 16; img_up += 16; img_up2 += 16; } } // Swap red and blue pixels to get the final CFA pattern for (uint32 y = 0; y < height-1; y+=2) { ushort16* topline = (ushort16*)mRaw->getData(0, y); ushort16* bottomline = (ushort16*)mRaw->getData(0, y+1); for (uint32 x = 0; x < width-1; x += 2) { ushort16 temp = topline[1]; topline[1] = bottomline[0]; bottomline[0] = temp; topline += 2; bottomline += 2; } } } // Decoder for compressed srw files (NX3000 and later) void SrwDecoder::decodeCompressed2( TiffIFD* raw, int bits) { uint32 width = raw->getEntry(IMAGEWIDTH)->getInt(); uint32 height = raw->getEntry(IMAGELENGTH)->getInt(); uint32 offset = raw->getEntry(STRIPOFFSETS)->getInt(); mRaw->dim = iPoint2D(width, height); mRaw->createData(); // This format has a variable length encoding of how many bits are needed // to encode the difference between pixels, we use a table to process it // that has two values, the first the number of bits that were used to // encode, the second the number of bits that come after with the difference // The table has 14 entries because the difference can have between 0 (no // difference) and 13 bits (differences between 12 bits numbers can need 13) const uchar8 tab[14][2] = {{3,4}, {3,7}, {2,6}, {2,5}, {4,3}, {6,0}, {7,9}, {8,10}, {9,11}, {10,12}, {10,13}, {5,1}, {4,8}, {4,2}}; encTableItem tbl[1024]; ushort16 vpred[2][2] = {{0,0},{0,0}}, hpred[2]; // We generate a 1024 entry table (to be addressed by reading 10 bits) by // consecutively filling in 2^(10-N) positions where N is the variable number of // bits of the encoding. So for example 4 is encoded with 3 bits so the first // 2^(10-3)=128 positions are set with 3,4 so that any time we read 000 we // know the next 4 bits are the difference. We read 10 bits because that is // the maximum number of bits used in the variable encoding (for the 12 and // 13 cases) uint32 n = 0; for (uint32 i=0; i < 14; i++) { for(int32 c = 0; c < (1024 >> tab[i][0]); c++) { tbl[n ].encLen = tab[i][0]; tbl[n++].diffLen = tab[i][1]; } } BitPumpMSB pump(mFile->getData(offset),mFile->getSize() - offset); for (uint32 y = 0; y < height; y++) { ushort16* img = (ushort16*)mRaw->getData(0, y); for (uint32 x = 0; x < width; x++) { int32 diff = samsungDiff(pump, tbl); if (x < 2) hpred[x] = vpred[y & 1][x] += diff; else hpred[x & 1] += diff; img[x] = hpred[x & 1]; if (img[x] >> bits) ThrowRDE("SRW: Error: decoded value out of bounds at %d:%d", x, y); } } } int32 SrwDecoder::samsungDiff (BitPumpMSB &pump, encTableItem *tbl) { // We read 10 bits to index into our table uint32 c = pump.peekBits(10); // Skip the bits that were used to encode this case pump.getBitsSafe(tbl[c].encLen); // Read the number of bits the table tells me int32 len = tbl[c].diffLen; int32 diff = pump.getBitsSafe(len); // If the first bit is 0 we need to turn this into a negative number if (len && (diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; return diff; } void SrwDecoder::checkSupportInternal(CameraMetaData *meta) { vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("Srw Support check: Model name found"); if (!data[0]->hasEntry(MAKE)) ThrowRDE("SRW Support: Make name not found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); this->checkCameraSupported(meta, make, model, ""); } void SrwDecoder::decodeMetaDataInternal(CameraMetaData *meta) { mRaw->cfa.setCFA(iPoint2D(2,2), CFA_RED, CFA_GREEN, CFA_GREEN2, CFA_BLUE); vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL); if (data.empty()) ThrowRDE("SRW Meta Decoder: Model name found"); string make = data[0]->getEntry(MAKE)->getString(); string model = data[0]->getEntry(MODEL)->getString(); data = mRootIFD->getIFDsWithTag(CFAPATTERN); if (!this->checkCameraSupported(meta, make, model, "") && !data.empty() && data[0]->hasEntry(CFAREPEATPATTERNDIM)) { const unsigned short* pDim = data[0]->getEntry(CFAREPEATPATTERNDIM)->getShortArray(); iPoint2D cfaSize(pDim[1], pDim[0]); if (cfaSize.x != 2 && cfaSize.y != 2) ThrowRDE("SRW Decoder: Unsupported CFA pattern size"); const uchar8* cPat = data[0]->getEntry(CFAPATTERN)->getData(); if (cfaSize.area() != data[0]->getEntry(CFAPATTERN)->count) ThrowRDE("SRW Decoder: CFA pattern dimension and pattern count does not match: %d."); for (int y = 0; y < cfaSize.y; y++) { for (int x = 0; x < cfaSize.x; x++) { uint32 c1 = cPat[x+y*cfaSize.x]; CFAColor c2; switch (c1) { case 0: c2 = CFA_RED; break; case 1: c2 = CFA_GREEN; break; case 2: c2 = CFA_BLUE; break; default: c2 = CFA_UNKNOWN; ThrowRDE("SRW Decoder: Unsupported CFA Color."); } mRaw->cfa.setColorAt(iPoint2D(x, y), c2); } } //printf("Camera CFA: %s\n", mRaw->cfa.asString().c_str()); } int iso = 0; if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS)) iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getInt(); setMetaData(meta, make, model, "", iso); } } // namespace RawSpeed <|endoftext|>
<commit_before>#include <QDebug> #include "httpparser.h" HTTPParser::HTTPParser(QObject *parent) : QObject(parent), isParsedHeader(false) { requestData.contentLength = -1; } void HTTPParser::parsePostData() { if(data.isEmpty()){ return; } QString postBody = data; QStringList pairs = postBody.split("&", QString::SkipEmptyParts); foreach(QString pair, pairs){ QStringList keyVal = pair.split("="); if(2 != keyVal.size()){ emit parseError("Invalid POST data!"); return; } requestData.postData.insert(QUrl::fromPercentEncoding(keyVal[0].toUtf8()), QUrl::fromPercentEncoding(keyVal[1].toUtf8())); } bytesToParse = 0; } void HTTPParser::parseRequestHeader() { QString request = data; QStringList fields = request.replace("\r", "").split("\n", QString::SkipEmptyParts); if(fields.isEmpty()){ emit parseError("Empty request!"); return; } QStringList statusLine = fields[0].split(" "); if(3 != statusLine.size()){ emit parseError("Invalid status line!"); return; } if(statusLine[1].isEmpty()){ emit parseError("Path cannot be empty!"); return; } QStringList protocol = statusLine[2].split("/"); bool ok; if(2 != protocol.size()){ emit parseError("Invalid protocol!"); return; } double ver = protocol[1].toDouble(&ok); if("HTTP" != protocol[0] || !ok || ver < 0.9 || ver > 1.1){ emit parseError("Invalid protocol!"); return; } requestData.url.setUrl(statusLine[1]); if(!requestData.url.isValid()){ emit parseError("Invalid URL!"); return; } requestData.method = statusLine[0]; requestData.protocol = protocol[0]; requestData.protocolVersion = ver; fields.removeAt(0); int spacePos; foreach(QString line, fields){ spacePos = line.indexOf(" "); requestData.fields.insert(line.left(spacePos-1), QStringList(line.right(line.size()-spacePos-1))); } if(requestData.fields.contains("Host")){ requestData.fields["Host"] = requestData.fields["Host"][0].split(":"); } if(requestData.fields.contains("Content-Length")){ requestData.contentLength = requestData.fields["Content-Length"][0] .toUInt(&ok); if(!ok){ emit parseError("Invalid Content-Length value!"); return; } requestData.fields.remove("Content-Length"); } bytesToParse = requestData.contentLength; isParsedHeader = true; } HTTPParser &HTTPParser::operator<<(const QString &chunk) { return *this << chunk.toUtf8(); } HTTPParser &HTTPParser::operator<<(const QByteArray &chunk) { data.append(chunk); parse(); return *this; } void HTTPParser::parse() { if(!isParsedHeader && (-1 != data.indexOf("\r\n\r\n") || -1 != data.indexOf("\n\n"))){ parseRequestHeader(); discardRequestHeader(); } if(isParsedHeader && "POST" == requestData.method){ if(bytesToParse < 0){ //a POST request with no Content-Length is bogus as per standard emit parseError("POST request with erroneous Content-Length field!"); return; } if(data.size() == bytesToParse){ parsePostData(); } } if(isParsedHeader && (0 == bytesToParse || "GET" == requestData.method)){ emit parsed(requestData); } } void HTTPParser::discardRequestHeader() { QString lf = "\n\n"; int crlfPos = data.indexOf("\r\n\r\n"); int lfPos = data.indexOf("\n\n"); if(-1 != crlfPos){ lf = "\r\n\r\n"; lfPos = crlfPos; } //discard the header from the request data = data.replace(lf, "").right(data.size()-lfPos-lf.size()); } <commit_msg>properly parsing the request method<commit_after>#include <QDebug> #include "httpparser.h" HTTPParser::HTTPParser(QObject *parent) : QObject(parent), isParsedHeader(false) { requestData.contentLength = -1; } void HTTPParser::parsePostData() { if(data.isEmpty()){ return; } QString postBody = data; QStringList pairs = postBody.split("&", QString::SkipEmptyParts); foreach(QString pair, pairs){ QStringList keyVal = pair.split("="); if(2 != keyVal.size()){ emit parseError("Invalid POST data!"); return; } requestData.postData.insert(QUrl::fromPercentEncoding(keyVal[0].toUtf8()), QUrl::fromPercentEncoding(keyVal[1].toUtf8())); } bytesToParse = 0; } void HTTPParser::parseRequestHeader() { QString request = data; QStringList fields = request.replace("\r", "").split("\n", QString::SkipEmptyParts); if(fields.isEmpty()){ emit parseError("Empty request!"); return; } QStringList statusLine = fields[0].split(" "); if(3 != statusLine.size()){ emit parseError("Invalid status line!"); return; } if("GET" != statusLine[0] && "POST" != statusLine[0] && "HEAD" != statusLine[0]){ emit parseError("Invalid method!"); return; } if(statusLine[1].isEmpty()){ emit parseError("Path cannot be empty!"); return; } QStringList protocol = statusLine[2].split("/"); bool ok; if(2 != protocol.size()){ emit parseError("Invalid protocol!"); return; } double ver = protocol[1].toDouble(&ok); if("HTTP" != protocol[0] || !ok || ver < 0.9 || ver > 1.1){ emit parseError("Invalid protocol!"); return; } requestData.url.setUrl(statusLine[1]); if(!requestData.url.isValid()){ emit parseError("Invalid URL!"); return; } requestData.method = statusLine[0]; requestData.protocol = protocol[0]; requestData.protocolVersion = ver; fields.removeAt(0); int spacePos; foreach(QString line, fields){ spacePos = line.indexOf(" "); requestData.fields.insert(line.left(spacePos-1), QStringList(line.right(line.size()-spacePos-1))); } if(requestData.fields.contains("Host")){ requestData.fields["Host"] = requestData.fields["Host"][0].split(":"); } if(requestData.fields.contains("Content-Length")){ requestData.contentLength = requestData.fields["Content-Length"][0] .toUInt(&ok); if(!ok){ emit parseError("Invalid Content-Length value!"); return; } requestData.fields.remove("Content-Length"); } bytesToParse = requestData.contentLength; isParsedHeader = true; } HTTPParser &HTTPParser::operator<<(const QString &chunk) { return *this << chunk.toUtf8(); } HTTPParser &HTTPParser::operator<<(const QByteArray &chunk) { data.append(chunk); parse(); return *this; } void HTTPParser::parse() { if(!isParsedHeader && (-1 != data.indexOf("\r\n\r\n") || -1 != data.indexOf("\n\n"))){ parseRequestHeader(); discardRequestHeader(); } if(isParsedHeader && "POST" == requestData.method){ if(bytesToParse < 0){ //a POST request with no Content-Length is bogus as per standard emit parseError("POST request with erroneous Content-Length field!"); return; } if(data.size() == bytesToParse){ parsePostData(); } } if(isParsedHeader && (0 == bytesToParse || "GET" == requestData.method || "HEAD" == requestData.method)){ emit parsed(requestData); } } void HTTPParser::discardRequestHeader() { QString lf = "\n\n"; int crlfPos = data.indexOf("\r\n\r\n"); int lfPos = data.indexOf("\n\n"); if(-1 != crlfPos){ lf = "\r\n\r\n"; lfPos = crlfPos; } //discard the header from the request data = data.replace(lf, "").right(data.size()-lfPos-lf.size()); } <|endoftext|>
<commit_before>#include <QtNetwork/QTcpSocket> #include "httpthread.h" HTTPThread::HTTPThread(int socketDescriptor, QString docRoot, QObject *parent) : QThread(parent), socketDescriptor(socketDescriptor), docRoot(docRoot) { } void HTTPThread::run() { QTcpSocket socket; if(!socket.setSocketDescriptor(socketDescriptor)){ qDebug() << "Setting the sd has failed: " << socket.errorString(); emit error(socket.error()); return; } QString request = read(&socket); qDebug() << request; parseRequest(request); //TODO: process the data //TODO: create the response //TODO: send the response socket.close(); } QString HTTPThread::read(QTcpSocket *socket){ QString request; do{ if(!socket->waitForReadyRead()){ qDebug() << "Error while waiting for client data: " << socket->errorString(); emit error(socket->error()); return request; } request.append(QString(socket->readAll())); }while(-1 == request.lastIndexOf("\n\n") && -1 == request.lastIndexOf("\r\n\r\n")); return request; } QHash<QString, QStringList> HTTPThread::parseRequest(QString request) { QHash<QString, QStringList> requestData; QStringList lines = request.replace("\r", "") .split("\n", QString::SkipEmptyParts); if(0 == lines.size()){ return requestData; } QStringList statusLine = lines[0].split(" "); if(3 != statusLine.size()){ return requestData; } QStringList protocol = statusLine[2].split("/"); bool ok; double ver = protocol[1].toDouble(&ok); if(2 != protocol.size() || "HTTP" != protocol[0] || !ok || ver < 0.9 || ver > 1.1){ return requestData; } statusLine.removeAt(2); requestData["status-line"] = statusLine + protocol; lines.removeAt(0); int spacePos; foreach(QString line, lines){ spacePos = line.indexOf(" "); requestData.insert(line.left(spacePos-1), QStringList(line.right(line.size()-spacePos-1))); } if(requestData.contains("Host")){ requestData["Host"] = requestData["Host"][0].split(":"); } //qDebug() << requestData; return requestData; } QString HTTPThread::processRequestData(QHash<QString, QStringList> requestData) { //TODO: add support for different Host values //TODO: parse the query_string QString response("HTTP/1.0 200 OK\r\n\r\ndummy text"); if(requestData.isEmpty()){ response = "HTTP/1.0 400 Bad request\r\n"; return response; } QString method = requestData["status-line"][0]; if("GET" == method){ qDebug() << "GET from " << docRoot << requestData["status-line"][1]; } else if("POST" == method){ qDebug() << "POST!"; } else{ response = "HTTP/1.0 501 Not Implemented\r\n"; qDebug() << "Unsupported HTTP method!"; } return response; } <commit_msg>writing the response to the client<commit_after>#include <QtNetwork/QTcpSocket> #include "httpthread.h" HTTPThread::HTTPThread(int socketDescriptor, QString docRoot, QObject *parent) : QThread(parent), socketDescriptor(socketDescriptor), docRoot(docRoot) { } void HTTPThread::run() { QTcpSocket socket; if(!socket.setSocketDescriptor(socketDescriptor)){ qDebug() << "Setting the sd has failed: " << socket.errorString(); emit error(socket.error()); return; } QString request = read(&socket); qDebug() << request; QByteArray response = processRequestData(parseRequest(request)).toUtf8(); socket.write(response, response.size()); if(!socket.waitForBytesWritten()){ qDebug() << "Could not write byts to socket: " << socket.errorString(); emit error(socket.error()); } socket.close(); } QString HTTPThread::read(QTcpSocket *socket){ QString request; do{ if(!socket->waitForReadyRead()){ qDebug() << "Error while waiting for client data: " << socket->errorString(); emit error(socket->error()); return request; } request.append(QString(socket->readAll())); }while(-1 == request.lastIndexOf("\n\n") && -1 == request.lastIndexOf("\r\n\r\n")); return request; } QHash<QString, QStringList> HTTPThread::parseRequest(QString request) { QHash<QString, QStringList> requestData; QStringList lines = request.replace("\r", "") .split("\n", QString::SkipEmptyParts); if(0 == lines.size()){ return requestData; } QStringList statusLine = lines[0].split(" "); if(3 != statusLine.size()){ return requestData; } QStringList protocol = statusLine[2].split("/"); bool ok; double ver = protocol[1].toDouble(&ok); if(2 != protocol.size() || "HTTP" != protocol[0] || !ok || ver < 0.9 || ver > 1.1){ return requestData; } statusLine.removeAt(2); requestData["status-line"] = statusLine + protocol; lines.removeAt(0); int spacePos; foreach(QString line, lines){ spacePos = line.indexOf(" "); requestData.insert(line.left(spacePos-1), QStringList(line.right(line.size()-spacePos-1))); } if(requestData.contains("Host")){ requestData["Host"] = requestData["Host"][0].split(":"); } //qDebug() << requestData; return requestData; } QString HTTPThread::processRequestData(QHash<QString, QStringList> requestData) { //TODO: add support for different Host values //TODO: parse the query_string QString response("HTTP/1.0 200 OK\r\n\r\ndummy text"); if(requestData.isEmpty()){ response = "HTTP/1.0 400 Bad request\r\n"; return response; } QString method = requestData["status-line"][0]; if("GET" == method){ qDebug() << "GET from " << docRoot << requestData["status-line"][1]; } else if("POST" == method){ qDebug() << "POST!"; } else{ response = "HTTP/1.0 501 Not Implemented\r\n"; qDebug() << "Unsupported HTTP method!"; } return response; } <|endoftext|>
<commit_before> #include "TeamMessage.h" #include <cstring> #include <cstdio> namespace rctc { // functions /** * */ bool binaryToMessage(const uint8_t* data, Message &msg) { // check header uint32_t header; memcpy(&header, &data[RCTC_HEADER], 4); header = ntohl(header); if (header != RCTC_HEADER_CONTENT) { printf("ERROR: Invalid header RCTC. Header is %c%c%c%c\n", data[0], data[1], data[2], data[3]); return false; } msg.teamID = data[RCTC_TEAMID]; msg.playerID = data[RCTC_PID]; msg.goalieID = data[RCTC_GOALIE_ID]; msg.mabID = data[RCTC_MAB_ID]; int16_t ballPosX; int16_t ballPosY; memcpy(&ballPosX, &data[RCTC_BALL_POS_X], 2); memcpy(&ballPosY, &data[RCTC_BALL_POS_Y], 2); msg.ballPosX = (int16_t) ntohs(ballPosX); msg.ballPosX = (int16_t) ntohs(ballPosY); return true; }//end binaryToMessage /** * */ void messageToBinary(const Message& msg, uint8_t *data) { // set header uint32_t header = htonl(RCTC_HEADER_CONTENT); memcpy(&data[RCTC_HEADER], &header, RCTC_HEADER_SIZE); // fill the message data[RCTC_TEAMID] = msg.teamID; data[RCTC_PID] = msg.playerID; data[RCTC_GOALIE_ID] = msg.goalieID; data[RCTC_MAB_ID] = msg.mabID; // ball information uint16_t ballPosX = htons( (uint16_t) msg.ballPosX); uint16_t ballPosY = htons( (uint16_t) msg.ballPosY); memcpy(&data[RCTC_BALL_POS_X], &ballPosX, 2); memcpy(&data[RCTC_BALL_POS_Y], &ballPosY, 2); }//end messageToBinary void print(const Message& msg) { printf("teamID: \t%d\n", msg.teamID); printf("playerID:\t%d\n", msg.playerID); printf("goalieID:\t%d\n", msg.goalieID); printf("mabID: \t%d\n", msg.mabID); printf("ballPosX:\t%d\n", msg.ballPosX); printf("ballPosY:\t%d\n", msg.ballPosY); } std::ostream& operator<< (std::ostream& stream, const rctc::Message& msg) { stream << "teamID: \t" << msg.teamID << std::endl; stream << "playerID:\t" << msg.playerID << std::endl; stream << "goalieID:\t" << msg.goalieID << std::endl; stream << "mabID: \t" << msg.mabID << std::endl; stream << "ballPosX:\t" << msg.ballPosX << std::endl; stream << "ballPosY:\t" << msg.ballPosY << std::endl; return stream; }//end print }//end namespace rctc <commit_msg>cleaned RCTC<commit_after> #include "TeamMessage.h" #include <cstring> #include <cstdio> namespace rctc { // functions /** * */ bool binaryToMessage(const uint8_t* data, Message &msg) { // check header uint32_t header; memcpy(&header, &data[RCTC_HEADER], 4); header = ntohl(header); if (header != RCTC_HEADER_CONTENT) { printf("ERROR: Invalid header RCTC. Header is %c%c%c%c\n", data[0], data[1], data[2], data[3]); return false; } msg.teamID = data[RCTC_TEAMID]; msg.playerID = data[RCTC_PID]; msg.goalieID = data[RCTC_GOALIE_ID]; msg.mabID = data[RCTC_MAB_ID]; uint16_t ballPosX; uint16_t ballPosY; memcpy(&ballPosX, &data[RCTC_BALL_POS_X], 2); memcpy(&ballPosY, &data[RCTC_BALL_POS_Y], 2); msg.ballPosX = (int16_t) ntohs(ballPosX); msg.ballPosX = (int16_t) ntohs(ballPosY); return true; }//end binaryToMessage /** * */ void messageToBinary(const Message& msg, uint8_t *data) { // set header uint32_t header = htonl(RCTC_HEADER_CONTENT); memcpy(&data[RCTC_HEADER], &header, RCTC_HEADER_SIZE); // fill the message data[RCTC_TEAMID] = msg.teamID; data[RCTC_PID] = msg.playerID; data[RCTC_GOALIE_ID] = msg.goalieID; data[RCTC_MAB_ID] = msg.mabID; // ball information uint16_t ballPosX = htons( (uint16_t) msg.ballPosX); uint16_t ballPosY = htons( (uint16_t) msg.ballPosY); memcpy(&data[RCTC_BALL_POS_X], &ballPosX, 2); memcpy(&data[RCTC_BALL_POS_Y], &ballPosY, 2); }//end messageToBinary void print(const Message& msg) { printf("teamID: \t%d\n", msg.teamID); printf("playerID:\t%d\n", msg.playerID); printf("goalieID:\t%d\n", msg.goalieID); printf("mabID: \t%d\n", msg.mabID); printf("ballPosX:\t%d\n", msg.ballPosX); printf("ballPosY:\t%d\n", msg.ballPosY); } std::ostream& operator<< (std::ostream& stream, const rctc::Message& msg) { stream << "teamID: \t" << msg.teamID << std::endl; stream << "playerID:\t" << msg.playerID << std::endl; stream << "goalieID:\t" << msg.goalieID << std::endl; stream << "mabID: \t" << msg.mabID << std::endl; stream << "ballPosX:\t" << msg.ballPosX << std::endl; stream << "ballPosY:\t" << msg.ballPosY << std::endl; return stream; }//end print }//end namespace rctc <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <iterator> #include <memory> #include <vector> class IObject { public: double m_value = 0; }; class IListOfObjects { public: class proxy { public: explicit proxy(IObject* pObject) : m_pObject(pObject) {} void operator = (const proxy&) = delete; IObject* operator->() { return m_pObject; } private: IObject* m_pObject; }; class iterator { public: typedef size_t difference_type; typedef size_t size_type; typedef IObject value_type; typedef IObject* pointer; typedef IObject& reference; bool operator==(const iterator& that) const {return m_position==that.m_position;} bool operator!=(const iterator& that) const {return m_position!=that.m_position;} const iterator& operator++() { ++m_position; return *this; } iterator(const iterator& it) : m_list(it.m_list), m_position(it.m_position) {} iterator(IListOfObjects& list, size_t position) : m_list(list), m_position(position) {} proxy operator*() { return proxy(m_list.get(m_position));} private: IListOfObjects& m_list; size_t m_position; }; iterator begin() { return iterator(*this, 0); } iterator end() { return iterator(*this, this->count()); } virtual size_t count() const = 0; virtual const IObject* get(size_t i) const = 0; virtual IObject* get(size_t i) = 0; }; class ListOfObjectsImpl : public IListOfObjects { public: ListOfObjectsImpl(size_t n) : m_ptrObjects(n) { std::generate(m_ptrObjects.begin(), m_ptrObjects.end(), []() { return std::unique_ptr<IObject>(new IObject()); }); } virtual size_t count() const { return m_ptrObjects.size(); } virtual const IObject* get(size_t i) const { return m_ptrObjects[i].get(); } virtual IObject* get(size_t i) { return m_ptrObjects[i].get(); } private: std::vector<std::unique_ptr<IObject>> m_ptrObjects; }; int main(int argc, char* argv[]) { ListOfObjectsImpl myList(100); std::for_each(myList.begin(), myList.end(), [](IListOfObjects::proxy pObject) { pObject->m_value = 3.14159; }); } <commit_msg>update typedefs for iterator using proxy<commit_after>#include <iostream> #include <algorithm> #include <iterator> #include <memory> #include <vector> class IObject { public: double m_value = 0; }; class IListOfObjects { public: class proxy { public: explicit proxy(IObject* pObject) : m_pObject(pObject) {} void operator = (const proxy&) = delete; IObject* operator->() { return m_pObject; } private: IObject* m_pObject; }; class iterator { public: typedef size_t difference_type; typedef size_t size_type; typedef proxy value_type; typedef proxy* pointer; typedef proxy& reference; bool operator==(const iterator& that) const {return m_position==that.m_position;} bool operator!=(const iterator& that) const {return m_position!=that.m_position;} const iterator& operator++() { ++m_position; return *this; } iterator(const iterator& it) : m_list(it.m_list), m_position(it.m_position) {} iterator(IListOfObjects& list, size_t position) : m_list(list), m_position(position) {} proxy operator*() { return proxy(m_list.get(m_position));} private: IListOfObjects& m_list; size_t m_position; }; iterator begin() { return iterator(*this, 0); } iterator end() { return iterator(*this, this->count()); } virtual size_t count() const = 0; virtual const IObject* get(size_t i) const = 0; virtual IObject* get(size_t i) = 0; }; class ListOfObjectsImpl : public IListOfObjects { public: ListOfObjectsImpl(size_t n) : m_ptrObjects(n) { std::generate(m_ptrObjects.begin(), m_ptrObjects.end(), []() { return std::unique_ptr<IObject>(new IObject()); }); } virtual size_t count() const { return m_ptrObjects.size(); } virtual const IObject* get(size_t i) const { return m_ptrObjects[i].get(); } virtual IObject* get(size_t i) { return m_ptrObjects[i].get(); } private: std::vector<std::unique_ptr<IObject>> m_ptrObjects; }; int main(int argc, char* argv[]) { ListOfObjectsImpl myList(100); std::for_each(myList.begin(), myList.end(), [](IListOfObjects::proxy pObject) { pObject->m_value = 3.14159; }); } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkGradientDescentOptimizerv4_hxx #define itkGradientDescentOptimizerv4_hxx #include "itkGradientDescentOptimizerv4.h" namespace itk { /** * Default constructor */ template<typename TInternalComputationValueType> GradientDescentOptimizerv4Template<TInternalComputationValueType> ::GradientDescentOptimizerv4Template() { this->m_LearningRate = NumericTraits<TInternalComputationValueType>::OneValue(); this->m_MinimumConvergenceValue = 1e-8; this->m_ReturnBestParametersAndValue = false; this->m_PreviousGradient.Fill( NumericTraits<TInternalComputationValueType>::ZeroValue() ); } /** * Destructor */ template<typename TInternalComputationValueType> GradientDescentOptimizerv4Template<TInternalComputationValueType> ::~GradientDescentOptimizerv4Template() {} /** *PrintSelf */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Learning rate:" << this->m_LearningRate << std::endl; os << indent << "MaximumStepSizeInPhysicalUnits: " << this->m_MaximumStepSizeInPhysicalUnits << std::endl; os << indent << "DoEstimateLearningRateAtEachIteration: " << this->m_DoEstimateLearningRateAtEachIteration << std::endl; os << indent << "DoEstimateLearningRateOnce: " << this->m_DoEstimateLearningRateOnce << std::endl; } /** * Start and run the optimization */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::StartOptimization( bool doOnlyInitialization ) { /* Must call the superclass version for basic validation and setup */ Superclass::StartOptimization( doOnlyInitialization ); if( this->m_ReturnBestParametersAndValue ) { this->m_BestParameters = this->GetCurrentPosition( ); this->m_CurrentBestValue = NumericTraits< MeasureType >::max(); } this->m_CurrentIteration = 0; if( ! doOnlyInitialization ) { this->ResumeOptimization(); } } /** * StopOptimization */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::StopOptimization(void) { if( this->m_ReturnBestParametersAndValue ) { this->m_Metric->SetParameters( this->m_BestParameters ); this->m_CurrentMetricValue = this->m_CurrentBestValue; } Superclass::StopOptimization(); } /** * Resume optimization. */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::ResumeOptimization() { this->m_StopConditionDescription.str(""); this->m_StopConditionDescription << this->GetNameOfClass() << ": "; this->InvokeEvent( StartEvent() ); this->m_Stop = false; while( ! this->m_Stop ) { // Do not run the loop if the maximum number of iterations is reached or its value is zero. if ( this->m_CurrentIteration >= this->m_NumberOfIterations ) { this->m_StopConditionDescription << "Maximum number of iterations (" << this->m_NumberOfIterations << ") exceeded."; this->m_StopCondition = Superclass::MAXIMUM_NUMBER_OF_ITERATIONS; this->StopOptimization(); break; } // Save previous value with shallow swap that will be used by child optimizer. swap( this->m_PreviousGradient, this->m_Gradient ); /* Compute metric value/derivative. */ try { /* m_Gradient will be sized as needed by metric. If it's already * proper size, no new allocation is done. */ this->m_Metric->GetValueAndDerivative( this->m_CurrentMetricValue, this->m_Gradient ); } catch ( ExceptionObject & err ) { this->m_StopCondition = Superclass::COSTFUNCTION_ERROR; this->m_StopConditionDescription << "Metric error during optimization"; this->StopOptimization(); // Pass exception to caller throw err; } /* Check if optimization has been stopped externally. * (Presumably this could happen from a multi-threaded client app?) */ if ( this->m_Stop ) { this->m_StopConditionDescription << "StopOptimization() called"; break; } /* Check the convergence by WindowConvergenceMonitoringFunction. */ if ( this->m_UseConvergenceMonitoring ) { this->m_ConvergenceMonitoring->AddEnergyValue( this->m_CurrentMetricValue ); try { this->m_ConvergenceValue = this->m_ConvergenceMonitoring->GetConvergenceValue(); if (this->m_ConvergenceValue <= this->m_MinimumConvergenceValue) { this->m_StopConditionDescription << "Convergence checker passed at iteration " << this->m_CurrentIteration << "."; this->m_StopCondition = Superclass::CONVERGENCE_CHECKER_PASSED; this->StopOptimization(); break; } } catch(std::exception & e) { std::cerr << "GetConvergenceValue() failed with exception: " << e.what() << std::endl; } } /* Advance one step along the gradient. * This will modify the gradient and update the transform. */ this->AdvanceOneStep(); /* Store best value and position */ if ( this->m_ReturnBestParametersAndValue && this->m_CurrentMetricValue < this->m_CurrentBestValue ) { this->m_CurrentBestValue = this->m_CurrentMetricValue; this->m_BestParameters = this->GetCurrentPosition( ); } /* Update and check iteration count */ this->m_CurrentIteration++; } //while (!m_Stop) } /** * Advance one Step following the gradient direction */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::AdvanceOneStep() { itkDebugMacro("AdvanceOneStep"); /* Begin threaded gradient modification. * Scale by gradient scales, then estimate the learning * rate if options are set to (using the scaled gradient), * then modify by learning rate. The m_Gradient variable * is modified in-place. */ this->ModifyGradientByScales(); this->EstimateLearningRate(); this->ModifyGradientByLearningRate(); try { /* Pass graident to transform and let it do its own updating */ this->m_Metric->UpdateTransformParameters( this->m_Gradient ); } catch ( ExceptionObject & err ) { this->m_StopCondition = Superclass::UPDATE_PARAMETERS_ERROR; this->m_StopConditionDescription << "UpdateTransformParameters error"; this->StopOptimization(); // Pass exception to caller throw err; } this->InvokeEvent( IterationEvent() ); } /** * Modify the gradient by scales and weights over a given index range. */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::ModifyGradientByScalesOverSubRange( const IndexRangeType& subrange ) { const ScalesType& scales = this->GetScales(); const ScalesType& weights = this->GetWeights(); ScalesType factor( scales.Size() ); if( this->GetWeightsAreIdentity() ) { for( SizeValueType i=0; i < factor.Size(); i++ ) { factor[i] = NumericTraits<typename ScalesType::ValueType>::OneValue() / scales[i]; } } else { for( SizeValueType i=0; i < factor.Size(); i++ ) { factor[i] = weights[i] / scales[i]; } } /* Loop over the range. It is inclusive. */ for ( IndexValueType j = subrange[0]; j <= subrange[1]; j++ ) { // scales is checked during StartOptmization for values <= // machine epsilon. // Take the modulo of the index to handle gradients from transforms // with local support. The gradient array stores the gradient of local // parameters at each local index with linear packing. IndexValueType index = j % scales.Size(); this->m_Gradient[j] = this->m_Gradient[j] * factor[index]; } } /** * Modify the gradient by learning rate over a given index range. */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::ModifyGradientByLearningRateOverSubRange( const IndexRangeType& subrange ) { /* Loop over the range. It is inclusive. */ for ( IndexValueType j = subrange[0]; j <= subrange[1]; j++ ) { this->m_Gradient[j] = this->m_Gradient[j] * this->m_LearningRate; } } /** * Estimate the learning rate. */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::EstimateLearningRate() { if ( this->m_ScalesEstimator.IsNull() ) { return; } if ( this->m_DoEstimateLearningRateAtEachIteration || (this->m_DoEstimateLearningRateOnce && this->m_CurrentIteration == 0) ) { TInternalComputationValueType stepScale = this->m_ScalesEstimator->EstimateStepScale(this->m_Gradient); if (stepScale <= NumericTraits<TInternalComputationValueType>::epsilon()) { this->m_LearningRate = NumericTraits<TInternalComputationValueType>::OneValue(); } else { this->m_LearningRate = this->m_MaximumStepSizeInPhysicalUnits / stepScale; } } } }//namespace itk #endif <commit_msg>BUG: Initialize ConvergenceValue in constructor<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkGradientDescentOptimizerv4_hxx #define itkGradientDescentOptimizerv4_hxx #include "itkGradientDescentOptimizerv4.h" namespace itk { /** * Default constructor */ template<typename TInternalComputationValueType> GradientDescentOptimizerv4Template<TInternalComputationValueType> ::GradientDescentOptimizerv4Template() { this->m_LearningRate = NumericTraits<TInternalComputationValueType>::OneValue(); this->m_MinimumConvergenceValue = 1e-8; this->m_ConvergenceValue = NumericTraits<TInternalComputationValueType>::max(); this->m_ReturnBestParametersAndValue = false; this->m_PreviousGradient.Fill( NumericTraits<TInternalComputationValueType>::ZeroValue() ); } /** * Destructor */ template<typename TInternalComputationValueType> GradientDescentOptimizerv4Template<TInternalComputationValueType> ::~GradientDescentOptimizerv4Template() {} /** *PrintSelf */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Learning rate:" << this->m_LearningRate << std::endl; os << indent << "MaximumStepSizeInPhysicalUnits: " << this->m_MaximumStepSizeInPhysicalUnits << std::endl; os << indent << "DoEstimateLearningRateAtEachIteration: " << this->m_DoEstimateLearningRateAtEachIteration << std::endl; os << indent << "DoEstimateLearningRateOnce: " << this->m_DoEstimateLearningRateOnce << std::endl; } /** * Start and run the optimization */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::StartOptimization( bool doOnlyInitialization ) { /* Must call the superclass version for basic validation and setup */ Superclass::StartOptimization( doOnlyInitialization ); if( this->m_ReturnBestParametersAndValue ) { this->m_BestParameters = this->GetCurrentPosition( ); this->m_CurrentBestValue = NumericTraits< MeasureType >::max(); } this->m_CurrentIteration = 0; this->m_ConvergenceValue = NumericTraits<TInternalComputationValueType>::max(); if( ! doOnlyInitialization ) { this->ResumeOptimization(); } } /** * StopOptimization */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::StopOptimization(void) { if( this->m_ReturnBestParametersAndValue ) { this->m_Metric->SetParameters( this->m_BestParameters ); this->m_CurrentMetricValue = this->m_CurrentBestValue; } Superclass::StopOptimization(); } /** * Resume optimization. */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::ResumeOptimization() { this->m_StopConditionDescription.str(""); this->m_StopConditionDescription << this->GetNameOfClass() << ": "; this->InvokeEvent( StartEvent() ); this->m_Stop = false; while( ! this->m_Stop ) { // Do not run the loop if the maximum number of iterations is reached or its value is zero. if ( this->m_CurrentIteration >= this->m_NumberOfIterations ) { this->m_StopConditionDescription << "Maximum number of iterations (" << this->m_NumberOfIterations << ") exceeded."; this->m_StopCondition = Superclass::MAXIMUM_NUMBER_OF_ITERATIONS; this->StopOptimization(); break; } // Save previous value with shallow swap that will be used by child optimizer. swap( this->m_PreviousGradient, this->m_Gradient ); /* Compute metric value/derivative. */ try { /* m_Gradient will be sized as needed by metric. If it's already * proper size, no new allocation is done. */ this->m_Metric->GetValueAndDerivative( this->m_CurrentMetricValue, this->m_Gradient ); } catch ( ExceptionObject & err ) { this->m_StopCondition = Superclass::COSTFUNCTION_ERROR; this->m_StopConditionDescription << "Metric error during optimization"; this->StopOptimization(); // Pass exception to caller throw err; } /* Check if optimization has been stopped externally. * (Presumably this could happen from a multi-threaded client app?) */ if ( this->m_Stop ) { this->m_StopConditionDescription << "StopOptimization() called"; break; } /* Check the convergence by WindowConvergenceMonitoringFunction. */ if ( this->m_UseConvergenceMonitoring ) { this->m_ConvergenceMonitoring->AddEnergyValue( this->m_CurrentMetricValue ); try { this->m_ConvergenceValue = this->m_ConvergenceMonitoring->GetConvergenceValue(); if (this->m_ConvergenceValue <= this->m_MinimumConvergenceValue) { this->m_StopConditionDescription << "Convergence checker passed at iteration " << this->m_CurrentIteration << "."; this->m_StopCondition = Superclass::CONVERGENCE_CHECKER_PASSED; this->StopOptimization(); break; } } catch(std::exception & e) { std::cerr << "GetConvergenceValue() failed with exception: " << e.what() << std::endl; } } /* Advance one step along the gradient. * This will modify the gradient and update the transform. */ this->AdvanceOneStep(); /* Store best value and position */ if ( this->m_ReturnBestParametersAndValue && this->m_CurrentMetricValue < this->m_CurrentBestValue ) { this->m_CurrentBestValue = this->m_CurrentMetricValue; this->m_BestParameters = this->GetCurrentPosition( ); } /* Update and check iteration count */ this->m_CurrentIteration++; } //while (!m_Stop) } /** * Advance one Step following the gradient direction */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::AdvanceOneStep() { itkDebugMacro("AdvanceOneStep"); /* Begin threaded gradient modification. * Scale by gradient scales, then estimate the learning * rate if options are set to (using the scaled gradient), * then modify by learning rate. The m_Gradient variable * is modified in-place. */ this->ModifyGradientByScales(); this->EstimateLearningRate(); this->ModifyGradientByLearningRate(); try { /* Pass graident to transform and let it do its own updating */ this->m_Metric->UpdateTransformParameters( this->m_Gradient ); } catch ( ExceptionObject & err ) { this->m_StopCondition = Superclass::UPDATE_PARAMETERS_ERROR; this->m_StopConditionDescription << "UpdateTransformParameters error"; this->StopOptimization(); // Pass exception to caller throw err; } this->InvokeEvent( IterationEvent() ); } /** * Modify the gradient by scales and weights over a given index range. */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::ModifyGradientByScalesOverSubRange( const IndexRangeType& subrange ) { const ScalesType& scales = this->GetScales(); const ScalesType& weights = this->GetWeights(); ScalesType factor( scales.Size() ); if( this->GetWeightsAreIdentity() ) { for( SizeValueType i=0; i < factor.Size(); i++ ) { factor[i] = NumericTraits<typename ScalesType::ValueType>::OneValue() / scales[i]; } } else { for( SizeValueType i=0; i < factor.Size(); i++ ) { factor[i] = weights[i] / scales[i]; } } /* Loop over the range. It is inclusive. */ for ( IndexValueType j = subrange[0]; j <= subrange[1]; j++ ) { // scales is checked during StartOptmization for values <= // machine epsilon. // Take the modulo of the index to handle gradients from transforms // with local support. The gradient array stores the gradient of local // parameters at each local index with linear packing. IndexValueType index = j % scales.Size(); this->m_Gradient[j] = this->m_Gradient[j] * factor[index]; } } /** * Modify the gradient by learning rate over a given index range. */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::ModifyGradientByLearningRateOverSubRange( const IndexRangeType& subrange ) { /* Loop over the range. It is inclusive. */ for ( IndexValueType j = subrange[0]; j <= subrange[1]; j++ ) { this->m_Gradient[j] = this->m_Gradient[j] * this->m_LearningRate; } } /** * Estimate the learning rate. */ template<typename TInternalComputationValueType> void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::EstimateLearningRate() { if ( this->m_ScalesEstimator.IsNull() ) { return; } if ( this->m_DoEstimateLearningRateAtEachIteration || (this->m_DoEstimateLearningRateOnce && this->m_CurrentIteration == 0) ) { TInternalComputationValueType stepScale = this->m_ScalesEstimator->EstimateStepScale(this->m_Gradient); if (stepScale <= NumericTraits<TInternalComputationValueType>::epsilon()) { this->m_LearningRate = NumericTraits<TInternalComputationValueType>::OneValue(); } else { this->m_LearningRate = this->m_MaximumStepSizeInPhysicalUnits / stepScale; } } } }//namespace itk #endif <|endoftext|>
<commit_before>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkConcentrationCurveGenerator.h" #include "mitkConvertToConcentrationTurboFlashFunctor.h" #include "mitkConvertT2ConcentrationFunctor.h" #include "mitkConvertToConcentrationViaT1Functor.h" #include "mitkImageTimeSelector.h" #include "mitkImageCast.h" #include "mitkITKImageImport.h" #include "mitkModelBase.h" #include "mitkExtractTimeGrid.h" #include "mitkArbitraryTimeGeometry.h" #include "itkNaryAddImageFilter.h" #include "mitkImageAccessByItk.h" #include "itkImageIOBase.h" #include "itkBinaryFunctorImageFilter.h" #include "itkTernaryFunctorImageFilter.h" #include <itkExtractImageFilter.h> #include "itkMeanProjectionImageFilter.h" mitk::ConcentrationCurveGenerator::ConcentrationCurveGenerator() : m_isT2weightedImage(false), m_isTurboFlashSequence(false), m_AbsoluteSignalEnhancement(false), m_RelativeSignalEnhancement(0.0), m_UsingT1Map(false), m_Factor(0.0), m_RecoveryTime(0.0), m_RelaxationTime(0.0), m_Relaxivity(0.0), m_FlipAngle(0.0), m_T2Factor(0.0), m_T2EchoTime(0.0) { } mitk::ConcentrationCurveGenerator::~ConcentrationCurveGenerator() { } mitk::Image::Pointer mitk::ConcentrationCurveGenerator::GetConvertedImage() { if(this->m_DynamicImage.IsNull()) { itkExceptionMacro( << "Dynamic Image not set!"); } else { Convert(); } return m_ConvertedImage; } void mitk::ConcentrationCurveGenerator::Convert() { mitk::Image::Pointer tempImage = mitk::Image::New(); mitk::PixelType pixeltype = mitk::MakeScalarPixelType<double>(); tempImage->Initialize(pixeltype,*this->m_DynamicImage->GetTimeGeometry()); mitk::TimeGeometry::Pointer timeGeometry = (this->m_DynamicImage->GetTimeGeometry())->Clone(); tempImage->SetTimeGeometry(timeGeometry); PrepareBaselineImage(); mitk::ImageTimeSelector::Pointer imageTimeSelector = mitk::ImageTimeSelector::New(); imageTimeSelector->SetInput(this->m_DynamicImage); for(unsigned int i = 0; i< this->m_DynamicImage->GetTimeSteps(); ++i) { imageTimeSelector->SetTimeNr(i); imageTimeSelector->UpdateLargestPossibleRegion(); mitk::Image::Pointer mitkInputImage = imageTimeSelector->GetOutput(); mitk::Image::Pointer outputImage = mitk::Image::New(); outputImage = ConvertSignalToConcentrationCurve(mitkInputImage,this->m_BaselineImage); mitk::ImageReadAccessor accessor(outputImage); tempImage->SetVolume(accessor.GetData(), i); } this->m_ConvertedImage = tempImage; } void mitk::ConcentrationCurveGenerator::PrepareBaselineImage() { mitk::ImageTimeSelector::Pointer imageTimeSelector = mitk::ImageTimeSelector::New(); imageTimeSelector->SetInput(this->m_DynamicImage); imageTimeSelector->SetTimeNr(0); imageTimeSelector->UpdateLargestPossibleRegion(); mitk::Image::Pointer baselineImage; baselineImage = imageTimeSelector->GetOutput(); if (m_BaselineStartTimeStep == m_BaselineEndTimeStep) { this->m_BaselineImage = imageTimeSelector->GetOutput(); } else { try { AccessFixedDimensionByItk(this->m_DynamicImage, mitk::ConcentrationCurveGenerator::CalculateAverageBaselineImage, 4); } catch (itk::ExceptionObject & err) { std::cerr << "ExceptionObject in ConcentrationCurveGenerator::CalculateAverageBaselineImage caught!" << std::endl; std::cerr << err << std::endl; } } } template<class TPixel> void mitk::ConcentrationCurveGenerator::CalculateAverageBaselineImage(const itk::Image<TPixel, 4> *itkBaselineImage) { if (itkBaselineImage == NULL) { mitkThrow() << "Error in ConcentrationCurveGenerator::CalculateAverageBaselineImage. Input image is NULL."; } if (m_BaselineStartTimeStep > m_BaselineEndTimeStep) { mitkThrow() << "Error in ConcentrationCurveGenerator::CalculateAverageBaselineImage. End time point is before start time point."; } typedef itk::Image<TPixel, 4> TPixel4DImageType; typedef itk::Image<TPixel, 3> TPixel3DImageType; typedef itk::Image<double, 3> Double3DImageType; typedef itk::Image<double, 4> Double4DImageType; typedef itk::ExtractImageFilter<TPixel4DImageType, TPixel4DImageType> ExtractImageFilterType; typedef itk::ExtractImageFilter<Double4DImageType, Double3DImageType> Extract3DImageFilterType; typedef itk::MeanProjectionImageFilter<TPixel4DImageType,Double4DImageType> MeanProjectionImageFilterType; typename MeanProjectionImageFilterType::Pointer MeanProjectionImageFilter = MeanProjectionImageFilterType::New(); typename Extract3DImageFilterType::Pointer Extract3DImageFilter = Extract3DImageFilterType::New(); typename TPixel4DImageType::RegionType region_input = itkBaselineImage->GetLargestPossibleRegion(); if (m_BaselineEndTimeStep > region_input.GetSize()[3]) { mitkThrow() << "Error in ConcentrationCurveGenerator::CalculateAverageBaselineImage. End time point is larger than total number of time points."; } ExtractImageFilterType::Pointer ExtractFilter = ExtractImageFilterType::New(); typename TPixel4DImageType::Pointer baselineTimeFrameImage = TPixel4DImageType::New(); typename TPixel4DImageType::RegionType extractionRegion; typename TPixel4DImageType::SizeType size_input_aux = region_input.GetSize(); size_input_aux[3] = m_BaselineEndTimeStep - m_BaselineStartTimeStep + 1; typename TPixel4DImageType::IndexType start_input_aux = region_input.GetIndex(); start_input_aux[3] = m_BaselineStartTimeStep; extractionRegion.SetSize(size_input_aux); extractionRegion.SetIndex(start_input_aux); ExtractFilter->SetExtractionRegion(extractionRegion); ExtractFilter->SetInput(itkBaselineImage); ExtractFilter->SetDirectionCollapseToSubmatrix(); try { ExtractFilter->Update(); } catch (itk::ExceptionObject & err) { std::cerr << "ExceptionObject caught!" << std::endl; std::cerr << err << std::endl; } baselineTimeFrameImage = ExtractFilter->GetOutput(); MeanProjectionImageFilter->SetProjectionDimension(3); MeanProjectionImageFilter->SetInput(baselineTimeFrameImage); try { MeanProjectionImageFilter->Update(); } catch (itk::ExceptionObject & err) { std::cerr << "ExceptionObject caught!" << std::endl; std::cerr << err << std::endl; } Extract3DImageFilter->SetInput(MeanProjectionImageFilter->GetOutput()); size_input_aux[3] = 0; start_input_aux[3] = 0; extractionRegion.SetSize(size_input_aux); extractionRegion.SetIndex(start_input_aux); Extract3DImageFilter->SetExtractionRegion(extractionRegion); Extract3DImageFilter->SetDirectionCollapseToSubmatrix(); try { Extract3DImageFilter->Update(); } catch (itk::ExceptionObject & err) { std::cerr << "ExceptionObject caught!" << std::endl; std::cerr << err << std::endl; } Image::Pointer mitkBaselineImage = Image::New(); CastToMitkImage(Extract3DImageFilter->GetOutput(), mitkBaselineImage); this->m_BaselineImage = mitkBaselineImage; } mitk::Image::Pointer mitk::ConcentrationCurveGenerator::ConvertSignalToConcentrationCurve(const mitk::Image* inputImage,const mitk::Image* baselineImage) { mitk::PixelType m_PixelType = inputImage->GetPixelType(); AccessTwoImagesFixedDimensionByItk(inputImage, baselineImage, mitk::ConcentrationCurveGenerator::convertToConcentration, 3); return m_ConvertSignalToConcentrationCurve_OutputImage; } template<class TPixel_input, class TPixel_baseline> mitk::Image::Pointer mitk::ConcentrationCurveGenerator::convertToConcentration(const itk::Image<TPixel_input, 3> *itkInputImage, const itk::Image<TPixel_baseline, 3> *itkBaselineImage) { typedef itk::Image<TPixel_input, 3> InputImageType; typedef itk::Image<TPixel_baseline, 3> BaselineImageType; if (this->m_isT2weightedImage) { typedef mitk::ConvertT2ConcentrationFunctor <TPixel_input, TPixel_baseline, double> ConversionFunctorT2Type; typedef itk::BinaryFunctorImageFilter<InputImageType, BaselineImageType, ConvertedImageType, ConversionFunctorT2Type> FilterT2Type; ConversionFunctorT2Type ConversionT2Functor; ConversionT2Functor.initialize(this->m_T2Factor, this->m_T2EchoTime); typename FilterT2Type::Pointer ConversionT2Filter = FilterT2Type::New(); ConversionT2Filter->SetFunctor(ConversionT2Functor); ConversionT2Filter->SetInput1(itkInputImage); ConversionT2Filter->SetInput2(itkBaselineImage); ConversionT2Filter->Update(); m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionT2Filter->GetOutput())->Clone(); } else { if(this->m_isTurboFlashSequence) { typedef mitk::ConvertToConcentrationTurboFlashFunctor <TPixel_input, TPixel_baseline, double> ConversionFunctorTurboFlashType; typedef itk::BinaryFunctorImageFilter<InputImageType, BaselineImageType, ConvertedImageType, ConversionFunctorTurboFlashType> FilterTurboFlashType; ConversionFunctorTurboFlashType ConversionTurboFlashFunctor; ConversionTurboFlashFunctor.initialize(this->m_RelaxationTime, this->m_Relaxivity, this->m_RecoveryTime); typename FilterTurboFlashType::Pointer ConversionTurboFlashFilter = FilterTurboFlashType::New(); ConversionTurboFlashFilter->SetFunctor(ConversionTurboFlashFunctor); ConversionTurboFlashFilter->SetInput1(itkInputImage); ConversionTurboFlashFilter->SetInput2(itkBaselineImage); ConversionTurboFlashFilter->Update(); m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionTurboFlashFilter->GetOutput())->Clone(); } else if(this->m_UsingT1Map) { typename ConvertedImageType::Pointer itkT10Image = ConvertedImageType::New(); mitk::CastToItkImage(m_T10Image, itkT10Image); typedef mitk::ConvertToConcentrationViaT1CalcFunctor <TPixel_input, TPixel_baseline, double, double> ConvertToConcentrationViaT1CalcFunctorType; typedef itk::TernaryFunctorImageFilter<InputImageType, BaselineImageType, ConvertedImageType, ConvertedImageType, ConvertToConcentrationViaT1CalcFunctorType> FilterT1MapType; ConvertToConcentrationViaT1CalcFunctorType ConversionT1MapFunctor; ConversionT1MapFunctor.initialize(this->m_Relaxivity, this->m_RecoveryTime, this->m_FlipAngle); typename FilterT1MapType::Pointer ConversionT1MapFilter = FilterT1MapType::New(); ConversionT1MapFilter->SetFunctor(ConversionT1MapFunctor); ConversionT1MapFilter->SetInput1(itkInputImage); ConversionT1MapFilter->SetInput2(itkBaselineImage); ConversionT1MapFilter->SetInput3(itkT10Image); ConversionT1MapFilter->Update(); m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionT1MapFilter->GetOutput())->Clone(); } else if(this->m_AbsoluteSignalEnhancement) { typedef mitk::ConvertToConcentrationAbsoluteFunctor <TPixel_input, TPixel_baseline, double> ConversionFunctorAbsoluteType; typedef itk::BinaryFunctorImageFilter<InputImageType, BaselineImageType, ConvertedImageType, ConversionFunctorAbsoluteType> FilterAbsoluteType; ConversionFunctorAbsoluteType ConversionAbsoluteFunctor; ConversionAbsoluteFunctor.initialize(this->m_Factor); typename FilterAbsoluteType::Pointer ConversionAbsoluteFilter = FilterAbsoluteType::New(); ConversionAbsoluteFilter->SetFunctor(ConversionAbsoluteFunctor); ConversionAbsoluteFilter->SetInput1(itkInputImage); ConversionAbsoluteFilter->SetInput2(itkBaselineImage); ConversionAbsoluteFilter->Update(); m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionAbsoluteFilter->GetOutput())->Clone(); } else if(this->m_RelativeSignalEnhancement) { typedef mitk::ConvertToConcentrationRelativeFunctor <TPixel_input, TPixel_baseline, double> ConversionFunctorRelativeType; typedef itk::BinaryFunctorImageFilter<InputImageType, BaselineImageType, ConvertedImageType, ConversionFunctorRelativeType> FilterRelativeType; ConversionFunctorRelativeType ConversionRelativeFunctor; ConversionRelativeFunctor.initialize(this->m_Factor); typename FilterRelativeType::Pointer ConversionRelativeFilter = FilterRelativeType::New(); ConversionRelativeFilter->SetFunctor(ConversionRelativeFunctor); ConversionRelativeFilter->SetInput1(itkInputImage); ConversionRelativeFilter->SetInput2(itkBaselineImage); ConversionRelativeFilter->Update(); m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionRelativeFilter->GetOutput())->Clone(); } } return m_ConvertSignalToConcentrationCurve_OutputImage; } <commit_msg>Fixed gcc compile errors<commit_after>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkConcentrationCurveGenerator.h" #include "mitkConvertToConcentrationTurboFlashFunctor.h" #include "mitkConvertT2ConcentrationFunctor.h" #include "mitkConvertToConcentrationViaT1Functor.h" #include "mitkImageTimeSelector.h" #include "mitkImageCast.h" #include "mitkITKImageImport.h" #include "mitkModelBase.h" #include "mitkExtractTimeGrid.h" #include "mitkArbitraryTimeGeometry.h" #include "itkNaryAddImageFilter.h" #include "mitkImageAccessByItk.h" #include "itkImageIOBase.h" #include "itkBinaryFunctorImageFilter.h" #include "itkTernaryFunctorImageFilter.h" #include <itkExtractImageFilter.h> #include "itkMeanProjectionImageFilter.h" mitk::ConcentrationCurveGenerator::ConcentrationCurveGenerator() : m_isT2weightedImage(false), m_isTurboFlashSequence(false), m_AbsoluteSignalEnhancement(false), m_RelativeSignalEnhancement(0.0), m_UsingT1Map(false), m_Factor(0.0), m_RecoveryTime(0.0), m_RelaxationTime(0.0), m_Relaxivity(0.0), m_FlipAngle(0.0), m_T2Factor(0.0), m_T2EchoTime(0.0) { } mitk::ConcentrationCurveGenerator::~ConcentrationCurveGenerator() { } mitk::Image::Pointer mitk::ConcentrationCurveGenerator::GetConvertedImage() { if(this->m_DynamicImage.IsNull()) { itkExceptionMacro( << "Dynamic Image not set!"); } else { Convert(); } return m_ConvertedImage; } void mitk::ConcentrationCurveGenerator::Convert() { mitk::Image::Pointer tempImage = mitk::Image::New(); mitk::PixelType pixeltype = mitk::MakeScalarPixelType<double>(); tempImage->Initialize(pixeltype,*this->m_DynamicImage->GetTimeGeometry()); mitk::TimeGeometry::Pointer timeGeometry = (this->m_DynamicImage->GetTimeGeometry())->Clone(); tempImage->SetTimeGeometry(timeGeometry); PrepareBaselineImage(); mitk::ImageTimeSelector::Pointer imageTimeSelector = mitk::ImageTimeSelector::New(); imageTimeSelector->SetInput(this->m_DynamicImage); for(unsigned int i = 0; i< this->m_DynamicImage->GetTimeSteps(); ++i) { imageTimeSelector->SetTimeNr(i); imageTimeSelector->UpdateLargestPossibleRegion(); mitk::Image::Pointer mitkInputImage = imageTimeSelector->GetOutput(); mitk::Image::Pointer outputImage = mitk::Image::New(); outputImage = ConvertSignalToConcentrationCurve(mitkInputImage,this->m_BaselineImage); mitk::ImageReadAccessor accessor(outputImage); tempImage->SetVolume(accessor.GetData(), i); } this->m_ConvertedImage = tempImage; } void mitk::ConcentrationCurveGenerator::PrepareBaselineImage() { mitk::ImageTimeSelector::Pointer imageTimeSelector = mitk::ImageTimeSelector::New(); imageTimeSelector->SetInput(this->m_DynamicImage); imageTimeSelector->SetTimeNr(0); imageTimeSelector->UpdateLargestPossibleRegion(); mitk::Image::Pointer baselineImage; baselineImage = imageTimeSelector->GetOutput(); if (m_BaselineStartTimeStep == m_BaselineEndTimeStep) { this->m_BaselineImage = imageTimeSelector->GetOutput(); } else { try { AccessFixedDimensionByItk(this->m_DynamicImage, mitk::ConcentrationCurveGenerator::CalculateAverageBaselineImage, 4); } catch (itk::ExceptionObject & err) { std::cerr << "ExceptionObject in ConcentrationCurveGenerator::CalculateAverageBaselineImage caught!" << std::endl; std::cerr << err << std::endl; } } } template<class TPixel> void mitk::ConcentrationCurveGenerator::CalculateAverageBaselineImage(const itk::Image<TPixel, 4> *itkBaselineImage) { if (itkBaselineImage == NULL) { mitkThrow() << "Error in ConcentrationCurveGenerator::CalculateAverageBaselineImage. Input image is NULL."; } if (m_BaselineStartTimeStep > m_BaselineEndTimeStep) { mitkThrow() << "Error in ConcentrationCurveGenerator::CalculateAverageBaselineImage. End time point is before start time point."; } typedef itk::Image<TPixel, 4> TPixel4DImageType; typedef itk::Image<double, 3> Double3DImageType; typedef itk::Image<double, 4> Double4DImageType; typedef itk::ExtractImageFilter<TPixel4DImageType, TPixel4DImageType> ExtractImageFilterType; typedef itk::ExtractImageFilter<Double4DImageType, Double3DImageType> Extract3DImageFilterType; typedef itk::MeanProjectionImageFilter<TPixel4DImageType,Double4DImageType> MeanProjectionImageFilterType; typename MeanProjectionImageFilterType::Pointer MeanProjectionImageFilter = MeanProjectionImageFilterType::New(); typename Extract3DImageFilterType::Pointer Extract3DImageFilter = Extract3DImageFilterType::New(); typename TPixel4DImageType::RegionType region_input = itkBaselineImage->GetLargestPossibleRegion(); if (m_BaselineEndTimeStep > region_input.GetSize()[3]) { mitkThrow() << "Error in ConcentrationCurveGenerator::CalculateAverageBaselineImage. End time point is larger than total number of time points."; } typename ExtractImageFilterType::Pointer ExtractFilter = ExtractImageFilterType::New(); typename TPixel4DImageType::Pointer baselineTimeFrameImage = TPixel4DImageType::New(); typename TPixel4DImageType::RegionType extractionRegion; typename TPixel4DImageType::SizeType size_input_aux = region_input.GetSize(); size_input_aux[3] = m_BaselineEndTimeStep - m_BaselineStartTimeStep + 1; typename TPixel4DImageType::IndexType start_input_aux = region_input.GetIndex(); start_input_aux[3] = m_BaselineStartTimeStep; extractionRegion.SetSize(size_input_aux); extractionRegion.SetIndex(start_input_aux); ExtractFilter->SetExtractionRegion(extractionRegion); ExtractFilter->SetInput(itkBaselineImage); ExtractFilter->SetDirectionCollapseToSubmatrix(); try { ExtractFilter->Update(); } catch (itk::ExceptionObject & err) { std::cerr << "ExceptionObject caught!" << std::endl; std::cerr << err << std::endl; } baselineTimeFrameImage = ExtractFilter->GetOutput(); MeanProjectionImageFilter->SetProjectionDimension(3); MeanProjectionImageFilter->SetInput(baselineTimeFrameImage); try { MeanProjectionImageFilter->Update(); } catch (itk::ExceptionObject & err) { std::cerr << "ExceptionObject caught!" << std::endl; std::cerr << err << std::endl; } Extract3DImageFilter->SetInput(MeanProjectionImageFilter->GetOutput()); size_input_aux[3] = 0; start_input_aux[3] = 0; extractionRegion.SetSize(size_input_aux); extractionRegion.SetIndex(start_input_aux); Extract3DImageFilter->SetExtractionRegion(extractionRegion); Extract3DImageFilter->SetDirectionCollapseToSubmatrix(); try { Extract3DImageFilter->Update(); } catch (itk::ExceptionObject & err) { std::cerr << "ExceptionObject caught!" << std::endl; std::cerr << err << std::endl; } Image::Pointer mitkBaselineImage = Image::New(); CastToMitkImage(Extract3DImageFilter->GetOutput(), mitkBaselineImage); this->m_BaselineImage = mitkBaselineImage; } mitk::Image::Pointer mitk::ConcentrationCurveGenerator::ConvertSignalToConcentrationCurve(const mitk::Image* inputImage,const mitk::Image* baselineImage) { mitk::PixelType m_PixelType = inputImage->GetPixelType(); AccessTwoImagesFixedDimensionByItk(inputImage, baselineImage, mitk::ConcentrationCurveGenerator::convertToConcentration, 3); return m_ConvertSignalToConcentrationCurve_OutputImage; } template<class TPixel_input, class TPixel_baseline> mitk::Image::Pointer mitk::ConcentrationCurveGenerator::convertToConcentration(const itk::Image<TPixel_input, 3> *itkInputImage, const itk::Image<TPixel_baseline, 3> *itkBaselineImage) { typedef itk::Image<TPixel_input, 3> InputImageType; typedef itk::Image<TPixel_baseline, 3> BaselineImageType; if (this->m_isT2weightedImage) { typedef mitk::ConvertT2ConcentrationFunctor <TPixel_input, TPixel_baseline, double> ConversionFunctorT2Type; typedef itk::BinaryFunctorImageFilter<InputImageType, BaselineImageType, ConvertedImageType, ConversionFunctorT2Type> FilterT2Type; ConversionFunctorT2Type ConversionT2Functor; ConversionT2Functor.initialize(this->m_T2Factor, this->m_T2EchoTime); typename FilterT2Type::Pointer ConversionT2Filter = FilterT2Type::New(); ConversionT2Filter->SetFunctor(ConversionT2Functor); ConversionT2Filter->SetInput1(itkInputImage); ConversionT2Filter->SetInput2(itkBaselineImage); ConversionT2Filter->Update(); m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionT2Filter->GetOutput())->Clone(); } else { if(this->m_isTurboFlashSequence) { typedef mitk::ConvertToConcentrationTurboFlashFunctor <TPixel_input, TPixel_baseline, double> ConversionFunctorTurboFlashType; typedef itk::BinaryFunctorImageFilter<InputImageType, BaselineImageType, ConvertedImageType, ConversionFunctorTurboFlashType> FilterTurboFlashType; ConversionFunctorTurboFlashType ConversionTurboFlashFunctor; ConversionTurboFlashFunctor.initialize(this->m_RelaxationTime, this->m_Relaxivity, this->m_RecoveryTime); typename FilterTurboFlashType::Pointer ConversionTurboFlashFilter = FilterTurboFlashType::New(); ConversionTurboFlashFilter->SetFunctor(ConversionTurboFlashFunctor); ConversionTurboFlashFilter->SetInput1(itkInputImage); ConversionTurboFlashFilter->SetInput2(itkBaselineImage); ConversionTurboFlashFilter->Update(); m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionTurboFlashFilter->GetOutput())->Clone(); } else if(this->m_UsingT1Map) { typename ConvertedImageType::Pointer itkT10Image = ConvertedImageType::New(); mitk::CastToItkImage(m_T10Image, itkT10Image); typedef mitk::ConvertToConcentrationViaT1CalcFunctor <TPixel_input, TPixel_baseline, double, double> ConvertToConcentrationViaT1CalcFunctorType; typedef itk::TernaryFunctorImageFilter<InputImageType, BaselineImageType, ConvertedImageType, ConvertedImageType, ConvertToConcentrationViaT1CalcFunctorType> FilterT1MapType; ConvertToConcentrationViaT1CalcFunctorType ConversionT1MapFunctor; ConversionT1MapFunctor.initialize(this->m_Relaxivity, this->m_RecoveryTime, this->m_FlipAngle); typename FilterT1MapType::Pointer ConversionT1MapFilter = FilterT1MapType::New(); ConversionT1MapFilter->SetFunctor(ConversionT1MapFunctor); ConversionT1MapFilter->SetInput1(itkInputImage); ConversionT1MapFilter->SetInput2(itkBaselineImage); ConversionT1MapFilter->SetInput3(itkT10Image); ConversionT1MapFilter->Update(); m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionT1MapFilter->GetOutput())->Clone(); } else if(this->m_AbsoluteSignalEnhancement) { typedef mitk::ConvertToConcentrationAbsoluteFunctor <TPixel_input, TPixel_baseline, double> ConversionFunctorAbsoluteType; typedef itk::BinaryFunctorImageFilter<InputImageType, BaselineImageType, ConvertedImageType, ConversionFunctorAbsoluteType> FilterAbsoluteType; ConversionFunctorAbsoluteType ConversionAbsoluteFunctor; ConversionAbsoluteFunctor.initialize(this->m_Factor); typename FilterAbsoluteType::Pointer ConversionAbsoluteFilter = FilterAbsoluteType::New(); ConversionAbsoluteFilter->SetFunctor(ConversionAbsoluteFunctor); ConversionAbsoluteFilter->SetInput1(itkInputImage); ConversionAbsoluteFilter->SetInput2(itkBaselineImage); ConversionAbsoluteFilter->Update(); m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionAbsoluteFilter->GetOutput())->Clone(); } else if(this->m_RelativeSignalEnhancement) { typedef mitk::ConvertToConcentrationRelativeFunctor <TPixel_input, TPixel_baseline, double> ConversionFunctorRelativeType; typedef itk::BinaryFunctorImageFilter<InputImageType, BaselineImageType, ConvertedImageType, ConversionFunctorRelativeType> FilterRelativeType; ConversionFunctorRelativeType ConversionRelativeFunctor; ConversionRelativeFunctor.initialize(this->m_Factor); typename FilterRelativeType::Pointer ConversionRelativeFilter = FilterRelativeType::New(); ConversionRelativeFilter->SetFunctor(ConversionRelativeFunctor); ConversionRelativeFilter->SetInput1(itkInputImage); ConversionRelativeFilter->SetInput2(itkBaselineImage); ConversionRelativeFilter->Update(); m_ConvertSignalToConcentrationCurve_OutputImage = mitk::ImportItkImage(ConversionRelativeFilter->GetOutput())->Clone(); } } return m_ConvertSignalToConcentrationCurve_OutputImage; } <|endoftext|>
<commit_before>/*! * Copyright (c) 2016 by Contributors * \file plan_memory.cc * \brief Assign memory tag to each of the data entries. */ #include <nnvm/graph.h> #include <nnvm/pass.h> #include <nnvm/graph_attr_types.h> #include <nnvm/op_attr_types.h> #include <memory> #include "./graph_algorithm.h" namespace nnvm { namespace pass { namespace { // simple graph based allocator. class GraphAllocator { public: // storage id equals integer. using StorageID = int; // bad storage id static const StorageID kBadStorageID = -1; // external storage id static const StorageID kExternalStorageID = -2; // dynamic storage id static const StorageID kDynamicStorageID = -3; // request a free storage StorageID Request(int dev_id, int dtype, TShape shape, uint32_t node_id) { if (shape.ndim() == 0) return kBadStorageID; // search memory block in [size / match_range_, size * match_range_) // TODO(tqchen) add size of the dtype, assume 4 bytes for now size_t size = shape.Size() * 4; if (match_range_ == 0) return this->Alloc(dev_id, size); auto begin = free_.lower_bound(size / match_range_); auto mid = free_.lower_bound(size); auto end = free_.upper_bound(size * match_range_); // search for memory blocks larger than requested for (auto it = mid; it != end; ++it) { StorageEntry *e = it->second; if (e->device_id != dev_id) continue; if (node_color_.size() != 0 && node_color_[e->released_by_node] != node_color_[node_id]) continue; // Use exect matching strategy e->max_bytes = std::max(size, e->max_bytes); // find a exact match, erase from map and return free_.erase(it); return e->id; } // then search for memory blocks smaller than requested space for (auto it = mid; it != begin;) { --it; StorageEntry *e = it->second; if (e->device_id != dev_id) continue; if (node_color_.size() != 0 && node_color_[e->released_by_node] != node_color_[node_id]) continue; // Use exect matching strategy e->max_bytes = std::max(size, e->max_bytes); // erase from map and return free_.erase(it); return e->id; } // cannot find anything return a new one. return this->Alloc(dev_id, size); } // release a memory space. void Release(StorageID id, uint32_t node_id) { CHECK_NE(id, kBadStorageID); if (id == kExternalStorageID || id == kDynamicStorageID) return; StorageEntry *e = data_[id].get(); e->released_by_node = node_id; free_.insert({e->max_bytes, e}); } // totoal number of bytes allocated size_t TotalAllocBytes() const { size_t total = 0; for (auto &p : data_) { total += p->max_bytes; } return total; } // constructor explicit GraphAllocator(const IndexedGraph* idx, const size_t match_range) : idx_(idx) { this->Init(match_range, dmlc::GetEnv("NNVM_EXEC_NUM_TEMP", 1)); } private: // initialize the graph allocator void Init(const size_t match_range, const uint32_t num_match_color) { match_range_ = match_range; num_match_color_ = num_match_color; if (num_match_color_ > 1) { std::vector<uint32_t> importance(idx_->num_nodes(), 0); for (uint32_t nid = 0; nid < idx_->num_nodes(); ++nid) { if ((*idx_)[nid].source->is_variable()) continue; importance[nid] = 1; } num_match_color_ = pass::ColorNodeGroup( *idx_, importance, num_match_color_, &node_color_); } } StorageID Alloc(int dev_id, size_t size) { StorageID id = static_cast<StorageID>(data_.size()); std::unique_ptr<StorageEntry> ptr(new StorageEntry()); ptr->id = id; ptr->device_id = dev_id; ptr->max_bytes = size; data_.emplace_back(std::move(ptr)); return id; } // internal storage entry struct StorageEntry { // the id of the entry. StorageID id; // the device id of the storage. int device_id; // maximum size of storage requested. size_t max_bytes{0}; // node index that released it last time uint32_t released_by_node{0}; }; // scale used for rough match size_t match_range_; // whether use color based match algorithm uint32_t num_match_color_{1}; // the size of each dtype std::vector<size_t> dtype_size_dict_; // free list of storage entry std::multimap<size_t, StorageEntry*> free_; // all the storage resources available std::vector<std::unique_ptr<StorageEntry> > data_; // color of nodes in the graph, used for auxiliary policy making. std::vector<uint32_t> node_color_; // internal indexed graph const IndexedGraph* idx_; }; /* * Internal method to perform the memory allocation for a graph * */ size_t AllocMemory(const Graph& ret, const IndexedGraph& idx, StorageVector* storage_ptr, std::vector<int>* storage_inplace_index_ptr, const std::vector<uint32_t>& entry_ref_count, GraphAllocator* allocator) { static auto& finplace_option = Op::GetAttr<FInplaceOption>("FInplaceOption"); static auto& finplace_identity = Op::GetAttr<FInplaceIdentity>("FInplaceIdentity"); // Get reference auto &storage = *storage_ptr; auto &storage_inplace_index = *storage_inplace_index_ptr; // Get attributes from the graph const ShapeVector& shape_vec = ret.GetAttr<ShapeVector>("shape"); const DTypeVector& dtype_vec = ret.GetAttr<DTypeVector>("dtype"); const DeviceVector* device_vec = nullptr; if (ret.attrs.count("device") != 0) { device_vec = &(ret.GetAttr<DeviceVector>("device")); } size_t num_not_allocated = 0; std::vector<GraphAllocator::StorageID> storage_ref_count(idx.num_node_entries(), 0); for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) { const auto& inode = idx[nid]; if (inode.source->is_variable()) continue; // check inplace option if (finplace_option.count(inode.source->op()) != 0) { auto inplace_pairs = finplace_option[inode.source->op()](inode.source->attrs); std::vector<bool> identity; if (finplace_identity.count(inode.source->op()) != 0) { identity = finplace_identity[inode.source->op()](inode.source->attrs); CHECK_EQ(identity.size(), inplace_pairs.size()) << "FInplaceOption and FInplaceIdentity returned vectors of different " << "size for operator " << inode.source->op()->name; } else { identity = std::vector<bool>(inplace_pairs.size(), false); } std::vector<bool> taken(inode.inputs.size(), false); for (size_t ipair = 0; ipair < inplace_pairs.size(); ++ipair) { const auto& kv = inplace_pairs[ipair]; uint32_t eid_out = idx.entry_id(nid, kv.second); uint32_t eid_in = idx.entry_id(inode.inputs[kv.first]); auto sid_out = storage[eid_out]; auto sid_in = storage[eid_in]; if (taken[kv.first] == false && sid_out == GraphAllocator::kBadStorageID && sid_in >= 0 && (storage_ref_count[sid_in] == 1 || identity[ipair]) && entry_ref_count[eid_out] > 0 && shape_vec[eid_out].Size() == shape_vec[eid_in].Size() && dtype_vec[eid_out] == dtype_vec[eid_in]) { // inplace optimization taken[kv.first] = true; storage[eid_out] = sid_in; // Reuse storage for output and add ref count of output // to storage. This will get substracted later in free // input section. storage_ref_count[sid_in] += entry_ref_count[eid_out]; storage_inplace_index[eid_out] = kv.first; } } } // normal allocation const int dev_id = (device_vec != nullptr) ? device_vec->at(nid) : 0; // sort output nodes based on size before allocating output std::multimap<size_t, uint32_t> eids; for (uint32_t index = 0; index < inode.source->num_outputs(); ++index) { uint32_t eid = idx.entry_id(nid, index); // only request memory for kBadStorageID if (storage[eid] == GraphAllocator::kBadStorageID) { auto &eshape = shape_vec[eid]; size_t esize = 0; if (eshape.ndim() != 0) esize = eshape.Size(); eids.insert(std::make_pair(esize, eid)); } } for (auto rit = eids.rbegin(); rit != eids.rend(); ++rit) { uint32_t eid = rit->second; auto sid = allocator->Request(dev_id, dtype_vec[eid], shape_vec[eid], nid); storage_ref_count[sid] = entry_ref_count[eid]; storage[eid] = sid; } // check if certain inputs is ignored. static auto& fignore_inputs = Op::GetAttr<FIgnoreInputs>("FIgnoreInputs"); std::vector<uint32_t> ignore_inputs; if (fignore_inputs.count(inode.source->op()) != 0) { ignore_inputs = fignore_inputs[inode.source->op()](inode.source->attrs); std::sort(ignore_inputs.begin(), ignore_inputs.end()); } // then free inputs for (size_t i = 0; i < inode.inputs.size(); ++i) { // ref counter of ignored input is already decreased. if (std::binary_search(ignore_inputs.begin(), ignore_inputs.end(), i)) continue; const auto& e = inode.inputs[i]; uint32_t eid = idx.entry_id(e); auto sid = storage[eid]; // storage_ref_count == 0 means it is taken by inplace op if (sid < 0) continue; // if we decrease it to zero, means we are ready to relase --storage_ref_count[sid]; if (storage_ref_count[sid] == 0) { allocator->Release(sid, nid); } } // check if there are outputs that can be freeded immediately // these output are not referenced by any operator. for (uint32_t index = 0; index < inode.source->num_outputs(); ++index) { uint32_t eid = idx.entry_id(nid, index); auto sid = storage[eid]; if (sid >= 0 && storage_ref_count[sid] == 0) { allocator->Release(sid, nid); // use -2 to indicate that the node was never touched. storage_inplace_index[eid] = -2; } if (storage[eid] == GraphAllocator::kBadStorageID) { ++num_not_allocated; } } } return num_not_allocated; } // function to plan memory Graph PlanMemory(Graph ret) { // setup ref counter const IndexedGraph& idx = ret.indexed_graph(); static auto& fignore_inputs = Op::GetAttr<FIgnoreInputs>("FIgnoreInputs"); // reference counter of each node std::vector<uint32_t> ref_count(idx.num_node_entries(), 0); // step 1: initialize reference count for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) { const auto& inode = idx[nid]; if (inode.source->is_variable()) continue; for (const auto& e : inode.inputs) { ++ref_count[idx.entry_id(e)]; } // no dataflow dependency is needed for those are ignored. // revoke the dependency counter. if (fignore_inputs.count(inode.source->op()) != 0) { auto ignore_inputs = fignore_inputs[inode.source->op()](inode.source->attrs); for (uint32_t i : ignore_inputs) { --ref_count[idx.entry_id(inode.inputs[i])]; } } } for (const auto& e : idx.outputs()) { ++ref_count[idx.entry_id(e)]; } // step 2: allocate memory. StorageVector storage; if (ret.attrs.count("storage") != 0) { storage = ret.MoveCopyAttr<StorageVector>("storage"); } else { storage.resize(idx.num_node_entries(), -1); } // Search the best NNVM_EXEC_MATCH_RANGE parameter. This is turned off by default size_t min_allocated_bytes = -1; size_t max_match_range = dmlc::GetEnv("NNVM_EXEC_MATCH_RANGE", 16); size_t min_match_range = dmlc::GetEnv("NNVM_AUTO_SEARCH_MATCH_RANGE", false) ? 1 : max_match_range; for (size_t match_range = min_match_range; match_range <= max_match_range; match_range *= 2) { // Make a copy of related fields StorageVector storage_vec(storage); std::vector<int> storage_inplace_index(idx.num_node_entries(), -1); // the allocator GraphAllocator allocator(&idx, match_range); // number of entries that are not statically allocated. size_t storage_num_not_allocated = AllocMemory(ret, idx, &storage_vec, &storage_inplace_index, ref_count, &allocator); size_t storage_allocated_bytes = allocator.TotalAllocBytes(); // Choose the plan which leads to minimal memory usage if (min_allocated_bytes > storage_allocated_bytes) { ret.attrs["storage_id"] = std::make_shared<any>(std::move(storage_vec)); ret.attrs["storage_inplace_index"] = std::make_shared<any>(std::move(storage_inplace_index)); ret.attrs["storage_allocated_bytes"] = std::make_shared<any>(storage_allocated_bytes); ret.attrs["storage_num_not_allocated"] = std::make_shared<any>(storage_num_not_allocated); min_allocated_bytes = storage_allocated_bytes; } if (max_match_range == 0) { break; } } return ret; } NNVM_REGISTER_PASS(PlanMemory) .describe("Plan the memory allocation of each node entries.") .set_body(PlanMemory) .set_change_graph(false) .depend_graph_attr("dtype") .depend_graph_attr("shape") .provide_graph_attr("storage_id") .provide_graph_attr("storage_inplace_index"); } // namespace } // namespace pass } // namespace nnvm <commit_msg>add range to plan memory (#147)<commit_after>/*! * Copyright (c) 2016 by Contributors * \file plan_memory.cc * \brief Assign memory tag to each of the data entries. */ #include <nnvm/graph.h> #include <nnvm/pass.h> #include <nnvm/graph_attr_types.h> #include <nnvm/op_attr_types.h> #include <memory> #include "./graph_algorithm.h" namespace nnvm { namespace pass { namespace { // simple graph based allocator. class GraphAllocator { public: // storage id equals integer. using StorageID = int; // bad storage id static const StorageID kBadStorageID = -1; // external storage id static const StorageID kExternalStorageID = -2; // dynamic storage id static const StorageID kDynamicStorageID = -3; // request a free storage StorageID Request(int dev_id, int dtype, TShape shape, uint32_t node_id) { if (shape.ndim() == 0) return kBadStorageID; // search memory block in [size / match_range_, size * match_range_) // TODO(tqchen) add size of the dtype, assume 4 bytes for now size_t size = shape.Size() * 4; if (match_range_ == 0) return this->Alloc(dev_id, size); auto begin = free_.lower_bound(size / match_range_); auto mid = free_.lower_bound(size); auto end = free_.upper_bound(size * match_range_); // search for memory blocks larger than requested for (auto it = mid; it != end; ++it) { StorageEntry *e = it->second; if (e->device_id != dev_id) continue; if (node_color_.size() != 0 && node_color_[e->released_by_node] != node_color_[node_id]) continue; // Use exect matching strategy e->max_bytes = std::max(size, e->max_bytes); // find a exact match, erase from map and return free_.erase(it); return e->id; } // then search for memory blocks smaller than requested space for (auto it = mid; it != begin;) { --it; StorageEntry *e = it->second; if (e->device_id != dev_id) continue; if (node_color_.size() != 0 && node_color_[e->released_by_node] != node_color_[node_id]) continue; // Use exect matching strategy e->max_bytes = std::max(size, e->max_bytes); // erase from map and return free_.erase(it); return e->id; } // cannot find anything return a new one. return this->Alloc(dev_id, size); } // release a memory space. void Release(StorageID id, uint32_t node_id) { CHECK_NE(id, kBadStorageID); if (id == kExternalStorageID || id == kDynamicStorageID) return; StorageEntry *e = data_[id].get(); e->released_by_node = node_id; free_.insert({e->max_bytes, e}); } // totoal number of bytes allocated size_t TotalAllocBytes() const { size_t total = 0; for (auto &p : data_) { total += p->max_bytes; } return total; } // constructor explicit GraphAllocator(const IndexedGraph* idx, const size_t match_range) : idx_(idx) { this->Init(match_range, dmlc::GetEnv("NNVM_EXEC_NUM_TEMP", 1)); } private: // initialize the graph allocator void Init(const size_t match_range, const uint32_t num_match_color) { match_range_ = match_range; num_match_color_ = num_match_color; if (num_match_color_ > 1) { std::vector<uint32_t> importance(idx_->num_nodes(), 0); for (uint32_t nid = 0; nid < idx_->num_nodes(); ++nid) { if ((*idx_)[nid].source->is_variable()) continue; importance[nid] = 1; } num_match_color_ = pass::ColorNodeGroup( *idx_, importance, num_match_color_, &node_color_); } } StorageID Alloc(int dev_id, size_t size) { StorageID id = static_cast<StorageID>(data_.size()); std::unique_ptr<StorageEntry> ptr(new StorageEntry()); ptr->id = id; ptr->device_id = dev_id; ptr->max_bytes = size; data_.emplace_back(std::move(ptr)); return id; } // internal storage entry struct StorageEntry { // the id of the entry. StorageID id; // the device id of the storage. int device_id; // maximum size of storage requested. size_t max_bytes{0}; // node index that released it last time uint32_t released_by_node{0}; }; // scale used for rough match size_t match_range_; // whether use color based match algorithm uint32_t num_match_color_{1}; // the size of each dtype std::vector<size_t> dtype_size_dict_; // free list of storage entry std::multimap<size_t, StorageEntry*> free_; // all the storage resources available std::vector<std::unique_ptr<StorageEntry> > data_; // color of nodes in the graph, used for auxiliary policy making. std::vector<uint32_t> node_color_; // internal indexed graph const IndexedGraph* idx_; }; /* * Internal method to perform the memory allocation for a graph * */ size_t AllocMemory(const Graph& ret, const IndexedGraph& idx, const std::pair<uint32_t, uint32_t>& node_range, StorageVector* storage_ptr, std::vector<int>* storage_inplace_index_ptr, const std::vector<uint32_t>& entry_ref_count, GraphAllocator* allocator) { static auto& finplace_option = Op::GetAttr<FInplaceOption>("FInplaceOption"); static auto& finplace_identity = Op::GetAttr<FInplaceIdentity>("FInplaceIdentity"); // Get reference auto &storage = *storage_ptr; auto &storage_inplace_index = *storage_inplace_index_ptr; // Get attributes from the graph const ShapeVector& shape_vec = ret.GetAttr<ShapeVector>("shape"); const DTypeVector& dtype_vec = ret.GetAttr<DTypeVector>("dtype"); const DeviceVector* device_vec = nullptr; if (ret.attrs.count("device") != 0) { device_vec = &(ret.GetAttr<DeviceVector>("device")); } size_t num_not_allocated = 0; std::vector<GraphAllocator::StorageID> storage_ref_count(idx.num_node_entries(), 0); for (uint32_t nid = node_range.first; nid < node_range.second; ++nid) { const auto& inode = idx[nid]; if (inode.source->is_variable()) continue; // check inplace option if (finplace_option.count(inode.source->op()) != 0) { auto inplace_pairs = finplace_option[inode.source->op()](inode.source->attrs); std::vector<bool> identity; if (finplace_identity.count(inode.source->op()) != 0) { identity = finplace_identity[inode.source->op()](inode.source->attrs); CHECK_EQ(identity.size(), inplace_pairs.size()) << "FInplaceOption and FInplaceIdentity returned vectors of different " << "size for operator " << inode.source->op()->name; } else { identity = std::vector<bool>(inplace_pairs.size(), false); } std::vector<bool> taken(inode.inputs.size(), false); for (size_t ipair = 0; ipair < inplace_pairs.size(); ++ipair) { const auto& kv = inplace_pairs[ipair]; uint32_t eid_out = idx.entry_id(nid, kv.second); uint32_t eid_in = idx.entry_id(inode.inputs[kv.first]); auto sid_out = storage[eid_out]; auto sid_in = storage[eid_in]; if (taken[kv.first] == false && sid_out == GraphAllocator::kBadStorageID && sid_in >= 0 && (storage_ref_count[sid_in] == 1 || identity[ipair]) && entry_ref_count[eid_out] > 0 && shape_vec[eid_out].Size() == shape_vec[eid_in].Size() && dtype_vec[eid_out] == dtype_vec[eid_in]) { // inplace optimization taken[kv.first] = true; storage[eid_out] = sid_in; // Reuse storage for output and add ref count of output // to storage. This will get substracted later in free // input section. storage_ref_count[sid_in] += entry_ref_count[eid_out]; storage_inplace_index[eid_out] = kv.first; } } } // normal allocation const int dev_id = (device_vec != nullptr) ? device_vec->at(nid) : 0; // sort output nodes based on size before allocating output std::multimap<size_t, uint32_t> eids; for (uint32_t index = 0; index < inode.source->num_outputs(); ++index) { uint32_t eid = idx.entry_id(nid, index); // only request memory for kBadStorageID if (storage[eid] == GraphAllocator::kBadStorageID) { auto &eshape = shape_vec[eid]; size_t esize = 0; if (eshape.ndim() != 0) esize = eshape.Size(); eids.insert(std::make_pair(esize, eid)); } } for (auto rit = eids.rbegin(); rit != eids.rend(); ++rit) { uint32_t eid = rit->second; auto sid = allocator->Request(dev_id, dtype_vec[eid], shape_vec[eid], nid); storage_ref_count[sid] = entry_ref_count[eid]; storage[eid] = sid; } // check if certain inputs is ignored. static auto& fignore_inputs = Op::GetAttr<FIgnoreInputs>("FIgnoreInputs"); std::vector<uint32_t> ignore_inputs; if (fignore_inputs.count(inode.source->op()) != 0) { ignore_inputs = fignore_inputs[inode.source->op()](inode.source->attrs); std::sort(ignore_inputs.begin(), ignore_inputs.end()); } // then free inputs for (size_t i = 0; i < inode.inputs.size(); ++i) { // ref counter of ignored input is already decreased. if (std::binary_search(ignore_inputs.begin(), ignore_inputs.end(), i)) continue; const auto& e = inode.inputs[i]; uint32_t eid = idx.entry_id(e); auto sid = storage[eid]; // storage_ref_count == 0 means it is taken by inplace op if (sid < 0) continue; // if we decrease it to zero, means we are ready to relase --storage_ref_count[sid]; if (storage_ref_count[sid] == 0) { allocator->Release(sid, nid); } } // check if there are outputs that can be freeded immediately // these output are not referenced by any operator. for (uint32_t index = 0; index < inode.source->num_outputs(); ++index) { uint32_t eid = idx.entry_id(nid, index); auto sid = storage[eid]; if (sid >= 0 && storage_ref_count[sid] == 0) { allocator->Release(sid, nid); // use -2 to indicate that the node was never touched. storage_inplace_index[eid] = -2; } if (storage[eid] == GraphAllocator::kBadStorageID) { ++num_not_allocated; } } } return num_not_allocated; } // function to plan memory Graph PlanMemory(Graph ret) { // setup ref counter const IndexedGraph& idx = ret.indexed_graph(); static auto& fignore_inputs = Op::GetAttr<FIgnoreInputs>("FIgnoreInputs"); std::pair<uint32_t, uint32_t> node_range = {0, idx.num_nodes()}; if (ret.attrs.count("node_range")) { node_range = ret.MoveCopyAttr<std::pair<uint32_t, uint32_t> >("node_range"); } // reference counter of each node std::vector<uint32_t> ref_count; // step 1: initialize reference count if (ret.attrs.count("ref_count") != 0) { ref_count = ret.MoveCopyAttr<std::vector<uint32_t> >("ref_count"); } else { ref_count.resize(idx.num_node_entries(), 0); for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) { const auto& inode = idx[nid]; if (inode.source->is_variable()) continue; for (const auto& e : inode.inputs) { ++ref_count[idx.entry_id(e)]; } // no dataflow dependency is needed for those are ignored. // revoke the dependency counter. if (fignore_inputs.count(inode.source->op()) != 0) { auto ignore_inputs = fignore_inputs[inode.source->op()](inode.source->attrs); for (uint32_t i : ignore_inputs) { --ref_count[idx.entry_id(inode.inputs[i])]; } } } for (const auto& e : idx.outputs()) { ++ref_count[idx.entry_id(e)]; } } // step 2: allocate memory. StorageVector storage; if (ret.attrs.count("storage") != 0) { storage = ret.MoveCopyAttr<StorageVector>("storage"); } else { storage.resize(idx.num_node_entries(), -1); } // Search the best NNVM_EXEC_MATCH_RANGE parameter. This is turned off by default size_t min_allocated_bytes = -1; size_t max_match_range = dmlc::GetEnv("NNVM_EXEC_MATCH_RANGE", 16); size_t min_match_range = dmlc::GetEnv("NNVM_AUTO_SEARCH_MATCH_RANGE", false) ? 1 : max_match_range; for (size_t match_range = min_match_range; match_range <= max_match_range; match_range *= 2) { // Make a copy of related fields StorageVector storage_vec(storage); std::vector<int> storage_inplace_index(idx.num_node_entries(), -1); // the allocator GraphAllocator allocator(&idx, match_range); // number of entries that are not statically allocated. size_t storage_num_not_allocated = AllocMemory(ret, idx, node_range, &storage_vec, &storage_inplace_index, ref_count, &allocator); size_t storage_allocated_bytes = allocator.TotalAllocBytes(); // Choose the plan which leads to minimal memory usage if (min_allocated_bytes > storage_allocated_bytes) { ret.attrs["storage_id"] = std::make_shared<any>(std::move(storage_vec)); ret.attrs["storage_inplace_index"] = std::make_shared<any>(std::move(storage_inplace_index)); ret.attrs["storage_allocated_bytes"] = std::make_shared<any>(storage_allocated_bytes); ret.attrs["storage_num_not_allocated"] = std::make_shared<any>(storage_num_not_allocated); min_allocated_bytes = storage_allocated_bytes; } if (max_match_range == 0) { break; } } return ret; } NNVM_REGISTER_PASS(PlanMemory) .describe("Plan the memory allocation of each node entries.") .set_body(PlanMemory) .set_change_graph(false) .depend_graph_attr("dtype") .depend_graph_attr("shape") .provide_graph_attr("storage_id") .provide_graph_attr("storage_inplace_index"); } // namespace } // namespace pass } // namespace nnvm <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/return_code_defs.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2012,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file return_code.H * @brief definitions for fapi2 return codes */ #ifndef __FAPI2_RETURN_CODE_DEFS_ #define __FAPI2_RETURN_CODE_DEFS_ #include <stdint.h> /// /// @brief Set HWP Error macro /// /// This macro should be used by a HWP to create an error. The ReturnCode's /// internal return code is set and any error information in the Error XML file /// is added to the ReturnCode /// #define FAPI_SET_HWP_ERROR(RC, ERROR) \ RC._setHwpError(fapi2::ERROR); \ ERROR##_CALL_FUNCS_TO_COLLECT_FFDC(RC); \ ERROR##_CALL_FUNCS_TO_COLLECT_REG_FFDC(RC); \ ERROR##_ADD_ERROR_INFO(RC) /// /// @brief Add info to HWP Error macro /// /// This macro should be used by an FFDC HWP to add error information from an /// Error XML file to an existing error. /// #define FAPI_ADD_INFO_TO_HWP_ERROR(RC, ERROR) \ ERROR##_CALL_FUNCS_TO_COLLECT_FFDC(RC); \ ERROR##_CALL_FUNCS_TO_COLLECT_REG_FFDC(RC); \ ERROR##_ADD_ERROR_INFO(RC) namespace fapi2 { /// /// @brief Enumeration of return codes /// enum ReturnCodes { ///< Success FAPI2_RC_SUCCESS = 0, // Flag bits indicating which code generated the error. FAPI2_RC_FAPI2_MASK = 0x04000000, ///< FAPI2 mask FAPI2_RC_PLAT_MASK = 0x02000000, ///< Platform mask FAPI2_RC_HWP_MASK = 0x00000000, ///< HWP mask // // FAPI generated return codes // FAPI2_RC_INVALID_ATTR_GET = FAPI2_RC_FAPI2_MASK | 0x01, ///< Initfile requested an attribute with an invalid attribute ID FAPI2_RC_INVALID_CHIP_EC_FEATURE_GET = FAPI2_RC_FAPI2_MASK | 0x02, ///< HWP requested a chip EC feature with an invalid attribute ID FAPI2_RC_INVALID_PARAMETER = FAPI2_RC_FAPI2_MASK | 0x04, ///< Invalid parameters to a FAPI2 function FAPI2_RC_OVERFLOW = FAPI2_RC_FAPI2_MASK | 0x05, ///< Overflow condition, typically a buffer operation FAPI2_RC_FALSE = FAPI2_RC_FAPI2_MASK | 0x06, ///< The logical opposite of SUCCESS. Needed where procedures want ///< a multi-bool type of operation (e.g., true, false, scom error) // // PLAT generated return codes. Additional details may be contained in // ReturnCode platData (this can only be looked at by PLAT code) // FAPI2_RC_PLAT_ERR_SEE_DATA = FAPI2_RC_PLAT_MASK | 0x01, ///< Generic platform error FAPI2_RC_PLAT_ERR_ADU_LOCKED = FAPI2_RC_PLAT_MASK | 0x02, ///< Operation to AlterDisplay unit failed because it is locked FAPI2_RC_PLAT_NOT_SUPPORTED_AT_RUNTIME = FAPI2_RC_PLAT_MASK | 0x03, ///< Operation not supported by HB runtime }; } #endif <commit_msg>Add explicit RC checkers to ReturnCode class<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/return_code_defs.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2012,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file return_code.H * @brief definitions for fapi2 return codes */ #ifndef __FAPI2_RETURN_CODE_DEFS_ #define __FAPI2_RETURN_CODE_DEFS_ #include <stdint.h> /// /// @brief Set HWP Error macro /// /// This macro should be used by a HWP to create an error. The ReturnCode's /// internal return code is set and any error information in the Error XML file /// is added to the ReturnCode /// #define FAPI_SET_HWP_ERROR(RC, ERROR) \ RC._setHwpError(fapi2::ERROR); \ ERROR##_CALL_FUNCS_TO_COLLECT_FFDC(RC); \ ERROR##_CALL_FUNCS_TO_COLLECT_REG_FFDC(RC); \ ERROR##_ADD_ERROR_INFO(RC) /// /// @brief Add info to HWP Error macro /// /// This macro should be used by an FFDC HWP to add error information from an /// Error XML file to an existing error. /// #define FAPI_ADD_INFO_TO_HWP_ERROR(RC, ERROR) \ ERROR##_CALL_FUNCS_TO_COLLECT_FFDC(RC); \ ERROR##_CALL_FUNCS_TO_COLLECT_REG_FFDC(RC); \ ERROR##_ADD_ERROR_INFO(RC) namespace fapi2 { /// /// @brief Enumeration of return codes /// enum ReturnCodes : uint32_t { ///< Success FAPI2_RC_SUCCESS = 0, // Flag bits indicating which code generated the error. FAPI2_RC_FAPI2_MASK = 0x04000000, ///< FAPI2 mask FAPI2_RC_PLAT_MASK = 0x02000000, ///< Platform mask FAPI2_RC_HWP_MASK = 0x00000000, ///< HWP mask // // FAPI generated return codes // FAPI2_RC_INVALID_ATTR_GET = FAPI2_RC_FAPI2_MASK | 0x01, ///< Initfile requested an attribute with an invalid attribute ID FAPI2_RC_INVALID_CHIP_EC_FEATURE_GET = FAPI2_RC_FAPI2_MASK | 0x02, ///< HWP requested a chip EC feature with an invalid attribute ID FAPI2_RC_INVALID_PARAMETER = FAPI2_RC_FAPI2_MASK | 0x04, ///< Invalid parameters to a FAPI2 function FAPI2_RC_OVERFLOW = FAPI2_RC_FAPI2_MASK | 0x05, ///< Overflow condition, typically a buffer operation FAPI2_RC_FALSE = FAPI2_RC_FAPI2_MASK | 0x06, ///< The logical opposite of SUCCESS. Needed where procedures want ///< a multi-bool type of operation (e.g., true, false, scom error) // // PLAT generated return codes. Additional details may be contained in // ReturnCode platData (this can only be looked at by PLAT code) // FAPI2_RC_PLAT_ERR_SEE_DATA = FAPI2_RC_PLAT_MASK | 0x01, ///< Generic platform error FAPI2_RC_PLAT_ERR_ADU_LOCKED = FAPI2_RC_PLAT_MASK | 0x02, ///< Operation to AlterDisplay unit failed because it is locked FAPI2_RC_PLAT_NOT_SUPPORTED_AT_RUNTIME = FAPI2_RC_PLAT_MASK | 0x03, ///< Operation not supported by HB runtime }; } #endif <|endoftext|>
<commit_before><commit_msg>Mean pT Analysis: Minor change in the class<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2014 Robert Kooima // // 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 "OVR_SDL2_app.hpp" //------------------------------------------------------------------------------ /// Initialize an OVR HMD and SDL2 window. OVR_SDL2_app::OVR_SDL2_app() : hmd(0), eye(ovrEye_Left), window(0) { if (init_OVR()) { running = init_SDL(hmd->WindowsPos.x, hmd->WindowsPos.y, hmd->Resolution.w, hmd->Resolution.h); conf_OVR(); } } /// Finalize the SDL and OVR. OVR_SDL2_app::~OVR_SDL2_app() { if (buffer[1]) delete buffer[1]; if (buffer[0]) delete buffer[0]; if (context) SDL_GL_DeleteContext(context); if (window) SDL_DestroyWindow(window); if (hmd) ovrHmd_Destroy(hmd); ovr_Shutdown(); } //------------------------------------------------------------------------------ /// Initialize an SDL window and GL context with the given position and size. bool OVR_SDL2_app::init_SDL(int x, int y, int w, int h) { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER) == 0) { int f = SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL; SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); if ((window = SDL_CreateWindow("OVR_SDL2", x, y, w, h, f))) { context = SDL_GL_CreateContext(window); SDL_GameControllerEventState(SDL_ENABLE); SDL_SetRelativeMouseMode(SDL_TRUE); #ifdef GLEW_VERSION glewExperimental = GL_TRUE; glewInit(); #endif return true; } } return false; } /// Initialize the Oculus SDK. /// /// Enable all tracking capability and fall back on a DK1 debug configuration /// if no HMD is available. bool OVR_SDL2_app::init_OVR() { ovr_Initialize(); hmd = ovrHmd_Create(0); if (hmd == 0) hmd = ovrHmd_CreateDebug(ovrHmd_DK1); if (hmd) ovrHmd_ConfigureTracking(hmd, ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position, 0); return true; } /// Configure the Oculus SDK renderer. /// /// This requires the presence of OpenGL state, so it much be performed AFTER /// the SDL window has been created. void OVR_SDL2_app::conf_OVR() { // Configure the renderer with all features. ovrGLConfig cfg; memset(&cfg, 0, sizeof (ovrGLConfig)); cfg.OGL.Header.API = ovrRenderAPI_OpenGL; cfg.OGL.Header.RTSize.w = hmd->Resolution.w; cfg.OGL.Header.RTSize.h = hmd->Resolution.h; ovrHmd_ConfigureRendering(hmd, &cfg.Config, ovrDistortionCap_Chromatic | ovrDistortionCap_TimeWarp | ovrDistortionCap_Overdrive, hmd->DefaultEyeFov, erd); // Initialize the off-screen render buffers. ovrSizei size[2]; size[0] = ovrHmd_GetFovTextureSize(hmd, ovrEye_Left, hmd->DefaultEyeFov[0], 1); size[1] = ovrHmd_GetFovTextureSize(hmd, ovrEye_Right, hmd->DefaultEyeFov[1], 1); for (int i = 0; i < 2; i++) { if ((buffer[i] = new framebuffer(size[i].w, size[i].h))) { ovrGLTexture *p = reinterpret_cast<ovrGLTexture*>(tex + i); p->OGL.Header.API = ovrRenderAPI_OpenGL; p->OGL.Header.TextureSize = size[i]; p->OGL.Header.RenderViewport.Size = size[i]; p->OGL.Header.RenderViewport.Pos.x = 0; p->OGL.Header.RenderViewport.Pos.y = 0; p->OGL.TexId = buffer[i]->color; } } } //------------------------------------------------------------------------------ /// Application main loop. void OVR_SDL2_app::run() { SDL_Event e; while (running) { // Dispatch all pending SDL events. while (SDL_PollEvent(&e)) dispatch(e); // Let the application animate. step(); // Render both views. Let the Oculus SDK display them on-screen. ovrHmd_BeginFrame(hmd, 0); { for (int i = 0; i < 2; i++) { eye = hmd->EyeRenderOrder[i]; pose[eye] = ovrHmd_GetEyePose(hmd, eye); buffer[eye]->bind(); draw(); } } ovrHmd_EndFrame(hmd, pose, tex); } } /// Dispatch an SDL event. void OVR_SDL2_app::dispatch(SDL_Event& e) { switch (e.type) { case SDL_KEYDOWN: keyboard(e.key.keysym.scancode, true, e.key.repeat); break; case SDL_KEYUP: keyboard(e.key.keysym.scancode, false, e.key.repeat); break; case SDL_MOUSEBUTTONDOWN: mouse_button(e.button.button, true); break; case SDL_MOUSEBUTTONUP: mouse_button(e.button.button, false); break; case SDL_MOUSEMOTION: mouse_motion(e.motion.xrel, e.motion.yrel); break; case SDL_MOUSEWHEEL: mouse_wheel(e.wheel.x, e.wheel.y); break; case SDL_CONTROLLERAXISMOTION: game_axis(e.caxis.which, e.caxis.axis, e.caxis.value / 32768.f); break; case SDL_CONTROLLERBUTTONDOWN: game_button(e.caxis.which, e.cbutton.button, true); break; case SDL_CONTROLLERBUTTONUP: game_button(e.caxis.which, e.cbutton.button, false); break; case SDL_CONTROLLERDEVICEADDED: game_connect(e.cdevice.which, true); break; case SDL_CONTROLLERDEVICEREMOVED: game_connect(e.cdevice.which, false); break; case SDL_QUIT: running = false; break; } } //------------------------------------------------------------------------------ /// Handle a key press or release. void OVR_SDL2_app::keyboard(int key, bool down, bool repeat) { dismiss_warning(); if (key == SDL_SCANCODE_ESCAPE && down == false) running = false; } /// Handle a mouse button press or release. void OVR_SDL2_app::mouse_button(int button, bool down) { dismiss_warning(); } /// Handle mouse wheel rotation. void OVR_SDL2_app::mouse_wheel(int dx, int dy) { } /// Handle mouse pointer motion. void OVR_SDL2_app::mouse_motion(int x, int y) { } /// Handle gamepad connection or disconnection void OVR_SDL2_app::game_connect(int device, bool connected) { controller.resize(device + 1); if (controller[device]) SDL_GameControllerClose(controller[device]); if (connected) controller[device] = SDL_GameControllerOpen(device); else controller[device] = 0; } /// Handle gamepad button press or release. void OVR_SDL2_app::game_button(int device, int button, bool down) { dismiss_warning(); } /// Handle gamepad axis motion. void OVR_SDL2_app::game_axis(int device, int axis, float value) { } //------------------------------------------------------------------------------ /// Convert an OVR matrix to a GLFundamentals matrix. static mat4 getMatrix4f(const OVR::Matrix4f& m) { return mat4(m.M[0][0], m.M[0][1], m.M[0][2], m.M[0][3], m.M[1][0], m.M[1][1], m.M[1][2], m.M[1][3], m.M[2][0], m.M[2][1], m.M[2][2], m.M[2][3], m.M[3][0], m.M[3][1], m.M[3][2], m.M[3][3]); } /// Return the current projection matrix. mat4 OVR_SDL2_app::projection() const { return getMatrix4f(ovrMatrix4f_Projection(erd[eye].Fov, 0.1f, 100.0f, true)); } /// Return the current view matrix. mat4 OVR_SDL2_app::view() const { OVR::Quatf q = OVR::Quatf(pose[eye].Orientation); mat4 O = getMatrix4f(OVR::Matrix4f(q.Inverted())); mat4 E = translation(vec3(erd[eye].ViewAdjust.x, erd[eye].ViewAdjust.y, erd[eye].ViewAdjust.z)); mat4 H = translation(vec3(-pose[eye].Position.x, -pose[eye].Position.y, -pose[eye].Position.z)); return E * O * H; } //------------------------------------------------------------------------------ void OVR_SDL2_app::dismiss_warning() { ovrHSWDisplayState state; ovrHmd_GetHSWDisplayState(hmd, &state); if (state.Displayed) ovrHmd_DismissHSWDisplay(hmd); } <commit_msg>App documentation<commit_after>// Copyright (c) 2014 Robert Kooima // // 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 "OVR_SDL2_app.hpp" //------------------------------------------------------------------------------ /// Initialize an OVR HMD and SDL2 window. OVR_SDL2_app::OVR_SDL2_app() : hmd(0), eye(ovrEye_Left), window(0) { if (init_OVR()) { running = init_SDL(hmd->WindowsPos.x, hmd->WindowsPos.y, hmd->Resolution.w, hmd->Resolution.h); conf_OVR(); } } /// Finalize the SDL and OVR. OVR_SDL2_app::~OVR_SDL2_app() { if (buffer[1]) delete buffer[1]; if (buffer[0]) delete buffer[0]; if (context) SDL_GL_DeleteContext(context); if (window) SDL_DestroyWindow(window); if (hmd) ovrHmd_Destroy(hmd); ovr_Shutdown(); } //------------------------------------------------------------------------------ /// Initialize an SDL window and GL context with the given position and size. bool OVR_SDL2_app::init_SDL(int x, int y, int w, int h) { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER) == 0) { int f = SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL; // Choose an OpenGL 3.2 Core Profile. This choice is arbitrary, and // and later version may be substituted. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // Configure 24-bit color and 24-bit depth. This is a common choice, // but may be altered as needed. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); // Create the window and initialize the OpenGL context. if ((window = SDL_CreateWindow("OVR_SDL2", x, y, w, h, f))) { context = SDL_GL_CreateContext(window); SDL_GameControllerEventState(SDL_ENABLE); #ifdef GLEW_VERSION glewExperimental = GL_TRUE; glewInit(); #endif return true; } } return false; } /// Initialize the Oculus SDK and return success. bool OVR_SDL2_app::init_OVR() { ovr_Initialize(); // Use the first connected HMD. hmd = ovrHmd_Create(0); // Fall back on a DK1 debug configuration if no HMD is available. if (hmd == 0) hmd = ovrHmd_CreateDebug(ovrHmd_DK1); // Enable all tracking capabilities on this HMD. if (hmd) ovrHmd_ConfigureTracking(hmd, ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position, 0); return (hmd != 0); } /// Configure the Oculus SDK renderer. This requires the presence of OpenGL /// state, so it much be performed AFTER the SDL window has been created. void OVR_SDL2_app::conf_OVR() { // Configure the renderer. Zeroing the configuration stucture causes all // display, window, and device specifications to take on current values // as put in place by SDL. This trick works cross-platform, freeing us // from dealing with any platform issues. ovrGLConfig cfg; memset(&cfg, 0, sizeof (ovrGLConfig)); cfg.OGL.Header.API = ovrRenderAPI_OpenGL; cfg.OGL.Header.RTSize.w = hmd->Resolution.w; cfg.OGL.Header.RTSize.h = hmd->Resolution.h; // Set the configuration and receive eye render descriptors in return. ovrHmd_ConfigureRendering(hmd, &cfg.Config, ovrDistortionCap_Chromatic | ovrDistortionCap_TimeWarp | ovrDistortionCap_Overdrive, hmd->DefaultEyeFov, erd); // Determine the buffer size required by each eye of the current HMD. ovrSizei size[2]; size[0] = ovrHmd_GetFovTextureSize(hmd, ovrEye_Left, hmd->DefaultEyeFov[0], 1); size[1] = ovrHmd_GetFovTextureSize(hmd, ovrEye_Right, hmd->DefaultEyeFov[1], 1); // Initialize the off-screen render buffers. We're using one buffer per-eye // instead of concatenating both eyes into a single buffer. for (int i = 0; i < 2; i++) { if ((buffer[i] = new framebuffer(size[i].w, size[i].h))) { ovrGLTexture *p = reinterpret_cast<ovrGLTexture*>(tex + i); memset(p, 0, sizeof (ovrGLTexture)); p->OGL.Header.API = ovrRenderAPI_OpenGL; p->OGL.Header.TextureSize = size[i]; p->OGL.Header.RenderViewport.Size = size[i]; p->OGL.TexId = buffer[i]->color; } } } //------------------------------------------------------------------------------ /// Application main loop. void OVR_SDL2_app::run() { SDL_Event e; while (running) { // Dispatch all pending SDL events. while (SDL_PollEvent(&e)) dispatch(e); // Let the application animate. step(); // Render both views and let the Oculus SDK display them on-screen. // 'eye' is a private member variable that notes which eye is being // rendered. This is used when the application calls back down to // learn the view and projection matrices. ovrHmd_BeginFrame(hmd, 0); { for (int i = 0; i < 2; i++) { eye = hmd->EyeRenderOrder[i]; pose[eye] = ovrHmd_GetEyePose(hmd, eye); buffer[eye]->bind(); draw(); } } ovrHmd_EndFrame(hmd, pose, tex); } } /// Dispatch an SDL event. void OVR_SDL2_app::dispatch(SDL_Event& e) { switch (e.type) { case SDL_KEYDOWN: keyboard(e.key.keysym.scancode, true, e.key.repeat); break; case SDL_KEYUP: keyboard(e.key.keysym.scancode, false, e.key.repeat); break; case SDL_MOUSEBUTTONDOWN: mouse_button(e.button.button, true); break; case SDL_MOUSEBUTTONUP: mouse_button(e.button.button, false); break; case SDL_MOUSEMOTION: mouse_motion(e.motion.xrel, e.motion.yrel); break; case SDL_MOUSEWHEEL: mouse_wheel(e.wheel.x, e.wheel.y); break; case SDL_CONTROLLERAXISMOTION: game_axis(e.caxis.which, e.caxis.axis, e.caxis.value / 32768.f); break; case SDL_CONTROLLERBUTTONDOWN: game_button(e.caxis.which, e.cbutton.button, true); break; case SDL_CONTROLLERBUTTONUP: game_button(e.caxis.which, e.cbutton.button, false); break; case SDL_CONTROLLERDEVICEADDED: game_connect(e.cdevice.which, true); break; case SDL_CONTROLLERDEVICEREMOVED: game_connect(e.cdevice.which, false); break; case SDL_QUIT: running = false; break; } } //------------------------------------------------------------------------------ /// Handle a key press or release. void OVR_SDL2_app::keyboard(int key, bool down, bool repeat) { dismiss_warning(); if (key == SDL_SCANCODE_ESCAPE && down == false) running = false; } /// Handle a mouse button press or release. void OVR_SDL2_app::mouse_button(int button, bool down) { dismiss_warning(); } /// Handle mouse wheel rotation. void OVR_SDL2_app::mouse_wheel(int dx, int dy) { } /// Handle mouse pointer motion. void OVR_SDL2_app::mouse_motion(int x, int y) { } /// Handle gamepad connection or disconnection void OVR_SDL2_app::game_connect(int device, bool connected) { controller.resize(device + 1); if (controller[device]) SDL_GameControllerClose(controller[device]); if (connected) controller[device] = SDL_GameControllerOpen(device); else controller[device] = 0; } /// Handle gamepad button press or release. void OVR_SDL2_app::game_button(int device, int button, bool down) { dismiss_warning(); } /// Handle gamepad axis motion. void OVR_SDL2_app::game_axis(int device, int axis, float value) { } //------------------------------------------------------------------------------ /// Convert an OVR matrix to a GLFundamentals matrix. static mat4 getMatrix4f(const OVR::Matrix4f& m) { return mat4(m.M[0][0], m.M[0][1], m.M[0][2], m.M[0][3], m.M[1][0], m.M[1][1], m.M[1][2], m.M[1][3], m.M[2][0], m.M[2][1], m.M[2][2], m.M[2][3], m.M[3][0], m.M[3][1], m.M[3][2], m.M[3][3]); } /// Return the current projection matrix as determined by the current OVR eye /// render descriptor. mat4 OVR_SDL2_app::projection() const { return getMatrix4f(ovrMatrix4f_Projection(erd[eye].Fov, 0.1f, 100.0f, true)); } /// Return the current view matrix as determined by the current OVR eye render /// descriptor and head pose. mat4 OVR_SDL2_app::view() const { // Orientation of the head OVR::Quatf q = OVR::Quatf(pose[eye].Orientation); mat4 O = getMatrix4f(OVR::Matrix4f(q.Inverted())); // Offset of the eye from the center of the head mat4 E = translation(vec3(erd[eye].ViewAdjust.x, erd[eye].ViewAdjust.y, erd[eye].ViewAdjust.z)); // Offset of the head from the center of the world mat4 P = translation(vec3(-pose[eye].Position.x, -pose[eye].Position.y, -pose[eye].Position.z)); return E * O * P; } //------------------------------------------------------------------------------ /// Check if the OVR health & safety warning is visible and try to dismiss it. void OVR_SDL2_app::dismiss_warning() { ovrHSWDisplayState state; ovrHmd_GetHSWDisplayState(hmd, &state); if (state.Displayed) ovrHmd_DismissHSWDisplay(hmd); } <|endoftext|>
<commit_before>#pragma once #include <stdint.h> #include <algorithm> #include <cstring> #include <iterator> struct can_Message_t { uint32_t id = 0x000; // 11-bit max is 0x7ff, 29-bit max is 0x1FFFFFFF bool isExt = false; bool rtr = false; uint8_t len = 8; uint8_t buf[8] = {0, 0, 0, 0, 0, 0, 0, 0}; } ; struct can_Signal_t { const uint8_t startBit; const uint8_t length; const bool isIntel; const float factor; const float offset; }; #include <iterator> template <typename T> T can_getSignal(can_Message_t msg, const uint8_t startBit, const uint8_t length, const bool isIntel) { uint64_t tempVal = 0; uint64_t mask = (1ULL << length) - 1; if (isIntel) { std::memcpy(&tempVal, msg.buf, sizeof(tempVal)); tempVal = (tempVal >> startBit) & mask; } else { std::reverse(std::begin(msg.buf), std::end(msg.buf)); std::memcpy(&tempVal, msg.buf, sizeof(tempVal)); tempVal = (tempVal >> (64 - startBit - length)) & mask; } T retVal; std::memcpy(&retVal, &tempVal, sizeof(T)); return retVal; } template <typename T> void can_setSignal(can_Message_t& msg, const T& val, const uint8_t startBit, const uint8_t length, const bool isIntel) { uint64_t valAsBits = 0; std::memcpy(&valAsBits, &val, sizeof(val)); uint64_t mask = (1ULL << length) - 1; if (isIntel) { uint64_t data = 0; std::memcpy(&data, msg.buf, sizeof(data)); data &= ~(mask << startBit); data |= valAsBits << startBit; std::memcpy(msg.buf, &data, sizeof(data)); } else { uint64_t data = 0; std::reverse(std::begin(msg.buf), std::end(msg.buf)); std::memcpy(&data, msg.buf, sizeof(data)); data &= ~(mask << (64 - startBit - length)); data |= valAsBits << (64 - startBit - length); std::memcpy(msg.buf, &data, sizeof(data)); std::reverse(std::begin(msg.buf), std::end(msg.buf)); } } template<typename T> void can_setSignal(can_Message_t& msg, const T& val, const uint8_t startBit, const uint8_t length, const bool isIntel, const float factor, const float offset) { T scaledVal = static_cast<T>((val - offset) / factor); can_setSignal<T>(msg, scaledVal, startBit, length, isIntel); } template<typename T> float can_getSignal(can_Message_t msg, const uint8_t startBit, const uint8_t length, const bool isIntel, const float factor, const float offset) { T retVal = can_getSignal<T>(msg, startBit, length, isIntel); return (retVal * factor) + offset; } template <typename T> float can_getSignal(can_Message_t msg, const can_Signal_t& signal) { return can_getSignal<T>(msg, signal.startBit, signal.length, signal.isIntel, signal.factor, signal.offset); } template <typename T> void can_setSignal(can_Message_t& msg, const T& val, const can_Signal_t& signal) { can_setSignal(msg, val, signal.startBit, signal.length, signal.isIntel, signal.factor, signal.offset); }<commit_msg>Protect against bad bitshifts<commit_after>#pragma once #include <stdint.h> #include <algorithm> #include <cstring> #include <iterator> struct can_Message_t { uint32_t id = 0x000; // 11-bit max is 0x7ff, 29-bit max is 0x1FFFFFFF bool isExt = false; bool rtr = false; uint8_t len = 8; uint8_t buf[8] = {0, 0, 0, 0, 0, 0, 0, 0}; } ; struct can_Signal_t { const uint8_t startBit; const uint8_t length; const bool isIntel; const float factor; const float offset; }; #include <iterator> template <typename T> constexpr T can_getSignal(can_Message_t msg, const uint8_t startBit, const uint8_t length, const bool isIntel) { uint64_t tempVal = 0; uint64_t mask = length < 64 ? (1ULL << length) - 1ULL : -1ULL; if (isIntel) { std::memcpy(&tempVal, msg.buf, sizeof(tempVal)); tempVal = (tempVal >> startBit) & mask; } else { std::reverse(std::begin(msg.buf), std::end(msg.buf)); std::memcpy(&tempVal, msg.buf, sizeof(tempVal)); tempVal = (tempVal >> (64 - startBit - length)) & mask; } T retVal; std::memcpy(&retVal, &tempVal, sizeof(T)); return retVal; } template <typename T> constexpr void can_setSignal(can_Message_t& msg, const T& val, const uint8_t startBit, const uint8_t length, const bool isIntel) { uint64_t valAsBits = 0; std::memcpy(&valAsBits, &val, sizeof(val)); uint64_t mask = length < 64 ? (1ULL << length) - 1ULL : -1ULL; if (isIntel) { uint64_t data = 0; std::memcpy(&data, msg.buf, sizeof(data)); data &= ~(mask << startBit); data |= valAsBits << startBit; std::memcpy(msg.buf, &data, sizeof(data)); } else { uint64_t data = 0; std::reverse(std::begin(msg.buf), std::end(msg.buf)); std::memcpy(&data, msg.buf, sizeof(data)); data &= ~(mask << (64 - startBit - length)); data |= valAsBits << (64 - startBit - length); std::memcpy(msg.buf, &data, sizeof(data)); std::reverse(std::begin(msg.buf), std::end(msg.buf)); } } template<typename T> void can_setSignal(can_Message_t& msg, const T& val, const uint8_t startBit, const uint8_t length, const bool isIntel, const float factor, const float offset) { T scaledVal = static_cast<T>((val - offset) / factor); can_setSignal<T>(msg, scaledVal, startBit, length, isIntel); } template<typename T> float can_getSignal(can_Message_t msg, const uint8_t startBit, const uint8_t length, const bool isIntel, const float factor, const float offset) { T retVal = can_getSignal<T>(msg, startBit, length, isIntel); return (retVal * factor) + offset; } template <typename T> float can_getSignal(can_Message_t msg, const can_Signal_t& signal) { return can_getSignal<T>(msg, signal.startBit, signal.length, signal.isIntel, signal.factor, signal.offset); } template <typename T> void can_setSignal(can_Message_t& msg, const T& val, const can_Signal_t& signal) { can_setSignal(msg, val, signal.startBit, signal.length, signal.isIntel, signal.factor, signal.offset); }<|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <sys/stat.h> # include <unistd.h> # include <glib-2.0/glib.h> # include <glib-2.0/gio/gio.h> # include <filesystem> # include <Siv3D/String.hpp> # include <Siv3D/FileSystem.hpp> # include <Siv3D/EnvironmentVariable.hpp> # include <Siv3D/INI.hpp> namespace s3d { namespace fs = std::filesystem; namespace detail { [[nodiscard]] static fs::path ToPath(const FilePathView path) { return fs::path(path.toUTF8()); } [[nodiscard]] static fs::file_status GetStatus(const FilePathView path) { return fs::status(detail::ToPath(path)); } [[nodiscard]] static bool GetStat(const FilePathView path, struct stat& s) { return (::stat(FilePath(path).replaced(U'\\', U'/').narrow().c_str(), &s) == 0); } [[nodiscard]] static bool Exists(const FilePathView path) { struct stat s; return GetStat(path, s); } [[nodiscard]] static bool IsRegular(const FilePathView path) { struct stat s; if (!GetStat(path, s)) { return false; } return S_ISREG(s.st_mode); } [[nodiscard]] static bool IsDirectory(const FilePathView path) { struct stat s; if (!GetStat(path, s)) { return false; } return S_ISDIR(s.st_mode); } [[nodiscard]] static FilePath NormalizePath(FilePath path, const bool skipDirectoryCheck = false) { path.replace(U'\\', U'/'); if (!path.ends_with(U'/') && (skipDirectoryCheck || (GetStatus(path).type() == fs::file_type::directory))) { path.push_back(U'/'); } return path; } [[nodiscard]] static DateTime ToDateTime(const ::timespec& tv) { ::tm lt; ::localtime_r(&tv.tv_sec, &lt); return{ (1900 + lt.tm_year), (1 + lt.tm_mon), (lt.tm_mday), lt.tm_hour, lt.tm_min, lt.tm_sec, static_cast<int32>(tv.tv_nsec / (1'000'000))}; } [[nodiscard]] inline constexpr std::filesystem::copy_options ToCopyOptions(const CopyOption copyOption) noexcept { switch (copyOption) { case CopyOption::SkipExisting: return fs::copy_options::skip_existing; case CopyOption::OverwriteExisting: return fs::copy_options::overwrite_existing; case CopyOption::UpdateExisting: return fs::copy_options::update_existing; default: return fs::copy_options::none; } } [[nodiscard]] static bool Linux_TrashFile(const char* path) { GFile* gf = g_file_new_for_path(path); GError* ge; gboolean ret = g_file_trash(gf, nullptr, &ge); if (ge) { g_error_free(ge); } g_object_unref(gf); if(!ret) { return false; } return true; } [[nodiscard]] FilePath AddSlash(FilePath path) { if (path.ends_with(U'/')) { return path; } return path + U'/'; } namespace init { const static FilePath g_initialPath = NormalizePath(Unicode::Widen(fs::current_path().string())); static FilePath g_modulePath; void InitModulePath(const char* arg) { g_modulePath = Unicode::Widen(arg); } const static std::array<FilePath, 11> g_specialFolderPaths = []() { std::array<FilePath, 11> specialFolderPaths; specialFolderPaths[FromEnum(SpecialFolder::ProgramFiles)] = U"/usr/"; specialFolderPaths[FromEnum(SpecialFolder::LocalAppData)] = U"/var/cache/"; specialFolderPaths[FromEnum(SpecialFolder::SystemFonts)] = U"/usr/share/fonts/"; const FilePath homeDirectory = EnvironmentVariable::Get(U"HOME"); if (not homeDirectory) { return specialFolderPaths; } if (const FilePath localCacheDirectory = homeDirectory + U"/.cache/"; FileSystem::Exists(localCacheDirectory)) { specialFolderPaths[FromEnum(SpecialFolder::LocalAppData)] = localCacheDirectory; } if (const FilePath localFontDirectory = homeDirectory + U"/usr/local/share/fonts/"; FileSystem::Exists(localFontDirectory)) { specialFolderPaths[FromEnum(SpecialFolder::LocalFonts)] = localFontDirectory; specialFolderPaths[FromEnum(SpecialFolder::UserFonts)] = localFontDirectory; } specialFolderPaths[FromEnum(SpecialFolder::UserProfile)] = (homeDirectory + U'/'); const FilePath iniFilePath = homeDirectory + U"/.config/user-dirs.dirs"; if (not FileSystem::Exists(iniFilePath)) { return specialFolderPaths; } const INI ini(iniFilePath); specialFolderPaths[FromEnum(SpecialFolder::Desktop)] = AddSlash(ini[U"XDG_DESKTOP_DIR"].removed(U'\"').replaced(U"$HOME", homeDirectory)); specialFolderPaths[FromEnum(SpecialFolder::Documents)] = AddSlash(ini[U"XDG_DOCUMENTS_DIR"].removed(U'\"').replaced(U"$HOME", homeDirectory)); specialFolderPaths[FromEnum(SpecialFolder::Music)] = AddSlash(ini[U"XDG_MUSIC_DIR"].removed(U'\"').replaced(U"$HOME", homeDirectory)); specialFolderPaths[FromEnum(SpecialFolder::Pictures)] = AddSlash(ini[U"XDG_PICTURES_DIR"].removed(U'\"').replaced(U"$HOME", homeDirectory)); specialFolderPaths[FromEnum(SpecialFolder::Videos)] = AddSlash(ini[U"XDG_VIDEOS_DIR"].removed(U'\"').replaced(U"$HOME", homeDirectory)); return specialFolderPaths; }(); const static Array<FilePath> g_resourceFilePaths = []() { Array<FilePath> paths = FileSystem::DirectoryContents(U"resources/", true); paths.remove_if(FileSystem::IsDirectory); paths.sort(); return paths; }(); const Array<FilePath>& GetResourceFilePaths() noexcept { return g_resourceFilePaths; } } } namespace FileSystem { bool IsResourcePath(const FilePathView path) noexcept { const FilePath resourceDirectory = FileSystem::ModulePath() + U"/resources/"; return FullPath(path).starts_with(resourceDirectory); } bool Exists(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return false; } return detail::Exists(path); } bool IsDirectory(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return false; } return detail::IsDirectory(path); } bool IsFile(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return false; } return detail::IsRegular(path); } bool IsResource(const FilePathView path) { return IsResourcePath(path) && detail::Exists(path); } FilePath FullPath(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return FilePath{}; } if (path.includes(U'/')) { return detail::NormalizePath(Unicode::Widen(fs::weakly_canonical(detail::ToPath(path)).string())); } else { return detail::NormalizePath(Unicode::Widen(fs::weakly_canonical(detail::ToPath(U"./" + path)).string())); } } Platform::NativeFilePath NativePath(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return Platform::NativeFilePath{}; } return fs::weakly_canonical(detail::ToPath(path)).string(); } FilePath VolumePath(const FilePathView) { return U"/"; } bool IsEmptyDirectory(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return false; } struct stat s; if (!detail::GetStat(path, s)) { return false; } if (S_ISDIR(s.st_mode)) { return (fs::directory_iterator(fs::path(path.toUTF8())) == fs::directory_iterator()); } else { return false; } } int64 Size(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return 0; } struct stat s; if (!detail::GetStat(FilePath(path), s)) { return 0; } if (S_ISREG(s.st_mode)) { return s.st_size; } else if (S_ISDIR(s.st_mode)) { int64 result = 0; for (const auto& v : fs::recursive_directory_iterator(path.narrow())) { struct stat s; if (::stat(v.path().c_str(), &s) != 0 || S_ISDIR(s.st_mode)) { continue; } result += s.st_size; } return result; } else { return 0; } } int64 FileSize(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return 0; } struct stat s; if (!detail::GetStat(path, s)) { return 0; } if (!S_ISREG(s.st_mode)) { return 0; } return s.st_size; } Optional<DateTime> CreationTime(const FilePathView path) { struct stat s; if (!detail::GetStat(path, s)) { return none; } return detail::ToDateTime(s.st_ctim); } Optional<DateTime> WriteTime(const FilePathView path) { struct stat s; if (!detail::GetStat(path, s)) { return none; } return detail::ToDateTime(s.st_mtim); } Optional<DateTime> AccessTime(const FilePathView path) { struct stat s; if (!detail::GetStat(path, s)) { return none; } return detail::ToDateTime(s.st_atim); } Array<FilePath> DirectoryContents(const FilePathView path, const bool recursive) { Array<FilePath> paths; if (not path) SIV3D_UNLIKELY { return paths; } if (detail::GetStatus(path).type() != fs::file_type::directory) { return paths; } if (recursive) { for (const auto& v : fs::recursive_directory_iterator(path.narrow())) { paths.push_back(detail::NormalizePath(Unicode::Widen(fs::weakly_canonical(v.path()).string()))); } } else { for (const auto& v : fs::directory_iterator(path.narrow())) { paths.push_back(detail::NormalizePath(Unicode::Widen(fs::weakly_canonical(v.path()).string()))); } } return paths; } const FilePath& InitialDirectory() noexcept { return detail::init::g_initialPath; } const FilePath& ModulePath() noexcept { return detail::init::g_modulePath; } FilePath CurrentDirectory() { return detail::NormalizePath(Unicode::Widen(fs::current_path().string())); } bool ChangeCurrentDirectory(const FilePathView path) { if (not IsDirectory(path)) { return false; } return (chdir(path.narrow().c_str()) == 0); } const FilePath& GetFolderPath(const SpecialFolder folder) { assert(FromEnum(folder) < static_cast<int32>(std::size(detail::init::g_specialFolderPaths))); return detail::init::g_specialFolderPaths[FromEnum(folder)]; } bool CreateDirectories(const FilePathView path) { if (not path) { return false; } if (IsResourcePath(path)) { return false; } try { fs::create_directories(detail::ToPath(path)); return true; } catch (const fs::filesystem_error&) { return false; } } bool CreateParentDirectories(const FilePathView path) { if (not path) { return false; } if (IsResourcePath(path)) { return false; } const FilePath parentDirectory = ParentPath(FullPath(path)); if (not Exists(parentDirectory)) { return CreateDirectories(parentDirectory); } return true; } bool Copy(const FilePathView from, const FilePathView to, const CopyOption copyOption) { if ((not from) || (not to)) { return false; } if (IsResourcePath(from) || IsResourcePath(to)) { return false; } CreateParentDirectories(to); const auto options = detail::ToCopyOptions(copyOption) | fs::copy_options::recursive; std::error_code error; fs::copy(detail::ToPath(from), detail::ToPath(to), options, error); return (error.value() == 0); } bool Remove(const FilePathView path, const bool allowUndo) { if (not path) { return false; } if (IsResourcePath(path)) { return false; } if (!allowUndo) { try { fs::remove_all(detail::ToPath(path)); return true; } catch (const fs::filesystem_error&) { return false; } } return detail::Linux_TrashFile(path.narrow().c_str()); } } } <commit_msg>[Linux] fix<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <sys/stat.h> # include <unistd.h> # include <glib-2.0/glib.h> # include <glib-2.0/gio/gio.h> # include <filesystem> # include <Siv3D/String.hpp> # include <Siv3D/FileSystem.hpp> # include <Siv3D/EnvironmentVariable.hpp> # include <Siv3D/INI.hpp> namespace s3d { namespace fs = std::filesystem; namespace detail { [[nodiscard]] static fs::path ToPath(const FilePathView path) { return fs::path(path.toUTF8()); } [[nodiscard]] static fs::file_status GetStatus(const FilePathView path) { return fs::status(detail::ToPath(path)); } [[nodiscard]] static bool GetStat(const FilePathView path, struct stat& s) { return (::stat(FilePath(path).replaced(U'\\', U'/').narrow().c_str(), &s) == 0); } [[nodiscard]] static bool Exists(const FilePathView path) { struct stat s; return GetStat(path, s); } [[nodiscard]] static bool IsRegular(const FilePathView path) { struct stat s; if (!GetStat(path, s)) { return false; } return S_ISREG(s.st_mode); } [[nodiscard]] static bool IsDirectory(const FilePathView path) { struct stat s; if (!GetStat(path, s)) { return false; } return S_ISDIR(s.st_mode); } [[nodiscard]] static FilePath NormalizePath(FilePath path, const bool skipDirectoryCheck = false) { path.replace(U'\\', U'/'); if (!path.ends_with(U'/') && (skipDirectoryCheck || (GetStatus(path).type() == fs::file_type::directory))) { path.push_back(U'/'); } return path; } [[nodiscard]] static DateTime ToDateTime(const ::timespec& tv) { ::tm lt; ::localtime_r(&tv.tv_sec, &lt); return{ (1900 + lt.tm_year), (1 + lt.tm_mon), (lt.tm_mday), lt.tm_hour, lt.tm_min, lt.tm_sec, static_cast<int32>(tv.tv_nsec / (1'000'000))}; } [[nodiscard]] inline constexpr std::filesystem::copy_options ToCopyOptions(const CopyOption copyOption) noexcept { switch (copyOption) { case CopyOption::SkipExisting: return fs::copy_options::skip_existing; case CopyOption::OverwriteExisting: return fs::copy_options::overwrite_existing; case CopyOption::UpdateExisting: return fs::copy_options::update_existing; default: return fs::copy_options::none; } } [[nodiscard]] static bool Linux_TrashFile(const char* path) { GFile* gf = g_file_new_for_path(path); GError* ge; gboolean ret = g_file_trash(gf, nullptr, &ge); if (ge) { g_error_free(ge); } g_object_unref(gf); if(!ret) { return false; } return true; } [[nodiscard]] FilePath AddSlash(FilePath path) { if (path.ends_with(U'/')) { return path; } return path + U'/'; } namespace init { const static FilePath g_initialPath = NormalizePath(Unicode::Widen(fs::current_path().string())); static FilePath g_modulePath; void InitModulePath(const char* arg) { g_modulePath = Unicode::Widen(arg); } const static std::array<FilePath, 11> g_specialFolderPaths = []() { std::array<FilePath, 11> specialFolderPaths; specialFolderPaths[FromEnum(SpecialFolder::ProgramFiles)] = U"/usr/"; specialFolderPaths[FromEnum(SpecialFolder::LocalAppData)] = U"/var/cache/"; specialFolderPaths[FromEnum(SpecialFolder::SystemFonts)] = U"/usr/share/fonts/"; const FilePath homeDirectory = EnvironmentVariable::Get(U"HOME"); if (not homeDirectory) { return specialFolderPaths; } if (const FilePath localCacheDirectory = EnvironmentVariable::Get(U"XDG_CACHE_HOME")) { specialFolderPaths[FromEnum(SpecialFolder::LocalAppData)] = (localCacheDirectory + U'/'); } else { specialFolderPaths[FromEnum(SpecialFolder::LocalAppData)] = (homeDirectory + U"/.cache/"); } if (const FilePath localFontDirectory = homeDirectory + U"/usr/local/share/fonts/"; FileSystem::Exists(localFontDirectory)) { specialFolderPaths[FromEnum(SpecialFolder::LocalFonts)] = localFontDirectory; specialFolderPaths[FromEnum(SpecialFolder::UserFonts)] = localFontDirectory; } specialFolderPaths[FromEnum(SpecialFolder::UserProfile)] = (homeDirectory + U'/'); const FilePath iniFilePath = homeDirectory + U"/.config/user-dirs.dirs"; if (not FileSystem::Exists(iniFilePath)) { return specialFolderPaths; } const INI ini(iniFilePath); specialFolderPaths[FromEnum(SpecialFolder::Desktop)] = AddSlash(ini[U"XDG_DESKTOP_DIR"].removed(U'\"').replaced(U"$HOME", homeDirectory)); specialFolderPaths[FromEnum(SpecialFolder::Documents)] = AddSlash(ini[U"XDG_DOCUMENTS_DIR"].removed(U'\"').replaced(U"$HOME", homeDirectory)); specialFolderPaths[FromEnum(SpecialFolder::Music)] = AddSlash(ini[U"XDG_MUSIC_DIR"].removed(U'\"').replaced(U"$HOME", homeDirectory)); specialFolderPaths[FromEnum(SpecialFolder::Pictures)] = AddSlash(ini[U"XDG_PICTURES_DIR"].removed(U'\"').replaced(U"$HOME", homeDirectory)); specialFolderPaths[FromEnum(SpecialFolder::Videos)] = AddSlash(ini[U"XDG_VIDEOS_DIR"].removed(U'\"').replaced(U"$HOME", homeDirectory)); return specialFolderPaths; }(); const static Array<FilePath> g_resourceFilePaths = []() { Array<FilePath> paths = FileSystem::DirectoryContents(U"resources/", true); paths.remove_if(FileSystem::IsDirectory); paths.sort(); return paths; }(); const Array<FilePath>& GetResourceFilePaths() noexcept { return g_resourceFilePaths; } } } namespace FileSystem { bool IsResourcePath(const FilePathView path) noexcept { const FilePath resourceDirectory = FileSystem::ModulePath() + U"/resources/"; return FullPath(path).starts_with(resourceDirectory); } bool Exists(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return false; } return detail::Exists(path); } bool IsDirectory(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return false; } return detail::IsDirectory(path); } bool IsFile(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return false; } return detail::IsRegular(path); } bool IsResource(const FilePathView path) { return IsResourcePath(path) && detail::Exists(path); } FilePath FullPath(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return FilePath{}; } if (path.includes(U'/')) { return detail::NormalizePath(Unicode::Widen(fs::weakly_canonical(detail::ToPath(path)).string())); } else { return detail::NormalizePath(Unicode::Widen(fs::weakly_canonical(detail::ToPath(U"./" + path)).string())); } } Platform::NativeFilePath NativePath(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return Platform::NativeFilePath{}; } return fs::weakly_canonical(detail::ToPath(path)).string(); } FilePath VolumePath(const FilePathView) { return U"/"; } bool IsEmptyDirectory(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return false; } struct stat s; if (!detail::GetStat(path, s)) { return false; } if (S_ISDIR(s.st_mode)) { return (fs::directory_iterator(fs::path(path.toUTF8())) == fs::directory_iterator()); } else { return false; } } int64 Size(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return 0; } struct stat s; if (!detail::GetStat(FilePath(path), s)) { return 0; } if (S_ISREG(s.st_mode)) { return s.st_size; } else if (S_ISDIR(s.st_mode)) { int64 result = 0; for (const auto& v : fs::recursive_directory_iterator(path.narrow())) { struct stat s; if (::stat(v.path().c_str(), &s) != 0 || S_ISDIR(s.st_mode)) { continue; } result += s.st_size; } return result; } else { return 0; } } int64 FileSize(const FilePathView path) { if (not path) SIV3D_UNLIKELY { return 0; } struct stat s; if (!detail::GetStat(path, s)) { return 0; } if (!S_ISREG(s.st_mode)) { return 0; } return s.st_size; } Optional<DateTime> CreationTime(const FilePathView path) { struct stat s; if (!detail::GetStat(path, s)) { return none; } return detail::ToDateTime(s.st_ctim); } Optional<DateTime> WriteTime(const FilePathView path) { struct stat s; if (!detail::GetStat(path, s)) { return none; } return detail::ToDateTime(s.st_mtim); } Optional<DateTime> AccessTime(const FilePathView path) { struct stat s; if (!detail::GetStat(path, s)) { return none; } return detail::ToDateTime(s.st_atim); } Array<FilePath> DirectoryContents(const FilePathView path, const bool recursive) { Array<FilePath> paths; if (not path) SIV3D_UNLIKELY { return paths; } if (detail::GetStatus(path).type() != fs::file_type::directory) { return paths; } if (recursive) { for (const auto& v : fs::recursive_directory_iterator(path.narrow())) { paths.push_back(detail::NormalizePath(Unicode::Widen(fs::weakly_canonical(v.path()).string()))); } } else { for (const auto& v : fs::directory_iterator(path.narrow())) { paths.push_back(detail::NormalizePath(Unicode::Widen(fs::weakly_canonical(v.path()).string()))); } } return paths; } const FilePath& InitialDirectory() noexcept { return detail::init::g_initialPath; } const FilePath& ModulePath() noexcept { return detail::init::g_modulePath; } FilePath CurrentDirectory() { return detail::NormalizePath(Unicode::Widen(fs::current_path().string())); } bool ChangeCurrentDirectory(const FilePathView path) { if (not IsDirectory(path)) { return false; } return (chdir(path.narrow().c_str()) == 0); } const FilePath& GetFolderPath(const SpecialFolder folder) { assert(FromEnum(folder) < static_cast<int32>(std::size(detail::init::g_specialFolderPaths))); return detail::init::g_specialFolderPaths[FromEnum(folder)]; } bool CreateDirectories(const FilePathView path) { if (not path) { return false; } if (IsResourcePath(path)) { return false; } try { fs::create_directories(detail::ToPath(path)); return true; } catch (const fs::filesystem_error&) { return false; } } bool CreateParentDirectories(const FilePathView path) { if (not path) { return false; } if (IsResourcePath(path)) { return false; } const FilePath parentDirectory = ParentPath(FullPath(path)); if (not Exists(parentDirectory)) { return CreateDirectories(parentDirectory); } return true; } bool Copy(const FilePathView from, const FilePathView to, const CopyOption copyOption) { if ((not from) || (not to)) { return false; } if (IsResourcePath(from) || IsResourcePath(to)) { return false; } CreateParentDirectories(to); const auto options = detail::ToCopyOptions(copyOption) | fs::copy_options::recursive; std::error_code error; fs::copy(detail::ToPath(from), detail::ToPath(to), options, error); return (error.value() == 0); } bool Remove(const FilePathView path, const bool allowUndo) { if (not path) { return false; } if (IsResourcePath(path)) { return false; } if (!allowUndo) { try { fs::remove_all(detail::ToPath(path)); return true; } catch (const fs::filesystem_error&) { return false; } } return detail::Linux_TrashFile(path.narrow().c_str()); } } } <|endoftext|>
<commit_before>#ifndef MEMBERDELEGATE_HPP # define MEMBERDELEGATE_HPP # pragma once #include <type_traits> namespace generic { #ifndef DELEGATE # define DELEGATE(f) decltype(&f),&f #endif // DELEGATE namespace detail { template <typename T> constexpr auto address(T&& t) -> typename ::std::remove_reference<T>::type* { return &t; } template <typename FP, FP fp, class C, typename ...A> struct S { static constexpr auto* l = false ? address([](C* const object) noexcept { return [object](A&& ...args) { return (object->*fp)(::std::forward<A>(args)...); }; }) : nullptr; }; template <typename FP, FP fp, typename R, class C, typename ...A> auto make_delegate(C* const object, R (C::* const)(A...)) -> decltype((*decltype(S<FP, fp, C, A...>::l)(nullptr))(object)) { return (*decltype(S<FP, fp, C, A...>::l)(nullptr))(object); } } template <typename FP, FP fp, class C> auto make_delegate(C* const object) -> decltype(detail::make_delegate<FP, fp>(object, fp)) { return detail::make_delegate<FP, fp>(object, fp); } } #endif // MEMBERDELEGATE_HPP <commit_msg>some fixes<commit_after>#ifndef MEMBERDELEGATE_HPP # define MEMBERDELEGATE_HPP # pragma once #include <type_traits> namespace generic { #ifndef DELEGATE # define DELEGATE(f) decltype(&f),&f #endif // DELEGATE namespace detail { template <typename T> auto address(T&& t) -> typename ::std::remove_reference<T>::type* { return &t; } template <typename FP, FP fp, class C, typename ...A> struct S { static constexpr auto* l = false ? address([](C* const object) noexcept { return [object](A&& ...args) { return (object->*fp)(::std::forward<A>(args)...); }; }) : nullptr; }; template <typename FP, FP fp, typename R, class C, typename ...A> auto make_delegate(C* const object, R (C::* const)(A...)) -> decltype((*decltype(S<FP, fp, C, A...>::l)(nullptr))(object)) { return (*decltype(S<FP, fp, C, A...>::l)(nullptr))(object); } } template <typename FP, FP fp, class C> auto make_delegate(C* const object) -> decltype(detail::make_delegate<FP, fp>(object, fp)) { return detail::make_delegate<FP, fp>(object, fp); } } #endif // MEMBERDELEGATE_HPP <|endoftext|>
<commit_before>/******************************************************************************* * c7a/api/reduce_node.hpp * * DIANode for a reduce operation. Performs the actual reduce operation * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_REDUCE_NODE_HEADER #define C7A_API_REDUCE_NODE_HEADER #include <c7a/api/dop_node.hpp> #include <c7a/api/context.hpp> #include <c7a/api/function_stack.hpp> #include <c7a/common/logger.hpp> #include <c7a/core/reduce_pre_table.hpp> #include <c7a/core/reduce_post_table.hpp> #include <unordered_map> #include <functional> #include <string> #include <vector> namespace c7a { //! \addtogroup api Interface //! \{ /*! * A DIANode which performs a Reduce operation. Reduce groups the elements in a * DIA by their key and reduces every key bucket to a single element each. The * ReduceNode stores the key_extractor and the reduce_function UDFs. The * chainable LOps ahead of the Reduce operation are stored in the Stack. The * ReduceNode has the type Output, which is the result type of the * reduce_function. * * \tparam Input Input type of the Reduce operation * \tparam Output Output type of the Reduce operation * \tparam Stack Function stack, which contains the chained lambdas between the last and this DIANode. * \tparam KeyExtractor Type of the key_extractor function. * \tparam ReduceFunction Type of the reduce_function */ template <typename Input, typename Output, typename Stack, typename KeyExtractor, typename ReduceFunction> class ReduceNode : public DOpNode<Output> { static const bool debug = true; typedef DOpNode<Output> Super; using reduce_arg_t = typename FunctionTraits<ReduceFunction>::template arg<0>; using Super::context_; using Super::data_id_; public: /*! * Constructor for a ReduceNode. Sets the DataManager, parent, stack, * key_extractor and reduce_function. * * \param ctx Reference to Context, which holds references to data and network. * \param parent Parent DIANode. * \param stack Function chain with all lambdas between the parent and this node * \param key_extractor Key extractor function * \param reduce_function Reduce function */ ReduceNode(Context& ctx, DIANode<Input>* parent, Stack& stack, KeyExtractor key_extractor, ReduceFunction reduce_function) : DOpNode<Output>(ctx, { parent }), local_stack_(stack), key_extractor_(key_extractor), reduce_function_(reduce_function), elements_() { // Hook PreOp auto pre_op_fn = [=](reduce_arg_t input) { PreOp(input); }; auto lop_chain = local_stack_.push(pre_op_fn).emit(); parent->RegisterChild(lop_chain); } //! Virtual destructor for a ReduceNode. virtual ~ReduceNode() { } /*! * Actually executes the reduce operation. Uses the member functions PreOp, * MainOp and PostOp. */ void execute() override { MainOp(); // get data from data manager data::BlockIterator<Output> it = context_.get_data_manager().template GetLocalBlocks<Output>(data_id_); // loop over input while (it.HasNext()) { const Output& item = it.Next(); for (auto func : DIANode<Output>::callbacks_) { func(item); } } } /*! * Produces a function stack, which only contains the PostOp function. * \return PostOp function stack */ auto ProduceStack() { // Hook PostOp auto post_op_fn = [=](Output elem, std::function<void(Output)> emit_func) { return PostOp(elem, emit_func); }; FunctionStack<> stack; return stack.push(post_op_fn); } /*! * Returns "[ReduceNode]" and its id as a string. * \return "[ReduceNode]" */ std::string ToString() override { return "[ReduceNode id=" + std::to_string(data_id_) + "]"; } private: //! Local stack Stack local_stack_; //!Key extractor function KeyExtractor key_extractor_; //!Reduce function ReduceFunction reduce_function_; //! Local storage std::vector<reduce_arg_t> elements_; //! Locally hash elements of the current DIA onto buckets and reduce each //! bucket to a single value, afterwards send data to another worker given //! by the shuffle algorithm. void PreOp(reduce_arg_t input) { elements_.push_back(input); } //!Recieve elements from other workers. auto MainOp() { using ReduceTable = core::ReducePostTable<KeyExtractor, ReduceFunction, std::function<void(reduce_arg_t)> >; std::function<void(Output)> print = [](Output elem) { LOG << elem.first << " " << elem.second; }; ReduceTable table(key_extractor_, reduce_function_, { print }); for (const reduce_arg_t& elem : elements_) { table.Insert(elem); } table.Flush(); } //! Hash recieved elements onto buckets and reduce each bucket to a single value. void PostOp(Output input, std::function<void(Output)> emit_func) { emit_func(input); } }; //! \} } // namespace c7a #endif // !C7A_API_REDUCE_NODE_HEADER /******************************************************************************/ <commit_msg>spelling correction<commit_after>/******************************************************************************* * c7a/api/reduce_node.hpp * * DIANode for a reduce operation. Performs the actual reduce operation * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_REDUCE_NODE_HEADER #define C7A_API_REDUCE_NODE_HEADER #include <c7a/api/dop_node.hpp> #include <c7a/api/context.hpp> #include <c7a/api/function_stack.hpp> #include <c7a/common/logger.hpp> #include <c7a/core/reduce_pre_table.hpp> #include <c7a/core/reduce_post_table.hpp> #include <unordered_map> #include <functional> #include <string> #include <vector> namespace c7a { //! \addtogroup api Interface //! \{ /*! * A DIANode which performs a Reduce operation. Reduce groups the elements in a * DIA by their key and reduces every key bucket to a single element each. The * ReduceNode stores the key_extractor and the reduce_function UDFs. The * chainable LOps ahead of the Reduce operation are stored in the Stack. The * ReduceNode has the type Output, which is the result type of the * reduce_function. * * \tparam Input Input type of the Reduce operation * \tparam Output Output type of the Reduce operation * \tparam Stack Function stack, which contains the chained lambdas between the last and this DIANode. * \tparam KeyExtractor Type of the key_extractor function. * \tparam ReduceFunction Type of the reduce_function */ template <typename Input, typename Output, typename Stack, typename KeyExtractor, typename ReduceFunction> class ReduceNode : public DOpNode<Output> { static const bool debug = true; typedef DOpNode<Output> Super; using reduce_arg_t = typename FunctionTraits<ReduceFunction>::template arg<0>; using Super::context_; using Super::data_id_; public: /*! * Constructor for a ReduceNode. Sets the DataManager, parent, stack, * key_extractor and reduce_function. * * \param ctx Reference to Context, which holds references to data and network. * \param parent Parent DIANode. * \param stack Function chain with all lambdas between the parent and this node * \param key_extractor Key extractor function * \param reduce_function Reduce function */ ReduceNode(Context& ctx, DIANode<Input>* parent, Stack& stack, KeyExtractor key_extractor, ReduceFunction reduce_function) : DOpNode<Output>(ctx, { parent }), local_stack_(stack), key_extractor_(key_extractor), reduce_function_(reduce_function), elements_() { // Hook PreOp auto pre_op_fn = [=](reduce_arg_t input) { PreOp(input); }; auto lop_chain = local_stack_.push(pre_op_fn).emit(); parent->RegisterChild(lop_chain); } //! Virtual destructor for a ReduceNode. virtual ~ReduceNode() { } /*! * Actually executes the reduce operation. Uses the member functions PreOp, * MainOp and PostOp. */ void execute() override { MainOp(); // get data from data manager data::BlockIterator<Output> it = context_.get_data_manager().template GetLocalBlocks<Output>(data_id_); // loop over input while (it.HasNext()) { const Output& item = it.Next(); for (auto func : DIANode<Output>::callbacks_) { func(item); } } } /*! * Produces a function stack, which only contains the PostOp function. * \return PostOp function stack */ auto ProduceStack() { // Hook PostOp auto post_op_fn = [=](Output elem, std::function<void(Output)> emit_func) { return PostOp(elem, emit_func); }; FunctionStack<> stack; return stack.push(post_op_fn); } /*! * Returns "[ReduceNode]" and its id as a string. * \return "[ReduceNode]" */ std::string ToString() override { return "[ReduceNode id=" + std::to_string(data_id_) + "]"; } private: //! Local stack Stack local_stack_; //!Key extractor function KeyExtractor key_extractor_; //!Reduce function ReduceFunction reduce_function_; //! Local storage std::vector<reduce_arg_t> elements_; //! Locally hash elements of the current DIA onto buckets and reduce each //! bucket to a single value, afterwards send data to another worker given //! by the shuffle algorithm. void PreOp(reduce_arg_t input) { elements_.push_back(input); } //!Receive elements from other workers. auto MainOp() { using ReduceTable = core::ReducePostTable<KeyExtractor, ReduceFunction, std::function<void(reduce_arg_t)> >; std::function<void(Output)> print = [](Output elem) { LOG << elem.first << " " << elem.second; }; ReduceTable table(key_extractor_, reduce_function_, { print }); for (const reduce_arg_t& elem : elements_) { table.Insert(elem); } table.Flush(); } //! Hash recieved elements onto buckets and reduce each bucket to a single value. void PostOp(Output input, std::function<void(Output)> emit_func) { emit_func(input); } }; //! \} } // namespace c7a #endif // !C7A_API_REDUCE_NODE_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>/******************************************************************************* Copyright (c) 2015-2019 Alexandra Cherdantseva <neluhus.vagus@gmail.com> 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 "PropertyWidgetEx.h" #include "PropertyView.h" #include "Utils/QtnConnections.h" #include <QMouseEvent> #include <QApplication> #include <QMimeData> #include <QDrag> #include <QShortcut> #include <QClipboard> #include <QAction> #include <QColor> #include <QMenu> #include <QContextMenuEvent> QtnPropertyWidgetEx::QtnPropertyWidgetEx(QWidget *parent) : QtnPropertyWidget(parent) , draggedProperty(nullptr) , mDrag(nullptr) , dropAction(Qt::IgnoreAction) , canRemove(false) { setAcceptDrops(true); propertyView()->installEventFilter(this); QObject::connect(propertyView(), &QtnPropertyView::mouseReleased, this, &QtnPropertyWidgetEx::onMouseReleased); } void QtnPropertyWidgetEx::connectDeleteAction(QAction *action, bool connect) { internalConnect( action, &QtnPropertyWidgetEx::deleteActiveProperty, connect); } void QtnPropertyWidgetEx::connectCutAction(QAction *action, bool connect) { internalConnect(action, &QtnPropertyWidgetEx::cutToClipboard, connect); } void QtnPropertyWidgetEx::connectCopyAction(QAction *action, bool connect) { internalConnect(action, &QtnPropertyWidgetEx::copyToClipboard, connect); } void QtnPropertyWidgetEx::connectPasteAction(QAction *action, bool connect) { internalConnect(action, &QtnPropertyWidgetEx::pasteFromClipboard, connect); } bool QtnPropertyWidgetEx::canDeleteActiveProperty() { return canDeleteProperty(getActiveProperty()); } bool QtnPropertyWidgetEx::canDeleteProperty(QtnPropertyBase *) { return false; } bool QtnPropertyWidgetEx::canCutToClipboard() { return false; } bool QtnPropertyWidgetEx::canCopyToClipboard() { return (nullptr != getActiveProperty()); } bool QtnPropertyWidgetEx::canPasteFromClipboard() { return dataHasSupportedFormats(QApplication::clipboard()->mimeData()) && (nullptr != getActiveProperty()); } QtnPropertyBase *QtnPropertyWidgetEx::getActiveProperty() const { return propertyView()->activeProperty(); } void QtnPropertyWidgetEx::addShortcutForAction(const QKeySequence &seq, QAction *action, QWidget *parent, Qt::ShortcutContext shortcutContext) { if (seq.isEmpty()) return; Q_ASSERT(nullptr != action); Q_ASSERT(nullptr != parent); auto shortcut = new QShortcut(seq, parent, nullptr, nullptr, shortcutContext); QObject::connect( shortcut, &QShortcut::activated, action, &QAction::trigger); } void QtnPropertyWidgetEx::onMouseReleased() { draggedProperty = nullptr; } void QtnPropertyWidgetEx::onResetTriggered() { auto activeProperty = getActiveProperty(); if (activeProperty && activeProperty->isResettable() && activeProperty->isEditableByUser()) { QtnConnections connections; propertyView()->connectPropertyToEdit(activeProperty, connections); QtnPropertyChangeReason reason = QtnPropertyChangeReasonEditValue; activeProperty->reset(reason); } } bool QtnPropertyWidgetEx::dataHasSupportedFormats(const QMimeData *data) { if (nullptr != data) { return data->hasText() || data->hasUrls() || data->hasColor(); } return false; } void QtnPropertyWidgetEx::deleteActiveProperty() { deleteProperty(getActiveProperty()); } void QtnPropertyWidgetEx::cutToClipboard() { copyToClipboard(); deleteActiveProperty(); } void QtnPropertyWidgetEx::copyToClipboard() { auto property = getActiveProperty(); if (nullptr != property) { auto mime = getPropertyDataForAction(property, Qt::IgnoreAction); if (nullptr != mime) QApplication::clipboard()->setMimeData(mime); } } void QtnPropertyWidgetEx::pasteFromClipboard() { auto data = QApplication::clipboard()->mimeData(); if (dataHasSupportedFormats(data)) { applyPropertyData(data, getActiveProperty(), QtnApplyPosition::None); } } void QtnPropertyWidgetEx::contextMenuEvent(QContextMenuEvent *event) { auto property = getActiveProperty(); if (nullptr == property) return; if (!property->isResettable() || !property->isEditableByUser()) return; QMenu menu; auto action = menu.addAction(tr("Reset to default")); action->setStatusTip( tr("Reset value of %1 to default").arg(property->name())); QObject::connect(action, &QAction::triggered, this, &QtnPropertyWidgetEx::onResetTriggered); menu.exec(event->globalPos()); } void QtnPropertyWidgetEx::deleteProperty(QtnPropertyBase *) { // do nothing } QMimeData *QtnPropertyWidgetEx::getPropertyDataForAction( QtnPropertyBase *property, Qt::DropAction) { Q_ASSERT(nullptr != property); QString str; if (property->toStr(str)) { auto mime = new QMimeData; mime->setText(str); return mime; } return nullptr; } bool QtnPropertyWidgetEx::applyPropertyData( const QMimeData *data, QtnPropertyBase *destination, QtnApplyPosition) { if (nullptr != destination) { QtnConnections connections; propertyView()->connectPropertyToEdit(destination, connections); Q_ASSERT(nullptr != data); QString str; if (data->hasUrls()) { QStringList list; for (auto &url : data->urls()) { if (url.isLocalFile()) list.push_back(url.toLocalFile()); else list.push_back(url.toString()); } str = list.join('\n'); } else if (data->hasColor()) { auto color = data->colorData().value<QColor>(); str = color.name( (color.alpha() < 255) ? QColor::HexArgb : QColor::HexRgb); } else if (data->hasText()) { str = data->text(); } else { return false; } return destination->fromStr(str, QtnPropertyChangeReasonEditValue); } return false; } bool QtnPropertyWidgetEx::eventFilter(QObject *obj, QEvent *event) { switch (event->type()) { case QEvent::MouseButtonPress: { if (draggedProperty) break; auto mevent = static_cast<QMouseEvent *>(event); if (mevent->button() == Qt::LeftButton) { dragStartPos = mevent->pos(); draggedProperty = propertyView()->getPropertyAt(dragStartPos); canRemove = canDeleteProperty(draggedProperty); return true; } break; } case QEvent::MouseMove: { if (mDrag) break; auto mevent = static_cast<QMouseEvent *>(event); if (nullptr != draggedProperty && 0 != (mevent->buttons() & Qt::LeftButton)) { if ((mevent->pos() - dragStartPos).manhattanLength() < QApplication::startDragDistance()) { dragAndDrop(); return true; } } break; } default: break; } return QtnPropertyWidget::eventFilter(obj, event); } void QtnPropertyWidgetEx::dragEnterEvent(QDragEnterEvent *event) { if (dataHasSupportedFormats(event->mimeData())) event->acceptProposedAction(); } void QtnPropertyWidgetEx::dragMoveEvent(QDragMoveEvent *event) { if (Qt::ControlModifier == QApplication::keyboardModifiers() || !canRemove) { event->setDropAction(Qt::CopyAction); dropAction = Qt::CopyAction; } else { event->setDropAction(Qt::MoveAction); dropAction = Qt::MoveAction; } event->accept(); } void QtnPropertyWidgetEx::dropEvent(QDropEvent *event) { switch (event->dropAction()) { case Qt::MoveAction: case Qt::CopyAction: { auto view = propertyView(); auto pos = view->mapFrom(this, event->pos()); QRect rect; auto destination = view->getPropertyAt(pos, &rect); if (destination == draggedProperty) { draggedProperty = nullptr; break; } QtnApplyPosition applyPosition; if (destination == nullptr) { applyPosition = QtnApplyPosition::After; } else { int partHeight = view->itemHeight() / 3; if (QRect(rect.left(), rect.top(), rect.width(), partHeight) .contains(pos)) applyPosition = QtnApplyPosition::Before; else if (QRect(rect.left(), rect.bottom() - partHeight, rect.width(), partHeight) .contains(pos)) applyPosition = QtnApplyPosition::After; else applyPosition = QtnApplyPosition::Over; } auto data = event->mimeData(); if (dataHasSupportedFormats(data) && drop(data, destination, applyPosition)) { event->accept(); } break; } default: break; } } bool QtnPropertyWidgetEx::drop(const QMimeData *data, QtnPropertyBase *property, QtnApplyPosition applyPosition) { return applyPropertyData(data, property, applyPosition); } void QtnPropertyWidgetEx::dropEnd() { if (nullptr != draggedProperty) { if (Qt::MoveAction == dropAction) deleteProperty(draggedProperty); } } void QtnPropertyWidgetEx::onDropFinished(Qt::DropAction) { dropEnd(); draggedProperty = nullptr; mDrag = nullptr; } bool QtnPropertyWidgetEx::dragAndDrop() { dropAction = Qt::IgnoreAction; auto data = getPropertyDataForAction(draggedProperty, Qt::CopyAction); if (nullptr != data) { mDrag = new QDrag(this); mDrag->setMimeData(data); // TODO generate cursor #ifdef __EMSCRIPTEN__ QObject::connect(mDrag, &QDrag::finished, this, &QtnPropertyWidgetEx::onDropFinished); mDrag->exec(Qt::CopyAction | Qt::MoveAction); #else onDropFinished(mDrag->exec(Qt::CopyAction | Qt::MoveAction)); #endif return true; } draggedProperty = nullptr; return false; } void QtnPropertyWidgetEx::internalConnect( QAction *action, void (QtnPropertyWidgetEx::*slot)(), bool connect) { if (connect) QObject::connect(action, &QAction::triggered, this, slot); else QObject::disconnect(action, &QAction::triggered, this, slot); } QtnPropertyWidgetExDelegate::~QtnPropertyWidgetExDelegate() {} <commit_msg>qt guard<commit_after>/******************************************************************************* Copyright (c) 2015-2019 Alexandra Cherdantseva <neluhus.vagus@gmail.com> 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 "PropertyWidgetEx.h" #include "PropertyView.h" #include "Utils/QtnConnections.h" #include <QMouseEvent> #include <QApplication> #include <QMimeData> #include <QDrag> #include <QShortcut> #include <QClipboard> #include <QAction> #include <QColor> #include <QMenu> #include <QContextMenuEvent> QtnPropertyWidgetEx::QtnPropertyWidgetEx(QWidget *parent) : QtnPropertyWidget(parent) , draggedProperty(nullptr) , mDrag(nullptr) , dropAction(Qt::IgnoreAction) , canRemove(false) { setAcceptDrops(true); propertyView()->installEventFilter(this); QObject::connect(propertyView(), &QtnPropertyView::mouseReleased, this, &QtnPropertyWidgetEx::onMouseReleased); } void QtnPropertyWidgetEx::connectDeleteAction(QAction *action, bool connect) { internalConnect( action, &QtnPropertyWidgetEx::deleteActiveProperty, connect); } void QtnPropertyWidgetEx::connectCutAction(QAction *action, bool connect) { internalConnect(action, &QtnPropertyWidgetEx::cutToClipboard, connect); } void QtnPropertyWidgetEx::connectCopyAction(QAction *action, bool connect) { internalConnect(action, &QtnPropertyWidgetEx::copyToClipboard, connect); } void QtnPropertyWidgetEx::connectPasteAction(QAction *action, bool connect) { internalConnect(action, &QtnPropertyWidgetEx::pasteFromClipboard, connect); } bool QtnPropertyWidgetEx::canDeleteActiveProperty() { return canDeleteProperty(getActiveProperty()); } bool QtnPropertyWidgetEx::canDeleteProperty(QtnPropertyBase *) { return false; } bool QtnPropertyWidgetEx::canCutToClipboard() { return false; } bool QtnPropertyWidgetEx::canCopyToClipboard() { return (nullptr != getActiveProperty()); } bool QtnPropertyWidgetEx::canPasteFromClipboard() { return dataHasSupportedFormats(QApplication::clipboard()->mimeData()) && (nullptr != getActiveProperty()); } QtnPropertyBase *QtnPropertyWidgetEx::getActiveProperty() const { return propertyView()->activeProperty(); } void QtnPropertyWidgetEx::addShortcutForAction(const QKeySequence &seq, QAction *action, QWidget *parent, Qt::ShortcutContext shortcutContext) { if (seq.isEmpty()) return; Q_ASSERT(nullptr != action); Q_ASSERT(nullptr != parent); auto shortcut = new QShortcut(seq, parent, nullptr, nullptr, shortcutContext); QObject::connect( shortcut, &QShortcut::activated, action, &QAction::trigger); } void QtnPropertyWidgetEx::onMouseReleased() { draggedProperty = nullptr; } void QtnPropertyWidgetEx::onResetTriggered() { auto activeProperty = getActiveProperty(); if (activeProperty && activeProperty->isResettable() && activeProperty->isEditableByUser()) { QtnConnections connections; propertyView()->connectPropertyToEdit(activeProperty, connections); QtnPropertyChangeReason reason = QtnPropertyChangeReasonEditValue; activeProperty->reset(reason); } } bool QtnPropertyWidgetEx::dataHasSupportedFormats(const QMimeData *data) { if (nullptr != data) { return data->hasText() || data->hasUrls() || data->hasColor(); } return false; } void QtnPropertyWidgetEx::deleteActiveProperty() { deleteProperty(getActiveProperty()); } void QtnPropertyWidgetEx::cutToClipboard() { copyToClipboard(); deleteActiveProperty(); } void QtnPropertyWidgetEx::copyToClipboard() { auto property = getActiveProperty(); if (nullptr != property) { auto mime = getPropertyDataForAction(property, Qt::IgnoreAction); if (nullptr != mime) QApplication::clipboard()->setMimeData(mime); } } void QtnPropertyWidgetEx::pasteFromClipboard() { auto data = QApplication::clipboard()->mimeData(); if (dataHasSupportedFormats(data)) { applyPropertyData(data, getActiveProperty(), QtnApplyPosition::None); } } void QtnPropertyWidgetEx::contextMenuEvent(QContextMenuEvent *event) { auto property = getActiveProperty(); if (nullptr == property) return; if (!property->isResettable() || !property->isEditableByUser()) return; QMenu menu; auto action = menu.addAction(tr("Reset to default")); action->setStatusTip( tr("Reset value of %1 to default").arg(property->name())); QObject::connect(action, &QAction::triggered, this, &QtnPropertyWidgetEx::onResetTriggered); menu.exec(event->globalPos()); } void QtnPropertyWidgetEx::deleteProperty(QtnPropertyBase *) { // do nothing } QMimeData *QtnPropertyWidgetEx::getPropertyDataForAction( QtnPropertyBase *property, Qt::DropAction) { Q_ASSERT(nullptr != property); QString str; if (property->toStr(str)) { auto mime = new QMimeData; mime->setText(str); return mime; } return nullptr; } bool QtnPropertyWidgetEx::applyPropertyData( const QMimeData *data, QtnPropertyBase *destination, QtnApplyPosition) { if (nullptr != destination) { QtnConnections connections; propertyView()->connectPropertyToEdit(destination, connections); Q_ASSERT(nullptr != data); QString str; if (data->hasUrls()) { QStringList list; for (auto &url : data->urls()) { if (url.isLocalFile()) list.push_back(url.toLocalFile()); else list.push_back(url.toString()); } str = list.join('\n'); } else if (data->hasColor()) { auto color = data->colorData().value<QColor>(); str = color.name( (color.alpha() < 255) ? QColor::HexArgb : QColor::HexRgb); } else if (data->hasText()) { str = data->text(); } else { return false; } return destination->fromStr(str, QtnPropertyChangeReasonEditValue); } return false; } bool QtnPropertyWidgetEx::eventFilter(QObject *obj, QEvent *event) { switch (event->type()) { case QEvent::MouseButtonPress: { if (draggedProperty) break; auto mevent = static_cast<QMouseEvent *>(event); if (mevent->button() == Qt::LeftButton) { dragStartPos = mevent->pos(); draggedProperty = propertyView()->getPropertyAt(dragStartPos); canRemove = canDeleteProperty(draggedProperty); return true; } break; } case QEvent::MouseMove: { if (mDrag) break; auto mevent = static_cast<QMouseEvent *>(event); if (nullptr != draggedProperty && 0 != (mevent->buttons() & Qt::LeftButton)) { if ((mevent->pos() - dragStartPos).manhattanLength() < QApplication::startDragDistance()) { dragAndDrop(); return true; } } break; } default: break; } return QtnPropertyWidget::eventFilter(obj, event); } void QtnPropertyWidgetEx::dragEnterEvent(QDragEnterEvent *event) { if (dataHasSupportedFormats(event->mimeData())) event->acceptProposedAction(); } void QtnPropertyWidgetEx::dragMoveEvent(QDragMoveEvent *event) { if (Qt::ControlModifier == QApplication::keyboardModifiers() || !canRemove) { event->setDropAction(Qt::CopyAction); dropAction = Qt::CopyAction; } else { event->setDropAction(Qt::MoveAction); dropAction = Qt::MoveAction; } event->accept(); } void QtnPropertyWidgetEx::dropEvent(QDropEvent *event) { switch (event->dropAction()) { case Qt::MoveAction: case Qt::CopyAction: { auto view = propertyView(); auto pos = view->mapFrom(this, event->pos()); QRect rect; auto destination = view->getPropertyAt(pos, &rect); if (destination == draggedProperty) { draggedProperty = nullptr; break; } QtnApplyPosition applyPosition; if (destination == nullptr) { applyPosition = QtnApplyPosition::After; } else { int partHeight = view->itemHeight() / 3; if (QRect(rect.left(), rect.top(), rect.width(), partHeight) .contains(pos)) applyPosition = QtnApplyPosition::Before; else if (QRect(rect.left(), rect.bottom() - partHeight, rect.width(), partHeight) .contains(pos)) applyPosition = QtnApplyPosition::After; else applyPosition = QtnApplyPosition::Over; } auto data = event->mimeData(); if (dataHasSupportedFormats(data) && drop(data, destination, applyPosition)) { event->accept(); } break; } default: break; } } bool QtnPropertyWidgetEx::drop(const QMimeData *data, QtnPropertyBase *property, QtnApplyPosition applyPosition) { return applyPropertyData(data, property, applyPosition); } void QtnPropertyWidgetEx::dropEnd() { if (nullptr != draggedProperty) { if (Qt::MoveAction == dropAction) deleteProperty(draggedProperty); } } void QtnPropertyWidgetEx::onDropFinished(Qt::DropAction) { dropEnd(); draggedProperty = nullptr; mDrag = nullptr; } bool QtnPropertyWidgetEx::dragAndDrop() { dropAction = Qt::IgnoreAction; auto data = getPropertyDataForAction(draggedProperty, Qt::CopyAction); if (nullptr != data) { mDrag = new QDrag(this); mDrag->setMimeData(data); // TODO generate cursor #ifdef Q_OS_WASM QObject::connect(mDrag, &QDrag::finished, this, &QtnPropertyWidgetEx::onDropFinished); mDrag->exec(Qt::CopyAction | Qt::MoveAction); #else onDropFinished(mDrag->exec(Qt::CopyAction | Qt::MoveAction)); #endif return true; } draggedProperty = nullptr; return false; } void QtnPropertyWidgetEx::internalConnect( QAction *action, void (QtnPropertyWidgetEx::*slot)(), bool connect) { if (connect) QObject::connect(action, &QAction::triggered, this, slot); else QObject::disconnect(action, &QAction::triggered, this, slot); } QtnPropertyWidgetExDelegate::~QtnPropertyWidgetExDelegate() {} <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CEvaluationNodeFunction.cpp,v $ $Revision: 1.20 $ $Name: $ $Author: gauges $ $Date: 2005/06/30 10:29:00 $ End CVS Header */ #include "copasi.h" #include "mathematics.h" #include "CEvaluationNode.h" #include "CEvaluationTree.h" #include "sbml/math/ASTNode.h" CEvaluationNodeFunction::CEvaluationNodeFunction(): CEvaluationNode(CEvaluationNode::INVALID, "") {mPrecedence = PRECEDENCE_NUMBER;} CEvaluationNodeFunction::CEvaluationNodeFunction(const SubType & subType, const Data & data): CEvaluationNode((Type) (CEvaluationNode::FUNCTION | subType), data), mpFunction(NULL), mpLeft(NULL) { switch (subType) { case LOG: mpFunction = log; break; case LOG10: mpFunction = log10; break; case EXP: mpFunction = exp; break; case SIN: mpFunction = sin; break; case COS: mpFunction = cos; break; case TAN: mpFunction = tan; break; case SEC: mpFunction = sec; break; case CSC: mpFunction = csc; break; case COT: mpFunction = cot; break; case SINH: mpFunction = sinh; break; case COSH: mpFunction = cosh; break; case TANH: mpFunction = tanh; break; case SECH: mpFunction = sech; break; case CSCH: mpFunction = csch; break; case COTH: mpFunction = coth; break; case ARCSIN: mpFunction = asin; break; case ARCCOS: mpFunction = acos; break; case ARCTAN: mpFunction = atan; break; case ARCSEC: mpFunction = arcsec; break; case ARCCSC: mpFunction = arccsc; break; case ARCCOT: mpFunction = arccot; break; case ARCSINH: mpFunction = asinh; break; case ARCCOSH: mpFunction = acosh; break; case ARCTANH: mpFunction = atanh; break; case ARCSECH: mpFunction = asech; break; case ARCCSCH: mpFunction = acsch; break; case ARCCOTH: mpFunction = acoth; break; case SQRT: mpFunction = sqrt; break; case ABS: mpFunction = fabs; break; case FLOOR: mpFunction = floor; break; case CEIL: mpFunction = ceil; break; case FACTORIAL: mpFunction = factorial; break; case MINUS: mpFunction = minus; break; case PLUS: mpFunction = plus; break; case NOT: mpFunction = copasiNot; break; default: mpFunction = NULL; fatalError(); break; } mPrecedence = PRECEDENCE_FUNCTION; } CEvaluationNodeFunction::CEvaluationNodeFunction(const CEvaluationNodeFunction & src): CEvaluationNode(src), mpFunction(src.mpFunction) {} CEvaluationNodeFunction::~CEvaluationNodeFunction() {} bool CEvaluationNodeFunction::compile(const CEvaluationTree * /* pTree */) { mpLeft = static_cast<CEvaluationNode *>(getChild()); if (mpLeft == NULL) return false; return (mpLeft->getSibling() == NULL); // We must have only one child } std::string CEvaluationNodeFunction::getInfix() const { if (const_cast<CEvaluationNodeFunction *>(this)->compile(NULL)) return mData + "(" + mpLeft->getData() + ")"; else return "@"; } CEvaluationNode* CEvaluationNodeFunction::createNodeFromASTTree(const ASTNode& node) { ASTNodeType_t type = node.getType(); SubType subType; std::string data = ""; switch (type) { case AST_FUNCTION_ABS: subType = ABS; data = "abs"; break; case AST_FUNCTION_ARCCOS: subType = ARCCOS; data = "acos"; break; case AST_FUNCTION_ARCCOT: subType = ARCCOT; data = "arccot"; break; case AST_FUNCTION_ARCCOTH: subType = ARCCOTH; data = "arccoth"; break; case AST_FUNCTION_ARCCSC: subType = ARCCSC; data = "arccsc"; break; case AST_FUNCTION_ARCCSCH: subType = ARCCSCH; data = "arccsch"; break; case AST_FUNCTION_ARCSEC: subType = ARCSEC; data = "arcsec"; break; case AST_FUNCTION_ARCSECH: subType = ARCSECH; data = "arcsech"; break; case AST_FUNCTION_ARCSIN: subType = ARCSIN; data = "asin"; break; case AST_FUNCTION_ARCSINH: subType = ARCSINH; data = "arcsinh"; break; case AST_FUNCTION_ARCTAN: subType = ARCTAN; data = "atan"; break; case AST_FUNCTION_ARCTANH: subType = ARCTANH; data = "arctanh"; break; case AST_FUNCTION_CEILING: subType = CEIL; data = "ceil"; break; case AST_FUNCTION_COS: subType = COS; data = "cos"; break; case AST_FUNCTION_COSH: subType = COSH; data = "cosh"; break; case AST_FUNCTION_COT: subType = COT; data = "cot"; break; case AST_FUNCTION_COTH: subType = COTH; data = "coth"; break; case AST_FUNCTION_CSC: subType = CSC; data = "csc"; break; case AST_FUNCTION_CSCH: subType = CSCH; data = "csch"; break; case AST_FUNCTION_EXP: subType = EXP; data = "exp"; break; case AST_FUNCTION_FACTORIAL: subType = FACTORIAL; data = "factorial"; break; case AST_FUNCTION_FLOOR: subType = FLOOR; data = "floor"; break; case AST_FUNCTION_LN: subType = LOG; data = "log"; break; case AST_FUNCTION_LOG: subType = LOG10; data = "log10"; break; /* case AST_FUNCTION_ROOT: subType=ROOT; break; */ case AST_FUNCTION_SEC: subType = SEC; data = "sec"; break; case AST_FUNCTION_SECH: subType = SECH; data = "sech"; break; case AST_FUNCTION_SIN: subType = SIN; data = "sin"; break; case AST_FUNCTION_SINH: subType = SINH; data = "sinh"; break; case AST_FUNCTION_TAN: subType = TAN; data = "tan"; break; case AST_FUNCTION_TANH: subType = TANH; data = "tanh"; break; case AST_LOGICAL_NOT: subType = NOT; data = "not"; break; default: subType = INVALID; break; } // all functions have one child // convert child and add the converted node as child // to the current node. CEvaluationNodeFunction* convertedNode = new CEvaluationNodeFunction(subType, data); if (subType != INVALID) { ASTNode* child = node.getLeftChild(); CEvaluationNode* convertedChildNode = CEvaluationTree::convertASTNode(*child); convertedNode->addChild(convertedChildNode); } return convertedNode; } ASTNode* CEvaluationNodeFunction::toASTNode() { SubType subType = (SubType)CEvaluationNode::subType(this->getType()); ASTNode* node = new ASTNode(); switch (subType) { case INVALID: break; case LOG: node->setType(AST_FUNCTION_LN); break; case LOG10: node->setType(AST_FUNCTION_LOG); break; case EXP: node->setType(AST_FUNCTION_EXP); break; case SIN: node->setType(AST_FUNCTION_SIN); break; case COS: node->setType(AST_FUNCTION_COS); break; case TAN: node->setType(AST_FUNCTION_TAN); break; case SEC: node->setType(AST_FUNCTION_SEC); break; case CSC: node->setType(AST_FUNCTION_CSC); break; case COT: node->setType(AST_FUNCTION_COT); break; case SINH: node->setType(AST_FUNCTION_SINH); break; case COSH: node->setType(AST_FUNCTION_COSH); break; case TANH: node->setType(AST_FUNCTION_TANH); break; case SECH: node->setType(AST_FUNCTION_SECH); break; case CSCH: node->setType(AST_FUNCTION_CSCH); break; case COTH: node->setType(AST_FUNCTION_COTH); break; case ARCSIN: node->setType(AST_FUNCTION_ARCSIN); break; case ARCCOS: node->setType(AST_FUNCTION_ARCCOS); break; case ARCTAN: node->setType(AST_FUNCTION_ARCTAN); break; case ARCSEC: node->setType(AST_FUNCTION_ARCSEC); break; case ARCCSC: node->setType(AST_FUNCTION_ARCCSC); break; case ARCCOT: node->setType(AST_FUNCTION_ARCCOT); break; case ARCSINH: node->setType(AST_FUNCTION_ARCSINH); break; case ARCCOSH: node->setType(AST_FUNCTION_ARCCOSH); break; case ARCTANH: node->setType(AST_FUNCTION_ARCTANH); break; case ARCSECH: node->setType(AST_FUNCTION_ARCSECH); break; case ARCCSCH: node->setType(AST_FUNCTION_ARCCSCH); break; case ARCCOTH: node->setType(AST_FUNCTION_ARCCOTH); break; case SQRT: node->setType(AST_FUNCTION_ROOT); break; case ABS: node->setType(AST_FUNCTION_ABS); break; case CEIL: node->setType(AST_FUNCTION_CEILING); break; case FLOOR: node->setType(AST_FUNCTION_FLOOR); break; case FACTORIAL: node->setType(AST_FUNCTION_FACTORIAL); break; case MINUS: node->setType(AST_MINUS); break; case PLUS: // if this is the unary plus as I suspect, // the nodde will be replaced by its only child delete node; node = dynamic_cast<CEvaluationNode*>(this->getChild())->toASTNode(); break; case NOT: fatalError(); break; } // for all but INVALID one child has to be converted if (subType != INVALID) { CEvaluationNode* child1 = dynamic_cast<CEvaluationNode*>(this->getChild()); node->addChild(child1->toASTNode()); } return node; } <commit_msg>I had forgotten arccosh in the conversion from the ASTNode.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CEvaluationNodeFunction.cpp,v $ $Revision: 1.21 $ $Name: $ $Author: gauges $ $Date: 2005/06/30 13:33:17 $ End CVS Header */ #include "copasi.h" #include "mathematics.h" #include "CEvaluationNode.h" #include "CEvaluationTree.h" #include "sbml/math/ASTNode.h" CEvaluationNodeFunction::CEvaluationNodeFunction(): CEvaluationNode(CEvaluationNode::INVALID, "") {mPrecedence = PRECEDENCE_NUMBER;} CEvaluationNodeFunction::CEvaluationNodeFunction(const SubType & subType, const Data & data): CEvaluationNode((Type) (CEvaluationNode::FUNCTION | subType), data), mpFunction(NULL), mpLeft(NULL) { switch (subType) { case LOG: mpFunction = log; break; case LOG10: mpFunction = log10; break; case EXP: mpFunction = exp; break; case SIN: mpFunction = sin; break; case COS: mpFunction = cos; break; case TAN: mpFunction = tan; break; case SEC: mpFunction = sec; break; case CSC: mpFunction = csc; break; case COT: mpFunction = cot; break; case SINH: mpFunction = sinh; break; case COSH: mpFunction = cosh; break; case TANH: mpFunction = tanh; break; case SECH: mpFunction = sech; break; case CSCH: mpFunction = csch; break; case COTH: mpFunction = coth; break; case ARCSIN: mpFunction = asin; break; case ARCCOS: mpFunction = acos; break; case ARCTAN: mpFunction = atan; break; case ARCSEC: mpFunction = arcsec; break; case ARCCSC: mpFunction = arccsc; break; case ARCCOT: mpFunction = arccot; break; case ARCSINH: mpFunction = asinh; break; case ARCCOSH: mpFunction = acosh; break; case ARCTANH: mpFunction = atanh; break; case ARCSECH: mpFunction = asech; break; case ARCCSCH: mpFunction = acsch; break; case ARCCOTH: mpFunction = acoth; break; case SQRT: mpFunction = sqrt; break; case ABS: mpFunction = fabs; break; case FLOOR: mpFunction = floor; break; case CEIL: mpFunction = ceil; break; case FACTORIAL: mpFunction = factorial; break; case MINUS: mpFunction = minus; break; case PLUS: mpFunction = plus; break; case NOT: mpFunction = copasiNot; break; default: mpFunction = NULL; fatalError(); break; } mPrecedence = PRECEDENCE_FUNCTION; } CEvaluationNodeFunction::CEvaluationNodeFunction(const CEvaluationNodeFunction & src): CEvaluationNode(src), mpFunction(src.mpFunction) {} CEvaluationNodeFunction::~CEvaluationNodeFunction() {} bool CEvaluationNodeFunction::compile(const CEvaluationTree * /* pTree */) { mpLeft = static_cast<CEvaluationNode *>(getChild()); if (mpLeft == NULL) return false; return (mpLeft->getSibling() == NULL); // We must have only one child } std::string CEvaluationNodeFunction::getInfix() const { if (const_cast<CEvaluationNodeFunction *>(this)->compile(NULL)) return mData + "(" + mpLeft->getData() + ")"; else return "@"; } CEvaluationNode* CEvaluationNodeFunction::createNodeFromASTTree(const ASTNode& node) { ASTNodeType_t type = node.getType(); SubType subType; std::string data = ""; switch (type) { case AST_FUNCTION_ABS: subType = ABS; data = "abs"; break; case AST_FUNCTION_ARCCOS: subType = ARCCOS; data = "acos"; break; case AST_FUNCTION_ARCCOSH: subType = ARCCOSH; data = "acosh"; break; case AST_FUNCTION_ARCCOT: subType = ARCCOT; data = "arccot"; break; case AST_FUNCTION_ARCCOTH: subType = ARCCOTH; data = "arccoth"; break; case AST_FUNCTION_ARCCSC: subType = ARCCSC; data = "arccsc"; break; case AST_FUNCTION_ARCCSCH: subType = ARCCSCH; data = "arccsch"; break; case AST_FUNCTION_ARCSEC: subType = ARCSEC; data = "arcsec"; break; case AST_FUNCTION_ARCSECH: subType = ARCSECH; data = "arcsech"; break; case AST_FUNCTION_ARCSIN: subType = ARCSIN; data = "asin"; break; case AST_FUNCTION_ARCSINH: subType = ARCSINH; data = "arcsinh"; break; case AST_FUNCTION_ARCTAN: subType = ARCTAN; data = "atan"; break; case AST_FUNCTION_ARCTANH: subType = ARCTANH; data = "arctanh"; break; case AST_FUNCTION_CEILING: subType = CEIL; data = "ceil"; break; case AST_FUNCTION_COS: subType = COS; data = "cos"; break; case AST_FUNCTION_COSH: subType = COSH; data = "cosh"; break; case AST_FUNCTION_COT: subType = COT; data = "cot"; break; case AST_FUNCTION_COTH: subType = COTH; data = "coth"; break; case AST_FUNCTION_CSC: subType = CSC; data = "csc"; break; case AST_FUNCTION_CSCH: subType = CSCH; data = "csch"; break; case AST_FUNCTION_EXP: subType = EXP; data = "exp"; break; case AST_FUNCTION_FACTORIAL: subType = FACTORIAL; data = "factorial"; break; case AST_FUNCTION_FLOOR: subType = FLOOR; data = "floor"; break; case AST_FUNCTION_LN: subType = LOG; data = "log"; break; case AST_FUNCTION_LOG: subType = LOG10; data = "log10"; break; /* case AST_FUNCTION_ROOT: subType=ROOT; break; */ case AST_FUNCTION_SEC: subType = SEC; data = "sec"; break; case AST_FUNCTION_SECH: subType = SECH; data = "sech"; break; case AST_FUNCTION_SIN: subType = SIN; data = "sin"; break; case AST_FUNCTION_SINH: subType = SINH; data = "sinh"; break; case AST_FUNCTION_TAN: subType = TAN; data = "tan"; break; case AST_FUNCTION_TANH: subType = TANH; data = "tanh"; break; case AST_LOGICAL_NOT: subType = NOT; data = "not"; break; default: subType = INVALID; break; } // all functions have one child // convert child and add the converted node as child // to the current node. CEvaluationNodeFunction* convertedNode = new CEvaluationNodeFunction(subType, data); if (subType != INVALID) { ASTNode* child = node.getLeftChild(); CEvaluationNode* convertedChildNode = CEvaluationTree::convertASTNode(*child); convertedNode->addChild(convertedChildNode); } return convertedNode; } ASTNode* CEvaluationNodeFunction::toASTNode() { SubType subType = (SubType)CEvaluationNode::subType(this->getType()); ASTNode* node = new ASTNode(); switch (subType) { case INVALID: break; case LOG: node->setType(AST_FUNCTION_LN); break; case LOG10: node->setType(AST_FUNCTION_LOG); break; case EXP: node->setType(AST_FUNCTION_EXP); break; case SIN: node->setType(AST_FUNCTION_SIN); break; case COS: node->setType(AST_FUNCTION_COS); break; case TAN: node->setType(AST_FUNCTION_TAN); break; case SEC: node->setType(AST_FUNCTION_SEC); break; case CSC: node->setType(AST_FUNCTION_CSC); break; case COT: node->setType(AST_FUNCTION_COT); break; case SINH: node->setType(AST_FUNCTION_SINH); break; case COSH: node->setType(AST_FUNCTION_COSH); break; case TANH: node->setType(AST_FUNCTION_TANH); break; case SECH: node->setType(AST_FUNCTION_SECH); break; case CSCH: node->setType(AST_FUNCTION_CSCH); break; case COTH: node->setType(AST_FUNCTION_COTH); break; case ARCSIN: node->setType(AST_FUNCTION_ARCSIN); break; case ARCCOS: node->setType(AST_FUNCTION_ARCCOS); break; case ARCTAN: node->setType(AST_FUNCTION_ARCTAN); break; case ARCSEC: node->setType(AST_FUNCTION_ARCSEC); break; case ARCCSC: node->setType(AST_FUNCTION_ARCCSC); break; case ARCCOT: node->setType(AST_FUNCTION_ARCCOT); break; case ARCSINH: node->setType(AST_FUNCTION_ARCSINH); break; case ARCCOSH: node->setType(AST_FUNCTION_ARCCOSH); break; case ARCTANH: node->setType(AST_FUNCTION_ARCTANH); break; case ARCSECH: node->setType(AST_FUNCTION_ARCSECH); break; case ARCCSCH: node->setType(AST_FUNCTION_ARCCSCH); break; case ARCCOTH: node->setType(AST_FUNCTION_ARCCOTH); break; case SQRT: node->setType(AST_FUNCTION_ROOT); break; case ABS: node->setType(AST_FUNCTION_ABS); break; case CEIL: node->setType(AST_FUNCTION_CEILING); break; case FLOOR: node->setType(AST_FUNCTION_FLOOR); break; case FACTORIAL: node->setType(AST_FUNCTION_FACTORIAL); break; case MINUS: node->setType(AST_MINUS); break; case PLUS: // if this is the unary plus as I suspect, // the nodde will be replaced by its only child delete node; node = dynamic_cast<CEvaluationNode*>(this->getChild())->toASTNode(); break; case NOT: fatalError(); break; } // for all but INVALID one child has to be converted if (subType != INVALID) { CEvaluationNode* child1 = dynamic_cast<CEvaluationNode*>(this->getChild()); node->addChild(child1->toASTNode()); } return node; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/system/logout_button/tray_logout_button.h" #include <cstddef> #include "ash/shell.h" #include "ash/system/tray/system_tray_delegate.h" #include "ash/system/user/login_status.h" #include "base/logging.h" #include "base/string16.h" #include "grit/ash_resources.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/views/controls/button/border_images.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/custom_button.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/label_button_border.h" namespace { const int kLogoutButtonBorderNormalImages[] = { IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_TOP_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_TOP, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_TOP_RIGHT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_CENTER, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_RIGHT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_BOTTOM_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_BOTTOM, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_BOTTOM_RIGHT }; const int kLogoutButtonBorderHotImages[] = { IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_TOP_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_TOP, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_TOP_RIGHT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_CENTER, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_RIGHT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_BOTTOM_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_BOTTOM, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_BOTTOM_RIGHT }; const int kLogoutButtonBorderPushedImages[] = { IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_TOP_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_TOP, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_TOP_RIGHT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_CENTER, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_RIGHT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_BOTTOM_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_BOTTOM, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_BOTTOM_RIGHT }; } // namespace namespace ash { namespace internal { namespace tray { class LogoutButton : public views::LabelButton, public views::ButtonListener { public: LogoutButton(user::LoginStatus status) : views::LabelButton(this, string16()), login_status_(user::LOGGED_IN_NONE), show_logout_button_in_tray_(false) { for (size_t state = 0; state < views::CustomButton::STATE_COUNT; ++state) { SetTextColor(static_cast<views::CustomButton::ButtonState>(state), SK_ColorWHITE); } SetFont(GetFont().DeriveFont(1)); views::LabelButtonBorder* border = new views::LabelButtonBorder(); border->SetImages(views::CustomButton::STATE_NORMAL, views::BorderImages(kLogoutButtonBorderNormalImages)); border->SetImages(views::CustomButton::STATE_HOVERED, views::BorderImages(kLogoutButtonBorderHotImages)); border->SetImages(views::CustomButton::STATE_PRESSED, views::BorderImages(kLogoutButtonBorderPushedImages)); set_border(border); OnLoginStatusChanged(status); } void OnLoginStatusChanged(user::LoginStatus status) { login_status_ = status; const string16 title = GetLocalizedSignOutStringForStatus(login_status_, false); SetText(title); SetAccessibleName(title); UpdateVisibility(); } void OnShowLogoutButtonInTrayChanged(bool show) { show_logout_button_in_tray_ = show; UpdateVisibility(); } // Overridden from views::ButtonListener. void ButtonPressed(views::Button* sender, const ui::Event& event) OVERRIDE { DCHECK_EQ(sender, this); Shell::GetInstance()->tray_delegate()->SignOut(); } private: void UpdateVisibility() { SetVisible(show_logout_button_in_tray_ && login_status_ != user::LOGGED_IN_NONE && login_status_ != user::LOGGED_IN_LOCKED); } user::LoginStatus login_status_; bool show_logout_button_in_tray_; DISALLOW_COPY_AND_ASSIGN(LogoutButton); }; } // namespace tray TrayLogoutButton::TrayLogoutButton(SystemTray* system_tray) : SystemTrayItem(system_tray), logout_button_(NULL) { } views::View* TrayLogoutButton::CreateTrayView(user::LoginStatus status) { CHECK(logout_button_ == NULL); logout_button_ = new tray::LogoutButton(status); return logout_button_; } void TrayLogoutButton::DestroyTrayView() { logout_button_ = NULL; } void TrayLogoutButton::UpdateAfterLoginStatusChange(user::LoginStatus status) { logout_button_->OnLoginStatusChanged(status); } void TrayLogoutButton::OnShowLogoutButtonInTrayChanged(bool show) { logout_button_->OnShowLogoutButtonInTrayChanged(show); } } // namespace internal } // namespace ash <commit_msg>Increase spacing between logout button and neighboring tray item<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/system/logout_button/tray_logout_button.h" #include <cstddef> #include "ash/shell.h" #include "ash/system/tray/system_tray_delegate.h" #include "ash/system/tray/tray_constants.h" #include "ash/system/user/login_status.h" #include "base/logging.h" #include "base/string16.h" #include "grit/ash_resources.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/views/border.h" #include "ui/views/controls/button/border_images.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/custom_button.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/label_button_border.h" #include "ui/views/layout/box_layout.h" #include "ui/views/view.h" namespace { const int kLogoutButtonBorderNormalImages[] = { IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_TOP_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_TOP, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_TOP_RIGHT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_CENTER, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_RIGHT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_BOTTOM_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_BOTTOM, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_NORMAL_BOTTOM_RIGHT }; const int kLogoutButtonBorderHotImages[] = { IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_TOP_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_TOP, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_TOP_RIGHT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_CENTER, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_RIGHT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_BOTTOM_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_BOTTOM, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_HOT_BOTTOM_RIGHT }; const int kLogoutButtonBorderPushedImages[] = { IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_TOP_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_TOP, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_TOP_RIGHT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_CENTER, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_RIGHT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_BOTTOM_LEFT, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_BOTTOM, IDR_AURA_UBER_TRAY_LOGOUT_BUTTON_PUSHED_BOTTOM_RIGHT }; } // namespace namespace ash { namespace internal { namespace tray { class LogoutButton : public views::View, public views::ButtonListener { public: LogoutButton(user::LoginStatus status) : button_(NULL), login_status_(user::LOGGED_IN_NONE), show_logout_button_in_tray_(false) { views::BoxLayout* layout = new views::BoxLayout( views::BoxLayout::kHorizontal, 0, 0, 0); layout->set_spread_blank_space(true); SetLayoutManager(layout); set_border(views::Border::CreateEmptyBorder( 0, kTrayLabelItemHorizontalPaddingBottomAlignment, 0, 0)); button_ = new views::LabelButton(this, string16()); for (size_t state = 0; state < views::CustomButton::STATE_COUNT; ++state) { button_->SetTextColor( static_cast<views::CustomButton::ButtonState>(state), SK_ColorWHITE); } button_->SetFont(button_->GetFont().DeriveFont(1)); views::LabelButtonBorder* border = new views::LabelButtonBorder(); border->SetImages(views::CustomButton::STATE_NORMAL, views::BorderImages(kLogoutButtonBorderNormalImages)); border->SetImages(views::CustomButton::STATE_HOVERED, views::BorderImages(kLogoutButtonBorderHotImages)); border->SetImages(views::CustomButton::STATE_PRESSED, views::BorderImages(kLogoutButtonBorderPushedImages)); button_->set_border(border); AddChildView(button_); OnLoginStatusChanged(status); } void OnLoginStatusChanged(user::LoginStatus status) { login_status_ = status; const string16 title = GetLocalizedSignOutStringForStatus(login_status_, false); button_->SetText(title); button_->SetAccessibleName(title); UpdateVisibility(); } void OnShowLogoutButtonInTrayChanged(bool show) { show_logout_button_in_tray_ = show; UpdateVisibility(); } // Overridden from views::ButtonListener. void ButtonPressed(views::Button* sender, const ui::Event& event) OVERRIDE { DCHECK_EQ(sender, button_); Shell::GetInstance()->tray_delegate()->SignOut(); } private: void UpdateVisibility() { SetVisible(show_logout_button_in_tray_ && login_status_ != user::LOGGED_IN_NONE && login_status_ != user::LOGGED_IN_LOCKED); } views::LabelButton* button_; user::LoginStatus login_status_; bool show_logout_button_in_tray_; DISALLOW_COPY_AND_ASSIGN(LogoutButton); }; } // namespace tray TrayLogoutButton::TrayLogoutButton(SystemTray* system_tray) : SystemTrayItem(system_tray), logout_button_(NULL) { } views::View* TrayLogoutButton::CreateTrayView(user::LoginStatus status) { CHECK(logout_button_ == NULL); logout_button_ = new tray::LogoutButton(status); return logout_button_; } void TrayLogoutButton::DestroyTrayView() { logout_button_ = NULL; } void TrayLogoutButton::UpdateAfterLoginStatusChange(user::LoginStatus status) { logout_button_->OnLoginStatusChanged(status); } void TrayLogoutButton::OnShowLogoutButtonInTrayChanged(bool show) { logout_button_->OnShowLogoutButtonInTrayChanged(show); } } // namespace internal } // namespace ash <|endoftext|>
<commit_before><commit_msg>Fix for MPISession<commit_after><|endoftext|>
<commit_before>/* Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include <stdio.h> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool InsertBST(TreeNode * &tree, int element) { if (tree == NULL) { tree = new TreeNode(element); return true; } if (element == tree->val) { return false; } else if (element < tree->val) { return InsertBST(tree->left, element); } else { return InsertBST(tree->right, element); } } void CreateBST(TreeNode * &tree, int a[], int n) { tree = NULL; for (int i = 0; i < n; i++) { InsertBST(tree, a[i]); } } void PreTraverse(TreeNode *tree) { if (tree) { printf("%d ", tree->val); PreTraverse(tree->left); PreTraverse(tree->right); } } void MidTraverse(TreeNode *tree) { if (tree) { MidTraverse(tree->left); printf("%d ", tree->val); MidTraverse(tree->right); } } void PostTraverse(TreeNode *tree) { if (tree) { MidTraverse(tree->left); MidTraverse(tree->right); printf("%d ", tree->val); } } class Solution { public: int GetDepth(TreeNode *root) { TreeNode *tree = root; int depth = 0; while (tree) { tree = tree->left; depth++; } return depth; } int countNodes(TreeNode* root) { if (root == NULL) { return 0; } int ldepth = GetDepth(root->left); int rdepth = GetDepth(root->right); // A complete binary tree has 2^h - 1 internal nodes, there must be at least one part is full if (ldepth == rdepth) { // In this case, left part is full return (1 << ldepth) + countNodes(root->right); } else { // In this case, left part may not full, but right part is full return (1 << rdepth) + countNodes(root->left); } } }; int main() { Solution s; int elements[10] = {4, 5, 2, 1, 0, 9, 3, 7, 6, 8}; TreeNode* tree = NULL; CreateBST(tree, elements, 10); printf("Root value is %d, depth is %d\n", tree->val, s.GetDepth(tree)); printf("Pre order:\n"); PreTraverse(tree); printf("\nMid order:\n"); MidTraverse(tree); printf("\nPost order:\n"); PostTraverse(tree); printf("\n"); int ret = s.countNodes(tree); printf("Return value is %d\n", ret); return 0; } <commit_msg>task222 accepted<commit_after>/* Given a complete binary tree, count the number of nodes. Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include <stdio.h> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool InsertBST(TreeNode * &tree, int element) { if (tree == NULL) { tree = new TreeNode(element); return true; } if (element == tree->val) { return false; } else if (element < tree->val) { return InsertBST(tree->left, element); } else { return InsertBST(tree->right, element); } } void CreateBST(TreeNode * &tree, int a[], int n) { tree = NULL; for (int i = 0; i < n; i++) { InsertBST(tree, a[i]); } } void PreTraverse(TreeNode *tree) { if (tree) { printf("%d ", tree->val); PreTraverse(tree->left); PreTraverse(tree->right); } } void MidTraverse(TreeNode *tree) { if (tree) { MidTraverse(tree->left); printf("%d ", tree->val); MidTraverse(tree->right); } } void PostTraverse(TreeNode *tree) { if (tree) { MidTraverse(tree->left); MidTraverse(tree->right); printf("%d ", tree->val); } } class Solution { public: int GetDepth(TreeNode *root) { TreeNode *tree = root; int depth = 0; while (tree) { tree = tree->left; depth++; } return depth; } int countNodes(TreeNode* root) { if (root == NULL) { return 0; } int ldepth = GetDepth(root->left); int rdepth = GetDepth(root->right); // A complete binary tree has 2^h - 1 internal nodes, there must be at least one part is full if (ldepth == rdepth) { // In this case, left part is full return (1 << ldepth) + countNodes(root->right); } else { // In this case, left part may not full, but right part is full return (1 << rdepth) + countNodes(root->left); } } }; int main() { Solution s; int elements[10] = {4, 5, 2, 1, 0, 9, 3, 7, 6, 8}; TreeNode* tree = NULL; CreateBST(tree, elements, 10); printf("Root value is %d, depth is %d\n", tree->val, s.GetDepth(tree)); printf("Pre order:\n"); PreTraverse(tree); printf("\nMid order:\n"); MidTraverse(tree); printf("\nPost order:\n"); PostTraverse(tree); printf("\n"); int ret = s.countNodes(tree); printf("Return value is %d\n", ret); return 0; } <|endoftext|>
<commit_before>#include "ptk/assert.h" #include "stm32f4xx.h" #if defined(PTK_USE_CC_STUBS) void *operator new[](unsigned size) { ptk_halt("unimplemented: operator new[]()"); // not reached return (void *) 0xffffffff; } void operator delete(void *ptr) { ptk_halt("unimplemented: operator delete()"); } extern "C" { void __cxa_pure_virtual() { ptk_halt("unimplemented: pure virtual"); } void *__dso_handle = NULL; void _exit(int status) { (void) status; ptk_halt("exit"); } pid_t _getpid(void) { return 1; } void _kill(pid_t id) { (void) id; } void *_sbrk(int incr) { extern unsigned long _bss_end; // Defined by the linker static char *limit = 0; if (limit == 0) limit = (char *) &_bss_end; void *allocated = limit; char *main_stack_pointer = (char *) __get_MSP(); if (limit + incr > main_stack_pointer) { ptk_halt("out of memory"); } // NOTE: even if we get here, the stack can collide with the heap later on limit += incr; return allocated; } }; #endif // defined(PTK_USE_CC_STUBS) <commit_msg>quick hack to avoid including STM32 headers for PSoC build<commit_after>#include "ptk/assert.h" #if !defined(PSOC) #include "stm32f4xx.h" #endif #if defined(PTK_USE_CC_STUBS) void *operator new[](unsigned size) { ptk_halt("unimplemented: operator new[]()"); // not reached return (void *) 0xffffffff; } void operator delete(void *ptr) { ptk_halt("unimplemented: operator delete()"); } extern "C" { void __cxa_pure_virtual() { ptk_halt("unimplemented: pure virtual"); } void *__dso_handle = NULL; void _exit(int status) { (void) status; ptk_halt("exit"); } pid_t _getpid(void) { return 1; } void _kill(pid_t id) { (void) id; } void *_sbrk(int incr) { extern unsigned long _bss_end; // Defined by the linker static char *limit = 0; if (limit == 0) limit = (char *) &_bss_end; void *allocated = limit; char *main_stack_pointer = (char *) __get_MSP(); if (limit + incr > main_stack_pointer) { ptk_halt("out of memory"); } // NOTE: even if we get here, the stack can collide with the heap later on limit += incr; return allocated; } }; #endif // defined(PTK_USE_CC_STUBS) <|endoftext|>
<commit_before>//****************************************************************************************************** // TransportTypes.cpp - Gbtc // // Copyright 2018, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 03/23/2018 - J. Ritchie Carroll // Generated original version of source code. // //****************************************************************************************************** #include "TransportTypes.h" #include "Constants.h" #include "../Common/Convert.h" using namespace std; using namespace GSF; using namespace GSF::TimeSeries; using namespace GSF::TimeSeries::Transport; SubscriberException::SubscriberException(string message) noexcept : m_message(move(message)) { } const char* SubscriberException::what() const noexcept { return &m_message[0]; } PublisherException::PublisherException(string message) noexcept : m_message(move(message)) { } const char* PublisherException::what() const noexcept { return &m_message[0]; } Measurement::Measurement() : ID(0), SignalID(Empty::Guid), Value(NAN), Adder(0), Multiplier(1), Timestamp(0), Flags(MeasurementStateFlags::Normal) { } float64_t Measurement::AdjustedValue() const { return Value * Multiplier + Adder; } datetime_t Measurement::GetDateTime() const { return FromTicks(Timestamp); } void Measurement::GetUnixTime(time_t& unixSOC, uint16_t& milliseconds) const { ToUnixTime(Timestamp, unixSOC, milliseconds); } MeasurementPtr TimeSeries::ToPtr(const Measurement& source) { MeasurementPtr destination = NewSharedPtr<Measurement>(); destination->ID = source.ID; destination->Source = source.Source; destination->SignalID = source.SignalID; destination->Tag = source.Tag; destination->Value = source.Value; destination->Adder = source.Adder; destination->Multiplier = source.Multiplier; destination->Timestamp = source.Timestamp; destination->Flags = source.Flags; return destination; } SignalReference::SignalReference() : SignalID(Empty::Guid), Index(0), Kind(SignalKind::Unknown) { } SignalReference::SignalReference(const string& signal) : SignalID(Guid()) { // Signal reference may contain multiple dashes, we're interested in the last one const auto splitIndex = signal.find_last_of('-'); // Assign default values to fields Index = 0; if (splitIndex == string::npos) { // This represents an error - best we can do is assume entire string is the acronym Acronym = ToUpper(Trim(signal)); Kind = SignalKind::Unknown; } else { string signalType = ToUpper(Trim(signal.substr(splitIndex + 1))); Acronym = ToUpper(Trim(signal.substr(0, splitIndex))); // If the length of the signal type acronym is greater than 2, then this // is an indexed signal type (e.g., CORDOVA-PA2) if (signalType.length() > 2) { Kind = ParseSignalKind(signalType.substr(0, 2)); if (Kind != SignalKind::Unknown) Index = stoi(signalType.substr(2)); } else { Kind = ParseSignalKind(signalType); } } } const char* GSF::TimeSeries::SignalKindDescription[] = { "Angle", "Magnitude", "Frequency", "DfDt", "Status", "Digital", "Analog", "Calculation", "Statistic", "Alarm", "Quality", "Unknown" }; const char* GSF::TimeSeries::SignalKindAcronym[] = { "PA", "PM", "FQ", "DF", "SF", "DV", "AV", "CV", "ST", "AL", "QF", "??" }; // SignalReference.ToString() ostream& GSF::TimeSeries::operator << (ostream& stream, const SignalReference& reference) { if (reference.Index > 0) return stream << reference.Acronym << "-" << SignalKindAcronym[reference.Kind] << reference.Index; return stream << reference.Acronym << "-" << SignalKindAcronym[reference.Kind]; } string GSF::TimeSeries::GetSignalTypeAcronym(SignalKind kind, char phasorType) { switch (kind) { case Angle: return toupper(phasorType) == 'V' ? "VPHA" : "IPHA"; case Magnitude: return toupper(phasorType) == 'V' ? "VPHM" : "IPHM"; case Frequency: return "FREQ"; case DfDt: return "DFDT"; case Status: return "FLAG"; case Digital: return "DIGI"; case Analog: return "ALOG"; case Calculation: return "CALC"; case Statistic: return "STAT"; case Alarm: return "ALRM"; case Quality: return "QUAL"; case Unknown: default: return "NULL"; } } std::string TimeSeries::GetEngineeringUnits(const std::string& signalType) { if (IsEqual(signalType, "IPHM")) return "Amps"; if (IsEqual(signalType, "VPHM")) return "Volts"; if (IsEqual(signalType, "FREQ")) return "Hz"; if (EndsWith(signalType, "PHA")) return "Degrees"; return Empty::String; } std::string GSF::TimeSeries::GetProtocolType(const std::string& protocolName) { if (StartsWith(protocolName, "Gateway") || StartsWith(protocolName, "Modbus") || StartsWith(protocolName, "DNP")) return "Measurement"; return "Frame"; } void TimeSeries::ParseMeasurementKey(const std::string& key, std::string& source, uint32_t& id) { const vector<string> parts = Split(key, ":"); if (parts.size() == 2) { source = parts[0]; id = uint32_t(stoul(parts[1])); } else { source = parts[0]; id = UInt32::MaxValue; } } // Gets the "SignalKind" enum for the specified "acronym". // params: // acronym: Acronym of the desired "SignalKind" // returns: The "SignalKind" for the specified "acronym". SignalKind GSF::TimeSeries::ParseSignalKind(const string& acronym) { if (acronym == "PA") // Phase Angle return SignalKind::Angle; if (acronym == "PM") // Phase Magnitude return SignalKind::Magnitude; if (acronym == "FQ") // Frequency return SignalKind::Frequency; if (acronym == "DF") // dF/dt return SignalKind::DfDt; if (acronym == "SF") // Status Flags return SignalKind::Status; if (acronym == "DV") // Digital Value return SignalKind::Digital; if (acronym == "AV") // Analog Value return SignalKind::Analog; if (acronym == "CV") // Calculated Value return SignalKind::Calculation; if (acronym == "ST") // Statistical Value return SignalKind::Statistic; if (acronym == "AL") // Alarm Value return SignalKind::Alarm; if (acronym == "QF") // Quality Flags return SignalKind::Quality; return SignalKind::Unknown; } TSSCPointMetadata::TSSCPointMetadata(function<void(int32_t, int32_t)> writeBits) : TSSCPointMetadata::TSSCPointMetadata( std::move(writeBits), function<int32_t()>(nullptr), function<int32_t()>(nullptr)) { } TSSCPointMetadata::TSSCPointMetadata(function<int32_t()> readBit, function<int32_t()> readBits5) : TSSCPointMetadata::TSSCPointMetadata( function<void(int32_t, int32_t)>(nullptr), std::move(readBit), std::move(readBits5)) { } TSSCPointMetadata::TSSCPointMetadata( function<void(int32_t, int32_t)> writeBits, function<int32_t()> readBit, function<int32_t()> readBits5) : m_commandsSentSinceLastChange(0), m_mode(4), m_mode21(0), m_mode31(0), m_mode301(0), m_mode41(TSSCCodeWords::Value1), m_mode401(TSSCCodeWords::Value2), m_mode4001(TSSCCodeWords::Value3), m_startupMode(0), m_writeBits(std::move(writeBits)), m_readBit(std::move(readBit)), m_readBits5(std::move(readBits5)), PrevNextPointId1(0), PrevQuality1(0), PrevQuality2(0), PrevValue1(0), PrevValue2(0), PrevValue3(0) { for (uint8_t i = 0; i < CommandStatsLength; i++) m_commandStats[i] = 0; } void TSSCPointMetadata::WriteCode(int32_t code) { switch (m_mode) { case 1: m_writeBits(code, 5); break; case 2: if (code == m_mode21) m_writeBits(1, 1); else m_writeBits(code, 6); break; case 3: if (code == m_mode31) m_writeBits(1, 1); else if (code == m_mode301) m_writeBits(1, 2); else m_writeBits(code, 7); break; case 4: if (code == m_mode41) m_writeBits(1, 1); else if (code == m_mode401) m_writeBits(1, 2); else if (code == m_mode4001) m_writeBits(1, 3); else m_writeBits(code, 8); break; default: throw PublisherException("Coding Error"); } UpdatedCodeStatistics(code); } int32_t TSSCPointMetadata::ReadCode() { int32_t code; switch (m_mode) { case 1: code = m_readBits5(); break; case 2: if (m_readBit() == 1) code = m_mode21; else code = m_readBits5(); break; case 3: if (m_readBit() == 1) code = m_mode31; else if (m_readBit() == 1) code = m_mode301; else code = m_readBits5(); break; case 4: if (m_readBit() == 1) code = m_mode41; else if (m_readBit() == 1) code = m_mode401; else if (m_readBit() == 1) code = m_mode4001; else code = m_readBits5(); break; default: throw SubscriberException("Unsupported compression mode"); } UpdatedCodeStatistics(code); return code; } void TSSCPointMetadata::UpdatedCodeStatistics(int32_t code) { m_commandsSentSinceLastChange++; m_commandStats[code]++; if (m_startupMode == 0 && m_commandsSentSinceLastChange > 5) { m_startupMode++; AdaptCommands(); } else if (m_startupMode == 1 && m_commandsSentSinceLastChange > 20) { m_startupMode++; AdaptCommands(); } else if (m_startupMode == 2 && m_commandsSentSinceLastChange > 100) { AdaptCommands(); } } void TSSCPointMetadata::AdaptCommands() { uint8_t code1 = 0; int32_t count1 = 0; uint8_t code2 = 1; int32_t count2 = 0; uint8_t code3 = 2; int32_t count3 = 0; int32_t total = 0; for (int32_t i = 0; i < CommandStatsLength; i++) { const int32_t count = m_commandStats[i]; m_commandStats[i] = 0; total += count; if (count > count3) { if (count > count1) { code3 = code2; count3 = count2; code2 = code1; count2 = count1; code1 = static_cast<uint8_t>(i); count1 = count; } else if (count > count2) { code3 = code2; count3 = count2; code2 = static_cast<uint8_t>(i); count2 = count; } else { code3 = static_cast<uint8_t>(i); count3 = count; } } } const int32_t mode1Size = total * 5; const int32_t mode2Size = count1 * 1 + (total - count1) * 6; const int32_t mode3Size = count1 * 1 + count2 * 2 + (total - count1 - count2) * 7; const int32_t mode4Size = count1 * 1 + count2 * 2 + count3 * 3 + (total - count1 - count2 - count3) * 8; int32_t minSize = Int32::MaxValue; minSize = min(minSize, mode1Size); minSize = min(minSize, mode2Size); minSize = min(minSize, mode3Size); minSize = min(minSize, mode4Size); if (minSize == mode1Size) { m_mode = 1; } else if (minSize == mode2Size) { m_mode = 2; m_mode21 = code1; } else if (minSize == mode3Size) { m_mode = 3; m_mode31 = code1; m_mode301 = code2; } else if (minSize == mode4Size) { m_mode = 4; m_mode41 = code1; m_mode401 = code2; m_mode4001 = code3; } else { if (m_writeBits == nullptr) throw SubscriberException("Coding Error"); else throw PublisherException("Coding Error"); } m_commandsSentSinceLastChange = 0; }<commit_msg>TimeSeriesPlatformLibrary: Updated protocol type test to check for STTP protocol as a Measurement class protocol.<commit_after>//****************************************************************************************************** // TransportTypes.cpp - Gbtc // // Copyright 2018, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 03/23/2018 - J. Ritchie Carroll // Generated original version of source code. // //****************************************************************************************************** #include "TransportTypes.h" #include "Constants.h" #include "../Common/Convert.h" using namespace std; using namespace GSF; using namespace GSF::TimeSeries; using namespace GSF::TimeSeries::Transport; SubscriberException::SubscriberException(string message) noexcept : m_message(move(message)) { } const char* SubscriberException::what() const noexcept { return &m_message[0]; } PublisherException::PublisherException(string message) noexcept : m_message(move(message)) { } const char* PublisherException::what() const noexcept { return &m_message[0]; } Measurement::Measurement() : ID(0), SignalID(Empty::Guid), Value(NAN), Adder(0), Multiplier(1), Timestamp(0), Flags(MeasurementStateFlags::Normal) { } float64_t Measurement::AdjustedValue() const { return Value * Multiplier + Adder; } datetime_t Measurement::GetDateTime() const { return FromTicks(Timestamp); } void Measurement::GetUnixTime(time_t& unixSOC, uint16_t& milliseconds) const { ToUnixTime(Timestamp, unixSOC, milliseconds); } MeasurementPtr TimeSeries::ToPtr(const Measurement& source) { MeasurementPtr destination = NewSharedPtr<Measurement>(); destination->ID = source.ID; destination->Source = source.Source; destination->SignalID = source.SignalID; destination->Tag = source.Tag; destination->Value = source.Value; destination->Adder = source.Adder; destination->Multiplier = source.Multiplier; destination->Timestamp = source.Timestamp; destination->Flags = source.Flags; return destination; } SignalReference::SignalReference() : SignalID(Empty::Guid), Index(0), Kind(SignalKind::Unknown) { } SignalReference::SignalReference(const string& signal) : SignalID(Guid()) { // Signal reference may contain multiple dashes, we're interested in the last one const auto splitIndex = signal.find_last_of('-'); // Assign default values to fields Index = 0; if (splitIndex == string::npos) { // This represents an error - best we can do is assume entire string is the acronym Acronym = ToUpper(Trim(signal)); Kind = SignalKind::Unknown; } else { string signalType = ToUpper(Trim(signal.substr(splitIndex + 1))); Acronym = ToUpper(Trim(signal.substr(0, splitIndex))); // If the length of the signal type acronym is greater than 2, then this // is an indexed signal type (e.g., CORDOVA-PA2) if (signalType.length() > 2) { Kind = ParseSignalKind(signalType.substr(0, 2)); if (Kind != SignalKind::Unknown) Index = stoi(signalType.substr(2)); } else { Kind = ParseSignalKind(signalType); } } } const char* GSF::TimeSeries::SignalKindDescription[] = { "Angle", "Magnitude", "Frequency", "DfDt", "Status", "Digital", "Analog", "Calculation", "Statistic", "Alarm", "Quality", "Unknown" }; const char* GSF::TimeSeries::SignalKindAcronym[] = { "PA", "PM", "FQ", "DF", "SF", "DV", "AV", "CV", "ST", "AL", "QF", "??" }; // SignalReference.ToString() ostream& GSF::TimeSeries::operator << (ostream& stream, const SignalReference& reference) { if (reference.Index > 0) return stream << reference.Acronym << "-" << SignalKindAcronym[reference.Kind] << reference.Index; return stream << reference.Acronym << "-" << SignalKindAcronym[reference.Kind]; } string GSF::TimeSeries::GetSignalTypeAcronym(SignalKind kind, char phasorType) { switch (kind) { case Angle: return toupper(phasorType) == 'V' ? "VPHA" : "IPHA"; case Magnitude: return toupper(phasorType) == 'V' ? "VPHM" : "IPHM"; case Frequency: return "FREQ"; case DfDt: return "DFDT"; case Status: return "FLAG"; case Digital: return "DIGI"; case Analog: return "ALOG"; case Calculation: return "CALC"; case Statistic: return "STAT"; case Alarm: return "ALRM"; case Quality: return "QUAL"; case Unknown: default: return "NULL"; } } std::string TimeSeries::GetEngineeringUnits(const std::string& signalType) { if (IsEqual(signalType, "IPHM")) return "Amps"; if (IsEqual(signalType, "VPHM")) return "Volts"; if (IsEqual(signalType, "FREQ")) return "Hz"; if (EndsWith(signalType, "PHA")) return "Degrees"; return Empty::String; } std::string GSF::TimeSeries::GetProtocolType(const std::string& protocolName) { if (IsEqual(protocolName, "Streaming Telemetry Transport Protocol") || IsEqual(protocolName, "STTP") || StartsWith(protocolName, "Gateway") || StartsWith(protocolName, "Modbus") || StartsWith(protocolName, "DNP")) return "Measurement"; return "Frame"; } void TimeSeries::ParseMeasurementKey(const std::string& key, std::string& source, uint32_t& id) { const vector<string> parts = Split(key, ":"); if (parts.size() == 2) { source = parts[0]; id = uint32_t(stoul(parts[1])); } else { source = parts[0]; id = UInt32::MaxValue; } } // Gets the "SignalKind" enum for the specified "acronym". // params: // acronym: Acronym of the desired "SignalKind" // returns: The "SignalKind" for the specified "acronym". SignalKind GSF::TimeSeries::ParseSignalKind(const string& acronym) { if (acronym == "PA") // Phase Angle return SignalKind::Angle; if (acronym == "PM") // Phase Magnitude return SignalKind::Magnitude; if (acronym == "FQ") // Frequency return SignalKind::Frequency; if (acronym == "DF") // dF/dt return SignalKind::DfDt; if (acronym == "SF") // Status Flags return SignalKind::Status; if (acronym == "DV") // Digital Value return SignalKind::Digital; if (acronym == "AV") // Analog Value return SignalKind::Analog; if (acronym == "CV") // Calculated Value return SignalKind::Calculation; if (acronym == "ST") // Statistical Value return SignalKind::Statistic; if (acronym == "AL") // Alarm Value return SignalKind::Alarm; if (acronym == "QF") // Quality Flags return SignalKind::Quality; return SignalKind::Unknown; } TSSCPointMetadata::TSSCPointMetadata(function<void(int32_t, int32_t)> writeBits) : TSSCPointMetadata::TSSCPointMetadata( std::move(writeBits), function<int32_t()>(nullptr), function<int32_t()>(nullptr)) { } TSSCPointMetadata::TSSCPointMetadata(function<int32_t()> readBit, function<int32_t()> readBits5) : TSSCPointMetadata::TSSCPointMetadata( function<void(int32_t, int32_t)>(nullptr), std::move(readBit), std::move(readBits5)) { } TSSCPointMetadata::TSSCPointMetadata( function<void(int32_t, int32_t)> writeBits, function<int32_t()> readBit, function<int32_t()> readBits5) : m_commandsSentSinceLastChange(0), m_mode(4), m_mode21(0), m_mode31(0), m_mode301(0), m_mode41(TSSCCodeWords::Value1), m_mode401(TSSCCodeWords::Value2), m_mode4001(TSSCCodeWords::Value3), m_startupMode(0), m_writeBits(std::move(writeBits)), m_readBit(std::move(readBit)), m_readBits5(std::move(readBits5)), PrevNextPointId1(0), PrevQuality1(0), PrevQuality2(0), PrevValue1(0), PrevValue2(0), PrevValue3(0) { for (uint8_t i = 0; i < CommandStatsLength; i++) m_commandStats[i] = 0; } void TSSCPointMetadata::WriteCode(int32_t code) { switch (m_mode) { case 1: m_writeBits(code, 5); break; case 2: if (code == m_mode21) m_writeBits(1, 1); else m_writeBits(code, 6); break; case 3: if (code == m_mode31) m_writeBits(1, 1); else if (code == m_mode301) m_writeBits(1, 2); else m_writeBits(code, 7); break; case 4: if (code == m_mode41) m_writeBits(1, 1); else if (code == m_mode401) m_writeBits(1, 2); else if (code == m_mode4001) m_writeBits(1, 3); else m_writeBits(code, 8); break; default: throw PublisherException("Coding Error"); } UpdatedCodeStatistics(code); } int32_t TSSCPointMetadata::ReadCode() { int32_t code; switch (m_mode) { case 1: code = m_readBits5(); break; case 2: if (m_readBit() == 1) code = m_mode21; else code = m_readBits5(); break; case 3: if (m_readBit() == 1) code = m_mode31; else if (m_readBit() == 1) code = m_mode301; else code = m_readBits5(); break; case 4: if (m_readBit() == 1) code = m_mode41; else if (m_readBit() == 1) code = m_mode401; else if (m_readBit() == 1) code = m_mode4001; else code = m_readBits5(); break; default: throw SubscriberException("Unsupported compression mode"); } UpdatedCodeStatistics(code); return code; } void TSSCPointMetadata::UpdatedCodeStatistics(int32_t code) { m_commandsSentSinceLastChange++; m_commandStats[code]++; if (m_startupMode == 0 && m_commandsSentSinceLastChange > 5) { m_startupMode++; AdaptCommands(); } else if (m_startupMode == 1 && m_commandsSentSinceLastChange > 20) { m_startupMode++; AdaptCommands(); } else if (m_startupMode == 2 && m_commandsSentSinceLastChange > 100) { AdaptCommands(); } } void TSSCPointMetadata::AdaptCommands() { uint8_t code1 = 0; int32_t count1 = 0; uint8_t code2 = 1; int32_t count2 = 0; uint8_t code3 = 2; int32_t count3 = 0; int32_t total = 0; for (int32_t i = 0; i < CommandStatsLength; i++) { const int32_t count = m_commandStats[i]; m_commandStats[i] = 0; total += count; if (count > count3) { if (count > count1) { code3 = code2; count3 = count2; code2 = code1; count2 = count1; code1 = static_cast<uint8_t>(i); count1 = count; } else if (count > count2) { code3 = code2; count3 = count2; code2 = static_cast<uint8_t>(i); count2 = count; } else { code3 = static_cast<uint8_t>(i); count3 = count; } } } const int32_t mode1Size = total * 5; const int32_t mode2Size = count1 * 1 + (total - count1) * 6; const int32_t mode3Size = count1 * 1 + count2 * 2 + (total - count1 - count2) * 7; const int32_t mode4Size = count1 * 1 + count2 * 2 + count3 * 3 + (total - count1 - count2 - count3) * 8; int32_t minSize = Int32::MaxValue; minSize = min(minSize, mode1Size); minSize = min(minSize, mode2Size); minSize = min(minSize, mode3Size); minSize = min(minSize, mode4Size); if (minSize == mode1Size) { m_mode = 1; } else if (minSize == mode2Size) { m_mode = 2; m_mode21 = code1; } else if (minSize == mode3Size) { m_mode = 3; m_mode31 = code1; m_mode301 = code2; } else if (minSize == mode4Size) { m_mode = 4; m_mode41 = code1; m_mode401 = code2; m_mode4001 = code3; } else { if (m_writeBits == nullptr) throw SubscriberException("Coding Error"); else throw PublisherException("Coding Error"); } m_commandsSentSinceLastChange = 0; }<|endoftext|>
<commit_before>/* * This file contains source code for a program that generates binary * species trees from a birth-death process. Given the two paramters, * birth- and death-rate, the program creates a binary tree with times * on the edges. The output is in newick format. */ #include "common.hh" #include <sys/time.h> #include <boost/shared_ptr.hpp> #include <boost/random.hpp> #include <boost/foreach.hpp> #include <boost/program_options.hpp> #include <cstdlib> // At least for EXIT_SUCCESS and EXIT_FAILURE #include <algorithm> #include <vector> #include <iostream> #include <iomanip> #include <sstream> //============================================================================ // Namespace declarations and using directives. //============================================================================ using namespace std; //============================================================================ // Typedefs and class declarations //============================================================================ struct Node; typedef boost::shared_ptr<Node> Node_ptr; struct Node { double time; Node_ptr parent, left, right; Node(double t, Node_ptr p, Node_ptr l, Node_ptr r) : time(t), parent(p), left(l), right(r) { } }; //============================================================================ // Global Constants and variables. //============================================================================ const string PROG_NAME = "phyltr-gen-stree"; const string USAGE = "Usage: " + PROG_NAME + " [OPTION]... TIME BIRTH-RATE DEATH-RATE"; const unsigned LENGTH_PRECISION = 4; // The precision with which // times on the trees will be // printed. boost::program_options::variables_map g_options; unsigned max_attempts = 0; // The maximum number of times the // process will be run. //============================================================================= // Function declarations //============================================================================= /* * acceptable_species_tree() * * Returns true if the species tree produced by the process is * acceptable according to the options, i.e., if the species tree is * not empty, it has more than min-size leaves, etc. */ bool acceptable_species_tree(const Node_ptr stree_root, const vector<Node_ptr> &leaves); /* * print_tree() * * Prints the tree rooted at 'root' to cout. If 'output_lengths' is * true, then the lenghts printed for each edge is the time of the * node minus the time of the parent's time. Otherwise, if * 'output_lengths' is false, then the time of each node is printed. */ void print_tree(Node_ptr root, bool output_lengths = true); //============================================================================= // Template and inline function and member definitions. //============================================================================= //============================================================================= // main() //============================================================================= int main(int argc, char *argv[]) { /* Seed the random number generator(s). */ init_rand(g_generator); namespace po = boost::program_options; po::options_description visible_opts("Command Line Options"); po::options_description hidden_opts(""); po::options_description all_options(""); double lambda, mu; // The birth- and death-rates respectively double T; // The length of time of the process try { /* Declare visible options */ visible_opts.add_options() ("help,h", "Display this help and exit") ("min-size", po::value<unsigned>(), "The minimum number of leaves required") ("max-size", po::value<unsigned>(), "The maximum number of leaves allowed") ("start-with-speciation,s", "If set, the birth-death process starts with a speciation") ("max-attempts,a", po::value<unsigned>(&max_attempts)->default_value(10000), "The maximum number of times the process will run if the " "species goes extinct during.") ; /* Declare positional options. */ hidden_opts.add_options() ("time", po::value<double>(&T)) ("birth-rate", po::value<double>(&lambda)) ("death-rate", po::value<double>(&mu)) ; po::positional_options_description positional_options; positional_options.add("time", 1); positional_options.add("birth-rate", 1); positional_options.add("death-rate", 1); /* Gather all options into a single options_description. */ all_options.add(visible_opts).add(hidden_opts); /* Parse the arguments. */ po::command_line_parser parser(argc, argv); parser.options(all_options); parser.positional(positional_options); po::store(parser.run(), g_options); po::notify(g_options); } catch (exception &e) { cerr << PROG_NAME << ": " << e.what() << '\n' << "Try '" << PROG_NAME << " --help' for more information.\n"; exit(EXIT_FAILURE); } /* Show help message if --help was given. */ if (g_options.count("help")) { cout << USAGE << '\n' << visible_opts << '\n'; exit(EXIT_SUCCESS); } /* Check that all required positional arguments are given. */ if (g_options.count("birth-rate") == 0 || g_options.count("death-rate") == 0 || g_options.count("time") == 0) { cerr << PROG_NAME << ": Too few arguments.\n" << "Try '" << PROG_NAME << " --help' for more information.\n"; exit(EXIT_FAILURE); } /* Check that max_attempt is not zero. */ if (g_options["max-attempts"].as<unsigned>() == 0) { cerr << PROG_NAME << ": " << "max-attempts was set to zero.\n"; exit(EXIT_FAILURE); } /* Check that the rates and time are non-negative. */ if (lambda < 0 || mu < 0) { cerr << PROG_NAME << ": negative rate\n" << "Try '" << PROG_NAME << " --help' for more information.\n"; exit(EXIT_FAILURE); } if (T < 0) { cerr << PROG_NAME << ": negative time\n" << "Try '" << PROG_NAME << " --help' for more information.\n"; exit(EXIT_FAILURE); } /* Check that min-size <= max-size if given and that max-size > 0. */ if (g_options.count("min-size") && g_options.count("max-size")) { if (g_options["min-size"].as<unsigned>() > g_options["max-size"].as<unsigned>()) { cerr << PROG_NAME << ": --min-size must be less than " << "or equal to --max-size\n"; exit(EXIT_FAILURE); } } if (g_options.count("max-size") && g_options["max-size"].as<unsigned>() == 0) { cerr << PROG_NAME << ": --max-size must be a positive integer.\n"; exit(EXIT_FAILURE); } /* * We now have everthing we need. Create the tree! */ Node_ptr null((Node *)0); // A constant to ease passing of zero-pointers. vector<Node_ptr> leaves; // The current set of leaves at cur_time. Node_ptr root(new Node(T, null, null, null)); int attempts = max_attempts; bool species_tree_accepted = false; while (attempts--) { /* * We will keep track of the root and the set of leaves at * cur_time during the process. Note that we keep the leaves at * time T and therefore we don't need to set their times at the * end of the process. */ leaves.clear(); leaves.push_back(root); double cur_time = 0; // Keeps track of the current time. // cur_time <= T at all times. /* If start-with-speciation is set, we want to start with a speciation at time 0. */ if (g_options.count("start-with-speciation") > 0) { Node_ptr np1(new Node(T, root, null, null)); Node_ptr np2(new Node(T, root, null, null)); root->time = 0; root->left = np1; root->right = np2; leaves[0] = np1; leaves.push_back(np2); } /* * In each iteration the loop advances cur_time according to the * distribution of time-intervals (i.e., an exponential * distribution with the sum of the intensities as paramter) and * decide the event according to the intensities. We prune the * tree immediately upon a death event. Keep doing this until * cur_time surpasses T. */ while (cur_time < T && !leaves.empty()) { double birth = lambda * leaves.size(); double death = mu * leaves.size(); if (birth + death > 0) { boost::exponential_distribution<double> rng_exp(birth + death); double elapsed_time = rng_exp(g_rng_d); cur_time = min(cur_time + elapsed_time, T); } else { cur_time = T; } /* If elapsed time continued passed T, we are done. */ if (cur_time == T) break; if (g_rng_d() < birth / (birth + death)) // birth { unsigned choice = g_rng_ui(leaves.size()); Node_ptr np1(new Node(T, leaves[choice], null, null)); Node_ptr np2(new Node(T, leaves[choice], null, null)); leaves[choice]->time = cur_time; leaves[choice]->left = np1; leaves[choice]->right = np2; leaves[choice] = np1; leaves.push_back(np2); } else //death { cout << "hej\n"; if (leaves.size() == 1) { leaves.pop_back(); break; } unsigned choice = g_rng_ui(leaves.size()); Node_ptr np = leaves[choice]; Node_ptr parent = np->parent; Node_ptr sibling = parent->left == np ? parent->right : parent->left; sibling->parent = sibling->parent->parent; if (sibling->parent) { if (sibling->parent->left == parent) sibling->parent->left = sibling; else sibling->parent->right = sibling; } else root = sibling; swap(leaves[choice], leaves.back()); leaves.pop_back(); } } if (acceptable_species_tree(root, leaves)) { species_tree_accepted = true; break; } } /* Print error message if all species went extinct. (what else?) */ if (!species_tree_accepted) { cerr << PROG_NAME << ": No acceptable species tree was produced in " << max_attempts << " runs of the process\n"; exit(EXIT_FAILURE); } /* Print the tree that is reachable from the root. */ print_tree(root); return EXIT_SUCCESS; } //============================================================================= // Helper function declarations //============================================================================= unsigned print_tree_r(Node_ptr node, unsigned next_leaf_id, bool output_lengths); void print_length(Node_ptr node, bool output_lengths); //============================================================================= // Function and member definitions. //============================================================================= bool acceptable_species_tree(const Node_ptr stree_root, const vector<Node_ptr> &leaves) { if (leaves.size() == 0) return false; if (g_options.count("min-size") && leaves.size() < g_options["min-size"].as<unsigned>()) { return false; } if (g_options.count("max-size") && leaves.size() > g_options["max-size"].as<unsigned>()) { return false; } return true; } void print_tree(Node_ptr root, bool output_lengths) { unsigned next_leaf_id = 1; /* if node is a leaf. */ if (!root->left) { cout << "s" << next_leaf_id; print_length(root, output_lengths); cout << ";\n"; return; } /* if node is not a leaf. */ cout << "("; next_leaf_id = print_tree_r(root->left, next_leaf_id, output_lengths); cout << ", "; next_leaf_id = print_tree_r(root->right, next_leaf_id, output_lengths); cout << ")"; print_length(root, output_lengths); cout << ";\n"; } unsigned print_tree_r(Node_ptr node, unsigned next_leaf_id, bool output_lengths) { /* if node is a leaf. */ if (!node->left) { cout << "s" << next_leaf_id; print_length(node, output_lengths); return next_leaf_id + 1; } /* if node is not a leaf. */ cout << "("; next_leaf_id = print_tree_r(node->left, next_leaf_id, output_lengths); cout << ", "; next_leaf_id = print_tree_r(node->right, next_leaf_id, output_lengths); cout << ")"; print_length(node, output_lengths); return next_leaf_id; } void print_length(Node_ptr node, bool output_lengths) { ostringstream os; os << ":" << setprecision(LENGTH_PRECISION) << showpoint; if (output_lengths) { if (node->parent) os << (node->time - node->parent->time); else os << node->time; } else os << node->time; string s = os.str(); cout << s; if (s[s.size() - 1] == '.') { cout << '0'; } } <commit_msg>Removed accidentally committed debug printout.<commit_after>/* * This file contains source code for a program that generates binary * species trees from a birth-death process. Given the two paramters, * birth- and death-rate, the program creates a binary tree with times * on the edges. The output is in newick format. */ #include "common.hh" #include <sys/time.h> #include <boost/shared_ptr.hpp> #include <boost/random.hpp> #include <boost/foreach.hpp> #include <boost/program_options.hpp> #include <cstdlib> // At least for EXIT_SUCCESS and EXIT_FAILURE #include <algorithm> #include <vector> #include <iostream> #include <iomanip> #include <sstream> //============================================================================ // Namespace declarations and using directives. //============================================================================ using namespace std; //============================================================================ // Typedefs and class declarations //============================================================================ struct Node; typedef boost::shared_ptr<Node> Node_ptr; struct Node { double time; Node_ptr parent, left, right; Node(double t, Node_ptr p, Node_ptr l, Node_ptr r) : time(t), parent(p), left(l), right(r) { } }; //============================================================================ // Global Constants and variables. //============================================================================ const string PROG_NAME = "phyltr-gen-stree"; const string USAGE = "Usage: " + PROG_NAME + " [OPTION]... TIME BIRTH-RATE DEATH-RATE"; const unsigned LENGTH_PRECISION = 4; // The precision with which // times on the trees will be // printed. boost::program_options::variables_map g_options; unsigned max_attempts = 0; // The maximum number of times the // process will be run. //============================================================================= // Function declarations //============================================================================= /* * acceptable_species_tree() * * Returns true if the species tree produced by the process is * acceptable according to the options, i.e., if the species tree is * not empty, it has more than min-size leaves, etc. */ bool acceptable_species_tree(const Node_ptr stree_root, const vector<Node_ptr> &leaves); /* * print_tree() * * Prints the tree rooted at 'root' to cout. If 'output_lengths' is * true, then the lenghts printed for each edge is the time of the * node minus the time of the parent's time. Otherwise, if * 'output_lengths' is false, then the time of each node is printed. */ void print_tree(Node_ptr root, bool output_lengths = true); //============================================================================= // Template and inline function and member definitions. //============================================================================= //============================================================================= // main() //============================================================================= int main(int argc, char *argv[]) { /* Seed the random number generator(s). */ init_rand(g_generator); namespace po = boost::program_options; po::options_description visible_opts("Command Line Options"); po::options_description hidden_opts(""); po::options_description all_options(""); double lambda, mu; // The birth- and death-rates respectively double T; // The length of time of the process try { /* Declare visible options */ visible_opts.add_options() ("help,h", "Display this help and exit") ("min-size", po::value<unsigned>(), "The minimum number of leaves required") ("max-size", po::value<unsigned>(), "The maximum number of leaves allowed") ("start-with-speciation,s", "If set, the birth-death process starts with a speciation") ("max-attempts,a", po::value<unsigned>(&max_attempts)->default_value(10000), "The maximum number of times the process will run if the " "species goes extinct during.") ; /* Declare positional options. */ hidden_opts.add_options() ("time", po::value<double>(&T)) ("birth-rate", po::value<double>(&lambda)) ("death-rate", po::value<double>(&mu)) ; po::positional_options_description positional_options; positional_options.add("time", 1); positional_options.add("birth-rate", 1); positional_options.add("death-rate", 1); /* Gather all options into a single options_description. */ all_options.add(visible_opts).add(hidden_opts); /* Parse the arguments. */ po::command_line_parser parser(argc, argv); parser.options(all_options); parser.positional(positional_options); po::store(parser.run(), g_options); po::notify(g_options); } catch (exception &e) { cerr << PROG_NAME << ": " << e.what() << '\n' << "Try '" << PROG_NAME << " --help' for more information.\n"; exit(EXIT_FAILURE); } /* Show help message if --help was given. */ if (g_options.count("help")) { cout << USAGE << '\n' << visible_opts << '\n'; exit(EXIT_SUCCESS); } /* Check that all required positional arguments are given. */ if (g_options.count("birth-rate") == 0 || g_options.count("death-rate") == 0 || g_options.count("time") == 0) { cerr << PROG_NAME << ": Too few arguments.\n" << "Try '" << PROG_NAME << " --help' for more information.\n"; exit(EXIT_FAILURE); } /* Check that max_attempt is not zero. */ if (g_options["max-attempts"].as<unsigned>() == 0) { cerr << PROG_NAME << ": " << "max-attempts was set to zero.\n"; exit(EXIT_FAILURE); } /* Check that the rates and time are non-negative. */ if (lambda < 0 || mu < 0) { cerr << PROG_NAME << ": negative rate\n" << "Try '" << PROG_NAME << " --help' for more information.\n"; exit(EXIT_FAILURE); } if (T < 0) { cerr << PROG_NAME << ": negative time\n" << "Try '" << PROG_NAME << " --help' for more information.\n"; exit(EXIT_FAILURE); } /* Check that min-size <= max-size if given and that max-size > 0. */ if (g_options.count("min-size") && g_options.count("max-size")) { if (g_options["min-size"].as<unsigned>() > g_options["max-size"].as<unsigned>()) { cerr << PROG_NAME << ": --min-size must be less than " << "or equal to --max-size\n"; exit(EXIT_FAILURE); } } if (g_options.count("max-size") && g_options["max-size"].as<unsigned>() == 0) { cerr << PROG_NAME << ": --max-size must be a positive integer.\n"; exit(EXIT_FAILURE); } /* * We now have everthing we need. Create the tree! */ Node_ptr null((Node *)0); // A constant to ease passing of zero-pointers. vector<Node_ptr> leaves; // The current set of leaves at cur_time. Node_ptr root(new Node(T, null, null, null)); int attempts = max_attempts; bool species_tree_accepted = false; while (attempts--) { /* * We will keep track of the root and the set of leaves at * cur_time during the process. Note that we keep the leaves at * time T and therefore we don't need to set their times at the * end of the process. */ leaves.clear(); leaves.push_back(root); double cur_time = 0; // Keeps track of the current time. // cur_time <= T at all times. /* If start-with-speciation is set, we want to start with a speciation at time 0. */ if (g_options.count("start-with-speciation") > 0) { Node_ptr np1(new Node(T, root, null, null)); Node_ptr np2(new Node(T, root, null, null)); root->time = 0; root->left = np1; root->right = np2; leaves[0] = np1; leaves.push_back(np2); } /* * In each iteration the loop advances cur_time according to the * distribution of time-intervals (i.e., an exponential * distribution with the sum of the intensities as paramter) and * decide the event according to the intensities. We prune the * tree immediately upon a death event. Keep doing this until * cur_time surpasses T. */ while (cur_time < T && !leaves.empty()) { double birth = lambda * leaves.size(); double death = mu * leaves.size(); if (birth + death > 0) { boost::exponential_distribution<double> rng_exp(birth + death); double elapsed_time = rng_exp(g_rng_d); cur_time = min(cur_time + elapsed_time, T); } else { cur_time = T; } /* If elapsed time continued passed T, we are done. */ if (cur_time == T) break; if (g_rng_d() < birth / (birth + death)) // birth { unsigned choice = g_rng_ui(leaves.size()); Node_ptr np1(new Node(T, leaves[choice], null, null)); Node_ptr np2(new Node(T, leaves[choice], null, null)); leaves[choice]->time = cur_time; leaves[choice]->left = np1; leaves[choice]->right = np2; leaves[choice] = np1; leaves.push_back(np2); } else //death { if (leaves.size() == 1) { leaves.pop_back(); break; } unsigned choice = g_rng_ui(leaves.size()); Node_ptr np = leaves[choice]; Node_ptr parent = np->parent; Node_ptr sibling = parent->left == np ? parent->right : parent->left; sibling->parent = sibling->parent->parent; if (sibling->parent) { if (sibling->parent->left == parent) sibling->parent->left = sibling; else sibling->parent->right = sibling; } else root = sibling; swap(leaves[choice], leaves.back()); leaves.pop_back(); } } if (acceptable_species_tree(root, leaves)) { species_tree_accepted = true; break; } } /* Print error message if all species went extinct. (what else?) */ if (!species_tree_accepted) { cerr << PROG_NAME << ": No acceptable species tree was produced in " << max_attempts << " runs of the process\n"; exit(EXIT_FAILURE); } /* Print the tree that is reachable from the root. */ print_tree(root); return EXIT_SUCCESS; } //============================================================================= // Helper function declarations //============================================================================= unsigned print_tree_r(Node_ptr node, unsigned next_leaf_id, bool output_lengths); void print_length(Node_ptr node, bool output_lengths); //============================================================================= // Function and member definitions. //============================================================================= bool acceptable_species_tree(const Node_ptr stree_root, const vector<Node_ptr> &leaves) { if (leaves.size() == 0) return false; if (g_options.count("min-size") && leaves.size() < g_options["min-size"].as<unsigned>()) { return false; } if (g_options.count("max-size") && leaves.size() > g_options["max-size"].as<unsigned>()) { return false; } return true; } void print_tree(Node_ptr root, bool output_lengths) { unsigned next_leaf_id = 1; /* if node is a leaf. */ if (!root->left) { cout << "s" << next_leaf_id; print_length(root, output_lengths); cout << ";\n"; return; } /* if node is not a leaf. */ cout << "("; next_leaf_id = print_tree_r(root->left, next_leaf_id, output_lengths); cout << ", "; next_leaf_id = print_tree_r(root->right, next_leaf_id, output_lengths); cout << ")"; print_length(root, output_lengths); cout << ";\n"; } unsigned print_tree_r(Node_ptr node, unsigned next_leaf_id, bool output_lengths) { /* if node is a leaf. */ if (!node->left) { cout << "s" << next_leaf_id; print_length(node, output_lengths); return next_leaf_id + 1; } /* if node is not a leaf. */ cout << "("; next_leaf_id = print_tree_r(node->left, next_leaf_id, output_lengths); cout << ", "; next_leaf_id = print_tree_r(node->right, next_leaf_id, output_lengths); cout << ")"; print_length(node, output_lengths); return next_leaf_id; } void print_length(Node_ptr node, bool output_lengths) { ostringstream os; os << ":" << setprecision(LENGTH_PRECISION) << showpoint; if (output_lengths) { if (node->parent) os << (node->time - node->parent->time); else os << node->time; } else os << node->time; string s = os.str(); cout << s; if (s[s.size() - 1] == '.') { cout << '0'; } } <|endoftext|>
<commit_before>/* -*- mode: C++; c-file-style: "gnu"; c-basic-offset: 2 -*- test_cryptoconfig.cpp This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. Libkleopatra 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 In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <backends/qgpgme/qgpgmecryptoconfig.h> #include <kapplication.h> #include <kaboutdata.h> #include <kcmdlineargs.h> #include <iostream> using namespace std; int main( int argc, char** argv ) { KAboutData aboutData( "test_cryptoconfig", "CryptoConfig Test", "0.1" ); KCmdLineArgs::init( argc, argv, &aboutData ); KApplication app( false, false ); Kleo::CryptoConfig * config = new QGpgMECryptoConfig(); // Dynamic querying of the options cout << "Components:" << endl; QStringList components = config->componentList(); for( QStringList::Iterator compit = components.begin(); compit != components.end(); ++compit ) { cout << "Component " << (*compit).local8Bit() << ":" << endl; const Kleo::CryptoConfigComponent* comp = config->component( *compit ); assert( comp ); QStringList groups = comp->groupList(); for( QStringList::Iterator groupit = groups.begin(); groupit != groups.end(); ++groupit ) { const Kleo::CryptoConfigGroup* group = comp->group( *groupit ); assert( group ); cout << " Group " << (*groupit).local8Bit() << ": descr=" << group->description().local8Bit() << " level=" << group->level() << endl; QStringList entries = group->entryList(); for( QStringList::Iterator entryit = entries.begin(); entryit != entries.end(); ++entryit ) { const Kleo::CryptoConfigEntry* entry = group->entry( *entryit ); assert( entry ); cout << " Entry " << (*entryit).local8Bit() << ":" << " descr=\"" << entry->description().local8Bit() << "\""; if ( !entry->isList() ) switch( entry->dataType() ) { case Kleo::CryptoConfigEntry::DataType_Bool: cout << " boolean value=" << ( entry->boolValue()?"true":"false"); break; case Kleo::CryptoConfigEntry::DataType_Int: cout << " int value=" << entry->intValue(); break; case Kleo::CryptoConfigEntry::DataType_UInt: cout << " uint value=" << entry->uintValue(); break; case Kleo::CryptoConfigEntry::DataType_URL: cout << " URL value=" << entry->urlValue().prettyURL().local8Bit(); // fallthrough case Kleo::CryptoConfigEntry::DataType_Path: // fallthrough case Kleo::CryptoConfigEntry::DataType_String: cout << " string value=" << entry->stringValue().local8Bit(); break; } else // lists switch( entry->dataType() ) { case Kleo::CryptoConfigEntry::DataType_Bool: { QValueList<bool> lst = entry->boolValueList(); QString str; for( QValueList<bool>::Iterator it = lst.begin(); it != lst.end(); ++it ) { str += ( *it ) ? "true" : "false"; } cout << " boolean values=" << str.local8Bit(); break; } case Kleo::CryptoConfigEntry::DataType_Int: { QValueList<int> lst = entry->intValueList(); QString str; for( QValueList<int>::Iterator it = lst.begin(); it != lst.end(); ++it ) { str += QString::number( *it ); } cout << " int values=" << str.local8Bit(); break; } case Kleo::CryptoConfigEntry::DataType_UInt: { QValueList<uint> lst = entry->uintValueList(); QString str; for( QValueList<uint>::Iterator it = lst.begin(); it != lst.end(); ++it ) { str += QString::number( *it ); } cout << " uint values=" << str.local8Bit(); break; } case Kleo::CryptoConfigEntry::DataType_URL: // fallthrough case Kleo::CryptoConfigEntry::DataType_Path: // fallthrough case Kleo::CryptoConfigEntry::DataType_String: { QStringList lst = entry->stringValueList(); cout << " string values=" << lst.join(" ").local8Bit(); break; } } cout << endl; } // ... } } { // Static querying of a single boolean option Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "<nogroup>", "ldaptimeout" ); if ( entry ) { assert( entry->dataType() == Kleo::CryptoConfigEntry::DataType_UInt ); uint val = entry->uintValue(); cout << "LDAP timeout: " << val << " seconds." << endl; // Test setting the option directly, then querying again //system( "echo 'ldaptimeout:101' | gpgconf --change-options dirmngr" ); // Now let's do it with the C++ API instead entry->setUIntValue( 101 ); assert( entry->isDirty() ); config->sync( true ); // Clear cached values! config->clear(); // Check new value const Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "<nogroup>", "ldaptimeout" ); assert( entry ); assert( entry->dataType() == Kleo::CryptoConfigEntry::DataType_UInt ); cout << "LDAP timeout: " << entry->uintValue() << " seconds." << endl; assert( entry->uintValue() == 101 ); // Reset old value QCString sys; sys.sprintf( "echo 'ldaptimeout:%d' | gpgconf --change-options dirmngr", val ); system( sys.data() ); cout << "LDAP timeout reset to " << val << " seconds." << endl; } else cout << "Entry dirmngr/<nogroup>/ldaptimeout not found" << endl; } { // Static querying of a single string option Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "<nogroup>", "log-file" ); if ( entry ) { assert( entry->dataType() == Kleo::CryptoConfigEntry::DataType_Path ); QString val = entry->stringValue(); cout << "Log-file: " << val.local8Bit() << endl; // Test setting the option directly, then querying again system( "echo 'log-file:\"/tmp/test%3a%e5' | gpgconf --change-options dirmngr" ); // Now let's do it with the C++ API instead entry->setStringValue( "/tmp/test:%e5" ); assert( entry->isDirty() ); config->sync( true ); // Let's see how it prints it system( "gpgconf --list-options dirmngr | grep log-file" ); // Clear cached values! config->clear(); // Check new value const Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "<nogroup>", "log-file" ); assert( entry ); assert( entry->dataType() == Kleo::CryptoConfigEntry::DataType_Path ); cout << "Log-file: " << entry->stringValue().local8Bit() << endl; // This is what it should be, but gpgconf escapes wrongly the arguments (aegypten issue90) //assert( entry->stringValue() == "/tmp/test:%e5" ); // (or even with %e5 decoded) // Reset old value QString arg( val ); if ( !arg.isEmpty() ) arg.prepend( '"' ); QCString sys; sys.sprintf( "echo 'log-file:%s' | gpgconf --change-options dirmngr", arg.local8Bit().data() ); system( sys.data() ); cout << "Log-file reset to " << val.local8Bit() << endl; } else cout << "Entry dirmngr/<nogroup>/log-file not found" << endl; } // TODO setting options cout << "Done." << endl; } <commit_msg>Less system() calls, test the C++ API a bit more<commit_after>/* -*- mode: C++; c-file-style: "gnu"; c-basic-offset: 2 -*- test_cryptoconfig.cpp This file is part of libkleopatra's test suite. Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. Libkleopatra 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 In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <backends/qgpgme/qgpgmecryptoconfig.h> #include <kapplication.h> #include <kaboutdata.h> #include <kcmdlineargs.h> #include <iostream> using namespace std; int main( int argc, char** argv ) { KAboutData aboutData( "test_cryptoconfig", "CryptoConfig Test", "0.1" ); KCmdLineArgs::init( argc, argv, &aboutData ); KApplication app( false, false ); Kleo::CryptoConfig * config = new QGpgMECryptoConfig(); // Dynamic querying of the options cout << "Components:" << endl; QStringList components = config->componentList(); for( QStringList::Iterator compit = components.begin(); compit != components.end(); ++compit ) { cout << "Component " << (*compit).local8Bit() << ":" << endl; const Kleo::CryptoConfigComponent* comp = config->component( *compit ); assert( comp ); QStringList groups = comp->groupList(); for( QStringList::Iterator groupit = groups.begin(); groupit != groups.end(); ++groupit ) { const Kleo::CryptoConfigGroup* group = comp->group( *groupit ); assert( group ); cout << " Group " << (*groupit).local8Bit() << ": descr=" << group->description().local8Bit() << " level=" << group->level() << endl; QStringList entries = group->entryList(); for( QStringList::Iterator entryit = entries.begin(); entryit != entries.end(); ++entryit ) { const Kleo::CryptoConfigEntry* entry = group->entry( *entryit ); assert( entry ); cout << " Entry " << (*entryit).local8Bit() << ":" << " descr=\"" << entry->description().local8Bit() << "\""; if ( !entry->isList() ) switch( entry->dataType() ) { case Kleo::CryptoConfigEntry::DataType_Bool: cout << " boolean value=" << ( entry->boolValue()?"true":"false"); break; case Kleo::CryptoConfigEntry::DataType_Int: cout << " int value=" << entry->intValue(); break; case Kleo::CryptoConfigEntry::DataType_UInt: cout << " uint value=" << entry->uintValue(); break; case Kleo::CryptoConfigEntry::DataType_URL: cout << " URL value=" << entry->urlValue().prettyURL().local8Bit(); // fallthrough case Kleo::CryptoConfigEntry::DataType_Path: // fallthrough case Kleo::CryptoConfigEntry::DataType_String: cout << " string value=" << entry->stringValue().local8Bit(); break; } else // lists switch( entry->dataType() ) { case Kleo::CryptoConfigEntry::DataType_Bool: { QValueList<bool> lst = entry->boolValueList(); QString str; for( QValueList<bool>::Iterator it = lst.begin(); it != lst.end(); ++it ) { str += ( *it ) ? "true" : "false"; } cout << " boolean values=" << str.local8Bit(); break; } case Kleo::CryptoConfigEntry::DataType_Int: { QValueList<int> lst = entry->intValueList(); QString str; for( QValueList<int>::Iterator it = lst.begin(); it != lst.end(); ++it ) { str += QString::number( *it ); } cout << " int values=" << str.local8Bit(); break; } case Kleo::CryptoConfigEntry::DataType_UInt: { QValueList<uint> lst = entry->uintValueList(); QString str; for( QValueList<uint>::Iterator it = lst.begin(); it != lst.end(); ++it ) { str += QString::number( *it ); } cout << " uint values=" << str.local8Bit(); break; } case Kleo::CryptoConfigEntry::DataType_URL: // fallthrough case Kleo::CryptoConfigEntry::DataType_Path: // fallthrough case Kleo::CryptoConfigEntry::DataType_String: { QStringList lst = entry->stringValueList(); cout << " string values=" << lst.join(" ").local8Bit(); break; } } cout << endl; } // ... } } { // Static querying of a single boolean option Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "<nogroup>", "ldaptimeout" ); if ( entry ) { assert( entry->dataType() == Kleo::CryptoConfigEntry::DataType_UInt ); uint val = entry->uintValue(); cout << "LDAP timeout: " << val << " seconds." << endl; // Test setting the option directly, then querying again //system( "echo 'ldaptimeout:101' | gpgconf --change-options dirmngr" ); // Now let's do it with the C++ API instead entry->setUIntValue( 101 ); assert( entry->isDirty() ); config->sync( true ); // Clear cached values! config->clear(); // Check new value Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "<nogroup>", "ldaptimeout" ); assert( entry ); assert( entry->dataType() == Kleo::CryptoConfigEntry::DataType_UInt ); cout << "LDAP timeout: " << entry->uintValue() << " seconds." << endl; assert( entry->uintValue() == 101 ); // Reset old value entry->setUIntValue( val ); assert( entry->isDirty() ); config->sync( true ); cout << "LDAP timeout reset to " << val << " seconds." << endl; } else cout << "Entry dirmngr/<nogroup>/ldaptimeout not found" << endl; } { // Static querying of a single string option Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "<nogroup>", "log-file" ); if ( entry ) { assert( entry->dataType() == Kleo::CryptoConfigEntry::DataType_Path ); QString val = entry->stringValue(); cout << "Log-file: " << val.local8Bit() << endl; // Test setting the option directly, then querying again //system( "echo 'log-file:\"/tmp/test%3a%e5' | gpgconf --change-options dirmngr" ); // Now let's do it with the C++ API instead entry->setStringValue( "/tmp/test:%e5" ); assert( entry->isDirty() ); config->sync( true ); // Let's see how it prints it system( "gpgconf --list-options dirmngr | grep log-file" ); // Clear cached values! config->clear(); // Check new value Kleo::CryptoConfigEntry* entry = config->entry( "dirmngr", "<nogroup>", "log-file" ); assert( entry ); assert( entry->dataType() == Kleo::CryptoConfigEntry::DataType_Path ); cout << "Log-file: " << entry->stringValue().local8Bit() << endl; // This is what it should be, but gpgconf escapes wrongly the arguments (aegypten issue90) //assert( entry->stringValue() == "/tmp/test:%e5" ); // (or even with %e5 decoded) // Reset old value #if 0 QString arg( val ); if ( !arg.isEmpty() ) arg.prepend( '"' ); QCString sys; sys.sprintf( "echo 'log-file:%s' | gpgconf --change-options dirmngr", arg.local8Bit().data() ); system( sys.data() ); #endif entry->setStringValue( val ); assert( entry->isDirty() ); config->sync( true ); cout << "Log-file reset to " << val.local8Bit() << endl; } else cout << "Entry dirmngr/<nogroup>/log-file not found" << endl; } // TODO setting options cout << "Done." << endl; } <|endoftext|>
<commit_before>#include "service.h" #include "evpp/libevent.h" #include "evpp/event_watcher.h" #include "evpp/event_loop.h" #if defined(EVPP_HTTP_SERVER_SUPPORTS_SSL) #include <openssl/err.h> #endif /* static struct bufferevent* bevcb (struct event_base *base, void *arg) { struct bufferevent* r; SSL_CTX *ctx = (SSL_CTX *) arg; r = bufferevent_openssl_socket_new (base, -1, SSL_new (ctx), BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE); return r; } */ namespace evpp { namespace http { #undef H_ARRAYSIZE #define H_ARRAYSIZE(a) \ ((sizeof(a) / sizeof(*(a))) / \ static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) static const int kMaxHTTPCode = 1000; static const char* g_http_code_string[kMaxHTTPCode + 1]; static void InitHTTPCodeString() { for (size_t i = 0; i < H_ARRAYSIZE(g_http_code_string); i++) { g_http_code_string[i] = "XX"; } g_http_code_string[200] = "OK"; g_http_code_string[302] = "Found"; g_http_code_string[400] = "Bad Request"; g_http_code_string[404] = "Not Found"; //TODO Add more http code string : https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html } #if defined(EVPP_HTTP_SERVER_SUPPORTS_SSL) Service::Service(EventLoop* l, bool enable_ssl, const char* certificate_chain_file, const char* private_key_file) : evhttp_(nullptr), evhttp_bound_socket_(nullptr), listen_loop_(l), enable_ssl_(enable_ssl), ssl_ctx_(nullptr), certificate_chain_file_(certificate_chain_file), private_key_file_(private_key_file) { #else Service::Service(EventLoop* l) : evhttp_(nullptr), evhttp_bound_socket_(nullptr), listen_loop_(l) { #endif evhttp_ = evhttp_new(listen_loop_->event_base()); if (!evhttp_) { return; } std::once_flag flag; std::call_once(flag, &InitHTTPCodeString); } Service::~Service() { assert(!evhttp_); assert(!evhttp_bound_socket_); #if defined(EVPP_HTTP_SERVER_SUPPORTS_SSL) if(ssl_ctx_) { SSL_CTX_free(ssl_ctx_); } #endif } #if defined(EVPP_HTTP_SERVER_SUPPORTS_SSL) bool Service::initSSL(bool force_enable) { DLOG_TRACE << "https service init ssl"; if(force_enable) { if(ssl_ctx_) { SSL_CTX_free(ssl_ctx_); } ssl_ctx_ = nullptr; enable_ssl_ = true; } if(!enable_ssl_) { return true; } if(ssl_ctx_){ return true; }; /* 初始化SSL协议环境 */ // SSL_library_int(); /* 创建SSL上下文 */ SSL_CTX *ctx = SSL_CTX_new (SSLv23_server_method ()); if(ctx == NULL) { LOG_ERROR << "SSL_CTX_new failed"; return false; } /* 设置SSL选项 https://linux.die.net/man/3/ssl_ctx_set_options */ SSL_CTX_set_options (ctx, SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE | SSL_OP_NO_SSLv2 /*禁用SSLv2*/ | SSL_OP_NO_TLSv1 /*禁用TLSv1*/); /* 是否校验对方证书(这里是服务端,使用SSL_VERIFY_NONE参数表示不校验) */ SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL); /* 创建椭圆曲线加密key */ EC_KEY *ecdh = EC_KEY_new_by_curve_name (NID_X9_62_prime256v1); if (ecdh == NULL) { LOG_ERROR << "EC_KEY_new_by_curve_name failed"; ERR_print_errors_fp(stderr); return false; } /* 设置ECDH临时公钥 */ if (1 != SSL_CTX_set_tmp_ecdh (ctx, ecdh)) { LOG_ERROR << "SSL_CTX_set_tmp_ecdh failed"; return false; } /* 加载证书链文件(文件编码必须为PEM格式,使用Base64编码) */ /* 此处也可使用SSL_CTX_use_certificate_file仅加载公钥证书 */ if (1 != SSL_CTX_use_certificate_chain_file ( ctx, certificate_chain_file_.c_str())) { LOG_ERROR << "Load certificate chain file(" << certificate_chain_file_.c_str() << ")failed"; ERR_print_errors_fp(stderr); return false; } /* 加载私钥文件 */ if (1 != SSL_CTX_use_PrivateKey_file ( ctx, private_key_file_.c_str(), SSL_FILETYPE_PEM)) { LOG_ERROR << "Load private key file(" << private_key_file_.c_str() << ")failed"; ERR_print_errors_fp(stderr); return false; } /* 校验私钥与证书是否匹配 */ if (1 != SSL_CTX_check_private_key (ctx)) { LOG_ERROR << "EC_KEY_new_by_curve_name failed"; ERR_print_errors_fp(stderr); return false; } auto bevcb = [](struct event_base *base, void *arg) -> struct bufferevent* { struct bufferevent* r; SSL_CTX *sslctx = (SSL_CTX *) arg; r = bufferevent_openssl_socket_new (base, -1, SSL_new (sslctx), BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE); return r; }; evhttp_set_bevcb (evhttp_, bevcb, ctx); ssl_ctx_ = ctx; return true; } #endif bool Service::Listen(int listen_port) { assert(evhttp_); assert(listen_loop_->IsInLoopThread()); port_ = listen_port; #if defined(EVPP_HTTP_SERVER_SUPPORTS_SSL) if(enable_ssl_) { initSSL(); } #endif #if LIBEVENT_VERSION_NUMBER >= 0x02001500 evhttp_bound_socket_ = evhttp_bind_socket_with_handle(evhttp_, "0.0.0.0", listen_port); if (!evhttp_bound_socket_) { return false; } #else if (evhttp_bind_socket(evhttp_, "0.0.0.0", listen_port) != 0) { return false; } #endif evhttp_set_gencb(evhttp_, &Service::GenericCallback, this); return true; } void Service::Stop() { DLOG_TRACE << "http service is stopping"; assert(listen_loop_->IsInLoopThread()); if (evhttp_) { evhttp_free(evhttp_); evhttp_ = nullptr; evhttp_bound_socket_ = nullptr; } callbacks_.clear(); default_callback_ = HTTPRequestCallback(); DLOG_TRACE << "http service stopped"; } void Service::Pause() { assert(listen_loop_->IsInLoopThread()); DLOG_TRACE << "http service pause"; #if LIBEVENT_VERSION_NUMBER >= 0x02001500 if (evhttp_bound_socket_) { evconnlistener_disable(evhttp_bound_socket_get_listener(evhttp_bound_socket_)); } #else LOG_ERROR << "Not support!".; assert(false && "Not support"); #endif } void Service::Continue() { assert(listen_loop_->IsInLoopThread()); DLOG_TRACE << "http service continue"; #if LIBEVENT_VERSION_NUMBER >= 0x02001500 if (evhttp_bound_socket_) { evconnlistener_enable(evhttp_bound_socket_get_listener(evhttp_bound_socket_)); } #else LOG_ERROR << "Not support!".; assert(false && "Not support"); #endif } void Service::RegisterHandler(const std::string& uri, HTTPRequestCallback callback) { callbacks_[uri] = callback; } void Service::RegisterDefaultHandler(HTTPRequestCallback callback) { default_callback_ = callback; } void Service::GenericCallback(struct evhttp_request* req, void* arg) { Service* hsrv = static_cast<Service*>(arg); hsrv->HandleRequest(req); } void Service::HandleRequest(struct evhttp_request* req) { // In the main HTTP listening thread, // this is the main entrance of the HTTP request processing. assert(listen_loop_->IsInLoopThread()); DLOG_TRACE << "handle request " << req << " url=" << req->uri; ContextPtr ctx(new Context(req)); ctx->Init(); if (callbacks_.empty()) { DefaultHandleRequest(ctx); return; } auto it = callbacks_.find(ctx->uri()); if (it != callbacks_.end()) { // This will forward to HTTPServer::Dispatch method to process this request. auto f = std::bind(&Service::SendReply, this, ctx, std::placeholders::_1); it->second(listen_loop_, ctx, f); return; } else { DefaultHandleRequest(ctx); } } void Service::DefaultHandleRequest(const ContextPtr& ctx) { DLOG_TRACE << "url=" << ctx->original_uri(); if (default_callback_) { auto f = std::bind(&Service::SendReply, this, ctx, std::placeholders::_1); default_callback_(listen_loop_, ctx, f); } else { evhttp_send_reply(ctx->req(), HTTP_BADREQUEST, g_http_code_string[HTTP_BADREQUEST], nullptr); } } struct Response { Response(const ContextPtr& c, const std::string& m) : ctx(c) { if (m.size() > 0) { buffer = evbuffer_new(); evbuffer_add(buffer, m.c_str(), m.size()); } } ~Response() { if (buffer) { evbuffer_free(buffer); buffer = nullptr; } // At this time, req is probably freed by evhttp framework. // So don't use req any more. // LOG_TRACE << "free request " << req->uri; } ContextPtr ctx; struct evbuffer* buffer = nullptr; }; void Service::SendReply(const ContextPtr& ctx, const std::string& response_data) { // In the worker thread DLOG_TRACE << "send reply in working thread"; // Build the response package in the worker thread std::shared_ptr<Response> response(new Response(ctx, response_data)); auto f = [this, response]() { // In the main HTTP listening thread assert(listen_loop_->IsInLoopThread()); DLOG_TRACE << "send reply in listening thread. evhttp_=" << evhttp_; auto x = response->ctx.get(); // At this moment, this Service maybe already stopped. if (!evhttp_) { LOG_WARN << "this=" << this << " Service has been stopped."; return; } if (!response->buffer) { evhttp_send_reply(x->req(), HTTP_NOTFOUND, g_http_code_string[HTTP_NOTFOUND], nullptr); return; } assert(x->response_http_code() <= kMaxHTTPCode); assert(x->response_http_code() >= 100); evhttp_send_reply(x->req(), x->response_http_code(), g_http_code_string[x->response_http_code()], response->buffer); }; // Forward this response sending task to HTTP listening thread if (listen_loop_->IsRunning()) { DLOG_TRACE << "dispatch this SendReply to listening thread"; listen_loop_->RunInLoop(f); } else { LOG_WARN << "this=" << this << " listening thread is going to stop. we discards this request."; // TODO do we need do some resource recycling about the evhttp_request? } } } } <commit_msg>remove extra comment<commit_after>#include "service.h" #include "evpp/libevent.h" #include "evpp/event_watcher.h" #include "evpp/event_loop.h" #if defined(EVPP_HTTP_SERVER_SUPPORTS_SSL) #include <openssl/err.h> #endif namespace evpp { namespace http { #undef H_ARRAYSIZE #define H_ARRAYSIZE(a) \ ((sizeof(a) / sizeof(*(a))) / \ static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) static const int kMaxHTTPCode = 1000; static const char* g_http_code_string[kMaxHTTPCode + 1]; static void InitHTTPCodeString() { for (size_t i = 0; i < H_ARRAYSIZE(g_http_code_string); i++) { g_http_code_string[i] = "XX"; } g_http_code_string[200] = "OK"; g_http_code_string[302] = "Found"; g_http_code_string[400] = "Bad Request"; g_http_code_string[404] = "Not Found"; //TODO Add more http code string : https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html } #if defined(EVPP_HTTP_SERVER_SUPPORTS_SSL) Service::Service(EventLoop* l, bool enable_ssl, const char* certificate_chain_file, const char* private_key_file) : evhttp_(nullptr), evhttp_bound_socket_(nullptr), listen_loop_(l), enable_ssl_(enable_ssl), ssl_ctx_(nullptr), certificate_chain_file_(certificate_chain_file), private_key_file_(private_key_file) { #else Service::Service(EventLoop* l) : evhttp_(nullptr), evhttp_bound_socket_(nullptr), listen_loop_(l) { #endif evhttp_ = evhttp_new(listen_loop_->event_base()); if (!evhttp_) { return; } std::once_flag flag; std::call_once(flag, &InitHTTPCodeString); } Service::~Service() { assert(!evhttp_); assert(!evhttp_bound_socket_); #if defined(EVPP_HTTP_SERVER_SUPPORTS_SSL) if(ssl_ctx_) { SSL_CTX_free(ssl_ctx_); } #endif } #if defined(EVPP_HTTP_SERVER_SUPPORTS_SSL) bool Service::initSSL(bool force_enable) { DLOG_TRACE << "https service init ssl"; if(force_enable) { if(ssl_ctx_) { SSL_CTX_free(ssl_ctx_); } ssl_ctx_ = nullptr; enable_ssl_ = true; } if(!enable_ssl_) { return true; } if(ssl_ctx_){ return true; }; /* 初始化SSL协议环境 */ // SSL_library_int(); /* 创建SSL上下文 */ SSL_CTX *ctx = SSL_CTX_new (SSLv23_server_method ()); if(ctx == NULL) { LOG_ERROR << "SSL_CTX_new failed"; return false; } /* 设置SSL选项 https://linux.die.net/man/3/ssl_ctx_set_options */ SSL_CTX_set_options (ctx, SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE | SSL_OP_NO_SSLv2 /*禁用SSLv2*/ | SSL_OP_NO_TLSv1 /*禁用TLSv1*/); /* 是否校验对方证书(这里是服务端,使用SSL_VERIFY_NONE参数表示不校验) */ SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL); /* 创建椭圆曲线加密key */ EC_KEY *ecdh = EC_KEY_new_by_curve_name (NID_X9_62_prime256v1); if (ecdh == NULL) { LOG_ERROR << "EC_KEY_new_by_curve_name failed"; ERR_print_errors_fp(stderr); return false; } /* 设置ECDH临时公钥 */ if (1 != SSL_CTX_set_tmp_ecdh (ctx, ecdh)) { LOG_ERROR << "SSL_CTX_set_tmp_ecdh failed"; return false; } /* 加载证书链文件(文件编码必须为PEM格式,使用Base64编码) */ /* 此处也可使用SSL_CTX_use_certificate_file仅加载公钥证书 */ if (1 != SSL_CTX_use_certificate_chain_file ( ctx, certificate_chain_file_.c_str())) { LOG_ERROR << "Load certificate chain file(" << certificate_chain_file_.c_str() << ")failed"; ERR_print_errors_fp(stderr); return false; } /* 加载私钥文件 */ if (1 != SSL_CTX_use_PrivateKey_file ( ctx, private_key_file_.c_str(), SSL_FILETYPE_PEM)) { LOG_ERROR << "Load private key file(" << private_key_file_.c_str() << ")failed"; ERR_print_errors_fp(stderr); return false; } /* 校验私钥与证书是否匹配 */ if (1 != SSL_CTX_check_private_key (ctx)) { LOG_ERROR << "EC_KEY_new_by_curve_name failed"; ERR_print_errors_fp(stderr); return false; } auto bevcb = [](struct event_base *base, void *arg) -> struct bufferevent* { struct bufferevent* r; SSL_CTX *sslctx = (SSL_CTX *) arg; r = bufferevent_openssl_socket_new (base, -1, SSL_new (sslctx), BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE); return r; }; evhttp_set_bevcb (evhttp_, bevcb, ctx); ssl_ctx_ = ctx; return true; } #endif bool Service::Listen(int listen_port) { assert(evhttp_); assert(listen_loop_->IsInLoopThread()); port_ = listen_port; #if defined(EVPP_HTTP_SERVER_SUPPORTS_SSL) if(enable_ssl_) { initSSL(); } #endif #if LIBEVENT_VERSION_NUMBER >= 0x02001500 evhttp_bound_socket_ = evhttp_bind_socket_with_handle(evhttp_, "0.0.0.0", listen_port); if (!evhttp_bound_socket_) { return false; } #else if (evhttp_bind_socket(evhttp_, "0.0.0.0", listen_port) != 0) { return false; } #endif evhttp_set_gencb(evhttp_, &Service::GenericCallback, this); return true; } void Service::Stop() { DLOG_TRACE << "http service is stopping"; assert(listen_loop_->IsInLoopThread()); if (evhttp_) { evhttp_free(evhttp_); evhttp_ = nullptr; evhttp_bound_socket_ = nullptr; } callbacks_.clear(); default_callback_ = HTTPRequestCallback(); DLOG_TRACE << "http service stopped"; } void Service::Pause() { assert(listen_loop_->IsInLoopThread()); DLOG_TRACE << "http service pause"; #if LIBEVENT_VERSION_NUMBER >= 0x02001500 if (evhttp_bound_socket_) { evconnlistener_disable(evhttp_bound_socket_get_listener(evhttp_bound_socket_)); } #else LOG_ERROR << "Not support!".; assert(false && "Not support"); #endif } void Service::Continue() { assert(listen_loop_->IsInLoopThread()); DLOG_TRACE << "http service continue"; #if LIBEVENT_VERSION_NUMBER >= 0x02001500 if (evhttp_bound_socket_) { evconnlistener_enable(evhttp_bound_socket_get_listener(evhttp_bound_socket_)); } #else LOG_ERROR << "Not support!".; assert(false && "Not support"); #endif } void Service::RegisterHandler(const std::string& uri, HTTPRequestCallback callback) { callbacks_[uri] = callback; } void Service::RegisterDefaultHandler(HTTPRequestCallback callback) { default_callback_ = callback; } void Service::GenericCallback(struct evhttp_request* req, void* arg) { Service* hsrv = static_cast<Service*>(arg); hsrv->HandleRequest(req); } void Service::HandleRequest(struct evhttp_request* req) { // In the main HTTP listening thread, // this is the main entrance of the HTTP request processing. assert(listen_loop_->IsInLoopThread()); DLOG_TRACE << "handle request " << req << " url=" << req->uri; ContextPtr ctx(new Context(req)); ctx->Init(); if (callbacks_.empty()) { DefaultHandleRequest(ctx); return; } auto it = callbacks_.find(ctx->uri()); if (it != callbacks_.end()) { // This will forward to HTTPServer::Dispatch method to process this request. auto f = std::bind(&Service::SendReply, this, ctx, std::placeholders::_1); it->second(listen_loop_, ctx, f); return; } else { DefaultHandleRequest(ctx); } } void Service::DefaultHandleRequest(const ContextPtr& ctx) { DLOG_TRACE << "url=" << ctx->original_uri(); if (default_callback_) { auto f = std::bind(&Service::SendReply, this, ctx, std::placeholders::_1); default_callback_(listen_loop_, ctx, f); } else { evhttp_send_reply(ctx->req(), HTTP_BADREQUEST, g_http_code_string[HTTP_BADREQUEST], nullptr); } } struct Response { Response(const ContextPtr& c, const std::string& m) : ctx(c) { if (m.size() > 0) { buffer = evbuffer_new(); evbuffer_add(buffer, m.c_str(), m.size()); } } ~Response() { if (buffer) { evbuffer_free(buffer); buffer = nullptr; } // At this time, req is probably freed by evhttp framework. // So don't use req any more. // LOG_TRACE << "free request " << req->uri; } ContextPtr ctx; struct evbuffer* buffer = nullptr; }; void Service::SendReply(const ContextPtr& ctx, const std::string& response_data) { // In the worker thread DLOG_TRACE << "send reply in working thread"; // Build the response package in the worker thread std::shared_ptr<Response> response(new Response(ctx, response_data)); auto f = [this, response]() { // In the main HTTP listening thread assert(listen_loop_->IsInLoopThread()); DLOG_TRACE << "send reply in listening thread. evhttp_=" << evhttp_; auto x = response->ctx.get(); // At this moment, this Service maybe already stopped. if (!evhttp_) { LOG_WARN << "this=" << this << " Service has been stopped."; return; } if (!response->buffer) { evhttp_send_reply(x->req(), HTTP_NOTFOUND, g_http_code_string[HTTP_NOTFOUND], nullptr); return; } assert(x->response_http_code() <= kMaxHTTPCode); assert(x->response_http_code() >= 100); evhttp_send_reply(x->req(), x->response_http_code(), g_http_code_string[x->response_http_code()], response->buffer); }; // Forward this response sending task to HTTP listening thread if (listen_loop_->IsRunning()) { DLOG_TRACE << "dispatch this SendReply to listening thread"; listen_loop_->RunInLoop(f); } else { LOG_WARN << "this=" << this << " listening thread is going to stop. we discards this request."; // TODO do we need do some resource recycling about the evhttp_request? } } } } <|endoftext|>
<commit_before>/* * Top Level window for KArm. * Distributed under the GPL. */ #include <numeric> #include <qkeycode.h> #include <qpopupmenu.h> #include <qptrlist.h> #include <qstring.h> #include <kaccel.h> #include <kaction.h> #include <kapplication.h> // kapp #include <kconfig.h> #include <kdebug.h> #include <kglobal.h> #include <kkeydialog.h> #include <klocale.h> // i18n #include <kmessagebox.h> #include <kstatusbar.h> // statusBar() #include <kstdaction.h> #include "kaccelmenuwatch.h" #include "karmutility.h" #include "mainwindow.h" #include "preferences.h" #include "print.h" #include "timekard.h" #include "task.h" #include "taskview.h" #include "tray.h" MainWindow::MainWindow() : KMainWindow(0), _accel( new KAccel( this ) ), _watcher( new KAccelMenuWatch( _accel, this ) ), _taskView( new TaskView( this ) ), _totalSum( 0 ), _sessionSum( 0 ) { setCentralWidget( _taskView ); // status bar startStatusBar(); // setup PreferenceDialog. _preferences = Preferences::instance(); // popup menus makeMenus(); _watcher->updateMenus(); // connections connect( _taskView, SIGNAL( totalTimesChanged( long, long ) ), this, SLOT( updateTime( long, long ) ) ); connect( _taskView, SIGNAL( selectionChanged ( QListViewItem * )), this, SLOT(slotSelectionChanged())); connect( _taskView, SIGNAL( updateButtons() ), this, SLOT(slotSelectionChanged())); loadGeometry(); // Setup context menu request handling connect( _taskView, SIGNAL( contextMenuRequested( QListViewItem*, const QPoint&, int )), this, SLOT( contextMenuRequest( QListViewItem*, const QPoint&, int ))); _tray = new KarmTray( this ); connect( _tray, SIGNAL( quitSelected() ), SLOT( quit() ) ); connect( _taskView, SIGNAL( timersActive() ), _tray, SLOT( startClock() ) ); connect( _taskView, SIGNAL( timersActive() ), this, SLOT( enableStopAll() )); connect( _taskView, SIGNAL( timersInactive() ), _tray, SLOT( stopClock() ) ); connect( _taskView, SIGNAL( timersInactive() ), this, SLOT( disableStopAll())); connect( _taskView, SIGNAL( tasksChanged( QPtrList<Task> ) ), _tray, SLOT( updateToolTip( QPtrList<Task> ) )); _taskView->load(); // Everything that uses Preferences has been created now, we can let it // emit its signals _preferences->emitSignals(); slotSelectionChanged(); } void MainWindow::slotSelectionChanged() { Task* item= _taskView->current_item(); actionDelete->setEnabled(item); actionEdit->setEnabled(item); actionStart->setEnabled(item && !item->isRunning()); actionStop->setEnabled(item && item->isRunning()); } // This is _old_ code, but shows how to enable/disable add comment menu item. // We'll need this kind of logic when comments are implemented. //void MainWindow::timeLoggingChanged(bool on) //{ // actionAddComment->setEnabled( on ); //} void MainWindow::save() { kdDebug(5970) << i18n("Saving time data to disk.") << endl; _taskView->save(); saveGeometry(); } void MainWindow::quit() { kapp->quit(); } MainWindow::~MainWindow() { kdDebug(5970) << i18n("MainWindow::~MainWindows: Quitting karm.") << endl; _taskView->stopAllTimers(); save(); } void MainWindow::enableStopAll() { actionStopAll->setEnabled(true); } void MainWindow::disableStopAll() { actionStopAll->setEnabled(false); } /** * Calculate the sum of the session time and the total time for all * toplevel tasks and put it in the statusbar. */ void MainWindow::updateTime( long sessionDiff, long totalDiff ) { _sessionSum += sessionDiff; _totalSum += totalDiff; updateStatusBar(); } void MainWindow::updateStatusBar( ) { QString time; time = formatTime( _sessionSum ); statusBar()->changeItem( i18n("Session: %1").arg(time), 0 ); time = formatTime( _totalSum ); statusBar()->changeItem( i18n("Total: %1" ).arg(time), 1); } void MainWindow::startStatusBar() { statusBar()->insertItem( i18n("Session"), 0, 0, true ); statusBar()->insertItem( i18n("Total" ), 1, 0, true ); } void MainWindow::saveProperties( KConfig* ) { _taskView->stopAllTimers(); _taskView->save(); } void MainWindow::keyBindings() { KKeyDialog::configure( actionCollection(), this ); } void MainWindow::startNewSession() { _taskView->startNewSession(); } void MainWindow::resetAllTimes() { if ( KMessageBox::warningContinueCancel( this, i18n( "Do you really want to reset the time to 0 for all tasks?" ), i18n( "Confirmation required" ), KGuiItem( i18n( "Reset All Times" ) ) ) == KMessageBox::Yes ) _taskView->resetTimeForAllTasks(); } void MainWindow::makeMenus() { KAction *actionKeyBindings, *actionNew, *actionNewSub; (void) KStdAction::quit( this, SLOT( quit() ), actionCollection()); (void) KStdAction::print( this, SLOT( print() ), actionCollection()); actionKeyBindings = KStdAction::keyBindings( this, SLOT( keyBindings() ), actionCollection() ); actionPreferences = KStdAction::preferences(_preferences, SLOT(showDialog()), actionCollection() ); (void) KStdAction::save( this, SLOT( save() ), actionCollection() ); KAction* actionStartNewSession = new KAction( i18n("Start &New Session"), 0, this, SLOT( startNewSession() ), actionCollection(), "start_new_session"); KAction* actionResetAll = new KAction( i18n("&Reset All Times"), 0, this, SLOT( resetAllTimes() ), actionCollection(), "reset_all_times"); actionStart = new KAction( i18n("&Start"), QString::fromLatin1("1rightarrow"), Key_S, _taskView, SLOT( startCurrentTimer() ), actionCollection(), "start"); actionStop = new KAction( i18n("S&top"), QString::fromLatin1("stop"), 0, _taskView, SLOT( stopCurrentTimer() ), actionCollection(), "stop"); actionStopAll = new KAction( i18n("Stop &All Timers"), Key_Escape, _taskView, SLOT( stopAllTimers() ), actionCollection(), "stopAll"); actionStopAll->setEnabled(false); actionNew = new KAction( i18n("&New..."), QString::fromLatin1("filenew"), CTRL+Key_N, _taskView, SLOT( newTask() ), actionCollection(), "new_task"); actionNewSub = new KAction( i18n("New &Subtask..."), QString::fromLatin1("kmultiple"), CTRL+ALT+Key_N, _taskView, SLOT( newSubTask() ), actionCollection(), "new_sub_task"); actionDelete = new KAction( i18n("&Delete"), QString::fromLatin1("editdelete"), Key_Delete, _taskView, SLOT( deleteTask() ), actionCollection(), "delete_task"); actionEdit = new KAction( i18n("&Edit..."), QString::fromLatin1("edit"), CTRL + Key_E, _taskView, SLOT( editTask() ), actionCollection(), "edit_task"); // actionAddComment = new KAction( i18n("&Add Comment..."), // QString::fromLatin1("document"), // CTRL+ALT+Key_E, // _taskView, // SLOT( addCommentToTask() ), // actionCollection(), // "add_comment_to_task"); actionMarkAsComplete = new KAction( i18n("&Mark as Complete..."), QString::fromLatin1("document"), CTRL+Key_M, _taskView, SLOT( markTaskAsComplete() ), actionCollection(), "mark_as_complete"); actionClipTotals = new KAction( i18n("&Copy Totals to Clipboard"), QString::fromLatin1("klipper"), CTRL+Key_C, _taskView, SLOT( clipTotals() ), actionCollection(), "clip_totals"); actionClipHistory = new KAction( i18n("Copy &History to Clipboard"), QString::fromLatin1("klipper"), CTRL+ALT+Key_C, _taskView, SLOT( clipHistory() ), actionCollection(), "clip_history"); new KAction( i18n("Import &Legacy Flat File..."), 0, _taskView, SLOT(loadFromFlatFile()), actionCollection(), "import_flatfile"); /* new KAction( i18n("Import E&vents"), 0, _taskView, SLOT( loadFromKOrgEvents() ), actionCollection(), "import_korg_events"); */ createGUI( QString::fromLatin1("karmui.rc") ); // Tool tops must be set after the createGUI. actionKeyBindings->setToolTip( i18n("Configure key bindings") ); actionKeyBindings->setWhatsThis( i18n("This will let you configure key" "bindings which is specific to karm") ); actionStartNewSession->setToolTip( i18n("Start a new session") ); actionStartNewSession->setWhatsThis( i18n("This will reset the session time " "to 0 for all tasks, to start a " "new session, without affecting " "the totals.") ); actionResetAll->setToolTip( i18n("Reset all times") ); actionResetAll->setWhatsThis( i18n("This will reset the session and total " "time to 0 for all tasks, to restart from " "scratch.") ); actionStart->setToolTip( i18n("Start timing for selected task") ); actionStart->setWhatsThis( i18n("This will start timing for the selected " "task.\n" "It is even possible to time several tasks " "simultaneously.\n\n" "You may also start timing of a tasks by " "double clicking the left mouse " "button on a given task. This will, however, " "stop timing of other tasks.")); actionStop->setToolTip( i18n("Stop timing of the selected task") ); actionStop->setWhatsThis( i18n("Stop timing of the selected task") ); actionStopAll->setToolTip( i18n("Stop all of the active timers") ); actionStopAll->setWhatsThis( i18n("Stop all of the active timers") ); actionNew->setToolTip( i18n("Create new top level task") ); actionNew->setWhatsThis( i18n("This will create a new top level task.") ); actionDelete->setToolTip( i18n("Delete selected task") ); actionDelete->setWhatsThis( i18n("This will delete the selected task and " "all its subtasks.") ); actionEdit->setToolTip( i18n("Edit name or times for selected task") ); actionEdit->setWhatsThis( i18n("This will bring up a dialog box where you " "may edit the parameters for the selected " "task.")); //actionAddComment->setToolTip( i18n("Add a comment to a task") ); //actionAddComment->setWhatsThis( i18n("This will bring up a dialog box where " // "you can add a comment to a task. The " // "comment can for instance add information on what you " // "are currently doing. The comment will " // "be logged in the log file.")); actionClipTotals->setToolTip(i18n("Copy task totals to clipboard")); actionClipHistory->setToolTip(i18n("Copy time card history to clipboard.")); slotSelectionChanged(); } void MainWindow::print() { MyPrinter printer(_taskView); printer.print(); } void MainWindow::loadGeometry() { KConfig &config = *kapp->config(); config.setGroup( QString::fromLatin1("Main Window Geometry") ); int w = config.readNumEntry( QString::fromLatin1("Width"), 100 ); int h = config.readNumEntry( QString::fromLatin1("Height"), 100 ); w = QMAX( w, sizeHint().width() ); h = QMAX( h, sizeHint().height() ); resize(w, h); } void MainWindow::saveGeometry() { KConfig &config = *KGlobal::config(); config.setGroup( QString::fromLatin1("Main Window Geometry")); config.writeEntry( QString::fromLatin1("Width"), width()); config.writeEntry( QString::fromLatin1("Height"), height()); config.sync(); } bool MainWindow::queryClose() { if ( !kapp->sessionSaving() ) { hide(); return false; } return KMainWindow::queryClose(); } void MainWindow::contextMenuRequest( QListViewItem*, const QPoint& point, int ) { QPopupMenu* pop = dynamic_cast<QPopupMenu*>( factory()->container( i18n( "task_popup" ), this ) ); if ( pop ) pop->popup( point ); } #include "mainwindow.moc" <commit_msg>Ooops, test for the correct value<commit_after>/* * Top Level window for KArm. * Distributed under the GPL. */ #include <numeric> #include <qkeycode.h> #include <qpopupmenu.h> #include <qptrlist.h> #include <qstring.h> #include <kaccel.h> #include <kaction.h> #include <kapplication.h> // kapp #include <kconfig.h> #include <kdebug.h> #include <kglobal.h> #include <kkeydialog.h> #include <klocale.h> // i18n #include <kmessagebox.h> #include <kstatusbar.h> // statusBar() #include <kstdaction.h> #include "kaccelmenuwatch.h" #include "karmutility.h" #include "mainwindow.h" #include "preferences.h" #include "print.h" #include "timekard.h" #include "task.h" #include "taskview.h" #include "tray.h" MainWindow::MainWindow() : KMainWindow(0), _accel( new KAccel( this ) ), _watcher( new KAccelMenuWatch( _accel, this ) ), _taskView( new TaskView( this ) ), _totalSum( 0 ), _sessionSum( 0 ) { setCentralWidget( _taskView ); // status bar startStatusBar(); // setup PreferenceDialog. _preferences = Preferences::instance(); // popup menus makeMenus(); _watcher->updateMenus(); // connections connect( _taskView, SIGNAL( totalTimesChanged( long, long ) ), this, SLOT( updateTime( long, long ) ) ); connect( _taskView, SIGNAL( selectionChanged ( QListViewItem * )), this, SLOT(slotSelectionChanged())); connect( _taskView, SIGNAL( updateButtons() ), this, SLOT(slotSelectionChanged())); loadGeometry(); // Setup context menu request handling connect( _taskView, SIGNAL( contextMenuRequested( QListViewItem*, const QPoint&, int )), this, SLOT( contextMenuRequest( QListViewItem*, const QPoint&, int ))); _tray = new KarmTray( this ); connect( _tray, SIGNAL( quitSelected() ), SLOT( quit() ) ); connect( _taskView, SIGNAL( timersActive() ), _tray, SLOT( startClock() ) ); connect( _taskView, SIGNAL( timersActive() ), this, SLOT( enableStopAll() )); connect( _taskView, SIGNAL( timersInactive() ), _tray, SLOT( stopClock() ) ); connect( _taskView, SIGNAL( timersInactive() ), this, SLOT( disableStopAll())); connect( _taskView, SIGNAL( tasksChanged( QPtrList<Task> ) ), _tray, SLOT( updateToolTip( QPtrList<Task> ) )); _taskView->load(); // Everything that uses Preferences has been created now, we can let it // emit its signals _preferences->emitSignals(); slotSelectionChanged(); } void MainWindow::slotSelectionChanged() { Task* item= _taskView->current_item(); actionDelete->setEnabled(item); actionEdit->setEnabled(item); actionStart->setEnabled(item && !item->isRunning()); actionStop->setEnabled(item && item->isRunning()); } // This is _old_ code, but shows how to enable/disable add comment menu item. // We'll need this kind of logic when comments are implemented. //void MainWindow::timeLoggingChanged(bool on) //{ // actionAddComment->setEnabled( on ); //} void MainWindow::save() { kdDebug(5970) << i18n("Saving time data to disk.") << endl; _taskView->save(); saveGeometry(); } void MainWindow::quit() { kapp->quit(); } MainWindow::~MainWindow() { kdDebug(5970) << i18n("MainWindow::~MainWindows: Quitting karm.") << endl; _taskView->stopAllTimers(); save(); } void MainWindow::enableStopAll() { actionStopAll->setEnabled(true); } void MainWindow::disableStopAll() { actionStopAll->setEnabled(false); } /** * Calculate the sum of the session time and the total time for all * toplevel tasks and put it in the statusbar. */ void MainWindow::updateTime( long sessionDiff, long totalDiff ) { _sessionSum += sessionDiff; _totalSum += totalDiff; updateStatusBar(); } void MainWindow::updateStatusBar( ) { QString time; time = formatTime( _sessionSum ); statusBar()->changeItem( i18n("Session: %1").arg(time), 0 ); time = formatTime( _totalSum ); statusBar()->changeItem( i18n("Total: %1" ).arg(time), 1); } void MainWindow::startStatusBar() { statusBar()->insertItem( i18n("Session"), 0, 0, true ); statusBar()->insertItem( i18n("Total" ), 1, 0, true ); } void MainWindow::saveProperties( KConfig* ) { _taskView->stopAllTimers(); _taskView->save(); } void MainWindow::keyBindings() { KKeyDialog::configure( actionCollection(), this ); } void MainWindow::startNewSession() { _taskView->startNewSession(); } void MainWindow::resetAllTimes() { if ( KMessageBox::warningContinueCancel( this, i18n( "Do you really want to reset the time to 0 for all tasks?" ), i18n( "Confirmation required" ), KGuiItem( i18n( "Reset All Times" ) ) ) == KMessageBox::Continue ) _taskView->resetTimeForAllTasks(); } void MainWindow::makeMenus() { KAction *actionKeyBindings, *actionNew, *actionNewSub; (void) KStdAction::quit( this, SLOT( quit() ), actionCollection()); (void) KStdAction::print( this, SLOT( print() ), actionCollection()); actionKeyBindings = KStdAction::keyBindings( this, SLOT( keyBindings() ), actionCollection() ); actionPreferences = KStdAction::preferences(_preferences, SLOT(showDialog()), actionCollection() ); (void) KStdAction::save( this, SLOT( save() ), actionCollection() ); KAction* actionStartNewSession = new KAction( i18n("Start &New Session"), 0, this, SLOT( startNewSession() ), actionCollection(), "start_new_session"); KAction* actionResetAll = new KAction( i18n("&Reset All Times"), 0, this, SLOT( resetAllTimes() ), actionCollection(), "reset_all_times"); actionStart = new KAction( i18n("&Start"), QString::fromLatin1("1rightarrow"), Key_S, _taskView, SLOT( startCurrentTimer() ), actionCollection(), "start"); actionStop = new KAction( i18n("S&top"), QString::fromLatin1("stop"), 0, _taskView, SLOT( stopCurrentTimer() ), actionCollection(), "stop"); actionStopAll = new KAction( i18n("Stop &All Timers"), Key_Escape, _taskView, SLOT( stopAllTimers() ), actionCollection(), "stopAll"); actionStopAll->setEnabled(false); actionNew = new KAction( i18n("&New..."), QString::fromLatin1("filenew"), CTRL+Key_N, _taskView, SLOT( newTask() ), actionCollection(), "new_task"); actionNewSub = new KAction( i18n("New &Subtask..."), QString::fromLatin1("kmultiple"), CTRL+ALT+Key_N, _taskView, SLOT( newSubTask() ), actionCollection(), "new_sub_task"); actionDelete = new KAction( i18n("&Delete"), QString::fromLatin1("editdelete"), Key_Delete, _taskView, SLOT( deleteTask() ), actionCollection(), "delete_task"); actionEdit = new KAction( i18n("&Edit..."), QString::fromLatin1("edit"), CTRL + Key_E, _taskView, SLOT( editTask() ), actionCollection(), "edit_task"); // actionAddComment = new KAction( i18n("&Add Comment..."), // QString::fromLatin1("document"), // CTRL+ALT+Key_E, // _taskView, // SLOT( addCommentToTask() ), // actionCollection(), // "add_comment_to_task"); actionMarkAsComplete = new KAction( i18n("&Mark as Complete..."), QString::fromLatin1("document"), CTRL+Key_M, _taskView, SLOT( markTaskAsComplete() ), actionCollection(), "mark_as_complete"); actionClipTotals = new KAction( i18n("&Copy Totals to Clipboard"), QString::fromLatin1("klipper"), CTRL+Key_C, _taskView, SLOT( clipTotals() ), actionCollection(), "clip_totals"); actionClipHistory = new KAction( i18n("Copy &History to Clipboard"), QString::fromLatin1("klipper"), CTRL+ALT+Key_C, _taskView, SLOT( clipHistory() ), actionCollection(), "clip_history"); new KAction( i18n("Import &Legacy Flat File..."), 0, _taskView, SLOT(loadFromFlatFile()), actionCollection(), "import_flatfile"); /* new KAction( i18n("Import E&vents"), 0, _taskView, SLOT( loadFromKOrgEvents() ), actionCollection(), "import_korg_events"); */ createGUI( QString::fromLatin1("karmui.rc") ); // Tool tops must be set after the createGUI. actionKeyBindings->setToolTip( i18n("Configure key bindings") ); actionKeyBindings->setWhatsThis( i18n("This will let you configure key" "bindings which is specific to karm") ); actionStartNewSession->setToolTip( i18n("Start a new session") ); actionStartNewSession->setWhatsThis( i18n("This will reset the session time " "to 0 for all tasks, to start a " "new session, without affecting " "the totals.") ); actionResetAll->setToolTip( i18n("Reset all times") ); actionResetAll->setWhatsThis( i18n("This will reset the session and total " "time to 0 for all tasks, to restart from " "scratch.") ); actionStart->setToolTip( i18n("Start timing for selected task") ); actionStart->setWhatsThis( i18n("This will start timing for the selected " "task.\n" "It is even possible to time several tasks " "simultaneously.\n\n" "You may also start timing of a tasks by " "double clicking the left mouse " "button on a given task. This will, however, " "stop timing of other tasks.")); actionStop->setToolTip( i18n("Stop timing of the selected task") ); actionStop->setWhatsThis( i18n("Stop timing of the selected task") ); actionStopAll->setToolTip( i18n("Stop all of the active timers") ); actionStopAll->setWhatsThis( i18n("Stop all of the active timers") ); actionNew->setToolTip( i18n("Create new top level task") ); actionNew->setWhatsThis( i18n("This will create a new top level task.") ); actionDelete->setToolTip( i18n("Delete selected task") ); actionDelete->setWhatsThis( i18n("This will delete the selected task and " "all its subtasks.") ); actionEdit->setToolTip( i18n("Edit name or times for selected task") ); actionEdit->setWhatsThis( i18n("This will bring up a dialog box where you " "may edit the parameters for the selected " "task.")); //actionAddComment->setToolTip( i18n("Add a comment to a task") ); //actionAddComment->setWhatsThis( i18n("This will bring up a dialog box where " // "you can add a comment to a task. The " // "comment can for instance add information on what you " // "are currently doing. The comment will " // "be logged in the log file.")); actionClipTotals->setToolTip(i18n("Copy task totals to clipboard")); actionClipHistory->setToolTip(i18n("Copy time card history to clipboard.")); slotSelectionChanged(); } void MainWindow::print() { MyPrinter printer(_taskView); printer.print(); } void MainWindow::loadGeometry() { KConfig &config = *kapp->config(); config.setGroup( QString::fromLatin1("Main Window Geometry") ); int w = config.readNumEntry( QString::fromLatin1("Width"), 100 ); int h = config.readNumEntry( QString::fromLatin1("Height"), 100 ); w = QMAX( w, sizeHint().width() ); h = QMAX( h, sizeHint().height() ); resize(w, h); } void MainWindow::saveGeometry() { KConfig &config = *KGlobal::config(); config.setGroup( QString::fromLatin1("Main Window Geometry")); config.writeEntry( QString::fromLatin1("Width"), width()); config.writeEntry( QString::fromLatin1("Height"), height()); config.sync(); } bool MainWindow::queryClose() { if ( !kapp->sessionSaving() ) { hide(); return false; } return KMainWindow::queryClose(); } void MainWindow::contextMenuRequest( QListViewItem*, const QPoint& point, int ) { QPopupMenu* pop = dynamic_cast<QPopupMenu*>( factory()->container( i18n( "task_popup" ), this ) ); if ( pop ) pop->popup( point ); } #include "mainwindow.moc" <|endoftext|>
<commit_before>// $Id: AliHLTCaloClusterAnalyser.cxx 35107 2009-09-30 01:45:06Z phille $ /************************************************************************** * This file is property of and copyright by the ALICE HLT Project * * All rights reserved. * * * * Primary Authors: Oystein Djuvsland * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /** * @file AliHLTCaloClusterAnalyser.cxx * @author Oystein Djuvsland * @date * @brief Cluster analyser for Calo HLT */ // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt #include "AliHLTCaloClusterAnalyser.h" #include "AliHLTCaloRecPointHeaderStruct.h" #include "AliHLTCaloRecPointDataStruct.h" #include "AliHLTCaloClusterDataStruct.h" //#include "AliHLTCaloPhysicsAnalyzer.h" #include "AliHLTCaloGeometry.h" #include "AliESDCaloCluster.h" #include "TMath.h" #include "TVector3.h" #include "TH1F.h" #include "TFile.h" #include "AliHLTCaloClusterizer.h" ClassImp(AliHLTCaloClusterAnalyser); AliHLTCaloClusterAnalyser::AliHLTCaloClusterAnalyser() : // AliHLTCaloBase(), fLogWeight(4.5), fRecPointArray(0), fDigitDataArray(0), fNRecPoints(0), fCaloClusterDataPtr(0), fCaloClusterHeaderPtr(0), //fAnalyzerPtr(0), fDoClusterFit(false), fHaveCPVInfo(false), fDoPID(false), fHaveDistanceToBadChannel(false), fGeometry(0), fClusterType(AliESDCaloCluster::kPHOSCluster) { //See header file for documentation } AliHLTCaloClusterAnalyser::~AliHLTCaloClusterAnalyser() { // See header file for class documentation } void AliHLTCaloClusterAnalyser::SetCaloClusterData(AliHLTCaloClusterDataStruct *caloClusterDataPtr) { //see header file for documentation fCaloClusterDataPtr = caloClusterDataPtr; } void AliHLTCaloClusterAnalyser::SetRecPointArray(AliHLTCaloRecPointDataStruct **recPointDataPtr, Int_t nRecPoints) { fRecPointArray = recPointDataPtr; fNRecPoints = nRecPoints; } void AliHLTCaloClusterAnalyser::SetDigitDataArray(AliHLTCaloDigitDataStruct *digits) { // AliHLTCaloClusterizer cl("PHOS"); // cl.CheckDigits(fRecPointArray, digits, fNRecPoints); fDigitDataArray = digits; //cl.CheckDigits(fRecPointArray, fDigitDataArray, fNRecPoints); } Int_t AliHLTCaloClusterAnalyser::CalculateCenterOfGravity() { //see header file for documentation Float_t wtot = 0.; Float_t x = 0.; Float_t z = 0.; Float_t xi = 0.; Float_t zi = 0.; AliHLTCaloDigitDataStruct *digit = 0; UInt_t iDigit = 0; for(Int_t iRecPoint=0; iRecPoint < fNRecPoints; iRecPoint++) { AliHLTCaloRecPointDataStruct *recPoint = fRecPointArray[iRecPoint]; // digit = &(recPoint->fDigits); Int_t *digitIndexPtr = &(recPoint->fDigits); wtot = 0; x = 0; z = 0; /*Float_t maxAmp = 0; Int_t maxX = 0; Int_t maxZ = 0; */for(iDigit = 0; iDigit < recPoint->fMultiplicity; iDigit++) { digit = &(fDigitDataArray[*digitIndexPtr]); xi = digit->fX+0.5; zi = digit->fZ+0.5; if (recPoint->fAmp > 0 && digit->fEnergy > 0) { Float_t w = TMath::Max( 0., fLogWeight + TMath::Log( digit->fEnergy / recPoint->fAmp ) ) ; x += xi * w ; z += zi * w ; wtot += w ; /* if(digit->fEnergy > maxAmp) { maxAmp = digit->fEnergy; maxX = digit->fX + 0.5; maxZ = digit->fZ + 0.5; }*/ } digitIndexPtr++; } if (wtot>0) { recPoint->fX = x/wtot ; recPoint->fZ = z/wtot ; } else { recPoint->fAmp = 0; } // printf("Max digit: E = %f, x = %d, z= %d, cluster: E = %f, x = %f, z = %f\n" , maxAmp, maxX, maxZ, recPoint->fAmp, recPoint->fX, recPoint->fZ); } return 0; } Int_t AliHLTCaloClusterAnalyser::CalculateRecPointMoments() { //See header file for documentation return 0; } Int_t AliHLTCaloClusterAnalyser::CalculateClusterMoments(AliHLTCaloRecPointDataStruct */*recPointPtr*/, AliHLTCaloClusterDataStruct* /*clusterPtr*/) { //See header file for documentation return 0; } Int_t AliHLTCaloClusterAnalyser::DeconvoluteClusters() { //See header file for documentation return 0; } Int_t AliHLTCaloClusterAnalyser::CreateClusters(Int_t nRecPoints, UInt_t availableSize, UInt_t& totSize) { //See header file for documentation fNRecPoints = nRecPoints; if(fGeometry == 0) { HLTError("No geometry object is initialised, creation of clusters stopped"); } CalculateCenterOfGravity(); // AliHLTCaloDigitDataStruct* digitPtr = &(recPointPtr->fDigits); AliHLTCaloDigitDataStruct* digitPtr = 0; AliHLTCaloClusterDataStruct* caloClusterPtr = 0; // Int_t id = -1; TVector3 globalPos; for(Int_t i = 0; i < fNRecPoints; i++) //TODO needs fix when we start unfolding (number of clusters not necessarily same as number of recpoints gotten from the clusterizer { if((availableSize - totSize) < sizeof(AliHLTCaloClusterDataStruct)) { HLTError("Out of buffer: available size is: %d, total size used: %d", availableSize, totSize); return -ENOBUFS; } totSize += sizeof(AliHLTCaloClusterDataStruct); caloClusterPtr = fCaloClusterDataPtr; caloClusterPtr->fChi2 = 0; caloClusterPtr->fClusterType = kUndef; caloClusterPtr->fDispersion = 0; caloClusterPtr->fDistanceToBadChannel = 0; caloClusterPtr->fDistToBadChannel = 0; caloClusterPtr->fEmcCpvDistance = 0; caloClusterPtr->fEnergy = 0; caloClusterPtr->fFitQuality = 0; caloClusterPtr->fID = 0; caloClusterPtr->fM02 = 0; caloClusterPtr->fM20 = 0; caloClusterPtr->fNCells = 0; caloClusterPtr->fNExMax = 0; caloClusterPtr->fTOF = 0; caloClusterPtr->fTrackDx = 0; caloClusterPtr->fTrackDz = 0; AliHLTCaloRecPointDataStruct *recPointPtr = fRecPointArray[i]; AliHLTCaloGlobalCoordinate globalCoord; fGeometry->GetGlobalCoordinates(*recPointPtr, globalCoord); caloClusterPtr->fGlobalPos[0] = globalCoord.fX; caloClusterPtr->fGlobalPos[1] = globalCoord.fY; caloClusterPtr->fGlobalPos[2] = globalCoord.fZ; HLTDebug("Cluster local position: x = %f, z = %f, module = %d", recPointPtr->fX, recPointPtr->fZ, recPointPtr->fModule); HLTDebug("Cluster global position: x = %f, y = %f, z = %f", globalCoord.fX, globalCoord.fY, globalCoord.fZ); //caloClusterPtr->fNCells = 0;//recPointPtr->fMultiplicity; caloClusterPtr->fNCells = recPointPtr->fMultiplicity; caloClusterPtr->fClusterType = fClusterType; // Int_t tmpSize = 0;//totSize + (caloClusterPtr->fNCells-1)*(sizeof(Short_t) + sizeof(Float_t)); //TODO remove hardcoded 10; memset(caloClusterPtr->fTracksMatched, 0xff, sizeof(Int_t)*10); //Int_t tmpSize = totSize + (caloClusterPtr->fNCells-1)*(sizeof(Short_t) + sizeof(Float_t)); UInt_t tmpSize = (caloClusterPtr->fNCells-1)*sizeof(AliHLTCaloCellDataStruct); if((availableSize - totSize) < tmpSize) { HLTError("Out of buffer, available size is: %d, total size used: %d, extra size needed: %d", availableSize, totSize, tmpSize); return -ENOBUFS; } Int_t *digitIndexPtr = &(recPointPtr->fDigits); Int_t id = 0; AliHLTCaloCellDataStruct *cellPtr = &(caloClusterPtr->fCaloCells); for(UInt_t j = 0; j < caloClusterPtr->fNCells; j++) { digitPtr = &(fDigitDataArray[*digitIndexPtr]); fGeometry->GetCellAbsId(recPointPtr->fModule, digitPtr->fX, digitPtr->fZ, id); cellPtr->fCellsAbsId= id; cellPtr->fCellsAmpFraction = digitPtr->fEnergy/recPointPtr->fAmp; //printf("Cell ID pointer: %x\n", cellIDPtr); //printf("Cell Amp Pointer: %x\n", cellAmpFracPtr); //printf("Cell pos: x = %d, z = %d\n", digitPtr->fX, digitPtr->fZ); // printf("Cell ID: %d\n", cellPtr->fCellsAbsId); //printf("Cell Amp: %f, pointer: %x\n", *cellAmpFracPtr, cellAmpFracPtr); cellPtr++; digitIndexPtr++; } totSize += tmpSize; caloClusterPtr->fEnergy = recPointPtr->fAmp; HLTDebug("Cluster global position: x = %f, y = %f, z = %f, energy: %f, number of cells: %d, cluster pointer: %x", globalCoord.fX, globalCoord.fY, globalCoord.fZ, caloClusterPtr->fEnergy, caloClusterPtr->fNCells, caloClusterPtr); if(fDoClusterFit) { FitCluster(recPointPtr); } else { caloClusterPtr->fDispersion = 0; caloClusterPtr->fFitQuality = 0; caloClusterPtr->fM20 = 0; caloClusterPtr->fM02 = 0; } if(fHaveCPVInfo) { caloClusterPtr->fEmcCpvDistance = GetCPVDistance(recPointPtr); } else { caloClusterPtr->fEmcCpvDistance = -1; } if(fDoPID) { DoParticleIdentification(caloClusterPtr); } else { for(Int_t k = 0; k < AliPID::kSPECIESN; k++) { caloClusterPtr->fPID[k] = 0; } } if(fHaveDistanceToBadChannel) { caloClusterPtr->fDistanceToBadChannel = GetDistanceToBadChannel(caloClusterPtr); } else { caloClusterPtr->fDistanceToBadChannel = -1; } caloClusterPtr->fClusterType = fClusterType; //totSize += sizeof(AliHLTCaloClusterDataStruct) + (caloClusterPtr->fNCells)*(sizeof(Short_t) +sizeof(Float_t)-1); //totSize += sizeof(AliHLTCaloClusterDataStruct) + (caloClusterPtr->fNCells-1)*(sizeof(Short_t) + sizeof(Float_t)); //printf("CaloClusterPtr: %x, energy: %f\n", caloClusterPtr, caloClusterPtr->fEnergy); // caloClusterPtr = reinterpret_cast<AliHLTCaloClusterDataStruct*>(cellAmpFracPtr); //caloClusterPtr = reinterpret_cast<AliHLTCaloClusterDataStruct*>(cellIDPtr); fCaloClusterDataPtr = reinterpret_cast<AliHLTCaloClusterDataStruct*>(cellPtr); recPointPtr = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(digitPtr); //digitPtr = &(recPointPtr->fDigits); } return fNRecPoints; } <commit_msg>- adding module to the internal calo cluster struct<commit_after>// $Id: AliHLTCaloClusterAnalyser.cxx 35107 2009-09-30 01:45:06Z phille $ /************************************************************************** * This file is property of and copyright by the ALICE HLT Project * * All rights reserved. * * * * Primary Authors: Oystein Djuvsland * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /** * @file AliHLTCaloClusterAnalyser.cxx * @author Oystein Djuvsland * @date * @brief Cluster analyser for Calo HLT */ // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt #include "AliHLTCaloClusterAnalyser.h" #include "AliHLTCaloRecPointHeaderStruct.h" #include "AliHLTCaloRecPointDataStruct.h" #include "AliHLTCaloClusterDataStruct.h" //#include "AliHLTCaloPhysicsAnalyzer.h" #include "AliHLTCaloGeometry.h" #include "AliESDCaloCluster.h" #include "TMath.h" #include "TVector3.h" #include "TH1F.h" #include "TFile.h" #include "AliHLTCaloClusterizer.h" ClassImp(AliHLTCaloClusterAnalyser); AliHLTCaloClusterAnalyser::AliHLTCaloClusterAnalyser() : // AliHLTCaloBase(), fLogWeight(4.5), fRecPointArray(0), fDigitDataArray(0), fNRecPoints(0), fCaloClusterDataPtr(0), fCaloClusterHeaderPtr(0), //fAnalyzerPtr(0), fDoClusterFit(false), fHaveCPVInfo(false), fDoPID(false), fHaveDistanceToBadChannel(false), fGeometry(0), fClusterType(AliESDCaloCluster::kPHOSCluster) { //See header file for documentation } AliHLTCaloClusterAnalyser::~AliHLTCaloClusterAnalyser() { // See header file for class documentation } void AliHLTCaloClusterAnalyser::SetCaloClusterData(AliHLTCaloClusterDataStruct *caloClusterDataPtr) { //see header file for documentation fCaloClusterDataPtr = caloClusterDataPtr; } void AliHLTCaloClusterAnalyser::SetRecPointArray(AliHLTCaloRecPointDataStruct **recPointDataPtr, Int_t nRecPoints) { fRecPointArray = recPointDataPtr; fNRecPoints = nRecPoints; } void AliHLTCaloClusterAnalyser::SetDigitDataArray(AliHLTCaloDigitDataStruct *digits) { // AliHLTCaloClusterizer cl("PHOS"); // cl.CheckDigits(fRecPointArray, digits, fNRecPoints); fDigitDataArray = digits; //cl.CheckDigits(fRecPointArray, fDigitDataArray, fNRecPoints); } Int_t AliHLTCaloClusterAnalyser::CalculateCenterOfGravity() { //see header file for documentation Float_t wtot = 0.; Float_t x = 0.; Float_t z = 0.; Float_t xi = 0.; Float_t zi = 0.; AliHLTCaloDigitDataStruct *digit = 0; UInt_t iDigit = 0; for(Int_t iRecPoint=0; iRecPoint < fNRecPoints; iRecPoint++) { AliHLTCaloRecPointDataStruct *recPoint = fRecPointArray[iRecPoint]; // digit = &(recPoint->fDigits); Int_t *digitIndexPtr = &(recPoint->fDigits); wtot = 0; x = 0; z = 0; /*Float_t maxAmp = 0; Int_t maxX = 0; Int_t maxZ = 0; */for(iDigit = 0; iDigit < recPoint->fMultiplicity; iDigit++) { digit = &(fDigitDataArray[*digitIndexPtr]); xi = digit->fX+0.5; zi = digit->fZ+0.5; if (recPoint->fAmp > 0 && digit->fEnergy > 0) { Float_t w = TMath::Max( 0., fLogWeight + TMath::Log( digit->fEnergy / recPoint->fAmp ) ) ; x += xi * w ; z += zi * w ; wtot += w ; /* if(digit->fEnergy > maxAmp) { maxAmp = digit->fEnergy; maxX = digit->fX + 0.5; maxZ = digit->fZ + 0.5; }*/ } digitIndexPtr++; } if (wtot>0) { recPoint->fX = x/wtot ; recPoint->fZ = z/wtot ; } else { recPoint->fAmp = 0; } // printf("Max digit: E = %f, x = %d, z= %d, cluster: E = %f, x = %f, z = %f\n" , maxAmp, maxX, maxZ, recPoint->fAmp, recPoint->fX, recPoint->fZ); } return 0; } Int_t AliHLTCaloClusterAnalyser::CalculateRecPointMoments() { //See header file for documentation return 0; } Int_t AliHLTCaloClusterAnalyser::CalculateClusterMoments(AliHLTCaloRecPointDataStruct */*recPointPtr*/, AliHLTCaloClusterDataStruct* /*clusterPtr*/) { //See header file for documentation return 0; } Int_t AliHLTCaloClusterAnalyser::DeconvoluteClusters() { //See header file for documentation return 0; } Int_t AliHLTCaloClusterAnalyser::CreateClusters(Int_t nRecPoints, UInt_t availableSize, UInt_t& totSize) { //See header file for documentation fNRecPoints = nRecPoints; if(fGeometry == 0) { HLTError("No geometry object is initialised, creation of clusters stopped"); } CalculateCenterOfGravity(); // AliHLTCaloDigitDataStruct* digitPtr = &(recPointPtr->fDigits); AliHLTCaloDigitDataStruct* digitPtr = 0; AliHLTCaloClusterDataStruct* caloClusterPtr = 0; // Int_t id = -1; TVector3 globalPos; for(Int_t i = 0; i < fNRecPoints; i++) //TODO needs fix when we start unfolding (number of clusters not necessarily same as number of recpoints gotten from the clusterizer { if((availableSize - totSize) < sizeof(AliHLTCaloClusterDataStruct)) { HLTError("Out of buffer: available size is: %d, total size used: %d", availableSize, totSize); return -ENOBUFS; } totSize += sizeof(AliHLTCaloClusterDataStruct); caloClusterPtr = fCaloClusterDataPtr; caloClusterPtr->fChi2 = 0; caloClusterPtr->fClusterType = kUndef; caloClusterPtr->fDispersion = 0; caloClusterPtr->fDistanceToBadChannel = 0; caloClusterPtr->fDistToBadChannel = 0; caloClusterPtr->fEmcCpvDistance = 0; caloClusterPtr->fEnergy = 0; caloClusterPtr->fFitQuality = 0; caloClusterPtr->fID = 0; caloClusterPtr->fM02 = 0; caloClusterPtr->fM20 = 0; caloClusterPtr->fNCells = 0; caloClusterPtr->fNExMax = 0; caloClusterPtr->fTOF = 0; caloClusterPtr->fTrackDx = 0; caloClusterPtr->fTrackDz = 0; AliHLTCaloRecPointDataStruct *recPointPtr = fRecPointArray[i]; AliHLTCaloGlobalCoordinate globalCoord; fGeometry->GetGlobalCoordinates(*recPointPtr, globalCoord); caloClusterPtr->fModule = recPointPtr->fModule; caloClusterPtr->fGlobalPos[0] = globalCoord.fX; caloClusterPtr->fGlobalPos[1] = globalCoord.fY; caloClusterPtr->fGlobalPos[2] = globalCoord.fZ; HLTDebug("Cluster local position: x = %f, z = %f, module = %d", recPointPtr->fX, recPointPtr->fZ, recPointPtr->fModule); HLTDebug("Cluster global position: x = %f, y = %f, z = %f", globalCoord.fX, globalCoord.fY, globalCoord.fZ); //caloClusterPtr->fNCells = 0;//recPointPtr->fMultiplicity; caloClusterPtr->fNCells = recPointPtr->fMultiplicity; caloClusterPtr->fClusterType = fClusterType; // Int_t tmpSize = 0;//totSize + (caloClusterPtr->fNCells-1)*(sizeof(Short_t) + sizeof(Float_t)); //TODO remove hardcoded 10; memset(caloClusterPtr->fTracksMatched, 0xff, sizeof(Int_t)*10); //Int_t tmpSize = totSize + (caloClusterPtr->fNCells-1)*(sizeof(Short_t) + sizeof(Float_t)); UInt_t tmpSize = (caloClusterPtr->fNCells-1)*sizeof(AliHLTCaloCellDataStruct); if((availableSize - totSize) < tmpSize) { HLTError("Out of buffer, available size is: %d, total size used: %d, extra size needed: %d", availableSize, totSize, tmpSize); return -ENOBUFS; } Int_t *digitIndexPtr = &(recPointPtr->fDigits); Int_t id = 0; AliHLTCaloCellDataStruct *cellPtr = &(caloClusterPtr->fCaloCells); for(UInt_t j = 0; j < caloClusterPtr->fNCells; j++) { digitPtr = &(fDigitDataArray[*digitIndexPtr]); fGeometry->GetCellAbsId(recPointPtr->fModule, digitPtr->fX, digitPtr->fZ, id); cellPtr->fCellsAbsId= id; cellPtr->fCellsAmpFraction = digitPtr->fEnergy/recPointPtr->fAmp; //printf("Cell ID pointer: %x\n", cellIDPtr); //printf("Cell Amp Pointer: %x\n", cellAmpFracPtr); //printf("Cell pos: x = %d, z = %d\n", digitPtr->fX, digitPtr->fZ); // printf("Cell ID: %d\n", cellPtr->fCellsAbsId); //printf("Cell Amp: %f, pointer: %x\n", *cellAmpFracPtr, cellAmpFracPtr); cellPtr++; digitIndexPtr++; } totSize += tmpSize; caloClusterPtr->fEnergy = recPointPtr->fAmp; HLTDebug("Cluster global position: x = %f, y = %f, z = %f, energy: %f, number of cells: %d, cluster pointer: %x", globalCoord.fX, globalCoord.fY, globalCoord.fZ, caloClusterPtr->fEnergy, caloClusterPtr->fNCells, caloClusterPtr); if(fDoClusterFit) { FitCluster(recPointPtr); } else { caloClusterPtr->fDispersion = 0; caloClusterPtr->fFitQuality = 0; caloClusterPtr->fM20 = 0; caloClusterPtr->fM02 = 0; } if(fHaveCPVInfo) { caloClusterPtr->fEmcCpvDistance = GetCPVDistance(recPointPtr); } else { caloClusterPtr->fEmcCpvDistance = -1; } if(fDoPID) { DoParticleIdentification(caloClusterPtr); } else { for(Int_t k = 0; k < AliPID::kSPECIESN; k++) { caloClusterPtr->fPID[k] = 0; } } if(fHaveDistanceToBadChannel) { caloClusterPtr->fDistanceToBadChannel = GetDistanceToBadChannel(caloClusterPtr); } else { caloClusterPtr->fDistanceToBadChannel = -1; } caloClusterPtr->fClusterType = fClusterType; //totSize += sizeof(AliHLTCaloClusterDataStruct) + (caloClusterPtr->fNCells)*(sizeof(Short_t) +sizeof(Float_t)-1); //totSize += sizeof(AliHLTCaloClusterDataStruct) + (caloClusterPtr->fNCells-1)*(sizeof(Short_t) + sizeof(Float_t)); //printf("CaloClusterPtr: %x, energy: %f\n", caloClusterPtr, caloClusterPtr->fEnergy); // caloClusterPtr = reinterpret_cast<AliHLTCaloClusterDataStruct*>(cellAmpFracPtr); //caloClusterPtr = reinterpret_cast<AliHLTCaloClusterDataStruct*>(cellIDPtr); fCaloClusterDataPtr = reinterpret_cast<AliHLTCaloClusterDataStruct*>(cellPtr); recPointPtr = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(digitPtr); //digitPtr = &(recPointPtr->fDigits); } return fNRecPoints; } <|endoftext|>
<commit_before>#ifndef ITER_CHAIN_HPP_ #define ITER_CHAIN_HPP_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <memory> #include <initializer_list> #include <type_traits> namespace iter { namespace impl { template <typename Container, typename... RestContainers> class Chained; template <typename Container> class Chained<Container>; template <typename Container> class ChainedFromIterable; // rather than a chain function, use a callable object to support // .from_iterable() class ChainMaker; } extern const impl::ChainMaker chain; } template <typename Container, typename... RestContainers> class iter::impl::Chained { static_assert(are_same<iterator_deref<Container>, iterator_deref<RestContainers>...>::value, "All chained iterables must have iterators that " "dereference to the same type, including cv-qualifiers " "and references."); friend class ChainMaker; template <typename, typename...> friend class Chained; private: Container container; Chained<RestContainers...> rest_chained; Chained(Container&& in_container, RestContainers&&... rest) : container(std::forward<Container>(in_container)), rest_chained{std::forward<RestContainers>(rest)...} {} public: class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<Container>> { private: using RestIter = typename Chained<RestContainers...>::Iterator; iterator_type<Container> sub_iter; iterator_type<Container> sub_end; RestIter rest_iter; bool at_end; public: Iterator(iterator_type<Container>&& s_begin, iterator_type<Container>&& s_end, RestIter&& in_rest_iter) : sub_iter{std::move(s_begin)}, sub_end{std::move(s_end)}, rest_iter{std::move(in_rest_iter)}, at_end{!(sub_iter != sub_end)} {} Iterator& operator++() { if (this->at_end) { ++this->rest_iter; } else { ++this->sub_iter; if (!(this->sub_iter != this->sub_end)) { this->at_end = true; } } return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter || this->rest_iter != other.rest_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } iterator_deref<Container> operator*() { return this->at_end ? *this->rest_iter : *this->sub_iter; } iterator_arrow<Container> operator->() { return this->at_end ? apply_arrow(this->rest_iter) : apply_arrow(this->sub_iter); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), std::begin(this->rest_chained)}; } Iterator end() { return {std::end(this->container), std::end(this->container), std::end(this->rest_chained)}; } }; template <typename Container> class iter::impl::Chained<Container> { friend class ChainMaker; template <typename, typename...> friend class Chained; private: Container container; Chained(Container&& in_container) : container(std::forward<Container>(in_container)) {} public: class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<Container>> { private: iterator_type<Container> sub_iter; iterator_type<Container> sub_end; public: Iterator(const iterator_type<Container>& s_begin, const iterator_type<Container>& s_end) : sub_iter{s_begin}, sub_end{s_end} {} Iterator& operator++() { ++this->sub_iter; return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } iterator_deref<Container> operator*() { return *this->sub_iter; } iterator_arrow<Container> operator->() { return apply_arrow(this->sub_iter); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container)}; } Iterator end() { return {std::end(this->container), std::end(this->container)}; } }; template <typename Container> class iter::impl::ChainedFromIterable { private: Container container; friend class ChainMaker; ChainedFromIterable(Container&& in_container) : container(std::forward<Container>(in_container)) {} public: class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<iterator_deref<Container>>> { private: using SubContainer = iterator_deref<Container>; using SubIter = iterator_type<SubContainer>; iterator_type<Container> top_level_iter; iterator_type<Container> top_level_end; std::unique_ptr<SubIter> sub_iter_p; std::unique_ptr<SubIter> sub_end_p; static std::unique_ptr<SubIter> clone_sub_pointer(const SubIter* sub_iter) { return std::unique_ptr<SubIter>{ sub_iter ? new SubIter{*sub_iter} : nullptr}; } bool sub_iters_differ(const Iterator& other) const { if (this->sub_iter_p == other.sub_iter_p) { return false; } if (this->sub_iter_p == nullptr || other.sub_iter_p == nullptr) { // since the first check tests if they're the same, // this will return if only one is nullptr return true; } return *this->sub_iter_p != *other.sub_iter_p; } public: Iterator( iterator_type<Container>&& top_iter, iterator_type<Container>&& top_end) : top_level_iter{std::move(top_iter)}, top_level_end{std::move(top_end)}, sub_iter_p{!(top_iter != top_end) ? // iter == end ? nullptr : new SubIter{std::begin(*top_iter)}}, sub_end_p{!(top_iter != top_end) ? // iter == end ? nullptr : new SubIter{std::end(*top_iter)}} { } Iterator(const Iterator& other) : top_level_iter{other.top_level_iter}, top_level_end{other.top_level_end}, sub_iter_p{clone_sub_pointer(other.sub_iter_p.get())}, sub_end_p{clone_sub_pointer(other.sub_end_p.get())} {} Iterator& operator=(const Iterator& other) { if (this == &other) return *this; this->top_level_iter = other.top_level_iter; this->top_level_end = other.top_level_end; this->sub_iter_p = clone_sub_pointer(other.sub_iter_p.get()); this->sub_end_p = clone_sub_pointer(other.sub_end_p.get()); return *this; } Iterator(Iterator&&) = default; Iterator& operator=(Iterator&&) = default; ~Iterator() = default; Iterator& operator++() { ++*this->sub_iter_p; if (!(*this->sub_iter_p != *this->sub_end_p)) { ++this->top_level_iter; if (this->top_level_iter != this->top_level_end) { sub_iter_p.reset(new SubIter{std::begin(*this->top_level_iter)}); sub_end_p.reset(new SubIter{std::end(*this->top_level_iter)}); } else { sub_iter_p.reset(nullptr); sub_end_p.reset(nullptr); } } return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->top_level_iter != other.top_level_iter || this->sub_iters_differ(other); } bool operator==(const Iterator& other) const { return !(*this != other); } iterator_deref<iterator_deref<Container>> operator*() { return **this->sub_iter_p; } iterator_arrow<iterator_deref<Container>> operator->() { return apply_arrow(*this->sub_iter_p); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container)}; } Iterator end() { return {std::end(this->container), std::end(this->container)}; } }; class iter::impl::ChainMaker { public: // expose regular call operator to provide usual chain() template <typename... Containers> Chained<Containers...> operator()(Containers&&... cs) const { return {std::forward<Containers>(cs)...}; } // chain.from_iterable() template <typename Container> ChainedFromIterable<Container> from_iterable(Container&& container) const { return {std::forward<Container>(container)}; } }; constexpr iter::impl::ChainMaker iter::chain{}; #endif <commit_msg>resolves chain link error<commit_after>#ifndef ITER_CHAIN_HPP_ #define ITER_CHAIN_HPP_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <memory> #include <initializer_list> #include <type_traits> namespace iter { namespace impl { template <typename Container, typename... RestContainers> class Chained; template <typename Container> class Chained<Container>; template <typename Container> class ChainedFromIterable; // rather than a chain function, use a callable object to support // .from_iterable() class ChainMaker; } } template <typename Container, typename... RestContainers> class iter::impl::Chained { static_assert(are_same<iterator_deref<Container>, iterator_deref<RestContainers>...>::value, "All chained iterables must have iterators that " "dereference to the same type, including cv-qualifiers " "and references."); friend class ChainMaker; template <typename, typename...> friend class Chained; private: Container container; Chained<RestContainers...> rest_chained; Chained(Container&& in_container, RestContainers&&... rest) : container(std::forward<Container>(in_container)), rest_chained{std::forward<RestContainers>(rest)...} {} public: class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<Container>> { private: using RestIter = typename Chained<RestContainers...>::Iterator; iterator_type<Container> sub_iter; iterator_type<Container> sub_end; RestIter rest_iter; bool at_end; public: Iterator(iterator_type<Container>&& s_begin, iterator_type<Container>&& s_end, RestIter&& in_rest_iter) : sub_iter{std::move(s_begin)}, sub_end{std::move(s_end)}, rest_iter{std::move(in_rest_iter)}, at_end{!(sub_iter != sub_end)} {} Iterator& operator++() { if (this->at_end) { ++this->rest_iter; } else { ++this->sub_iter; if (!(this->sub_iter != this->sub_end)) { this->at_end = true; } } return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter || this->rest_iter != other.rest_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } iterator_deref<Container> operator*() { return this->at_end ? *this->rest_iter : *this->sub_iter; } iterator_arrow<Container> operator->() { return this->at_end ? apply_arrow(this->rest_iter) : apply_arrow(this->sub_iter); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), std::begin(this->rest_chained)}; } Iterator end() { return {std::end(this->container), std::end(this->container), std::end(this->rest_chained)}; } }; template <typename Container> class iter::impl::Chained<Container> { friend class ChainMaker; template <typename, typename...> friend class Chained; private: Container container; Chained(Container&& in_container) : container(std::forward<Container>(in_container)) {} public: class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<Container>> { private: iterator_type<Container> sub_iter; iterator_type<Container> sub_end; public: Iterator(const iterator_type<Container>& s_begin, const iterator_type<Container>& s_end) : sub_iter{s_begin}, sub_end{s_end} {} Iterator& operator++() { ++this->sub_iter; return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } iterator_deref<Container> operator*() { return *this->sub_iter; } iterator_arrow<Container> operator->() { return apply_arrow(this->sub_iter); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container)}; } Iterator end() { return {std::end(this->container), std::end(this->container)}; } }; template <typename Container> class iter::impl::ChainedFromIterable { private: Container container; friend class ChainMaker; ChainedFromIterable(Container&& in_container) : container(std::forward<Container>(in_container)) {} public: class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<iterator_deref<Container>>> { private: using SubContainer = iterator_deref<Container>; using SubIter = iterator_type<SubContainer>; iterator_type<Container> top_level_iter; iterator_type<Container> top_level_end; std::unique_ptr<SubIter> sub_iter_p; std::unique_ptr<SubIter> sub_end_p; static std::unique_ptr<SubIter> clone_sub_pointer(const SubIter* sub_iter) { return std::unique_ptr<SubIter>{ sub_iter ? new SubIter{*sub_iter} : nullptr}; } bool sub_iters_differ(const Iterator& other) const { if (this->sub_iter_p == other.sub_iter_p) { return false; } if (this->sub_iter_p == nullptr || other.sub_iter_p == nullptr) { // since the first check tests if they're the same, // this will return if only one is nullptr return true; } return *this->sub_iter_p != *other.sub_iter_p; } public: Iterator( iterator_type<Container>&& top_iter, iterator_type<Container>&& top_end) : top_level_iter{std::move(top_iter)}, top_level_end{std::move(top_end)}, sub_iter_p{!(top_iter != top_end) ? // iter == end ? nullptr : new SubIter{std::begin(*top_iter)}}, sub_end_p{!(top_iter != top_end) ? // iter == end ? nullptr : new SubIter{std::end(*top_iter)}} { } Iterator(const Iterator& other) : top_level_iter{other.top_level_iter}, top_level_end{other.top_level_end}, sub_iter_p{clone_sub_pointer(other.sub_iter_p.get())}, sub_end_p{clone_sub_pointer(other.sub_end_p.get())} {} Iterator& operator=(const Iterator& other) { if (this == &other) return *this; this->top_level_iter = other.top_level_iter; this->top_level_end = other.top_level_end; this->sub_iter_p = clone_sub_pointer(other.sub_iter_p.get()); this->sub_end_p = clone_sub_pointer(other.sub_end_p.get()); return *this; } Iterator(Iterator&&) = default; Iterator& operator=(Iterator&&) = default; ~Iterator() = default; Iterator& operator++() { ++*this->sub_iter_p; if (!(*this->sub_iter_p != *this->sub_end_p)) { ++this->top_level_iter; if (this->top_level_iter != this->top_level_end) { sub_iter_p.reset(new SubIter{std::begin(*this->top_level_iter)}); sub_end_p.reset(new SubIter{std::end(*this->top_level_iter)}); } else { sub_iter_p.reset(nullptr); sub_end_p.reset(nullptr); } } return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->top_level_iter != other.top_level_iter || this->sub_iters_differ(other); } bool operator==(const Iterator& other) const { return !(*this != other); } iterator_deref<iterator_deref<Container>> operator*() { return **this->sub_iter_p; } iterator_arrow<iterator_deref<Container>> operator->() { return apply_arrow(*this->sub_iter_p); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container)}; } Iterator end() { return {std::end(this->container), std::end(this->container)}; } }; class iter::impl::ChainMaker { public: // expose regular call operator to provide usual chain() template <typename... Containers> Chained<Containers...> operator()(Containers&&... cs) const { return {std::forward<Containers>(cs)...}; } // chain.from_iterable() template <typename Container> ChainedFromIterable<Container> from_iterable(Container&& container) const { return {std::forward<Container>(container)}; } }; namespace iter { namespace { constexpr auto chain = impl::ChainMaker{}; } } #endif <|endoftext|>
<commit_before>#include <QDebug> #include <QElapsedTimer> // For performance measurement #include <QTime> #include "engine.h" #include "rotator.h" #include "resizer.h" Engine::Engine(QObject *parent) : QObject(parent), m_rotation(0), m_smoothPixmapTransformHint(false), m_privateOpeningState(false), m_privateSavingState(false) { } void Engine::rotate(qreal angle) { if(!m_previewImage.isNull()) { m_previewImage = Rotator::rotate(m_inputPreviewImage, angle, smoothPixmapTransformHint()); emit previewImageChanged(); } } QImage Engine::previewImage() const { return m_previewImage; } void Engine::setPreviewImage(const QImage image) { if(m_previewImage != image) { m_previewImage = image; emit previewImageChanged(); } } void Engine::setInputPreviewImage(QImage image) { if(m_inputPreviewImage != image) { m_inputPreviewImage = image; } } QString Engine::imagePath() const { return m_imagePath; } void Engine::setImagePath(QString path) { if(m_imagePath != path) { m_imagePath = path; if(!m_imagePath.isEmpty()) { setState(Engine::Processing, Engine::Opening); QThread *thread = new QThread(); Resizer *resizer = new Resizer(); resizer->moveToThread(thread); resizer->setInputImagePath(imagePath()); resizer->setWidth(previewWidth()); resizer->setHeight(previewHeight()); connect(thread, SIGNAL(started()), resizer, SLOT(process())); connect(resizer, SIGNAL(finished(QImage)), this, SLOT(setPreviewImage(QImage))); connect(resizer, SIGNAL(finished(QImage)), this, SLOT(setInputPreviewImage(QImage))); connect(resizer, SIGNAL(finished()), thread, SLOT(quit())); connect(resizer, SIGNAL(finished()), resizer, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), this, SLOT(resetPrivateOpeningState())); thread->start(); thread->setPriority(QThread::LowPriority); } emit imagePathChanged(); } } int Engine::previewWidth() const { return m_previewWidth; } void Engine::setPreviewWidth(int width) { if(m_previewWidth != width) { m_previewWidth = width; emit previewWidthChanged(); } } int Engine::previewHeight() const { return m_previewHeight; } void Engine::setPreviewHeight(int height) { if(m_previewHeight != height) { m_previewHeight = height; emit previewHeightChanged(); } } qreal Engine::rotation() const { return m_rotation; } void Engine::setRotation(qreal rotation) { if(m_rotation != rotation) { m_rotation = rotation; emit rotationChanged(); rotate(m_rotation); } } bool Engine::smoothPixmapTransformHint() const { return m_smoothPixmapTransformHint; } void Engine::setSmoothPixmapTransformHint(bool hint) { if(m_smoothPixmapTransformHint != hint) { m_smoothPixmapTransformHint = hint; } } Engine::EngineState Engine::state() const { return m_state; } void Engine::save(int quality) { if(!imagePath().isEmpty()) { setState(Engine::Processing, Engine::Saving); QString outputPath = imagePath(). insert(imagePath().lastIndexOf("."), "_rotated(" + QTime::currentTime().toString("mmss") + ")"); QThread *thread = new QThread(); Rotator *rotator = new Rotator(); rotator->moveToThread(thread); rotator->setInputImagePath(imagePath()); rotator->setAngle(rotation()); rotator->setQuality(quality); rotator->setOutputImagePath(outputPath); rotator->setSpth(smoothPixmapTransformHint()); connect(thread, SIGNAL(started()), rotator, SLOT(process())); connect(rotator, SIGNAL(finished()), thread, SLOT(quit())); connect(rotator, SIGNAL(finished()), rotator, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), this, SLOT(resetPrivateSavingState())); connect(thread , SIGNAL(finished()), this, SIGNAL(savingFinished())); thread->start(); thread->setPriority(QThread::LowPriority); } } void Engine::setState(Engine::EngineState state, Engine::PrivateEngineState privateState) { if(m_state != state) { m_state = state; switch(privateState) { case Engine::Opening: m_privateOpeningState = true; break; case Engine::Saving: m_privateSavingState = true; break; default: break; } emit stateChanged(); } } void Engine::resetState() { if((!m_privateOpeningState) && (!m_privateSavingState)) { m_state = Engine::Passive; emit stateChanged(); } } void Engine::resetPrivateOpeningState() { m_privateOpeningState = false; resetState(); } void Engine::resetPrivateSavingState() { m_privateSavingState = false; resetState(); } <commit_msg>Added exif enable settings<commit_after>#include <QDebug> #include <QElapsedTimer> // For performance measurement #include <QTime> #include "engine.h" #include "rotator.h" #include "resizer.h" Engine::Engine(QObject *parent) : QObject(parent), m_rotation(0), m_smoothPixmapTransformHint(false), m_privateOpeningState(false), m_privateSavingState(false), m_saveExifEnable(false) { } void Engine::rotate(qreal angle) { if(!m_previewImage.isNull()) { m_previewImage = Rotator::rotate(m_inputPreviewImage, angle, smoothPixmapTransformHint()); emit previewImageChanged(); } } QImage Engine::previewImage() const { return m_previewImage; } void Engine::setPreviewImage(const QImage image) { if(m_previewImage != image) { m_previewImage = image; emit previewImageChanged(); } } void Engine::setInputPreviewImage(QImage image) { if(m_inputPreviewImage != image) { m_inputPreviewImage = image; } } QString Engine::imagePath() const { return m_imagePath; } void Engine::setImagePath(QString path) { if(m_imagePath != path) { m_imagePath = path; if(!m_imagePath.isEmpty()) { setState(Engine::Processing, Engine::Opening); QThread *thread = new QThread(); Resizer *resizer = new Resizer(); resizer->moveToThread(thread); resizer->setInputImagePath(imagePath()); resizer->setWidth(previewWidth()); resizer->setHeight(previewHeight()); connect(thread, SIGNAL(started()), resizer, SLOT(process())); connect(resizer, SIGNAL(finished(QImage)), this, SLOT(setPreviewImage(QImage))); connect(resizer, SIGNAL(finished(QImage)), this, SLOT(setInputPreviewImage(QImage))); connect(resizer, SIGNAL(finished()), thread, SLOT(quit())); connect(resizer, SIGNAL(finished()), resizer, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), this, SLOT(resetPrivateOpeningState())); thread->start(); thread->setPriority(QThread::LowPriority); } emit imagePathChanged(); } } int Engine::previewWidth() const { return m_previewWidth; } void Engine::setPreviewWidth(int width) { if(m_previewWidth != width) { m_previewWidth = width; emit previewWidthChanged(); } } int Engine::previewHeight() const { return m_previewHeight; } void Engine::setPreviewHeight(int height) { if(m_previewHeight != height) { m_previewHeight = height; emit previewHeightChanged(); } } qreal Engine::rotation() const { return m_rotation; } void Engine::setRotation(qreal rotation) { if(m_rotation != rotation) { m_rotation = rotation; emit rotationChanged(); rotate(m_rotation); } } bool Engine::smoothPixmapTransformHint() const { return m_smoothPixmapTransformHint; } void Engine::setSmoothPixmapTransformHint(bool hint) { if(m_smoothPixmapTransformHint != hint) { m_smoothPixmapTransformHint = hint; } } bool Engine::saveExifEnable() const { return m_saveExifEnable; } void Engine::setSaveExifEnable(bool exifEn) { if(m_saveExifEnable != exifEn) { m_saveExifEnable = exifEn; emit saveExifEnableChanged(); } } Engine::EngineState Engine::state() const { return m_state; } void Engine::save(int quality) { if(!imagePath().isEmpty()) { setState(Engine::Processing, Engine::Saving); QString outputPath = imagePath(). insert(imagePath().lastIndexOf("."), "_rotated(" + QTime::currentTime().toString("mmss") + ")"); QThread *thread = new QThread(); Rotator *rotator = new Rotator(); rotator->moveToThread(thread); rotator->setInputImagePath(imagePath()); rotator->setAngle(rotation()); rotator->setQuality(quality); rotator->setOutputImagePath(outputPath); rotator->setSpth(smoothPixmapTransformHint()); rotator->setSaveExifEn(saveExifEnable()); connect(thread, SIGNAL(started()), rotator, SLOT(process())); connect(rotator, SIGNAL(finished()), thread, SLOT(quit())); connect(rotator, SIGNAL(finished()), rotator, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), this, SLOT(resetPrivateSavingState())); connect(thread , SIGNAL(finished()), this, SIGNAL(savingFinished())); thread->start(); thread->setPriority(QThread::LowPriority); } } void Engine::setState(Engine::EngineState state, Engine::PrivateEngineState privateState) { if(m_state != state) { m_state = state; switch(privateState) { case Engine::Opening: m_privateOpeningState = true; break; case Engine::Saving: m_privateSavingState = true; break; default: break; } emit stateChanged(); } } void Engine::resetState() { if((!m_privateOpeningState) && (!m_privateSavingState)) { m_state = Engine::Passive; emit stateChanged(); } } void Engine::resetPrivateOpeningState() { m_privateOpeningState = false; resetState(); } void Engine::resetPrivateSavingState() { m_privateSavingState = false; resetState(); } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * Simbody(tm): SimTKcommon * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2014 Stanford University and the Authors. * * Authors: Chris Dembia, Michael Sherman * * Contributors: * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include "SimTKcommon/internal/common.h" #include <string> #include <regex> #include <array> #include <algorithm> #include <iostream> #if defined(__GNUG__) // https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html #include <cxxabi.h> #include <cstdlib> #endif namespace SimTK { std::string demangle(const char* name) { #if defined(__GNUG__) int status=-100; // just in case it doesn't get set char* ret = abi::__cxa_demangle(name, NULL, NULL, &status); const char* const demangled_name = (status == 0) ? ret : name; std::string demangled_string(demangled_name); if (ret) std::free(ret); return demangled_string; #else // On other platforms, we hope the typeid name is not mangled. return name; #endif } // Given a demangled string, attempt to canonicalize it for platform // indpendence. We'll remove Microsoft's "class ", "struct ", etc. // designations, and get rid of all unnecessary spaces. std::string canonicalizeTypeName(std::string&& demangled) { using SPair = std::pair<std::regex,std::string>; // These are applied in this order. static const std::array<SPair,7> subs{ // Remove unwanted keywords and following space. SPair(std::regex("\\b(class|struct|enum|union) "), ""), // Tidy up anonymous namespace, without output like boost. SPair(std::regex("[`(]anonymous namespace[')]"), "{anonymous}"), // Standardize "unsigned int" -> "unsigned". SPair(std::regex("\\bunsigned int\\b"), "unsigned"), // Temporarily replace spaces we want to keep with "!". (\w is // alphanumeric or underscore.) SPair(std::regex("(\\w) (\\w)"), "$1!$2"), SPair(std::regex(" "), ""), // Delete unwanted spaces. // OSX clang throws in extra namespaces like "__1". Delete them. SPair(std::regex("\\b__[0-9]+::"), ""), SPair(std::regex("!"), " ") // Restore wanted spaces. }; std::string canonical(std::move(demangled)); for (const auto& sp : subs) { canonical = std::regex_replace(canonical, sp.first, sp.second); } return canonical; } std::string encodeTypeNameForXML(std::string&& nicestr) { std::string xmlstr(std::move(nicestr)); std::replace(xmlstr.begin(), xmlstr.end(), '<', '{'); std::replace(xmlstr.begin(), xmlstr.end(), '>', '}'); return xmlstr; } std::string decodeXMLTypeName(std::string&& xmlstr) { std::string nicestr(std::move(xmlstr)); std::replace(nicestr.begin(), nicestr.end(), '{', '<'); std::replace(nicestr.begin(), nicestr.end(), '}', '>'); return nicestr; } } <commit_msg>Put anonymous in parens rather than curlies to avoid conflict with angle brackets that get mapped to curlies.<commit_after>/* -------------------------------------------------------------------------- * * Simbody(tm): SimTKcommon * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org/home/simbody. * * * * Portions copyright (c) 2014 Stanford University and the Authors. * * Authors: Chris Dembia, Michael Sherman * * Contributors: * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include "SimTKcommon/internal/common.h" #include <string> #include <regex> #include <array> #include <algorithm> #include <iostream> #if defined(__GNUG__) // https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html #include <cxxabi.h> #include <cstdlib> #endif namespace SimTK { std::string demangle(const char* name) { #if defined(__GNUG__) int status=-100; // just in case it doesn't get set char* ret = abi::__cxa_demangle(name, NULL, NULL, &status); const char* const demangled_name = (status == 0) ? ret : name; std::string demangled_string(demangled_name); if (ret) std::free(ret); return demangled_string; #else // On other platforms, we hope the typeid name is not mangled. return name; #endif } // Given a demangled string, attempt to canonicalize it for platform // indpendence. We'll remove Microsoft's "class ", "struct ", etc. // designations, and get rid of all unnecessary spaces. std::string canonicalizeTypeName(std::string&& demangled) { using SPair = std::pair<std::regex,std::string>; // These are applied in this order. static const std::array<SPair,7> subs{ // Remove unwanted keywords and following space. SPair(std::regex("\\b(class|struct|enum|union) "), ""), // Tidy up anonymous namespace. SPair(std::regex("[`(]anonymous namespace[')]"), "(anonymous)"), // Standardize "unsigned int" -> "unsigned". SPair(std::regex("\\bunsigned int\\b"), "unsigned"), // Temporarily replace spaces we want to keep with "!". (\w is // alphanumeric or underscore.) SPair(std::regex("(\\w) (\\w)"), "$1!$2"), SPair(std::regex(" "), ""), // Delete unwanted spaces. // OSX clang throws in extra namespaces like "__1". Delete them. SPair(std::regex("\\b__[0-9]+::"), ""), SPair(std::regex("!"), " ") // Restore wanted spaces. }; std::string canonical(std::move(demangled)); for (const auto& sp : subs) { canonical = std::regex_replace(canonical, sp.first, sp.second); } return canonical; } std::string encodeTypeNameForXML(std::string&& nicestr) { std::string xmlstr(std::move(nicestr)); std::replace(xmlstr.begin(), xmlstr.end(), '<', '{'); std::replace(xmlstr.begin(), xmlstr.end(), '>', '}'); return xmlstr; } std::string decodeXMLTypeName(std::string&& xmlstr) { std::string nicestr(std::move(xmlstr)); std::replace(nicestr.begin(), nicestr.end(), '{', '<'); std::replace(nicestr.begin(), nicestr.end(), '}', '>'); return nicestr; } } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> //#include <codecvt> //#include <cstddef> #include <locale> #include <string> #include <iomanip> #include "cp-neural.h" using std::wcout; using std::wstring; using std::cerr; using std::vector; class Text { private: bool isinit=false; bool readDataFile(string inputfile) { std::wifstream txtfile(inputfile, std::ios::binary); if (!txtfile.is_open()) { return false; } txtfile.imbue(std::locale("en_US.UTF8")); wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)), std::istreambuf_iterator<wchar_t>()); txtfile.close(); text=ttext; filename=inputfile; return true; } public: wstring text; string filename; std::map<wchar_t,int> freq; std::map<wchar_t,int> w2v; std::map<int,wchar_t> v2w; Text(string filename) { if (readDataFile(filename)) { for (auto wc : text) { freq[wc]++; } int it=0; for (auto wc : freq) { w2v[wc.first]=it; v2w[it]=wc.first; ++it; } isinit=true; cerr << "Freq:" << freq.size() << ", w2v:" << w2v.size() << ", v2w:" << v2w.size() << endl; } } ~Text() { } bool isInit() { return isinit; } int vocsize() { if (!isinit) return 0; return v2w.size(); } }; int main(int argc, char *argv[]) { std::setlocale (LC_ALL, ""); wcout << L"Rnn-Readär" << std::endl; bool allOk=true; if (argc!=2) { cerr << "rnnreader <path-to-text-file>" << endl; exit(-1); } Text txt(argv[1]); if (!txt.isInit()) { cerr << "Cannot initialize Text object from inputfile: " << argv[1] << endl; exit(-1); } wcout << L"Text size: " << txt.text.size() << endl; wcout << L"Size of vocabulary:" << txt.freq.size() << std::endl; /* for (auto f : txt.freq) { int c=(int)f.first; wstring wc(1,f.first); wcout << wc << L"|" << wchar_t(f.first) << L"(0x" << std::hex << c << L")" ": " << std::dec << f.second << endl; } */ Color::Modifier red(Color::FG_RED); Color::Modifier green(Color::FG_GREEN); Color::Modifier def(Color::FG_DEFAULT); int T=32; int N=txt.text.size()-T-1; MatrixN Xr(N,T); MatrixN yr(N,T); wstring chunk,chunky; int n=0; for (int i=0; i<N-T-1; i+=T) { chunk=txt.text.substr(i,T); chunky=txt.text.substr(i+1,T); for (int t=0; t<T; t++) { Xr(i,t)=txt.w2v[chunk[t]]; yr(i,t)=txt.w2v[chunky[t]]; ++n; } } int maxN = 50000; if (n>maxN) n=maxN; int n1=n*0.9; int dn=(n-n1)/2; cerr << n1 << " datasets" << endl; /* MatrixN X(n1,T); MatrixN y(n1,T); MatrixN Xv(dn,T); MatrixN yv(dn,T); MatrixN Xt(dn,T); MatrixN yt(dn,T); */ MatrixN X=Xr.block(0,0,n1,T); MatrixN y=yr.block(0,0,n1,T); MatrixN Xv=Xr.block(n1,0,dn,T); MatrixN yv=yr.block(n1,0,dn,T); MatrixN Xt=Xr.block(n1+dn,0,dn,T); MatrixN yt=yr.block(n1+dn,0,dn,T); /* X=Xr.block(0,0,100000,T); y=yr.block(0,0,100000,T); Xv=Xr.block(100000,0,10000,T); yv=yr.block(100000,0,10000,T); Xt=Xr.block(110000,0,10000,T); yt=yr.block(110000,0,10000,T); */ /* X=Xr.block(0,0,10000,T); y=yr.block(0,0,10000,T); Xv=Xr.block(10000,0,1000,T); yv=yr.block(10000,0,1000,T); Xt=Xr.block(11000,0,1000,T); yt=yr.block(11000,0,1000,T); */ cpInitCompute("Rnnreader"); registerLayers(); LayerBlock lb("{name='rnnreader';init='normal';initfactor=0.5}"); int VS=txt.vocsize(); int H=64; int D=128; int BS=32; float clip=5.0; CpParams cp0; cp0.setPar("inputShape",vector<int>{T}); cp0.setPar("V",VS); cp0.setPar("D",D); lb.addLayer("WordEmbedding","WE0",cp0,{"input"}); CpParams cp1; cp1.setPar("inputShape",vector<int>{D,T}); cp1.setPar("N",BS); cp1.setPar("H",H); cp1.setPar("clip",clip); lb.addLayer("RNN","rnn1",cp1,{"WE0"}); CpParams cp2; cp2.setPar("inputShape",vector<int>{H,T}); cp2.setPar("N",BS); cp2.setPar("H",H); cp2.setPar("clip",clip); //lb.addLayer("RNN","rnn2",cp2,{"rnn1"}); CpParams cp3; cp3.setPar("inputShape",vector<int>{H,T}); cp3.setPar("N",BS); cp3.setPar("H",H); cp3.setPar("clip",clip); //lb.addLayer("RNN","rnn3",cp3,{"rnn2"}); CpParams cp10; cp10.setPar("inputShape",vector<int>{H,T}); //cp10.setPar("T",T); //cp10.setPar("D",H); cp10.setPar("M",VS); lb.addLayer("TemporalAffine","af1",cp10,{"rnn1"}); CpParams cp11; cp11.setPar("inputShape",vector<int>{VS,T}); lb.addLayer("TemporalSoftmax","sm1",cp11,{"af1"}); if (!lb.checkTopology(true)) { allOk=false; cerr << red << "Topology-check for LayerBlock: ERROR." << def << endl; } else { cerr << green << "Topology-check for LayerBlock: ok." << def << endl; } /* wstring chunk; chunk = txt.text.substr(512,128); wcout << chunk << endl; */ CpParams cpo("{verbose=true;epsilon=1e-8}"); // CpParams cpo("{verbose=false;epsilon=1e-8}"); cpo.setPar("learning_rate", (floatN)1e-3); //2.2e-2); cpo.setPar("lr_decay", (floatN)0.95); //cpo.setPar("regularization", (floatN)1.); floatN dep=1.0; floatN sep=0.0; cpo.setPar("epochs",(floatN)dep); cpo.setPar("batch_size",BS); MatrixN xg(1,1); MatrixN xg2(1,1); wstring sg; for (int i=0; i<10000; i++) { cpo.setPar("startepoch", (floatN)sep); cpo.setPar("maxthreads", (int)1); // RNN can't cope with threads. Layer *prnn1=lb.layerMap["rnn1"]; prnn1->params["ho"]->setZero(); /*Layer *prnn2=lb.layerMap["rnn2"]; prnn2->params["ho"]->setZero(); Layer *prnn3=lb.layerMap["rnn3"]; prnn3->params["ho"]->setZero(); */ floatN cAcc=lb.train(X, y, Xv, yv, "Adam", cpo); sep+=dep; int pos=rand() % 1000 + 5000; wstring instr=txt.text.substr(pos,T); xg(0,0)='A'+rand()%20; /* for (auto wc : instr) { sg[0]=wc; xg(0,0)=txt.w2v[sg[0]]; MatrixN z(0,0); MatrixN yg=lb.forward(xg,z,nullptr); } */ //xg(0,0)=txt.w2v[sg[0]]; lb.cp.setPar("T-Steps",1); /* Layer *prnn; prnn=lb.layerMap["WE0"]; prnn->cp.setPar("T-Steps",1); prnn=lb.layerMap["rnn1"]; prnn->cp.setPar("T-Steps",1); prnn=lb.layerMap["rnn2"]; prnn->cp.setPar("T-Steps",1); prnn=lb.layerMap["rnn3"]; prnn->cp.setPar("T-Steps",1); prnn=lb.layerMap["af1"]; prnn->cp.setPar("T-Steps",1); prnn=lb.layerMap["sm1"]; prnn->cp.setPar("T-Steps",1); */ int TT=1; for (int rep=0; rep<3; rep++) { t_cppl cache{}; cppl_set(&cache,"rnn1-ho",new MatrixN(1,TT)); cache["rnn1-ho"]->setZero(); /*cppl_set(&cache,"rnn2-ho",new MatrixN(1,TT)); cache["rnn2-ho"]->setZero(); cppl_set(&cache,"rnn3-ho",new MatrixN(1,TT)); cache["rnn3-ho"]->setZero();*/ cerr << "------------" << rep << "--------------------------" << endl; for (int g=0; g<200; g++) { //wcout << g << L">"; MatrixN z(0,0); //for (int i; i<xg.cols(); i++) wcout << txt.v2w[xg(0,i)]; //wcout << L"<" << endl << L">"; MatrixN probst=lb.forward(xg,z,&cache); MatrixN probsd=MatrixN(N*TT,VS); for (int n=0; n<1; n++) { for (int t=0; t<TT; t++) { for (int d=0; d<VS; d++) { probsd(n*TT+t,d)=probst(n,t*VS+d); } } } for (int t=0; t<TT; t++) { vector<floatN> probs(VS); vector<floatN> index(VS); for (int d=0; d<VS; d++) { probs[d]=probsd(0*TT+t,d); index[d]=d; } int ind=(int)index[randomChoice(index, probs)]; /* float mx=-1000.0; int ind=-1; for (int d=0; d<VS; d++) { floatN p=yg(0,t*D+d); floatN pr=p*((floatN)(rand()%100)/5000.0+0.98); if (pr>mx) { mx=pr; // yg(0,t*D+d); ind=d; } } */ wchar_t cw=txt.v2w[ind]; //if (t==0) wcout << L"[" << cw << L"<"; //wcout << L"<" << cw << L">"; if (t==0) wcout << cw; // << L"(" << ind << L")"; // if (ind==0) cerr << "probs: " << probs << endl; xg2(0,t)=ind; } //wcout << L"<" << endl; //for (int t=T-1; t>0; t--) xg(0,t)=xg(0,t-1); //for (int t=0; t< T-1; t++) xg(0,t)=xg(0,t+1); xg(0,0)=xg2(0,0); //xg=xg2; } cppl_delete(&cache); //cache.clear(); wcout << endl; } lb.cp.setPar("T-Steps",T); /* prnn=lb.layerMap["WE0"]; prnn->cp.setPar("T-Steps",T); prnn=lb.layerMap["rnn1"]; prnn->cp.setPar("T-Steps",T); prnn=lb.layerMap["rnn2"]; prnn->cp.setPar("T-Steps",T); prnn=lb.layerMap["rnn3"]; prnn->cp.setPar("T-Steps",T); prnn=lb.layerMap["af1"]; prnn->cp.setPar("T-Steps",T); prnn=lb.layerMap["sm1"]; prnn->cp.setPar("T-Steps",T); */ } /* floatN train_err, val_err, test_err; bool evalFinal=true; if (evalFinal) { train_err=lb.test(X, y, cpo.getPar("batch_size", 50)); val_err=lb.test(Xv, yv, cpo.getPar("batch_size", 50)); test_err=lb.test(Xt, yt, cpo.getPar("batch_size", 50)); cerr << "Final results on RnnReader after " << cpo.getPar("epochs",(floatN)0.0) << " epochs:" << endl; cerr << " Train-error: " << train_err << " train-acc: " << 1.0-train_err << endl; cerr << " Validation-error: " << val_err << " val-acc: " << 1.0-val_err << endl; cerr << " Test-error: " << test_err << " test-acc: " << 1.0-test_err << endl; } //return cAcc; */ cpExitCompute(); } <commit_msg>oh what a mess<commit_after>#include <iostream> #include <fstream> //#include <codecvt> //#include <cstddef> #include <locale> #include <string> #include <iomanip> #include "cp-neural.h" using std::wcout; using std::wstring; using std::cerr; using std::vector; class Text { private: bool isinit=false; bool readDataFile(string inputfile) { std::wifstream txtfile(inputfile, std::ios::binary); if (!txtfile.is_open()) { return false; } txtfile.imbue(std::locale("en_US.UTF8")); wstring ttext((std::istreambuf_iterator<wchar_t>(txtfile)), std::istreambuf_iterator<wchar_t>()); txtfile.close(); text=ttext; filename=inputfile; return true; } public: wstring text; string filename; std::map<wchar_t,int> freq; std::map<wchar_t,int> w2v; std::map<int,wchar_t> v2w; Text(string filename) { if (readDataFile(filename)) { for (auto wc : text) { freq[wc]++; } int it=0; for (auto wc : freq) { w2v[wc.first]=it; v2w[it]=wc.first; ++it; } isinit=true; cerr << "Freq:" << freq.size() << ", w2v:" << w2v.size() << ", v2w:" << v2w.size() << endl; } } ~Text() { } bool isInit() { return isinit; } int vocsize() { if (!isinit) return 0; return v2w.size(); } }; int main(int argc, char *argv[]) { std::setlocale (LC_ALL, ""); wcout << L"Rnn-Readär" << std::endl; bool allOk=true; if (argc!=2) { cerr << "rnnreader <path-to-text-file>" << endl; exit(-1); } Text txt(argv[1]); if (!txt.isInit()) { cerr << "Cannot initialize Text object from inputfile: " << argv[1] << endl; exit(-1); } wcout << L"Text size: " << txt.text.size() << endl; wcout << L"Size of vocabulary:" << txt.freq.size() << std::endl; /* for (auto f : txt.freq) { int c=(int)f.first; wstring wc(1,f.first); wcout << wc << L"|" << wchar_t(f.first) << L"(0x" << std::hex << c << L")" ": " << std::dec << f.second << endl; } */ Color::Modifier red(Color::FG_RED); Color::Modifier green(Color::FG_GREEN); Color::Modifier def(Color::FG_DEFAULT); int T=32; int N=txt.text.size()-T-1; MatrixN Xr(N,T); MatrixN yr(N,T); wstring chunk,chunky; int n=0; for (int i=0; i<N-T-1; i+=T) { chunk=txt.text.substr(i,T); chunky=txt.text.substr(i+1,T); for (int t=0; t<T; t++) { Xr(i,t)=txt.w2v[chunk[t]]; yr(i,t)=txt.w2v[chunky[t]]; ++n; } } int maxN = 50000; if (n>maxN) n=maxN; int n1=n*0.9; int dn=(n-n1)/2; cerr << n1 << " datasets" << endl; /* MatrixN X(n1,T); MatrixN y(n1,T); MatrixN Xv(dn,T); MatrixN yv(dn,T); MatrixN Xt(dn,T); MatrixN yt(dn,T); */ MatrixN X=Xr.block(0,0,n1,T); MatrixN y=yr.block(0,0,n1,T); MatrixN Xv=Xr.block(n1,0,dn,T); MatrixN yv=yr.block(n1,0,dn,T); MatrixN Xt=Xr.block(n1+dn,0,dn,T); MatrixN yt=yr.block(n1+dn,0,dn,T); /* X=Xr.block(0,0,100000,T); y=yr.block(0,0,100000,T); Xv=Xr.block(100000,0,10000,T); yv=yr.block(100000,0,10000,T); Xt=Xr.block(110000,0,10000,T); yt=yr.block(110000,0,10000,T); */ /* X=Xr.block(0,0,10000,T); y=yr.block(0,0,10000,T); Xv=Xr.block(10000,0,1000,T); yv=yr.block(10000,0,1000,T); Xt=Xr.block(11000,0,1000,T); yt=yr.block(11000,0,1000,T); */ cpInitCompute("Rnnreader"); registerLayers(); LayerBlock lb("{name='rnnreader';init='normal';initfactor=0.5}"); int VS=txt.vocsize(); int H=64; int D=128; int BS=32; float clip=5.0; CpParams cp0; cp0.setPar("inputShape",vector<int>{T}); cp0.setPar("V",VS); cp0.setPar("D",D); lb.addLayer("WordEmbedding","WE0",cp0,{"input"}); CpParams cp1; cp1.setPar("inputShape",vector<int>{D,T}); cp1.setPar("N",BS); cp1.setPar("H",H); cp1.setPar("clip",clip); lb.addLayer("RNN","rnn1",cp1,{"WE0"}); CpParams cp2; cp2.setPar("inputShape",vector<int>{H,T}); cp2.setPar("N",BS); cp2.setPar("H",H); cp2.setPar("clip",clip); //lb.addLayer("RNN","rnn2",cp2,{"rnn1"}); CpParams cp3; cp3.setPar("inputShape",vector<int>{H,T}); cp3.setPar("N",BS); cp3.setPar("H",H); cp3.setPar("clip",clip); //lb.addLayer("RNN","rnn3",cp3,{"rnn2"}); CpParams cp10; cp10.setPar("inputShape",vector<int>{H,T}); //cp10.setPar("T",T); //cp10.setPar("D",H); cp10.setPar("M",VS); lb.addLayer("TemporalAffine","af1",cp10,{"rnn1"}); CpParams cp11; cp11.setPar("inputShape",vector<int>{VS,T}); lb.addLayer("TemporalSoftmax","sm1",cp11,{"af1"}); if (!lb.checkTopology(true)) { allOk=false; cerr << red << "Topology-check for LayerBlock: ERROR." << def << endl; } else { cerr << green << "Topology-check for LayerBlock: ok." << def << endl; } /* wstring chunk; chunk = txt.text.substr(512,128); wcout << chunk << endl; */ CpParams cpo("{verbose=true;epsilon=1e-8}"); // CpParams cpo("{verbose=false;epsilon=1e-8}"); cpo.setPar("learning_rate", (floatN)1e-2); //2.2e-2); cpo.setPar("lr_decay", (floatN)0.95); //cpo.setPar("regularization", (floatN)1.); floatN dep=1.0; floatN sep=0.0; cpo.setPar("epochs",(floatN)dep); cpo.setPar("batch_size",BS); MatrixN xg(1,1); MatrixN xg2(1,1); wstring sg; for (int i=0; i<10000; i++) { cpo.setPar("startepoch", (floatN)sep); cpo.setPar("maxthreads", (int)1); // RNN can't cope with threads. //Layer *prnn1=lb.layerMap["rnn1"]; //prnn1->params["ho"]->setZero(); /*Layer *prnn2=lb.layerMap["rnn2"]; prnn2->params["ho"]->setZero(); Layer *prnn3=lb.layerMap["rnn3"]; prnn3->params["ho"]->setZero(); */ floatN cAcc=lb.train(X, y, Xv, yv, "Adam", cpo); sep+=dep; int pos=rand() % 1000 + 5000; wstring instr=txt.text.substr(pos,T); xg(0,0)='A'+rand()%20; /* for (auto wc : instr) { sg[0]=wc; xg(0,0)=txt.w2v[sg[0]]; MatrixN z(0,0); MatrixN yg=lb.forward(xg,z,nullptr); } */ //xg(0,0)=txt.w2v[sg[0]]; lb.cp.setPar("T-Steps",1); /* Layer *prnn; prnn=lb.layerMap["WE0"]; prnn->cp.setPar("T-Steps",1); prnn=lb.layerMap["rnn1"]; prnn->cp.setPar("T-Steps",1); prnn=lb.layerMap["rnn2"]; prnn->cp.setPar("T-Steps",1); prnn=lb.layerMap["rnn3"]; prnn->cp.setPar("T-Steps",1); prnn=lb.layerMap["af1"]; prnn->cp.setPar("T-Steps",1); prnn=lb.layerMap["sm1"]; prnn->cp.setPar("T-Steps",1); */ int TT=1; for (int rep=0; rep<3; rep++) { t_cppl cache{}; /* cppl_set(&cache,"rnn1-ho",new MatrixN(1,TT)); cache["rnn1-ho"]->setZero(); */ /*cppl_set(&cache,"rnn2-ho",new MatrixN(1,TT)); cache["rnn2-ho"]->setZero(); cppl_set(&cache,"rnn3-ho",new MatrixN(1,TT)); cache["rnn3-ho"]->setZero();*/ cerr << "------------" << rep << "--------------------------" << endl; for (int g=0; g<200; g++) { //wcout << g << L">"; MatrixN z(0,0); //for (int i; i<xg.cols(); i++) wcout << txt.v2w[xg(0,i)]; //wcout << L"<" << endl << L">"; MatrixN probst=lb.forward(xg,z,nullptr); //&cach e); MatrixN probsd=MatrixN(N*TT,VS); for (int n=0; n<1; n++) { for (int t=0; t<TT; t++) { for (int d=0; d<VS; d++) { probsd(n*TT+t,d)=probst(n,t*VS+d); } } } for (int t=0; t<TT; t++) { vector<floatN> probs(VS); vector<floatN> index(VS); for (int d=0; d<VS; d++) { probs[d]=probsd(0*TT+t,d); index[d]=d; } int ind=(int)index[randomChoice(index, probs)]; /* float mx=-1000.0; int ind=-1; for (int d=0; d<VS; d++) { floatN p=yg(0,t*D+d); floatN pr=p*((floatN)(rand()%100)/5000.0+0.98); if (pr>mx) { mx=pr; // yg(0,t*D+d); ind=d; } } */ wchar_t cw=txt.v2w[ind]; //if (t==0) wcout << L"[" << cw << L"<"; //wcout << L"<" << cw << L">"; if (t==0) wcout << cw; // << L"(" << ind << L")"; // if (ind==0) cerr << "probs: " << probs << endl; xg2(0,t)=ind; } //wcout << L"<" << endl; //for (int t=T-1; t>0; t--) xg(0,t)=xg(0,t-1); //for (int t=0; t< T-1; t++) xg(0,t)=xg(0,t+1); xg(0,0)=xg2(0,0); //xg=xg2; } cppl_delete(&cache); //cache.clear(); wcout << endl; } lb.cp.setPar("T-Steps",T); /* prnn=lb.layerMap["WE0"]; prnn->cp.setPar("T-Steps",T); prnn=lb.layerMap["rnn1"]; prnn->cp.setPar("T-Steps",T); prnn=lb.layerMap["rnn2"]; prnn->cp.setPar("T-Steps",T); prnn=lb.layerMap["rnn3"]; prnn->cp.setPar("T-Steps",T); prnn=lb.layerMap["af1"]; prnn->cp.setPar("T-Steps",T); prnn=lb.layerMap["sm1"]; prnn->cp.setPar("T-Steps",T); */ } /* floatN train_err, val_err, test_err; bool evalFinal=true; if (evalFinal) { train_err=lb.test(X, y, cpo.getPar("batch_size", 50)); val_err=lb.test(Xv, yv, cpo.getPar("batch_size", 50)); test_err=lb.test(Xt, yt, cpo.getPar("batch_size", 50)); cerr << "Final results on RnnReader after " << cpo.getPar("epochs",(floatN)0.0) << " epochs:" << endl; cerr << " Train-error: " << train_err << " train-acc: " << 1.0-train_err << endl; cerr << " Validation-error: " << val_err << " val-acc: " << 1.0-val_err << endl; cerr << " Test-error: " << test_err << " test-acc: " << 1.0-test_err << endl; } //return cAcc; */ cpExitCompute(); } <|endoftext|>
<commit_before>#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ drawSpeed = 200; // number of drawn shapes per draw() call drawMode = 0; // move through the drawing modes by clicking the mouse bg_color = ofColor(255); fbo_color = ofColor(0); bUpdateDrawMode = false; ofBackground(bg_color); ofSetBackgroundAuto(false); ofEnableAntiAliasing(); ofSetFrameRate(60); // cap frameRate otherwise it goes too fast ofSetRectMode(OF_RECTMODE_CENTER); ofTrueTypeFont ttf; ttf.loadFont(OF_TTF_SANS, 350); string s = "TYPE"; ofFbo fbo; fbo.allocate(ofGetWidth(), ofGetHeight(), GL_RGBA); pix.allocate(ofGetWidth(), ofGetHeight(), OF_PIXELS_RGBA); fbo.begin(); // Center string code from: // https://github.com/armadillu/ofxCenteredTrueTypeFont/blob/master/src/ofxCenteredTrueTypeFont.h ofRectangle r = ttf.getStringBoundingBox(s, 0, 0); ofVec2f offset = ofVec2f(floor(-r.x - r.width * 0.5f), floor(-r.y - r.height * 0.5f)); ofSetColor(fbo_color); ttf.drawString(s, fbo.getWidth() / 2 + offset.x, fbo.getHeight() / 2 + offset.y); fbo.end(); fbo.readToPixels(pix); // the ofPixels class has a convenient getColor() method } //-------------------------------------------------------------- void ofApp::update(){ if(bUpdateDrawMode){ updateDrawMode(); } } //-------------------------------------------------------------- void ofApp::draw(){ // This for loop ensures the code is repeated 'drawSpeed' times for(int i = 0; i < drawSpeed; i++){ // pick a random coordinate float x = ofRandom(ofGetWidth()); float y = ofRandom(ofGetHeight()); // check if the coordinate is inside the text (in the offscreen fbo's pixels) bool insideText = (pix.getColor(x, y) == fbo_color); // if it is indeed, then draw a shape in the main screen if(insideText){ // switch based on the current draw mode (move through them by clicking the mouse) // each drawing mode has custom settings (stroke, fill, shape, rotation) // note that the ofColor HSB range is from 0 to 255 // note that ofRotate works in degrees ofPushMatrix(); ofTranslate(x, y); switch(drawMode){ case 0: { float er = ofRandom(5, 45); ofColor ec; ec.setHsb(ofRandom(255), 255, 255); ofFill(); ofSetColor(ec); ofEllipse(0, 0, er, er); ofNoFill(); ofSetColor(0); ofEllipse(0, 0, er, er); break; } case 1: { float td = ofRandom(3, 10); float tr = ofRandom(360); ofColor tc; tc.setHsb(ofRandom(127.5, 212.5), 255, ofRandom(127.5, 255)); ofFill(); ofSetColor(tc); ofRotate(tr); ofTriangle(0, -td, -td, td, td, td); break; } case 2: { float rw = ofRandom(5, 20); float rh = ofRandom(5, 50); float rr = ofRandom(360); ofColor rc; rc.setHsb(ofRandom(15), ofRandom(178.5, 255), ofRandom(51, 255)); ofRotate(rr); ofFill(); ofSetColor(rc); ofRect(0, 0, rw, rh); ofNoFill(); ofSetColor(0); ofRect(0, 0, rw, rh); break; } } ofPopMatrix(); } } } //-------------------------------------------------------------- void ofApp::updateDrawMode(){ drawMode = ++drawMode % 3; // move through 3 drawing modes (0, 1, 2) ofBackground(bg_color); // clear the screen when changing drawing mode bUpdateDrawMode = false; } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ bUpdateDrawMode = true; } <commit_msg>Update AggregateDrawing example<commit_after>#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ drawSpeed = 200; // number of drawn shapes per draw() call drawMode = 0; // move through the drawing modes by clicking the mouse bg_color = ofColor(255); fbo_color = ofColor(0); bUpdateDrawMode = false; ofBackground(bg_color); ofSetBackgroundAuto(false); ofEnableAntiAliasing(); ofSetFrameRate(60); // cap frameRate otherwise it goes too fast ofSetRectMode(OF_RECTMODE_CENTER); ofTrueTypeFont ttf; ttf.loadFont(OF_TTF_SANS, 350); string s = "TYPE"; ofFbo fbo; fbo.allocate(ofGetWidth(), ofGetHeight(), GL_RGBA); pix.allocate(ofGetWidth(), ofGetHeight(), OF_PIXELS_RGBA); fbo.begin(); ofClear(0, 0, 0, 0); // Center string code from: // https://github.com/armadillu/ofxCenteredTrueTypeFont/blob/master/src/ofxCenteredTrueTypeFont.h ofRectangle r = ttf.getStringBoundingBox(s, 0, 0); ofVec2f offset = ofVec2f(floor(-r.x - r.width * 0.5f), floor(-r.y - r.height * 0.5f)); ofSetColor(fbo_color); ttf.drawString(s, fbo.getWidth() / 2 + offset.x, fbo.getHeight() / 2 + offset.y); fbo.end(); fbo.readToPixels(pix); // the ofPixels class has a convenient getColor() method } //-------------------------------------------------------------- void ofApp::update(){ if(bUpdateDrawMode){ updateDrawMode(); } ofSetWindowTitle("drawMode: " + ofToString(drawMode) + " | fps: " + ofToString(ofGetFrameRate(), 0)); } //-------------------------------------------------------------- void ofApp::draw(){ // This for loop ensures the code is repeated 'drawSpeed' times for(int i = 0; i < drawSpeed; i++){ // pick a random coordinate float x = ofRandom(ofGetWidth()); float y = ofRandom(ofGetHeight()); // check if the coordinate is inside the text (in the offscreen fbo's pixels) bool insideText = (pix.getColor(x, y) == fbo_color); // if it is indeed, then draw a shape in the main screen if(insideText){ // switch based on the current draw mode (move through them by clicking the mouse) // each drawing mode has custom settings (stroke, fill, shape, rotation) // note that the ofColor HSB range is from 0 to 255 // note that ofRotate works in degrees ofPushMatrix(); ofTranslate(x, y); switch(drawMode){ case 0: { float er = ofRandom(5, 45); ofColor ec; ec.setHsb(ofRandom(255), 255, 255); ofFill(); ofSetColor(ec); ofEllipse(0, 0, er, er); ofNoFill(); ofSetColor(0); ofEllipse(0, 0, er, er); break; } case 1: { float td = ofRandom(3, 10); float tr = ofRandom(360); ofColor tc; tc.setHsb(ofRandom(127.5, 212.5), 255, ofRandom(127.5, 255)); ofFill(); ofSetColor(tc); ofRotate(tr); ofTriangle(0, -td, -td, td, td, td); break; } case 2: { float rw = ofRandom(5, 20); float rh = ofRandom(5, 50); float rr = ofRandom(360); ofColor rc; rc.setHsb(ofRandom(15), ofRandom(178.5, 255), ofRandom(51, 255)); ofRotate(rr); ofFill(); ofSetColor(rc); ofRect(0, 0, rw, rh); ofNoFill(); ofSetColor(0); ofRect(0, 0, rw, rh); break; } } ofPopMatrix(); } } } //-------------------------------------------------------------- void ofApp::updateDrawMode(){ drawMode = ++drawMode % 3; // move through 3 drawing modes (0, 1, 2) ofBackground(bg_color); // clear the screen when changing drawing mode bUpdateDrawMode = false; } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ bUpdateDrawMode = true; } <|endoftext|>
<commit_before>#ifndef DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_HH #define DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_HH #include <dune/common/exceptions.hh> #include <dune/common/parametertree.hh> #include <dune/stuff/common/color.hh> #include "model/interface.hh" #include "model/default.hh" #include "model/thermalblock.hh" //#include "model/affineparametric/default.hh" //#include "model/affineparametric/twophase.hh" //#include "model/affineparametric/thermalblock.hh" namespace Dune { namespace DetailedSolvers { namespace LinearElliptic { template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange, bool scalarDiffusion = true > class Models { public: static std::vector< std::string > available() { return { "model.linearelliptic.default" , "model.linearelliptic.thermalblock" // , "model.linearelliptic.affineparametric.default" // , "model.linearelliptic.affineparametric.twophase" // , "model.linearelliptic.affineparametric.thermalblock" }; } // ... available() static Dune::ParameterTree defaultSettings(const std::string type, const std::string subname = "") { if (type == "model.linearelliptic.default") return ModelDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion > ::defaultSettings(subname); else if (type == "model.linearelliptic.thermalblock") return ModelThermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion > ::defaultSettings(subname); // else if (type == "model.linearelliptic.affineparametric.default") // return ModelAffineParametricDefault< DomainFieldType, dimDomain, // RangeFieldType, dimRange >::createDefaultSettings(subname); // else if (type == "model.linearelliptic.affineparametric.twophase") // return ModelAffineParametricTwoPhase< DomainFieldType, dimDomain, // RangeFieldType, dimRange >::createDefaultSettings(subname); // else if (type == "model.linearelliptic.affineparametric.thermalblock") // return ModelAffineParametricThermalblock< DomainFieldType, dimDomain, // RangeFieldType, dimRange >::createDefaultSettings(subname); else DUNE_THROW(Dune::RangeError, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " unknown model '" << type << "' requested!"); } // ... createDefaultSettings(...) static ModelInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >* create(const std::string type = available()[0], const Dune::ParameterTree description = Dune::ParameterTree()) { if (type == "model.linearelliptic.default") return ModelDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >::create(description); else if (type == "model.linearelliptic.thermalblock") return ModelThermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >::create(description); // else if (type == "model.linearelliptic.affineparametric.default") // return ModelAffineParametricDefault< DomainFieldType, dimDomain, // RangeFieldType, dimRange >::create(description); // else if (type == "model.linearelliptic.affineparametric.twophase") // return ModelAffineParametricTwoPhase< DomainFieldType, dimDomain, // RangeFieldType, dimRange >::create(description); // else if (type == "model.linearelliptic.affineparametric.thermalblock") // return ModelAffineParametricThermalblock< DomainFieldType, dimDomain, // RangeFieldType, dimRange >::create(description); else DUNE_THROW(Dune::RangeError, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " unknown model '" << type << "' requested!"); } // ... create(...) }; // class Models } // namespace LinearElliptic } // namespace DetailedSolvers } // namespace Dune #endif // DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_HH <commit_msg>[linearelliptic.model] reenabled affineparametric.default<commit_after>#ifndef DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_HH #define DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_HH #include <dune/common/exceptions.hh> #include <dune/common/parametertree.hh> #include <dune/stuff/common/color.hh> #include "model/interface.hh" #include "model/default.hh" #include "model/thermalblock.hh" #include "model/affineparametric/default.hh" //#include "model/affineparametric/twophase.hh" //#include "model/affineparametric/thermalblock.hh" namespace Dune { namespace DetailedSolvers { namespace LinearElliptic { template< class DomainFieldType, int dimDomain, class RangeFieldType, int dimRange, bool scalarDiffusion = true > class Models { public: static std::vector< std::string > available() { return { "model.linearelliptic.default" , "model.linearelliptic.thermalblock" , "model.linearelliptic.affineparametric.default" // , "model.linearelliptic.affineparametric.twophase" // , "model.linearelliptic.affineparametric.thermalblock" }; } // ... available() static Dune::ParameterTree defaultSettings(const std::string type, const std::string subname = "") { if (type == "model.linearelliptic.default") return ModelDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion > ::defaultSettings(subname); else if (type == "model.linearelliptic.thermalblock") return ModelThermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion > ::defaultSettings(subname); else if (type == "model.linearelliptic.affineparametric.default") return ModelAffineParametricDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >::defaultSettings(subname); // else if (type == "model.linearelliptic.affineparametric.twophase") // return ModelAffineParametricTwoPhase< DomainFieldType, dimDomain, // RangeFieldType, dimRange >::createDefaultSettings(subname); // else if (type == "model.linearelliptic.affineparametric.thermalblock") // return ModelAffineParametricThermalblock< DomainFieldType, dimDomain, // RangeFieldType, dimRange >::createDefaultSettings(subname); else DUNE_THROW(Dune::RangeError, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " unknown model '" << type << "' requested!"); } // ... createDefaultSettings(...) static ModelInterface< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >* create(const std::string type = available()[0], const Dune::ParameterTree description = Dune::ParameterTree()) { if (type == "model.linearelliptic.default") return ModelDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >::create(description); else if (type == "model.linearelliptic.thermalblock") return ModelThermalblock< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >::create(description); else if (type == "model.linearelliptic.affineparametric.default") return ModelAffineParametricDefault< DomainFieldType, dimDomain, RangeFieldType, dimRange, scalarDiffusion >::create(description); // else if (type == "model.linearelliptic.affineparametric.twophase") // return ModelAffineParametricTwoPhase< DomainFieldType, dimDomain, // RangeFieldType, dimRange >::create(description); // else if (type == "model.linearelliptic.affineparametric.thermalblock") // return ModelAffineParametricThermalblock< DomainFieldType, dimDomain, // RangeFieldType, dimRange >::create(description); else DUNE_THROW(Dune::RangeError, "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " unknown model '" << type << "' requested!"); } // ... create(...) }; // class Models } // namespace LinearElliptic } // namespace DetailedSolvers } // namespace Dune #endif // DUNE_DETAILED_SOLVERS_LINEARELLIPTIC_MODEL_HH <|endoftext|>
<commit_before>/*! \file exampleEarthOrbitingSatellite.cpp * Source file that contains an example application of an Earth-orbiting * satellite mission scenario using Tudat. * * Path : /Applications/ * Version : 3 * Check status : Checked * * Author : K. Kumar * Affiliation : Delft University of Technology * E-mail address : K.Kumar@tudelft.nl * * Checker : J.C.P Melman * Affiliation : Delft University of Technology * E-mail address : J.C.P.Melman@tudelft.nl * * Checker : B. Romgens * Affiliation : Delft University of Technology * E-mail address : bart.romgens@gmail.com * * Date created : 11 November, 2010 * Last modified : 17 February, 2011 * * References * * Notes * * Copyright (c) 2010 Delft University of Technology. * * This software is protected by national and international copyright. * Any unauthorized use, reproduction or modification is unlawful and * will be prosecuted. Commercial and non-private application of the * software in any form is strictly prohibited unless otherwise granted * by the authors. * * The code is provided without any warranty; without even the implied * warranty of merchantibility or fitness for a particular purpose. * * Changelog * YYMMDD Author Comment * 101111 K. Kumar File created. * 110113 K. Kumar Scenario updated to use latest version of * code; added file header and footer. * 110202 K. Kumar Scenario updated to use latest version of * code. * 110216 K. Kumar Migrated to applications namespace. * 110217 K. Kumar Function name changed. */ // Include statements. #include "exampleEarthOrbitingSatellite.h" // Using declarations. using std::cout; using std::endl; //! Namespace for all applications. namespace applications { //! Execute example of an Earth-orbiting satellite. void executeEarthOrbitingSatelliteExample( ) { // Create pointer to the state of Asterix given in Cartesian elements. CartesianElements* pointerToStateOfAsterix = new CartesianElements; // Fill initial state vector with position and // velocity given for Asterix. // Position is given in kilometers and // velocity is given in kilometers per second. pointerToStateOfAsterix->setCartesianElementX( 7000.0 ); pointerToStateOfAsterix->setCartesianElementY( 0.0 ); pointerToStateOfAsterix->setCartesianElementZ( 0.0 ); pointerToStateOfAsterix->setCartesianElementXDot( 0.0 ); pointerToStateOfAsterix->setCartesianElementYDot( 5.0 ); pointerToStateOfAsterix->setCartesianElementZDot( 7.0 ); // Convert initial state vector to meters from // kilometers. pointerToStateOfAsterix->state = unit_conversions::convertKilometersToMeters( pointerToStateOfAsterix->state ); // Create map of propagation history of Asterix. std::map < double, State* > asterixPropagationHistory; // Create a pointer to new vehicle for Asterix. Vehicle* pointerToAsterix = new Vehicle; // Create pre-defined Earth object. CelestialBody* pointerToEarth = predefined_planets:: createPredefinedPlanet( predefined_planets::earth ); // Create a pointer to a new Gravity object for Earth. Gravity* pointerToEarthGravity = new Gravity; // Set Earth as central body for gravity. pointerToEarthGravity->setBody( pointerToEarth ); // Create a pointer to a new RK4 integrator. RungeKutta4thOrderFixedStepsize* pointerToRK4 = new RungeKutta4thOrderFixedStepsize; // Set an initial stepsize for our integrator. pointerToRK4->setInitialStepsize( 30.0 ); // Create numerical propagator object. NumericalPropagator numericalPropagator; // Set fixed output interval for output in numerical // propagator object. numericalPropagator.setFixedOutputInterval( 60.0 ); // Set the propagation start time. numericalPropagator.setPropagationIntervalStart( 0.0 ); // Set the propagation end time. numericalPropagator.setPropagationIntervalEnd( 86400.0 ); // Set the integrator to use RK4. numericalPropagator.setIntegrator( pointerToRK4 ); // Add Asterix as the body that has to be propagated. numericalPropagator.addBody( pointerToAsterix ); // Add Earth gravity as force acting on Asterix. numericalPropagator.addForceModel( pointerToAsterix, pointerToEarthGravity ); // Set initial state of Asterix. numericalPropagator.setInitialState( pointerToAsterix, pointerToStateOfAsterix ); // Run simulation.86400 numericalPropagator.propagate( ); // Get propagation history of Asterix. asterixPropagationHistory = numericalPropagator. getPropagationHistoryAtFixedOutputIntervals( pointerToAsterix ); // Output final state vector of Asterix to screen. cout << "Asterix final state in km(/s):" << endl; cout << unit_conversions::convertMetersToKilometers( numericalPropagator.getFinalState( pointerToAsterix )->state ) << endl; // Write propagation history of Asterix to file. WritingOutputToFile:: writePropagationHistoryToFile( asterixPropagationHistory, "AsterixExampleEarthOrbitingSatellite.dat" ); } } // End of file. <commit_msg>Commit of small correction to Earth-orbiting satellite example.<commit_after>/*! \file exampleEarthOrbitingSatellite.cpp * Source file that contains an example application of an Earth-orbiting * satellite mission scenario using Tudat. * * Path : /Applications/ * Version : 3 * Check status : Checked * * Author : K. Kumar * Affiliation : Delft University of Technology * E-mail address : K.Kumar@tudelft.nl * * Checker : J.C.P Melman * Affiliation : Delft University of Technology * E-mail address : J.C.P.Melman@tudelft.nl * * Checker : B. Romgens * Affiliation : Delft University of Technology * E-mail address : bart.romgens@gmail.com * * Date created : 11 November, 2010 * Last modified : 17 February, 2011 * * References * * Notes * * Copyright (c) 2010 Delft University of Technology. * * This software is protected by national and international copyright. * Any unauthorized use, reproduction or modification is unlawful and * will be prosecuted. Commercial and non-private application of the * software in any form is strictly prohibited unless otherwise granted * by the authors. * * The code is provided without any warranty; without even the implied * warranty of merchantibility or fitness for a particular purpose. * * Changelog * YYMMDD Author Comment * 101111 K. Kumar File created. * 110113 K. Kumar Scenario updated to use latest version of * code; added file header and footer. * 110202 K. Kumar Scenario updated to use latest version of * code. * 110216 K. Kumar Migrated to applications namespace. * 110217 K. Kumar Function name changed. */ // Include statements. #include "exampleEarthOrbitingSatellite.h" // Using declarations. using std::cout; using std::endl; //! Namespace for all applications. namespace applications { //! Execute example of an Earth-orbiting satellite. void executeEarthOrbitingSatelliteExample( ) { // Create pointer to the state of Asterix given in Cartesian elements. CartesianElements* pointerToStateOfAsterix = new CartesianElements; // Fill initial state vector with position and // velocity given for Asterix. // Position is given in kilometers and // velocity is given in kilometers per second. pointerToStateOfAsterix->setCartesianElementX( 7000.0 ); pointerToStateOfAsterix->setCartesianElementY( 0.0 ); pointerToStateOfAsterix->setCartesianElementZ( 0.0 ); pointerToStateOfAsterix->setCartesianElementXDot( 0.0 ); pointerToStateOfAsterix->setCartesianElementYDot( 5.0 ); pointerToStateOfAsterix->setCartesianElementZDot( 7.0 ); // Convert initial state vector to meters from // kilometers. pointerToStateOfAsterix->state = unit_conversions::convertKilometersToMeters( pointerToStateOfAsterix->state ); // Create map of propagation history of Asterix. std::map < double, State* > asterixPropagationHistory; // Create a pointer to new vehicle for Asterix. Vehicle* pointerToAsterix = new Vehicle; // Create pre-defined Earth object. CelestialBody* pointerToEarth = predefined_planets:: createPredefinedPlanet( predefined_planets::earth ); // Create a pointer to a new Gravity object for Earth. Gravity* pointerToEarthGravity = new Gravity; // Set Earth as central body for gravity. pointerToEarthGravity->setBody( pointerToEarth ); // Create a pointer to a new RK4 integrator. RungeKutta4thOrderFixedStepsize* pointerToRK4 = new RungeKutta4thOrderFixedStepsize; // Set an initial stepsize for our integrator. pointerToRK4->setInitialStepsize( 30.0 ); // Create numerical propagator object. NumericalPropagator numericalPropagator; // Set fixed output interval for output in numerical // propagator object. numericalPropagator.setFixedOutputInterval( 60.0 ); // Set the propagation start time. numericalPropagator.setPropagationIntervalStart( 0.0 ); // Set the propagation end time. numericalPropagator.setPropagationIntervalEnd( 86400.0 ); // Set the integrator to use RK4. numericalPropagator.setIntegrator( pointerToRK4 ); // Add Asterix as the body that has to be propagated. numericalPropagator.addBody( pointerToAsterix ); // Add Earth gravity as force acting on Asterix. numericalPropagator.addForceModel( pointerToAsterix, pointerToEarthGravity ); // Set initial state of Asterix. numericalPropagator.setInitialState( pointerToAsterix, pointerToStateOfAsterix ); // Run simulation.86400 numericalPropagator.propagate( ); // Get propagation history of Asterix. asterixPropagationHistory = numericalPropagator. getPropagationHistoryAtFixedOutputIntervals( pointerToAsterix ); // Output final state vector of Asterix to screen. cout << "Asterix final state in km(/s):" << endl; cout << unit_conversions::convertMetersToKilometers( numericalPropagator.getFinalState( pointerToAsterix )->state ) << endl; // Write propagation history of Asterix to file. WritingOutputToFile:: writePropagationHistoryToFile( asterixPropagationHistory, "AsterixExampleEarthOrbitingSatellite.dat" ); } } // End of file. <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "KristalliProtocolModule.h" #include "KristalliProtocolModuleEvents.h" #include "Profiler.h" #include "EventManager.h" #include "CoreStringUtils.h" #include "ConsoleCommandUtils.h" #include "UiAPI.h" #include "UiMainWindow.h" #include "ConsoleAPI.h" #include <kNet.h> #include <kNet/qt/NetworkDialog.h> #include <kNet/UDPMessageConnection.h> #include <algorithm> using namespace kNet; namespace KristalliProtocol { namespace { const std::string moduleName("KristalliProtocol"); /* const struct { SocketTransportLayer transport; int portNumber; } destinationPorts[] = { { SocketOverUDP, 2345 }, // The default Kristalli over UDP port. { SocketOverTCP, 2345 }, // The default Kristalli over TCP port. { SocketOverUDP, 123 }, // Network Time Protocol. { SocketOverTCP, 80 }, // HTTP. { SocketOverTCP, 443 }, // HTTPS. { SocketOverTCP, 20 }, // FTP Data. { SocketOverTCP, 21 }, // FTP Control. { SocketOverTCP, 22 }, // SSH. { SocketOverTCP, 23 }, // TELNET. { SocketOverUDP, 25 }, // SMTP. (Microsoft) { SocketOverTCP, 25 }, // SMTP. { SocketOverTCP, 110 }, // POP3 Server listen port. { SocketOverTCP, 995 }, // POP3 over SSL. { SocketOverTCP, 109 }, // POP2. { SocketOverTCP, 6667 }, // IRC. // For more info on the following windows ports, see: http://support.microsoft.com/kb/832017 { SocketOverTCP, 135 }, // Windows RPC. { SocketOverUDP, 137 }, // Windows Cluster Administrator. / NetBIOS Name Resolution. { SocketOverUDP, 138 }, // Windows NetBIOS Datagram Service. { SocketOverTCP, 139 }, // Windows NetBIOS Session Service. { SocketOverUDP, 389 }, // Windows LDAP Server. { SocketOverTCP, 389 }, // Windows LDAP Server. { SocketOverTCP, 445 }, // Windows SMB. { SocketOverTCP, 5722 }, // Windows RPC. { SocketOverTCP, 993 }, // IMAP over SSL. // { SocketOverTCP, 1433 }, // SQL over TCP. // { SocketOverUDP, 1434 }, // SQL over UDP. { SocketOverUDP, 53 }, // DNS. { SocketOverTCP, 53 }, // DNS. Microsoft states it uses TCP 53 for DNS as well. { SocketOverUDP, 161 }, // SNMP agent port. { SocketOverUDP, 162 }, // SNMP manager port. { SocketOverUDP, 520 }, // RIP. { SocketOverUDP, 67 }, // DHCP client->server. { SocketOverUDP, 68 }, // DHCP server->client. }; /// The number of different port choices to try from the list. const int cNumPortChoices = sizeof(destinationPorts) / sizeof(destinationPorts[0]); */ } static const int cInitialAttempts = 1; static const int cReconnectAttempts = 5; KristalliProtocolModule::KristalliProtocolModule() :IModule(NameStatic()) , serverConnection(0) , server(0) , reconnectAttempts(0) { } KristalliProtocolModule::~KristalliProtocolModule() { Disconnect(); } void KristalliProtocolModule::Load() { } void KristalliProtocolModule::Unload() { Disconnect(); } void KristalliProtocolModule::PreInitialize() { kNet::SetLogChannels(kNet::LogInfo | kNet::LogError | kNet::LogUser); // Enable all log channels. } void KristalliProtocolModule::Initialize() { EventManagerPtr event_manager = framework_->GetEventManager(); networkEventCategory = event_manager->RegisterEventCategory("Kristalli"); event_manager->RegisterEvent(networkEventCategory, Events::NETMESSAGE_IN, "NetMessageIn"); defaultTransport = kNet::SocketOverTCP; const boost::program_options::variables_map &options = framework_->ProgramOptions(); if (options.count("protocol") > 0) if (QString(options["protocol"].as<std::string>().c_str()).trimmed().toLower() == "udp") defaultTransport = kNet::SocketOverUDP; } void KristalliProtocolModule::PostInitialize() { #ifdef KNET_USE_QT framework_->Console()->RegisterCommand(CreateConsoleCommand( "kNet", "Shows the kNet statistics window.", ConsoleBind(this, &KristalliProtocolModule::OpenKNetLogWindow))); #endif } void KristalliProtocolModule::Uninitialize() { Disconnect(); } #ifdef KNET_USE_QT ConsoleCommandResult KristalliProtocolModule::OpenKNetLogWindow(const StringVector &) { NetworkDialog *networkDialog = new NetworkDialog(0, &network); networkDialog->setAttribute(Qt::WA_DeleteOnClose); networkDialog->show(); return ConsoleResultSuccess(); } #endif void KristalliProtocolModule::Update(f64 frametime) { // Pulls all new inbound network messages and calls the message handler we've registered // for each of them. if (serverConnection) serverConnection->Process(); // Note: Calling the above serverConnection->Process() may set serverConnection to null if the connection gets disconnected. // Therefore, in the code below, we cannot assume serverConnection is non-null, and must check it again. // Our client->server connection is never kept half-open. // That is, at the moment the server write-closes the connection, we also write-close the connection. // Check here if the server has write-closed, and also write-close our end if so. if (serverConnection && !serverConnection->IsReadOpen() && serverConnection->IsWriteOpen()) serverConnection->Disconnect(0); // Process server incoming connections & messages if server up if (server) { server->Process(); // In Tundra, we *never* keep half-open server->client connections alive. // (the usual case would be to wait for a file transfer to complete, but Tundra messaging mechanism doesn't use that). // So, bidirectionally close all half-open connections. NetworkServer::ConnectionMap connections = server->GetConnections(); for(NetworkServer::ConnectionMap::iterator iter = connections.begin(); iter != connections.end(); ++iter) if (!iter->second->IsReadOpen() && iter->second->IsWriteOpen()) iter->second->Disconnect(0); } if ((!serverConnection || serverConnection->GetConnectionState() == ConnectionClosed || serverConnection->GetConnectionState() == ConnectionPending) && serverIp.length() != 0) { const int cReconnectTimeout = 5 * 1000.f; if (reconnectTimer.Test()) { if (reconnectAttempts) { PerformConnection(); --reconnectAttempts; } else { LogInfo("Failed to connect to " + serverIp + ":" + ToString(serverPort)); framework_->GetEventManager()->SendEvent(networkEventCategory, Events::CONNECTION_FAILED, 0); emit ConnectionAttemptFailed(); reconnectTimer.Stop(); serverIp = ""; } } else if (!reconnectTimer.Enabled()) reconnectTimer.StartMSecs(cReconnectTimeout); } // If connection was made, enable a larger number of reconnection attempts in case it gets lost if (serverConnection && serverConnection->GetConnectionState() == ConnectionOK) reconnectAttempts = cReconnectAttempts; RESETPROFILER; } const std::string &KristalliProtocolModule::NameStatic() { return moduleName; } void KristalliProtocolModule::Connect(const char *ip, unsigned short port, SocketTransportLayer transport) { if (Connected() && serverConnection && serverConnection->RemoteEndPoint().IPToString() != serverIp) Disconnect(); serverIp = ip; serverPort = port; serverTransport = transport; reconnectAttempts = cInitialAttempts; // Initial attempts when establishing connection if (!Connected()) PerformConnection(); // Start performing a connection attempt to the desired address/port/transport } void KristalliProtocolModule::PerformConnection() { if (Connected() && serverConnection) { serverConnection->Close(); // network.CloseMessageConnection(serverConnection); serverConnection = 0; } // Connect to the server. serverConnection = network.Connect(serverIp.c_str(), serverPort, serverTransport, this); if (!serverConnection) { LogError("Unable to connect to " + serverIp + ":" + ToString(serverPort)); return; } if (serverTransport == kNet::SocketOverUDP) dynamic_cast<kNet::UDPMessageConnection*>(serverConnection.ptr())->SetDatagramSendRate(500); // For TCP mode sockets, set the TCP_NODELAY option to improve latency for the messages we send. if (serverConnection->GetSocket() && serverConnection->GetSocket()->TransportLayer() == kNet::SocketOverTCP) serverConnection->GetSocket()->SetNaglesAlgorithmEnabled(false); } void KristalliProtocolModule::Disconnect() { // Clear the remembered destination server ip address so that the automatic connection timer will not try to reconnect. serverIp = ""; reconnectTimer.Stop(); if (serverConnection) { serverConnection->Disconnect(); // network.CloseMessageConnection(serverConnection); ///\todo Wait? This closes the connection. serverConnection = 0; } } bool KristalliProtocolModule::StartServer(unsigned short port, SocketTransportLayer transport) { StopServer(); const bool allowAddressReuse = true; server = network.StartServer(port, transport, this, allowAddressReuse); if (!server) { LogError("Failed to start server on port " + ToString((int)port)); throw Exception(("Failed to start server on port " + ToString((int)port) + ". Please make sure that the port is free and not used by another application. The program will now abort.").c_str()); } LogInfo("Started server on port " + ToString((int)port)); return true; } void KristalliProtocolModule::StopServer() { if (server) { network.StopServer(); connections.clear(); LogInfo("Stopped server"); server = 0; } } void KristalliProtocolModule::NewConnectionEstablished(kNet::MessageConnection *source) { assert(source); if (!source) return; if (dynamic_cast<kNet::UDPMessageConnection*>(source)) dynamic_cast<kNet::UDPMessageConnection*>(source)->SetDatagramSendRate(500); source->RegisterInboundMessageHandler(this); UserConnection* connection = new UserConnection(); connection->userID = AllocateNewConnectionID(); connection->connection = source; connections.push_back(connection); // For TCP mode sockets, set the TCP_NODELAY option to improve latency for the messages we send. if (source->GetSocket() && source->GetSocket()->TransportLayer() == kNet::SocketOverTCP) source->GetSocket()->SetNaglesAlgorithmEnabled(false); LogInfo("User connected from " + source->RemoteEndPoint().ToString() + ", connection ID " + ToString((int)connection->userID)); Events::KristalliUserConnected msg(connection); framework_->GetEventManager()->SendEvent(networkEventCategory, Events::USER_CONNECTED, &msg); emit ClientConnectedEvent(connection); } void KristalliProtocolModule::ClientDisconnected(MessageConnection *source) { // Delete from connection list if it was a known user for(UserConnectionList::iterator iter = connections.begin(); iter != connections.end(); ++iter) if ((*iter)->connection == source) { Events::KristalliUserDisconnected msg((*iter)); framework_->GetEventManager()->SendEvent(networkEventCategory, Events::USER_DISCONNECTED, &msg); emit ClientDisconnectedEvent(*iter); LogInfo("User disconnected, connection ID " + ToString((int)(*iter)->userID)); delete(*iter); connections.erase(iter); return; } LogInfo("Unknown user disconnected"); } void KristalliProtocolModule::HandleMessage(MessageConnection *source, message_id_t id, const char *data, size_t numBytes) { assert(source); assert(data); try { Events::KristalliNetMessageIn msg(source, id, data, numBytes); framework_->GetEventManager()->SendEvent(networkEventCategory, Events::NETMESSAGE_IN, &msg); emit NetworkMessageReceived(source, id, data, numBytes); } catch(std::exception &e) { LogError("KristalliProtocolModule: Exception \"" + std::string(e.what()) + "\" thrown when handling network message id " + ToString(id) + " size " + ToString((int)numBytes) + " from client " + source->ToString()); } } bool KristalliProtocolModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, IEventData* data) { return false; } u8 KristalliProtocolModule::AllocateNewConnectionID() const { u8 newID = 1; for(UserConnectionList::const_iterator iter = connections.begin(); iter != connections.end(); ++iter) newID = std::max((int)newID, (int)((*iter)->userID+1)); return newID; } UserConnection* KristalliProtocolModule::GetUserConnection(MessageConnection* source) { for (UserConnectionList::iterator iter = connections.begin(); iter != connections.end(); ++iter) if ((*iter)->connection == source) return (*iter); return 0; } UserConnection* KristalliProtocolModule::GetUserConnection(u8 id) { for (UserConnectionList::iterator iter = connections.begin(); iter != connections.end(); ++iter) if ((*iter)->userID == id) return (*iter); return 0; } } // ~KristalliProtocolModule namespace extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler); void SetProfiler(Foundation::Profiler *profiler) { Foundation::ProfilerSection::SetProfiler(profiler); } using namespace KristalliProtocol; POCO_BEGIN_MANIFEST(IModule) POCO_EXPORT_CLASS(KristalliProtocolModule) POCO_END_MANIFEST <commit_msg>Fixed bad automerge which resulted in duplicate signals to be emitted.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "KristalliProtocolModule.h" #include "KristalliProtocolModuleEvents.h" #include "Profiler.h" #include "EventManager.h" #include "CoreStringUtils.h" #include "ConsoleCommandUtils.h" #include "UiAPI.h" #include "UiMainWindow.h" #include "ConsoleAPI.h" #include <kNet.h> #include <kNet/qt/NetworkDialog.h> #include <kNet/UDPMessageConnection.h> #include <algorithm> using namespace kNet; namespace KristalliProtocol { namespace { const std::string moduleName("KristalliProtocol"); /* const struct { SocketTransportLayer transport; int portNumber; } destinationPorts[] = { { SocketOverUDP, 2345 }, // The default Kristalli over UDP port. { SocketOverTCP, 2345 }, // The default Kristalli over TCP port. { SocketOverUDP, 123 }, // Network Time Protocol. { SocketOverTCP, 80 }, // HTTP. { SocketOverTCP, 443 }, // HTTPS. { SocketOverTCP, 20 }, // FTP Data. { SocketOverTCP, 21 }, // FTP Control. { SocketOverTCP, 22 }, // SSH. { SocketOverTCP, 23 }, // TELNET. { SocketOverUDP, 25 }, // SMTP. (Microsoft) { SocketOverTCP, 25 }, // SMTP. { SocketOverTCP, 110 }, // POP3 Server listen port. { SocketOverTCP, 995 }, // POP3 over SSL. { SocketOverTCP, 109 }, // POP2. { SocketOverTCP, 6667 }, // IRC. // For more info on the following windows ports, see: http://support.microsoft.com/kb/832017 { SocketOverTCP, 135 }, // Windows RPC. { SocketOverUDP, 137 }, // Windows Cluster Administrator. / NetBIOS Name Resolution. { SocketOverUDP, 138 }, // Windows NetBIOS Datagram Service. { SocketOverTCP, 139 }, // Windows NetBIOS Session Service. { SocketOverUDP, 389 }, // Windows LDAP Server. { SocketOverTCP, 389 }, // Windows LDAP Server. { SocketOverTCP, 445 }, // Windows SMB. { SocketOverTCP, 5722 }, // Windows RPC. { SocketOverTCP, 993 }, // IMAP over SSL. // { SocketOverTCP, 1433 }, // SQL over TCP. // { SocketOverUDP, 1434 }, // SQL over UDP. { SocketOverUDP, 53 }, // DNS. { SocketOverTCP, 53 }, // DNS. Microsoft states it uses TCP 53 for DNS as well. { SocketOverUDP, 161 }, // SNMP agent port. { SocketOverUDP, 162 }, // SNMP manager port. { SocketOverUDP, 520 }, // RIP. { SocketOverUDP, 67 }, // DHCP client->server. { SocketOverUDP, 68 }, // DHCP server->client. }; /// The number of different port choices to try from the list. const int cNumPortChoices = sizeof(destinationPorts) / sizeof(destinationPorts[0]); */ } static const int cInitialAttempts = 1; static const int cReconnectAttempts = 5; KristalliProtocolModule::KristalliProtocolModule() :IModule(NameStatic()) , serverConnection(0) , server(0) , reconnectAttempts(0) { } KristalliProtocolModule::~KristalliProtocolModule() { Disconnect(); } void KristalliProtocolModule::Load() { } void KristalliProtocolModule::Unload() { Disconnect(); } void KristalliProtocolModule::PreInitialize() { kNet::SetLogChannels(kNet::LogInfo | kNet::LogError | kNet::LogUser); // Enable all log channels. } void KristalliProtocolModule::Initialize() { EventManagerPtr event_manager = framework_->GetEventManager(); networkEventCategory = event_manager->RegisterEventCategory("Kristalli"); event_manager->RegisterEvent(networkEventCategory, Events::NETMESSAGE_IN, "NetMessageIn"); defaultTransport = kNet::SocketOverTCP; const boost::program_options::variables_map &options = framework_->ProgramOptions(); if (options.count("protocol") > 0) if (QString(options["protocol"].as<std::string>().c_str()).trimmed().toLower() == "udp") defaultTransport = kNet::SocketOverUDP; } void KristalliProtocolModule::PostInitialize() { #ifdef KNET_USE_QT framework_->Console()->RegisterCommand(CreateConsoleCommand( "kNet", "Shows the kNet statistics window.", ConsoleBind(this, &KristalliProtocolModule::OpenKNetLogWindow))); #endif } void KristalliProtocolModule::Uninitialize() { Disconnect(); } #ifdef KNET_USE_QT ConsoleCommandResult KristalliProtocolModule::OpenKNetLogWindow(const StringVector &) { NetworkDialog *networkDialog = new NetworkDialog(0, &network); networkDialog->setAttribute(Qt::WA_DeleteOnClose); networkDialog->show(); return ConsoleResultSuccess(); } #endif void KristalliProtocolModule::Update(f64 frametime) { // Pulls all new inbound network messages and calls the message handler we've registered // for each of them. if (serverConnection) serverConnection->Process(); // Note: Calling the above serverConnection->Process() may set serverConnection to null if the connection gets disconnected. // Therefore, in the code below, we cannot assume serverConnection is non-null, and must check it again. // Our client->server connection is never kept half-open. // That is, at the moment the server write-closes the connection, we also write-close the connection. // Check here if the server has write-closed, and also write-close our end if so. if (serverConnection && !serverConnection->IsReadOpen() && serverConnection->IsWriteOpen()) serverConnection->Disconnect(0); // Process server incoming connections & messages if server up if (server) { server->Process(); // In Tundra, we *never* keep half-open server->client connections alive. // (the usual case would be to wait for a file transfer to complete, but Tundra messaging mechanism doesn't use that). // So, bidirectionally close all half-open connections. NetworkServer::ConnectionMap connections = server->GetConnections(); for(NetworkServer::ConnectionMap::iterator iter = connections.begin(); iter != connections.end(); ++iter) if (!iter->second->IsReadOpen() && iter->second->IsWriteOpen()) iter->second->Disconnect(0); } if ((!serverConnection || serverConnection->GetConnectionState() == ConnectionClosed || serverConnection->GetConnectionState() == ConnectionPending) && serverIp.length() != 0) { const int cReconnectTimeout = 5 * 1000.f; if (reconnectTimer.Test()) { if (reconnectAttempts) { PerformConnection(); --reconnectAttempts; } else { LogInfo("Failed to connect to " + serverIp + ":" + ToString(serverPort)); framework_->GetEventManager()->SendEvent(networkEventCategory, Events::CONNECTION_FAILED, 0); emit ConnectionAttemptFailed(); reconnectTimer.Stop(); serverIp = ""; } } else if (!reconnectTimer.Enabled()) reconnectTimer.StartMSecs(cReconnectTimeout); } // If connection was made, enable a larger number of reconnection attempts in case it gets lost if (serverConnection && serverConnection->GetConnectionState() == ConnectionOK) reconnectAttempts = cReconnectAttempts; RESETPROFILER; } const std::string &KristalliProtocolModule::NameStatic() { return moduleName; } void KristalliProtocolModule::Connect(const char *ip, unsigned short port, SocketTransportLayer transport) { if (Connected() && serverConnection && serverConnection->RemoteEndPoint().IPToString() != serverIp) Disconnect(); serverIp = ip; serverPort = port; serverTransport = transport; reconnectAttempts = cInitialAttempts; // Initial attempts when establishing connection if (!Connected()) PerformConnection(); // Start performing a connection attempt to the desired address/port/transport } void KristalliProtocolModule::PerformConnection() { if (Connected() && serverConnection) { serverConnection->Close(); // network.CloseMessageConnection(serverConnection); serverConnection = 0; } // Connect to the server. serverConnection = network.Connect(serverIp.c_str(), serverPort, serverTransport, this); if (!serverConnection) { LogError("Unable to connect to " + serverIp + ":" + ToString(serverPort)); return; } if (serverTransport == kNet::SocketOverUDP) dynamic_cast<kNet::UDPMessageConnection*>(serverConnection.ptr())->SetDatagramSendRate(500); // For TCP mode sockets, set the TCP_NODELAY option to improve latency for the messages we send. if (serverConnection->GetSocket() && serverConnection->GetSocket()->TransportLayer() == kNet::SocketOverTCP) serverConnection->GetSocket()->SetNaglesAlgorithmEnabled(false); } void KristalliProtocolModule::Disconnect() { // Clear the remembered destination server ip address so that the automatic connection timer will not try to reconnect. serverIp = ""; reconnectTimer.Stop(); if (serverConnection) { serverConnection->Disconnect(); // network.CloseMessageConnection(serverConnection); ///\todo Wait? This closes the connection. serverConnection = 0; } } bool KristalliProtocolModule::StartServer(unsigned short port, SocketTransportLayer transport) { StopServer(); const bool allowAddressReuse = true; server = network.StartServer(port, transport, this, allowAddressReuse); if (!server) { LogError("Failed to start server on port " + ToString((int)port)); throw Exception(("Failed to start server on port " + ToString((int)port) + ". Please make sure that the port is free and not used by another application. The program will now abort.").c_str()); } LogInfo("Started server on port " + ToString((int)port)); return true; } void KristalliProtocolModule::StopServer() { if (server) { network.StopServer(); connections.clear(); LogInfo("Stopped server"); server = 0; } } void KristalliProtocolModule::NewConnectionEstablished(kNet::MessageConnection *source) { assert(source); if (!source) return; if (dynamic_cast<kNet::UDPMessageConnection*>(source)) dynamic_cast<kNet::UDPMessageConnection*>(source)->SetDatagramSendRate(500); source->RegisterInboundMessageHandler(this); UserConnection* connection = new UserConnection(); connection->userID = AllocateNewConnectionID(); connection->connection = source; connections.push_back(connection); // For TCP mode sockets, set the TCP_NODELAY option to improve latency for the messages we send. if (source->GetSocket() && source->GetSocket()->TransportLayer() == kNet::SocketOverTCP) source->GetSocket()->SetNaglesAlgorithmEnabled(false); LogInfo("User connected from " + source->RemoteEndPoint().ToString() + ", connection ID " + ToString((int)connection->userID)); Events::KristalliUserConnected msg(connection); framework_->GetEventManager()->SendEvent(networkEventCategory, Events::USER_CONNECTED, &msg); emit ClientConnectedEvent(connection); } void KristalliProtocolModule::ClientDisconnected(MessageConnection *source) { // Delete from connection list if it was a known user for(UserConnectionList::iterator iter = connections.begin(); iter != connections.end(); ++iter) if ((*iter)->connection == source) { Events::KristalliUserDisconnected msg((*iter)); framework_->GetEventManager()->SendEvent(networkEventCategory, Events::USER_DISCONNECTED, &msg); emit ClientDisconnectedEvent(*iter); LogInfo("User disconnected, connection ID " + ToString((int)(*iter)->userID)); delete(*iter); connections.erase(iter); return; } LogInfo("Unknown user disconnected"); } void KristalliProtocolModule::HandleMessage(MessageConnection *source, message_id_t id, const char *data, size_t numBytes) { assert(source); assert(data); try { Events::KristalliNetMessageIn msg(source, id, data, numBytes); framework_->GetEventManager()->SendEvent(networkEventCategory, Events::NETMESSAGE_IN, &msg); emit NetworkMessageReceived(source, id, data, numBytes); } catch(std::exception &e) { LogError("KristalliProtocolModule: Exception \"" + std::string(e.what()) + "\" thrown when handling network message id " + ToString(id) + " size " + ToString((int)numBytes) + " from client " + source->ToString()); } } bool KristalliProtocolModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, IEventData* data) { return false; } u8 KristalliProtocolModule::AllocateNewConnectionID() const { u8 newID = 1; for(UserConnectionList::const_iterator iter = connections.begin(); iter != connections.end(); ++iter) newID = std::max((int)newID, (int)((*iter)->userID+1)); return newID; } UserConnection* KristalliProtocolModule::GetUserConnection(MessageConnection* source) { for (UserConnectionList::iterator iter = connections.begin(); iter != connections.end(); ++iter) if ((*iter)->connection == source) return (*iter); return 0; } UserConnection* KristalliProtocolModule::GetUserConnection(u8 id) { for (UserConnectionList::iterator iter = connections.begin(); iter != connections.end(); ++iter) if ((*iter)->userID == id) return (*iter); return 0; } } // ~KristalliProtocolModule namespace extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler); void SetProfiler(Foundation::Profiler *profiler) { Foundation::ProfilerSection::SetProfiler(profiler); } using namespace KristalliProtocol; POCO_BEGIN_MANIFEST(IModule) POCO_EXPORT_CLASS(KristalliProtocolModule) POCO_END_MANIFEST<|endoftext|>
<commit_before>// // main.cpp // Unit Tests // // Created by Evan McCartney-Melstad on 12/31/14. // Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved. // #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "../cPWP/generateSimulatedData.h" #include "../cPWP/bamsToPWP.h" #include "catch.hpp" #include <string> /* TEST_CASE( "Simulated reads are generated", "[generateReads]" ) { // Make sure that the read simulation finishes REQUIRE( generateReadsAndMap(1, 0.01, "0.0", "300", "50", "1000000", "100", "1234", "scaffold_0.fasta") == 0); } */ TEST_CASE( "Generate reference genome for simulation tests", "[generateReference]") { REQUIRE( createReferenceGenome(10000, 0.42668722, "simulatedReferenceGenome.fasta") == 0 ); } TEST_CASE ( "Mutate a reference genome", "[mutateRefGenome]") { REQUIRE( createMutatedGenome("simulatedReferenceGenome.fasta", "simulatedReferenceGenomeMutated.fasta", 0.01) == 0); } TEST_CASE( "Generate sequence reads", "[perfectReads]") { REQUIRE( generatePerfectReads ("simulatedReferenceGenome.fasta", 1, 100, 300, "blah") == 0); } /* TEST_CASE( "Generate mutated reference genomes and simulate reads", "[genomeAndReadSim]") { REQUIRE( generateReadsAndMap(3, 0.01, "300", "25", "10000", "100", "1234", "simulatedReferenceGenome.fasta", "25") == 0); } TEST_CASE( "Run ANGSD on simulated reads", "[runANGSD]" ) { REQUIRE( runANGSDforReadCounts("bamlist.txt", "angsdOut", "25", "angsdOutLog.txt") == 0); } TEST_CASE( "Convert ANGSD read counts to unsigned chars for major and minor counts", "[convertCountsToBinary]") { REQUIRE( convertANGSDcountsToBinary("angsdOut", "angsdOut.readCounts.binary", 4, 5000) == 0); // 3 individuals, not 2, because generateReadsAndMap actually generates n+1 individuals, since one individual is identical to the reference genome. And 5000 as a max because we don't want to exclude any loci for this test } TEST_CASE( "Calculate PWP from the binary representations of the ANGSD readcounts", "[calcPWP]") { REQUIRE( calcPWPfromBinaryFile ("angsdOut.readCounts.binary", 74963, 4) == 0); } */<commit_msg>Troubleshooting<commit_after>// // main.cpp // Unit Tests // // Created by Evan McCartney-Melstad on 12/31/14. // Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved. // #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "../cPWP/generateSimulatedData.h" #include "../cPWP/bamsToPWP.h" #include "catch.hpp" #include <string> /* TEST_CASE( "Simulated reads are generated", "[generateReads]" ) { // Make sure that the read simulation finishes REQUIRE( generateReadsAndMap(1, 0.01, "0.0", "300", "50", "1000000", "100", "1234", "scaffold_0.fasta") == 0); } */ TEST_CASE( "Generate reference genome for simulation tests", "[generateReference]") { REQUIRE( createReferenceGenome(10000, 0.42668722, "simulatedReferenceGenome.fasta") == 0 ); } TEST_CASE ( "Mutate a reference genome", "[mutateRefGenome]") { REQUIRE( createMutatedGenome("simulatedReferenceGenome.fasta", "simulatedReferenceGenomeMutated.fasta", 0.01) == 0); } TEST_CASE( "Generate sequence reads", "[perfectReads]") { REQUIRE( generatePerfectReads ("simulatedReferenceGenome.fasta", 1, 100, 300, "normalRef") == 0); } TEST_CASE( "Generate sequence reads", "[perfectReads]") { REQUIRE( generatePerfectReads ("simulatedReferenceGenomeMutated.fasta", 1, 100, 300, "mutatedRef") == 0); } /* TEST_CASE( "Generate mutated reference genomes and simulate reads", "[genomeAndReadSim]") { REQUIRE( generateReadsAndMap(3, 0.01, "300", "25", "10000", "100", "1234", "simulatedReferenceGenome.fasta", "25") == 0); } TEST_CASE( "Run ANGSD on simulated reads", "[runANGSD]" ) { REQUIRE( runANGSDforReadCounts("bamlist.txt", "angsdOut", "25", "angsdOutLog.txt") == 0); } TEST_CASE( "Convert ANGSD read counts to unsigned chars for major and minor counts", "[convertCountsToBinary]") { REQUIRE( convertANGSDcountsToBinary("angsdOut", "angsdOut.readCounts.binary", 4, 5000) == 0); // 3 individuals, not 2, because generateReadsAndMap actually generates n+1 individuals, since one individual is identical to the reference genome. And 5000 as a max because we don't want to exclude any loci for this test } TEST_CASE( "Calculate PWP from the binary representations of the ANGSD readcounts", "[calcPWP]") { REQUIRE( calcPWPfromBinaryFile ("angsdOut.readCounts.binary", 74963, 4) == 0); } */<|endoftext|>
<commit_before>/* $Id$ */ // Simple task to test the collision normalization. Can be called for // both MC and data and shows how to fill the collision normalization // class // // Author: Michele Floris // CERN #include "AliCollisionNormalizationTask.h" #include <TFile.h> #include <TH1F.h> #include <TH2F.h> #include <AliLog.h> #include <AliESDEvent.h> #include <AliHeader.h> #include "AliCollisionNormalization.h" #include "AliAnalysisManager.h" #include "AliInputEventHandler.h" //#include "AliBackgroundSelection.h" #include "AliMultiplicity.h" #include "AliMCEvent.h" ClassImp(AliCollisionNormalizationTask) AliCollisionNormalizationTask::AliCollisionNormalizationTask() : AliAnalysisTaskSE("AliCollisionNormalizationTask"), fOutput(0), fIsMC(0), fCollisionNormalization(0) { // // Default event handler // // Define input and output slots here DefineOutput(1, TList::Class()); } AliCollisionNormalizationTask::AliCollisionNormalizationTask(const char* name) : AliAnalysisTaskSE(name), fOutput(0), fIsMC(0), fCollisionNormalization(new AliCollisionNormalization()) { // // Constructor. Initialization of pointers // // Define input and output slots here DefineOutput(1, TList::Class()); // AliLog::SetClassDebugLevel("AliCollisionNormalizationTask", AliLog::kWarning); } AliCollisionNormalizationTask::~AliCollisionNormalizationTask() { // // Destructor // // histograms are in the output list and deleted when the output // list is deleted by the TSelector dtor if (fOutput && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()) { delete fOutput; fOutput = 0; } } void AliCollisionNormalizationTask::UserCreateOutputObjects() { // create result objects and add to output list Printf("AliCollisionNormalizationTask::CreateOutputObjects"); fOutput = new TList; fOutput->SetOwner(); if (!fCollisionNormalization) fCollisionNormalization = new AliCollisionNormalization; fOutput->Add(fCollisionNormalization); // fOutput->Add(fCollisionNormalization->GetVzCorrZeroBin ()); // fOutput->Add(fCollisionNormalization->GetVzMCGen ()); // fOutput->Add(fCollisionNormalization->GetVzMCRec ()); // fOutput->Add(fCollisionNormalization->GetVzMCTrg ()); // fOutput->Add(fCollisionNormalization->GetVzData ()); // fOutput->Add(fCollisionNormalization->GetNEvents ()); // fOutput->Add(fCollisionNormalization->GetStatBin0 ()); } void AliCollisionNormalizationTask::UserExec(Option_t*) { // process the event PostData(1, fOutput); // Get the ESD AliESDEvent * aESD = dynamic_cast<AliESDEvent*>(fInputEvent); if (strcmp(aESD->ClassName(),"AliESDEvent")) { AliFatal("Not processing ESDs"); } // Get MC event, if needed AliMCEvent* mcEvent = fIsMC ? MCEvent() : 0; if (!mcEvent && fIsMC){ AliFatal("Running on MC but no MC handler available"); } // Physics selection. At least in the case of MC we cannot use // yourTask->SelectCollisionCandidates();, because we also need to // fill the "generated" histogram // NB never call IsEventSelected more than once per event // (statistics histogram would be altered) Bool_t isSelected = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected(); // Get the Multiplicity cut const AliMultiplicity* mult = aESD->GetMultiplicity(); if (!mult){ AliError("Can't get mult object"); return; } // Check if the event is "reconstructed" according to some quality // cuts. Tipically, we mean "it has a good-eonugh vertex" Int_t ntracklet = mult->GetNumberOfTracklets(); const AliESDVertex * vtxESD = aESD->GetPrimaryVertexSPD(); if (IsEventInBinZero()) { ntracklet = 0; vtxESD = 0; } if (ntracklet > 0 && !vtxESD) { AliError("No vertex but reconstructed tracklets?"); } // assign vz. For MC we use generated vz Float_t vz = 0; if (!fIsMC) vz = vtxESD ? vtxESD->GetZ() : 0; // FIXME : is zv used anywhere in Gen? else vz = mcEvent->GetPrimaryVertex()->GetZ(); if (fIsMC) { // Monte Carlo: we fill 3 histos if (!isSelected || !vtxESD) ntracklet = 0; //If the event does not pass the physics selection or is not rec, it goes in the bin0 fCollisionNormalization->FillVzMCGen(vz, ntracklet, mcEvent); // If triggered == passing the physics selection if (isSelected) { fCollisionNormalization->FillVzMCTrg(vz, ntracklet, mcEvent); // If reconstructer == good enough vertex if (vtxESD) fCollisionNormalization->FillVzMCRec(vz, ntracklet, mcEvent); } } else { if (isSelected) { // Passing the trigger fCollisionNormalization->FillVzData(vz,ntracklet); } } } void AliCollisionNormalizationTask::Terminate(Option_t *) { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. fOutput = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutput) Printf("ERROR: fOutput not available"); } Bool_t AliCollisionNormalizationTask::IsEventInBinZero() { // Returns true if an event is to be assigned to the zero bin // // You should have your own version of this method in the class: in // general, the definition of "reconstructed" event is subjective. Bool_t isZeroBin = kTRUE; const AliESDEvent* esd= dynamic_cast<AliESDEvent*>(fInputEvent); if (!esd){ Printf("AliCollisionNormalizationTask::IsEventInBinZero: Can't get ESD"); return kFALSE; } const AliMultiplicity* mult = esd->GetMultiplicity(); if (!mult){ Printf("AliCollisionNormalizationTask::IsEventInBinZero: Can't get mult object"); return kFALSE; } Int_t ntracklet = mult->GetNumberOfTracklets(); const AliESDVertex * vtxESD = esd->GetPrimaryVertexSPD(); if(vtxESD) { // If there is a vertex from vertexer z with delta phi > 0.02 we // don't consider it rec (we keep the event in bin0). If quality // is good eneough we check the number of tracklets // if the vertex is more than 15 cm away, this is autamatically bin0 if( TMath::Abs(vtxESD->GetZ()) <= 15 ) { if (vtxESD->IsFromVertexerZ()) { if (vtxESD->GetDispersion()<=0.02 ) { if(ntracklet>0) isZeroBin = kFALSE; } } else if(ntracklet>0) isZeroBin = kFALSE; // if the event is not from Vz we chek the n of tracklets } } return isZeroBin; } <commit_msg>Coverity fix 10664<commit_after>/* $Id$ */ // Simple task to test the collision normalization. Can be called for // both MC and data and shows how to fill the collision normalization // class // // Author: Michele Floris // CERN #include "AliCollisionNormalizationTask.h" #include <TFile.h> #include <TH1F.h> #include <TH2F.h> #include <AliLog.h> #include <AliESDEvent.h> #include <AliHeader.h> #include "AliCollisionNormalization.h" #include "AliAnalysisManager.h" #include "AliInputEventHandler.h" //#include "AliBackgroundSelection.h" #include "AliMultiplicity.h" #include "AliMCEvent.h" ClassImp(AliCollisionNormalizationTask) AliCollisionNormalizationTask::AliCollisionNormalizationTask() : AliAnalysisTaskSE("AliCollisionNormalizationTask"), fOutput(0), fIsMC(0), fCollisionNormalization(0) { // // Default event handler // // Define input and output slots here DefineOutput(1, TList::Class()); } AliCollisionNormalizationTask::AliCollisionNormalizationTask(const char* name) : AliAnalysisTaskSE(name), fOutput(0), fIsMC(0), fCollisionNormalization(new AliCollisionNormalization()) { // // Constructor. Initialization of pointers // // Define input and output slots here DefineOutput(1, TList::Class()); // AliLog::SetClassDebugLevel("AliCollisionNormalizationTask", AliLog::kWarning); } AliCollisionNormalizationTask::~AliCollisionNormalizationTask() { // // Destructor // // histograms are in the output list and deleted when the output // list is deleted by the TSelector dtor if (fOutput && !AliAnalysisManager::GetAnalysisManager()->IsProofMode()) { delete fOutput; fOutput = 0; } } void AliCollisionNormalizationTask::UserCreateOutputObjects() { // create result objects and add to output list Printf("AliCollisionNormalizationTask::CreateOutputObjects"); fOutput = new TList; fOutput->SetOwner(); if (!fCollisionNormalization) fCollisionNormalization = new AliCollisionNormalization; fOutput->Add(fCollisionNormalization); // fOutput->Add(fCollisionNormalization->GetVzCorrZeroBin ()); // fOutput->Add(fCollisionNormalization->GetVzMCGen ()); // fOutput->Add(fCollisionNormalization->GetVzMCRec ()); // fOutput->Add(fCollisionNormalization->GetVzMCTrg ()); // fOutput->Add(fCollisionNormalization->GetVzData ()); // fOutput->Add(fCollisionNormalization->GetNEvents ()); // fOutput->Add(fCollisionNormalization->GetStatBin0 ()); } void AliCollisionNormalizationTask::UserExec(Option_t*) { // process the event PostData(1, fOutput); // Get the ESD AliESDEvent * aESD = dynamic_cast<AliESDEvent*>(fInputEvent); if(!aESD) { AliFatal("Cannot get ESD"); } if (strcmp(aESD->ClassName(),"AliESDEvent")) { AliFatal("Not processing ESDs"); } // Get MC event, if needed AliMCEvent* mcEvent = fIsMC ? MCEvent() : 0; if (!mcEvent && fIsMC){ AliFatal("Running on MC but no MC handler available"); } // Physics selection. At least in the case of MC we cannot use // yourTask->SelectCollisionCandidates();, because we also need to // fill the "generated" histogram // NB never call IsEventSelected more than once per event // (statistics histogram would be altered) Bool_t isSelected = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected(); // Get the Multiplicity cut const AliMultiplicity* mult = aESD->GetMultiplicity(); if (!mult){ AliError("Can't get mult object"); return; } // Check if the event is "reconstructed" according to some quality // cuts. Tipically, we mean "it has a good-eonugh vertex" Int_t ntracklet = mult->GetNumberOfTracklets(); const AliESDVertex * vtxESD = aESD->GetPrimaryVertexSPD(); if (IsEventInBinZero()) { ntracklet = 0; vtxESD = 0; } if (ntracklet > 0 && !vtxESD) { AliError("No vertex but reconstructed tracklets?"); } // assign vz. For MC we use generated vz Float_t vz = 0; if (!fIsMC) vz = vtxESD ? vtxESD->GetZ() : 0; // FIXME : is zv used anywhere in Gen? else vz = mcEvent->GetPrimaryVertex()->GetZ(); if (fIsMC) { // Monte Carlo: we fill 3 histos if (!isSelected || !vtxESD) ntracklet = 0; //If the event does not pass the physics selection or is not rec, it goes in the bin0 fCollisionNormalization->FillVzMCGen(vz, ntracklet, mcEvent); // If triggered == passing the physics selection if (isSelected) { fCollisionNormalization->FillVzMCTrg(vz, ntracklet, mcEvent); // If reconstructer == good enough vertex if (vtxESD) fCollisionNormalization->FillVzMCRec(vz, ntracklet, mcEvent); } } else { if (isSelected) { // Passing the trigger fCollisionNormalization->FillVzData(vz,ntracklet); } } } void AliCollisionNormalizationTask::Terminate(Option_t *) { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. fOutput = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutput) Printf("ERROR: fOutput not available"); } Bool_t AliCollisionNormalizationTask::IsEventInBinZero() { // Returns true if an event is to be assigned to the zero bin // // You should have your own version of this method in the class: in // general, the definition of "reconstructed" event is subjective. Bool_t isZeroBin = kTRUE; const AliESDEvent* esd= dynamic_cast<AliESDEvent*>(fInputEvent); if (!esd){ Printf("AliCollisionNormalizationTask::IsEventInBinZero: Can't get ESD"); return kFALSE; } const AliMultiplicity* mult = esd->GetMultiplicity(); if (!mult){ Printf("AliCollisionNormalizationTask::IsEventInBinZero: Can't get mult object"); return kFALSE; } Int_t ntracklet = mult->GetNumberOfTracklets(); const AliESDVertex * vtxESD = esd->GetPrimaryVertexSPD(); if(vtxESD) { // If there is a vertex from vertexer z with delta phi > 0.02 we // don't consider it rec (we keep the event in bin0). If quality // is good eneough we check the number of tracklets // if the vertex is more than 15 cm away, this is autamatically bin0 if( TMath::Abs(vtxESD->GetZ()) <= 15 ) { if (vtxESD->IsFromVertexerZ()) { if (vtxESD->GetDispersion()<=0.02 ) { if(ntracklet>0) isZeroBin = kFALSE; } } else if(ntracklet>0) isZeroBin = kFALSE; // if the event is not from Vz we chek the n of tracklets } } return isZeroBin; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2005-2007 by the FIFE Team * * fife-public@lists.sourceforge.net * * This file is part of FIFE. * * * * FIFE is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ // Standard C++ library includes #include <cstring> #include <algorithm> // 3rd party library includes #include <boost/scoped_array.hpp> // FIFE includes // These includes are split up in two parts, separated by one empty line // First block: files included from the FIFE root src directory // Second block: files included from the same folder #include "vfs/raw/rawdata.h" #include "video/animation.h" #include "video/image.h" #include "video/renderbackend.h" #include "video/rendermanager.h" #include "exception.h" #include "debugutils.h" #include "imagecache.h" #include "settingsmanager.h" #include "frm.h" #include "animatedpal.h" namespace FIFE { namespace map { namespace loaders { namespace fallout { // FIXME: If this is an intrinsic part of the file format, then we should // just use arrays of that size. Otherwise, there's a bug anyway :) const int FRM_MAX_FRAME_CT = 6; FRM::FRM(const std::string& path, AnimatedPalette* palette) : m_file(path), m_palette(palette), m_version(0), m_frames_per_direction(0), m_directions(0), m_shifts_x(FRM_MAX_FRAME_CT), m_shifts_y(FRM_MAX_FRAME_CT), m_offsets(FRM_MAX_FRAME_CT), m_frame_info(FRM_MAX_FRAME_CT) { init(); load(); } void FRM::init() { m_light_level = SettingsManager::instance()->read<int>("LightingLevel", 4); if (m_light_level < 1) { m_light_level = 1; } if (m_light_level > 4) { m_light_level = 4; } m_palette->setLightLevel(m_light_level); } FRM::~FRM() { m_data.reset(); } RenderAble* FRM::getFrame(uint16_t dir, uint16_t frame) { FrameInfo fi = m_frame_info[dir][frame]; loadFrame(fi); return fi.image; } void FRM::load() { m_data = VFS::instance()->open(m_file); m_data->setIndex(0); m_version = m_data->read32Big(); m_frames_per_second = m_data->read16Big(); m_action_frame_idx = m_data->read16Big(); m_frames_per_direction = m_data->read16Big(); // safeguard against div-by-zero; maybe it should generally be +1? if (m_frames_per_second == 0) { m_frames_per_second = 50; //m_frames_per_direction / 2; } for (size_t i = 0; i < m_shifts_x.size(); ++i) { m_shifts_x[i] = m_data->read16Big(); } for (size_t i = 0; i < m_shifts_y.size(); ++i) { m_shifts_y[i] = m_data->read16Big(); } for (size_t i = 0; i < m_offsets.size(); ++i) { m_offsets[i] = m_data->read32Big(); } // not sure if mess up with the indices for (size_t i = 0; i < m_offsets.size(); ++i) { unsigned int pos = 0x3e + m_offsets[i]; m_data->setIndex(pos); int16_t xoff_total = 0; int16_t yoff_total = 0; for (uint16_t k = 0; k < m_frames_per_direction; ++k) { FrameInfo fi; fi.width = m_data->read16Big(); fi.height = m_data->read16Big(); uint32_t s = m_data->read32Big(); if (s != static_cast<uint32_t>(fi.width * fi.height)) { // FIXME cleanup? throw InvalidFormat("Frame size mismatch in file " + m_file); } xoff_total += m_data->read16Big(); fi.xoff = xoff_total; yoff_total += m_data->read16Big(); fi.yoff = yoff_total; fi.fpos = m_data->getCurrentIndex(); fi.image = 0; m_data->moveIndex(s); m_frame_info[i].push_back(fi); } } // adds the offset ref fix (formerly in loadFrames()): m_directions = 0; for (size_t i = 0; i < m_offsets.size(); ++i) { uint32_t offset = m_offsets[i]; size_t ref_i = i; for(size_t j =0; j<i; ++j) { if(offset == m_offsets[j]) { ref_i = j; } } for (size_t k = 0; k < m_frames_per_direction; ++k) { if (ref_i < i) { m_frame_info[i][k].fpos = m_frame_info[ref_i][k].fpos; m_frame_info[i][k].xoff = m_frame_info[ref_i][k].xoff; m_frame_info[i][k].yoff = m_frame_info[ref_i][k].yoff; m_frame_info[i][k].width = m_frame_info[ref_i][k].width; m_frame_info[i][k].height = m_frame_info[ref_i][k].height; } else { ++m_directions; } } } m_directions /= m_frames_per_direction; } int16_t FRM::getShiftX(size_t idx) const { if (idx >= m_shifts_x.size()) throw IndexOverflow("no such shift"); return *(m_shifts_x.begin() + idx); } int16_t FRM::getShiftY(size_t idx) const { if (idx >= m_shifts_y.size()) throw IndexOverflow("no such shift"); return *(m_shifts_y.begin() + idx); } int16_t FRM::getShiftX(size_t idx, size_t frame) const { return m_frame_info[idx][frame].xoff; } int16_t FRM::getShiftY(size_t idx, size_t frame) const { return m_frame_info[idx][frame].yoff; } void FRM::loadFrame(FrameInfo& fi) { if (fi.image) { return; } uint32_t size = fi.width * fi.height; m_data->setIndex(fi.fpos); boost::scoped_array<uint8_t> imgdata(new uint8_t[size]); m_data->readInto(imgdata.get(), size); RenderAble* img = transferImgToSurface(imgdata.get(), fi.width, fi.height); img->setXShift(fi.xoff); img->setYShift(fi.yoff); fi.image = img; } /** Creates an SDL_Surface with pixel data taken from the given 8-bit pixel data and palette. The returned surface's format will be RGBA if withAlphaChannel is true, or 8-bit indexed surface if withAlphaChannel is false. */ SDL_Surface* createSDLSurface(uint8_t* data, uint16_t width, uint16_t height, const AnimatedPalette* palette, bool withAlphaChannel) { SDL_Surface* image = 0; if (withAlphaChannel) { #if SDL_BYTEORDER == SDL_BIG_ENDIAN Uint32 rmask = 0xff000000; Uint32 gmask = 0x00ff0000; Uint32 bmask = 0x0000ff00; Uint32 amask = 0x000000ff; #else Uint32 rmask = 0x000000ff; Uint32 gmask = 0x0000ff00; Uint32 bmask = 0x00ff0000; Uint32 amask = 0xff000000; #endif image = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 32, rmask, gmask, bmask, amask); if (image == 0) { return 0; } // load pixels into image SDL_LockSurface(image); int wastedspace = image->pitch - image->format->BytesPerPixel * width; uint8_t* from = data; uint32_t* pixeldata = static_cast<uint32_t*>(image->pixels); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { uint8_t index = *(from++); if (index == 0) { *pixeldata = 0x00000000; } else { uint8_t alpha = 0xff; if( index == 108 ) { // 108 is the transparent window pixel index alpha = 0x80; } /** @todo: find solution: 13 should be yellow/red and transparent only for specific objects. else if( 13 == index ) { ///< 13 is transparent force-field alpha = 0x80; } */ *pixeldata = (palette->getRed(index) << 24) | (palette->getGreen(index) << 16) | (palette->getBlue(index) << 8) | alpha; } ++pixeldata; } pixeldata += wastedspace; } SDL_UnlockSurface(image); } else { // Create an SDL palette palette SDL_Color colors[256]; for (int i = 0; i < 256; i++) { colors[i].r = palette->getRed(i); colors[i].g = palette->getGreen(i); colors[i].b = palette->getBlue(i); } // create 8-bit palette surface image = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 8, 0, 0, 0, 0); if (image == 0) { return 0; } SDL_SetColors(image, colors, 0, 256); // set color key. 0 is transparent SDL_SetColorKey(image, SDL_SRCCOLORKEY | SDL_RLEACCEL, 0); // load pixels into image SDL_LockSurface(image); if (image->pitch != width) { // have to copy a line at a time uint8_t* from = data; uint8_t* to = static_cast<uint8_t*>(image->pixels); for (int line = 0; line < height; line++) { std::memcpy(to, from, width); from += width; to += image->pitch; } } else { std::memcpy(image->pixels, data, width * height); } SDL_UnlockSurface(image); } return image; } RenderAble* FRM::transferImgToSurface(uint8_t* data, uint16_t width, uint16_t height) { /* Must loop over the pixels to find special pixels. For readability, this is done in two seperate steps. 1) Look for pixels with the value #108 which should be transparent. 2) Look for pixels whose color is meant to be animated. */ bool convertToAlpha = false; int size = width * height; uint8_t* end = data + size; if (end != std::find(data, end, 108)) { // found a partial transparent pixel. Use alpha channel. convertToAlpha = true; } // Check for animated pixels. Can only animate one set of pixels right now. Do not animate // if more sets are found. const AnimatedBlock* block = 0; for (int i = 0; i < size; i++) { const AnimatedBlock* b = m_palette->getBlock(data[i]); if (b != 0 && b != block) { if (block == 0) { // first pixel of any animation block found, remember it block = b; } else { // found a pixel from a second animation block. Can't animate the palette. block = 0; break; } } } m_palette->setCurrentAnimation(block); if (block == 0) { // No animation. Create one image. SDL_Surface* image = createSDLSurface(data, width, height, m_palette, convertToAlpha); if (image != 0) { return CRenderBackend()->createStaticImageFromSDL(image); } } else { // Create an animation. Log("palanim") << "Generating Animation " << block->getName() << " with w,h= " << width << ", " << height << " frames: " << block->getNumFrames() << " delay: " << block->getFrameDuration(); Animation *anim = new Animation(block->getNumFrames()); anim->setFrameDuration(block->getFrameDuration()); for(int i = 0; i < block->getNumFrames(); ++i) { m_palette->setCurrentFrame(i); SDL_Surface* image = createSDLSurface(data, width, height, m_palette, convertToAlpha); Image* createdImage = 0; if (image != 0) { createdImage = CRenderBackend()->createStaticImageFromSDL(image); } if (!createdImage) { PANIC_PRINT("image == NULL"); } anim->setFrame(i, createdImage); } anim->setCurrentFrame(0); return anim; } return 0; } uint16_t FRM::getFramesPerSecond() const { return m_frames_per_second; } uint16_t FRM::getActionFrameIdx() const { return m_action_frame_idx; } uint32_t FRM::getNumFrames() const { return m_frames_per_direction; } } } } } <commit_msg>Removed endian check that was plain wrong. This was causing the bug described in ticket 112.<commit_after>/*************************************************************************** * Copyright (C) 2005-2007 by the FIFE Team * * fife-public@lists.sourceforge.net * * This file is part of FIFE. * * * * FIFE is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************/ // Standard C++ library includes #include <cstring> #include <algorithm> // 3rd party library includes #include <boost/scoped_array.hpp> // FIFE includes // These includes are split up in two parts, separated by one empty line // First block: files included from the FIFE root src directory // Second block: files included from the same folder #include "vfs/raw/rawdata.h" #include "video/animation.h" #include "video/image.h" #include "video/renderbackend.h" #include "video/rendermanager.h" #include "exception.h" #include "debugutils.h" #include "imagecache.h" #include "settingsmanager.h" #include "frm.h" #include "animatedpal.h" namespace FIFE { namespace map { namespace loaders { namespace fallout { // FIXME: If this is an intrinsic part of the file format, then we should // just use arrays of that size. Otherwise, there's a bug anyway :) const int FRM_MAX_FRAME_CT = 6; FRM::FRM(const std::string& path, AnimatedPalette* palette) : m_file(path), m_palette(palette), m_version(0), m_frames_per_direction(0), m_directions(0), m_shifts_x(FRM_MAX_FRAME_CT), m_shifts_y(FRM_MAX_FRAME_CT), m_offsets(FRM_MAX_FRAME_CT), m_frame_info(FRM_MAX_FRAME_CT) { init(); load(); } void FRM::init() { m_light_level = SettingsManager::instance()->read<int>("LightingLevel", 4); if (m_light_level < 1) { m_light_level = 1; } if (m_light_level > 4) { m_light_level = 4; } m_palette->setLightLevel(m_light_level); } FRM::~FRM() { m_data.reset(); } RenderAble* FRM::getFrame(uint16_t dir, uint16_t frame) { FrameInfo fi = m_frame_info[dir][frame]; loadFrame(fi); return fi.image; } void FRM::load() { m_data = VFS::instance()->open(m_file); m_data->setIndex(0); m_version = m_data->read32Big(); m_frames_per_second = m_data->read16Big(); m_action_frame_idx = m_data->read16Big(); m_frames_per_direction = m_data->read16Big(); // safeguard against div-by-zero; maybe it should generally be +1? if (m_frames_per_second == 0) { m_frames_per_second = 50; //m_frames_per_direction / 2; } for (size_t i = 0; i < m_shifts_x.size(); ++i) { m_shifts_x[i] = m_data->read16Big(); } for (size_t i = 0; i < m_shifts_y.size(); ++i) { m_shifts_y[i] = m_data->read16Big(); } for (size_t i = 0; i < m_offsets.size(); ++i) { m_offsets[i] = m_data->read32Big(); } // not sure if mess up with the indices for (size_t i = 0; i < m_offsets.size(); ++i) { unsigned int pos = 0x3e + m_offsets[i]; m_data->setIndex(pos); int16_t xoff_total = 0; int16_t yoff_total = 0; for (uint16_t k = 0; k < m_frames_per_direction; ++k) { FrameInfo fi; fi.width = m_data->read16Big(); fi.height = m_data->read16Big(); uint32_t s = m_data->read32Big(); if (s != static_cast<uint32_t>(fi.width * fi.height)) { // FIXME cleanup? throw InvalidFormat("Frame size mismatch in file " + m_file); } xoff_total += m_data->read16Big(); fi.xoff = xoff_total; yoff_total += m_data->read16Big(); fi.yoff = yoff_total; fi.fpos = m_data->getCurrentIndex(); fi.image = 0; m_data->moveIndex(s); m_frame_info[i].push_back(fi); } } // adds the offset ref fix (formerly in loadFrames()): m_directions = 0; for (size_t i = 0; i < m_offsets.size(); ++i) { uint32_t offset = m_offsets[i]; size_t ref_i = i; for(size_t j =0; j<i; ++j) { if(offset == m_offsets[j]) { ref_i = j; } } for (size_t k = 0; k < m_frames_per_direction; ++k) { if (ref_i < i) { m_frame_info[i][k].fpos = m_frame_info[ref_i][k].fpos; m_frame_info[i][k].xoff = m_frame_info[ref_i][k].xoff; m_frame_info[i][k].yoff = m_frame_info[ref_i][k].yoff; m_frame_info[i][k].width = m_frame_info[ref_i][k].width; m_frame_info[i][k].height = m_frame_info[ref_i][k].height; } else { ++m_directions; } } } m_directions /= m_frames_per_direction; } int16_t FRM::getShiftX(size_t idx) const { if (idx >= m_shifts_x.size()) throw IndexOverflow("no such shift"); return *(m_shifts_x.begin() + idx); } int16_t FRM::getShiftY(size_t idx) const { if (idx >= m_shifts_y.size()) throw IndexOverflow("no such shift"); return *(m_shifts_y.begin() + idx); } int16_t FRM::getShiftX(size_t idx, size_t frame) const { return m_frame_info[idx][frame].xoff; } int16_t FRM::getShiftY(size_t idx, size_t frame) const { return m_frame_info[idx][frame].yoff; } void FRM::loadFrame(FrameInfo& fi) { if (fi.image) { return; } uint32_t size = fi.width * fi.height; m_data->setIndex(fi.fpos); boost::scoped_array<uint8_t> imgdata(new uint8_t[size]); m_data->readInto(imgdata.get(), size); RenderAble* img = transferImgToSurface(imgdata.get(), fi.width, fi.height); img->setXShift(fi.xoff); img->setYShift(fi.yoff); fi.image = img; } /** Creates an SDL_Surface with pixel data taken from the given 8-bit pixel data and palette. The returned surface's format will be RGBA if withAlphaChannel is true, or 8-bit indexed surface if withAlphaChannel is false. */ SDL_Surface* createSDLSurface(uint8_t* data, uint16_t width, uint16_t height, const AnimatedPalette* palette, bool withAlphaChannel) { SDL_Surface* image = 0; if (withAlphaChannel) { image = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 32, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff); if (image == 0) { return 0; } // load pixels into image SDL_LockSurface(image); int wastedspace = image->pitch - image->format->BytesPerPixel * width; uint8_t* from = data; uint32_t* pixeldata = static_cast<uint32_t*>(image->pixels); for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { uint8_t index = *(from++); if (index == 0) { *pixeldata = 0x00000000; } else { uint8_t alpha = 0xff; if( index == 108 ) { // 108 is the transparent window pixel index alpha = 0x80; } /** @todo: find solution: 13 should be yellow/red and transparent only for specific objects. else if( 13 == index ) { ///< 13 is transparent force-field alpha = 0x80; } */ *pixeldata = (palette->getRed(index) << 24) | (palette->getGreen(index) << 16) | (palette->getBlue(index) << 8) | alpha; } ++pixeldata; } pixeldata += wastedspace; } SDL_UnlockSurface(image); } else { // Create an SDL palette palette SDL_Color colors[256]; for (int i = 0; i < 256; i++) { colors[i].r = palette->getRed(i); colors[i].g = palette->getGreen(i); colors[i].b = palette->getBlue(i); } // create 8-bit palette surface image = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 8, 0, 0, 0, 0); if (image == 0) { return 0; } SDL_SetColors(image, colors, 0, 256); // set color key. 0 is transparent SDL_SetColorKey(image, SDL_SRCCOLORKEY | SDL_RLEACCEL, 0); // load pixels into image SDL_LockSurface(image); if (image->pitch != width) { // have to copy a line at a time uint8_t* from = data; uint8_t* to = static_cast<uint8_t*>(image->pixels); for (int line = 0; line < height; line++) { std::memcpy(to, from, width); from += width; to += image->pitch; } } else { std::memcpy(image->pixels, data, width * height); } SDL_UnlockSurface(image); } return image; } RenderAble* FRM::transferImgToSurface(uint8_t* data, uint16_t width, uint16_t height) { /* Must loop over the pixels to find special pixels. For readability, this is done in two seperate steps. 1) Look for pixels with the value #108 which should be transparent. 2) Look for pixels whose color is meant to be animated. */ bool convertToAlpha = false; int size = width * height; uint8_t* end = data + size; if (end != std::find(data, end, 108)) { // found a partial transparent pixel. Use alpha channel. convertToAlpha = true; } // Check for animated pixels. Can only animate one set of pixels right now. Do not animate // if more sets are found. const AnimatedBlock* block = 0; for (int i = 0; i < size; i++) { const AnimatedBlock* b = m_palette->getBlock(data[i]); if (b != 0 && b != block) { if (block == 0) { // first pixel of any animation block found, remember it block = b; } else { // found a pixel from a second animation block. Can't animate the palette. block = 0; break; } } } m_palette->setCurrentAnimation(block); if (block == 0) { // No animation. Create one image. SDL_Surface* image = createSDLSurface(data, width, height, m_palette, convertToAlpha); if (image != 0) { return CRenderBackend()->createStaticImageFromSDL(image); } } else { // Create an animation. Log("palanim") << "Generating Animation " << block->getName() << " with w,h= " << width << ", " << height << " frames: " << block->getNumFrames() << " delay: " << block->getFrameDuration(); Animation *anim = new Animation(block->getNumFrames()); anim->setFrameDuration(block->getFrameDuration()); for(int i = 0; i < block->getNumFrames(); ++i) { m_palette->setCurrentFrame(i); SDL_Surface* image = createSDLSurface(data, width, height, m_palette, convertToAlpha); Image* createdImage = 0; if (image != 0) { createdImage = CRenderBackend()->createStaticImageFromSDL(image); } if (!createdImage) { PANIC_PRINT("image == NULL"); } anim->setFrame(i, createdImage); } anim->setCurrentFrame(0); return anim; } return 0; } uint16_t FRM::getFramesPerSecond() const { return m_frames_per_second; } uint16_t FRM::getActionFrameIdx() const { return m_action_frame_idx; } uint32_t FRM::getNumFrames() const { return m_frames_per_direction; } } } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: AccessibleViewForwarder.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: af $ $Date: 2002-04-11 17:03:58 $ * * 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 _SD_ACCESSIBILITY_ACCESSIBLE_VIEW_FORWARDER_HXX #define _SD_ACCESSIBILITY_ACCESSIBLE_VIEW_FORWARDER_HXX #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_IVIEW_FORWARDER_HXX #include <svx/IAccessibleViewForwarder.hxx> #endif class SdrPaintView; class OutputDevice; namespace accessibility { /** <p>This class provides the means to transform between internal coordinates and screen coordinates without giving direct access to the underlying view. It represents a certain window. A call to <method>GetVisArea</method> returns the corresponding visible rectangle.</p> @attention Note, that modifications of the underlying view that lead to different transformations between internal and screen coordinates or change the validity of the forwarder have to be signaled seperately. */ class AccessibleViewForwarder : public IAccessibleViewForwarder { public: //===== internal ======================================================== AccessibleViewForwarder (SdrPaintView* pView, USHORT nWindowId); AccessibleViewForwarder (SdrPaintView* pView, OutputDevice& rDevice); virtual ~AccessibleViewForwarder (void) SAL_THROW(()); void SetView (SdrPaintView* pView); //===== IAccessibleViewforwarder ======================================== /** This method informs you about the state of the forwarder. Do not use it when the returned value is <false/>. @return Return <true/> if the view forwarder is valid and <false/> else. */ virtual BOOL IsValid (void) const; /** Returns the area of the underlying document that is visible in the * corresponding window. @return The rectangle of the visible part of the document. */ virtual Rectangle GetVisibleArea() const; /** Transform the specified point from internal coordinates to an absolute screen position. @param rPoint Point in internal coordinates. @return The same point but in screen coordinates relative to the upper left corner of the (current) screen. */ virtual Point LogicToPixel (const Point& rPoint) const; /** Transform the specified size from internal coordinates to a screen * position. @param rSize Size in internal coordinates. @return The same size but in screen coordinates. */ virtual Size LogicToPixel (const Size& rSize) const; /** Transform the specified point from absolute screen coordinates to internal coordinates. @param rPoint Point in screen coordinates relative to the upper left corner of the (current) screen. @return The same point but in internal coordinates. */ virtual Point PixelToLogic (const Point& rPoint) const; /** Transform the specified Size from screen coordinates to internal coordinates. @param rSize Size in screen coordinates. @return The same size but in internal coordinates. */ virtual Size PixelToLogic (const Size& rSize) const; protected: SdrPaintView* mpView; USHORT mnWindowId; OutputDevice& mrDevice; private: AccessibleViewForwarder (AccessibleViewForwarder&); operator= (AccessibleViewForwarder&); }; } // end of namespace accessibility #endif <commit_msg>#95585# Removed SAL_THROW(()) from destructor declaration.<commit_after>/************************************************************************* * * $RCSfile: AccessibleViewForwarder.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: af $ $Date: 2002-04-12 14:47:45 $ * * 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 _SD_ACCESSIBILITY_ACCESSIBLE_VIEW_FORWARDER_HXX #define _SD_ACCESSIBILITY_ACCESSIBLE_VIEW_FORWARDER_HXX #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_IVIEW_FORWARDER_HXX #include <svx/IAccessibleViewForwarder.hxx> #endif class SdrPaintView; class OutputDevice; namespace accessibility { /** <p>This class provides the means to transform between internal coordinates and screen coordinates without giving direct access to the underlying view. It represents a certain window. A call to <method>GetVisArea</method> returns the corresponding visible rectangle.</p> @attention Note, that modifications of the underlying view that lead to different transformations between internal and screen coordinates or change the validity of the forwarder have to be signaled seperately. */ class AccessibleViewForwarder : public IAccessibleViewForwarder { public: //===== internal ======================================================== AccessibleViewForwarder (SdrPaintView* pView, USHORT nWindowId); AccessibleViewForwarder (SdrPaintView* pView, OutputDevice& rDevice); virtual ~AccessibleViewForwarder (void); void SetView (SdrPaintView* pView); //===== IAccessibleViewforwarder ======================================== /** This method informs you about the state of the forwarder. Do not use it when the returned value is <false/>. @return Return <true/> if the view forwarder is valid and <false/> else. */ virtual BOOL IsValid (void) const; /** Returns the area of the underlying document that is visible in the * corresponding window. @return The rectangle of the visible part of the document. */ virtual Rectangle GetVisibleArea() const; /** Transform the specified point from internal coordinates to an absolute screen position. @param rPoint Point in internal coordinates. @return The same point but in screen coordinates relative to the upper left corner of the (current) screen. */ virtual Point LogicToPixel (const Point& rPoint) const; /** Transform the specified size from internal coordinates to a screen * position. @param rSize Size in internal coordinates. @return The same size but in screen coordinates. */ virtual Size LogicToPixel (const Size& rSize) const; /** Transform the specified point from absolute screen coordinates to internal coordinates. @param rPoint Point in screen coordinates relative to the upper left corner of the (current) screen. @return The same point but in internal coordinates. */ virtual Point PixelToLogic (const Point& rPoint) const; /** Transform the specified Size from screen coordinates to internal coordinates. @param rSize Size in screen coordinates. @return The same size but in internal coordinates. */ virtual Size PixelToLogic (const Size& rSize) const; protected: SdrPaintView* mpView; USHORT mnWindowId; OutputDevice& mrDevice; private: AccessibleViewForwarder (AccessibleViewForwarder&); operator= (AccessibleViewForwarder&); }; } // end of namespace accessibility #endif <|endoftext|>
<commit_before>#include <stdio.h> #include <string.h> #include <stdint.h> #include <malloc.h> #include "sensorhandler.h" extern uint8_t find_type_for_sensor_number(uint8_t); struct sensorRES_t { uint8_t sensor_number; uint8_t operation; uint8_t sensor_reading; uint8_t assert_state7_0; uint8_t assert_state14_8; uint8_t deassert_state7_0; uint8_t deassert_state14_8; uint8_t event_data1; uint8_t event_data2; uint8_t event_data3; } __attribute__ ((packed)); #define ISBITSET(x,y) (((x)>>(y))&0x01) #define ASSERTINDEX 0 #define DEASSERTINDEX 1 // Sensor Type, Offset, function handler, Dbus Method, Assert value, Deassert value struct lookup_t { uint8_t sensor_type; uint8_t offset; int (*func)(const sensorRES_t *, const lookup_t *, const char *); char member[16]; char assertion[64]; char deassertion[64]; }; extern int updateDbusInterface(uint8_t , const char *, const char *); int set_sensor_dbus_state_simple(const sensorRES_t *pRec, const lookup_t *pTable, const char *value) { return set_sensor_dbus_state_s(pRec->sensor_number, pTable->member, value); } struct event_data_t { uint8_t data; char text[64]; }; event_data_t g_fwprogress02h[] = { {0x00, "Unspecified"}, {0x01, "Memory Init"}, {0x02, "HD Init"}, {0x03, "Secondary Proc Init"}, {0x04, "User Authentication"}, {0x05, "User init system setup"}, {0x06, "USB configuration"}, {0x07, "PCI configuration"}, {0x08, "Option ROM Init"}, {0x09, "Video Init"}, {0x0A, "Cache Init"}, {0x0B, "SM Bus init"}, {0x0C, "Keyboard Init"}, {0x0D, "Embedded ctrl init"}, {0x0E, "Docking station attachment"}, {0x0F, "Enable docking station"}, {0x10, "Docking station ejection"}, {0x11, "Disabling docking station"}, {0x12, "Calling OS Wakeup"}, {0x13, "Starting OS"}, {0x14, "Baseboard Init"}, {0x15, ""}, {0x16, "Floppy Init"}, {0x17, "Keyboard Test"}, {0x18, "Pointing Device Test"}, {0x19, "Primary Proc Init"}, {0xFF, "Unknown"} }; event_data_t g_fwprogress00h[] = { {0x00, "Unspecified."}, {0x01, "No system memory detected"}, {0x02, "No usable system memory"}, {0x03, "Unrecoverable hard-disk/ATAPI/IDE"}, {0x04, "Unrecoverable system-board"}, {0x05, "Unrecoverable diskette"}, {0x06, "Unrecoverable hard-disk controller"}, {0x07, "Unrecoverable PS/2 or USB keyboard"}, {0x08, "Removable boot media not found"}, {0x09, "Unrecoverable video controller"}, {0x0A, "No video device detected"}, {0x0B, "Firmware ROM corruption detected"}, {0x0C, "CPU voltage mismatch"}, {0x0D, "CPU speed matching"}, {0xFF, "unknown"}, }; char *event_data_lookup(event_data_t *p, uint8_t b) { while(p->data != 0xFF) { if (p->data == b) { break; } p++; } return p->text; } // The fw progress sensor contains some additional information that needs to be processed // prior to calling the dbus code. int set_sensor_dbus_state_fwprogress(const sensorRES_t *pRec, const lookup_t *pTable, const char *value) { char valuestring[128]; char* p = valuestring; switch (pTable->offset) { case 0x00 : snprintf(p, sizeof(valuestring), "POST Error, %s", event_data_lookup(g_fwprogress00h, pRec->event_data2)); break; case 0x01 : /* Using g_fwprogress02h for 0x01 because thats what the ipmi spec says to do */ snprintf(p, sizeof(valuestring), "FW Hang, %s", event_data_lookup(g_fwprogress02h, pRec->event_data2)); break; case 0x02 : snprintf(p, sizeof(valuestring), "FW Progress, %s", event_data_lookup(g_fwprogress02h, pRec->event_data2)); break; default : snprintf(p, sizeof(valuestring), "Internal warning, fw_progres offset unknown (0x%02x)", pTable->offset); break; } return set_sensor_dbus_state_s(pRec->sensor_number, pTable->member, p); } // Handling this special OEM sensor by coping what is in byte 4. I also think that is odd // considering byte 3 is for sensor reading. This seems like a misuse of the IPMI spec int set_sensor_dbus_state_osbootcount(const sensorRES_t *pRec, const lookup_t *pTable, const char *value) { return set_sensor_dbus_state_y(pRec->sensor_number, "setValue", pRec->assert_state7_0); } int set_sensor_dbus_state_system_event(const sensorRES_t *pRec, const lookup_t *pTable, const char *value) { char valuestring[128]; char* p = valuestring; switch (pTable->offset) { case 0x00 : snprintf(p, sizeof(valuestring), "System Reconfigured"); break; case 0x01 : snprintf(p, sizeof(valuestring), "OEM Boot Event"); break; case 0x02 : snprintf(p, sizeof(valuestring), "Undetermine System Hardware Failure"); break; case 0x03 : snprintf(p, sizeof(valuestring), "System Failure see error log for more details (0x%02x)", pRec->event_data2); break; case 0x04 : snprintf(p, sizeof(valuestring), "System Failure see PEF error log for more details (0x%02x)", pRec->event_data2); break; default : snprintf(p, sizeof(valuestring), "Internal warning, system_event offset unknown (0x%02x)", pTable->offset); break; } return set_sensor_dbus_state_s(pRec->sensor_number, pTable->member, p); } // This table lists only senors we care about telling dbus about. // Offset definition cab be found in section 42.2 of the IPMI 2.0 // spec. Add more if/when there are more items of interest. lookup_t g_ipmidbuslookup[] = { {0xe9, 0x00, set_sensor_dbus_state_simple, "setValue", "Disabled", ""}, // OCC Inactive 0 {0xe9, 0x01, set_sensor_dbus_state_simple, "setValue", "Enabled", ""}, // OCC Active 1 // Turbo Allowed {0xda, 0x00, set_sensor_dbus_state_simple, "setValue", "True", "False"}, // Power Supply Derating {0xb4, 0x00, set_sensor_dbus_state_simple, "setValue", "", ""}, // Power Cap {0xC2, 0x00, set_sensor_dbus_state_simple, "setValue", "", ""}, {0x07, 0x07, set_sensor_dbus_state_simple, "setPresent", "True", "False"}, {0x07, 0x08, set_sensor_dbus_state_simple, "setFault", "True", "False"}, {0x0C, 0x06, set_sensor_dbus_state_simple, "setPresent", "True", "False"}, {0x0C, 0x04, set_sensor_dbus_state_simple, "setFault", "True", "False"}, {0x0F, 0x02, set_sensor_dbus_state_fwprogress, "setValue", "True", "False"}, {0x0F, 0x01, set_sensor_dbus_state_fwprogress, "setValue", "True", "False"}, {0x0F, 0x00, set_sensor_dbus_state_fwprogress, "setValue", "True", "False"}, {0xC7, 0x01, set_sensor_dbus_state_simple, "setFault", "True", "False"}, {0xc3, 0x00, set_sensor_dbus_state_osbootcount, "setValue", "" ,""}, {0x1F, 0x00, set_sensor_dbus_state_simple, "setValue", "Boot completed (00)", ""}, {0x1F, 0x01, set_sensor_dbus_state_simple, "setValue", "Boot completed (01)", ""}, {0x1F, 0x02, set_sensor_dbus_state_simple, "setValue", "PXE boot completed", ""}, {0x1F, 0x03, set_sensor_dbus_state_simple, "setValue", "Diagnostic boot completed", ""}, {0x1F, 0x04, set_sensor_dbus_state_simple, "setValue", "CD-ROM boot completed", ""}, {0x1F, 0x05, set_sensor_dbus_state_simple, "setValue", "ROM boot completed", ""}, {0x1F, 0x06, set_sensor_dbus_state_simple, "setValue", "Boot completed (06)", ""}, {0x12, 0x00, set_sensor_dbus_state_system_event, "setValue", "", ""}, {0x12, 0x01, set_sensor_dbus_state_system_event, "setValue", "", ""}, {0x12, 0x02, set_sensor_dbus_state_system_event, "setValue", "", ""}, {0x12, 0x03, set_sensor_dbus_state_system_event, "setValue", "", ""}, {0x12, 0x04, set_sensor_dbus_state_system_event, "setValue", "", ""}, {0xD8, 0x00, set_sensor_dbus_state_simple, "setValue", "Disabled", ""}, {0xFF, 0xFF, NULL, "", "", ""} }; void reportSensorEventAssert(sensorRES_t *pRec, int index) { lookup_t *pTable = &g_ipmidbuslookup[index]; (*pTable->func)(pRec, pTable, pTable->assertion); } void reportSensorEventDeassert(sensorRES_t *pRec, int index) { lookup_t *pTable = &g_ipmidbuslookup[index]; (*pTable->func)(pRec, pTable, pTable->deassertion); } int findindex(const uint8_t sensor_type, int offset, int *index) { int i=0, rc=0; lookup_t *pTable = g_ipmidbuslookup; do { if ( ((pTable+i)->sensor_type == sensor_type) && ((pTable+i)->offset == offset) ) { rc = 1; *index = i; break; } i++; } while ((pTable+i)->sensor_type != 0xFF); return rc; } void debug_print_ok_to_dont_care(uint8_t stype, int offset) { printf("LOOKATME: Sensor should not be reported: Type 0x%02x, Offset 0x%02x\n", stype, offset); } bool shouldReport(uint8_t sensorType, int offset, int *index) { bool rc = false; if (findindex(sensorType, offset, index)) { rc = true; } if (rc==false) { debug_print_ok_to_dont_care(sensorType, offset); } return rc; } int updateSensorRecordFromSSRAESC(const void *record) { sensorRES_t *pRec = (sensorRES_t *) record; uint8_t stype; int index, i=0; stype = find_type_for_sensor_number(pRec->sensor_number); // 0xC3 types use the assertion7_0 for the value to be set // so skip the reseach and call the correct event reporting // function if (stype == 0xC3) { shouldReport(stype, 0x00, &index); reportSensorEventAssert(pRec, index); } else { // Scroll through each bit position . Determine // if any bit is either asserted or Deasserted. for(i=0;i<8;i++) { if ((ISBITSET(pRec->assert_state7_0,i)) && (shouldReport(stype, i, &index))) { reportSensorEventAssert(pRec, index); } if ((ISBITSET(pRec->assert_state14_8,i)) && (shouldReport(stype, i+8, &index))) { reportSensorEventAssert(pRec, index); } if ((ISBITSET(pRec->deassert_state7_0,i)) && (shouldReport(stype, i, &index))) { reportSensorEventDeassert(pRec, index); } if ((ISBITSET(pRec->deassert_state14_8,i)) && (shouldReport(stype, i+8, &index))) { reportSensorEventDeassert(pRec, index); } } } return 0; } <commit_msg>ipmisensor.cpp: Fix msg from "Undetermine" to "Undetermined"<commit_after>#include <stdio.h> #include <string.h> #include <stdint.h> #include <malloc.h> #include "sensorhandler.h" extern uint8_t find_type_for_sensor_number(uint8_t); struct sensorRES_t { uint8_t sensor_number; uint8_t operation; uint8_t sensor_reading; uint8_t assert_state7_0; uint8_t assert_state14_8; uint8_t deassert_state7_0; uint8_t deassert_state14_8; uint8_t event_data1; uint8_t event_data2; uint8_t event_data3; } __attribute__ ((packed)); #define ISBITSET(x,y) (((x)>>(y))&0x01) #define ASSERTINDEX 0 #define DEASSERTINDEX 1 // Sensor Type, Offset, function handler, Dbus Method, Assert value, Deassert value struct lookup_t { uint8_t sensor_type; uint8_t offset; int (*func)(const sensorRES_t *, const lookup_t *, const char *); char member[16]; char assertion[64]; char deassertion[64]; }; extern int updateDbusInterface(uint8_t , const char *, const char *); int set_sensor_dbus_state_simple(const sensorRES_t *pRec, const lookup_t *pTable, const char *value) { return set_sensor_dbus_state_s(pRec->sensor_number, pTable->member, value); } struct event_data_t { uint8_t data; char text[64]; }; event_data_t g_fwprogress02h[] = { {0x00, "Unspecified"}, {0x01, "Memory Init"}, {0x02, "HD Init"}, {0x03, "Secondary Proc Init"}, {0x04, "User Authentication"}, {0x05, "User init system setup"}, {0x06, "USB configuration"}, {0x07, "PCI configuration"}, {0x08, "Option ROM Init"}, {0x09, "Video Init"}, {0x0A, "Cache Init"}, {0x0B, "SM Bus init"}, {0x0C, "Keyboard Init"}, {0x0D, "Embedded ctrl init"}, {0x0E, "Docking station attachment"}, {0x0F, "Enable docking station"}, {0x10, "Docking station ejection"}, {0x11, "Disabling docking station"}, {0x12, "Calling OS Wakeup"}, {0x13, "Starting OS"}, {0x14, "Baseboard Init"}, {0x15, ""}, {0x16, "Floppy Init"}, {0x17, "Keyboard Test"}, {0x18, "Pointing Device Test"}, {0x19, "Primary Proc Init"}, {0xFF, "Unknown"} }; event_data_t g_fwprogress00h[] = { {0x00, "Unspecified."}, {0x01, "No system memory detected"}, {0x02, "No usable system memory"}, {0x03, "Unrecoverable hard-disk/ATAPI/IDE"}, {0x04, "Unrecoverable system-board"}, {0x05, "Unrecoverable diskette"}, {0x06, "Unrecoverable hard-disk controller"}, {0x07, "Unrecoverable PS/2 or USB keyboard"}, {0x08, "Removable boot media not found"}, {0x09, "Unrecoverable video controller"}, {0x0A, "No video device detected"}, {0x0B, "Firmware ROM corruption detected"}, {0x0C, "CPU voltage mismatch"}, {0x0D, "CPU speed matching"}, {0xFF, "unknown"}, }; char *event_data_lookup(event_data_t *p, uint8_t b) { while(p->data != 0xFF) { if (p->data == b) { break; } p++; } return p->text; } // The fw progress sensor contains some additional information that needs to be processed // prior to calling the dbus code. int set_sensor_dbus_state_fwprogress(const sensorRES_t *pRec, const lookup_t *pTable, const char *value) { char valuestring[128]; char* p = valuestring; switch (pTable->offset) { case 0x00 : snprintf(p, sizeof(valuestring), "POST Error, %s", event_data_lookup(g_fwprogress00h, pRec->event_data2)); break; case 0x01 : /* Using g_fwprogress02h for 0x01 because thats what the ipmi spec says to do */ snprintf(p, sizeof(valuestring), "FW Hang, %s", event_data_lookup(g_fwprogress02h, pRec->event_data2)); break; case 0x02 : snprintf(p, sizeof(valuestring), "FW Progress, %s", event_data_lookup(g_fwprogress02h, pRec->event_data2)); break; default : snprintf(p, sizeof(valuestring), "Internal warning, fw_progres offset unknown (0x%02x)", pTable->offset); break; } return set_sensor_dbus_state_s(pRec->sensor_number, pTable->member, p); } // Handling this special OEM sensor by coping what is in byte 4. I also think that is odd // considering byte 3 is for sensor reading. This seems like a misuse of the IPMI spec int set_sensor_dbus_state_osbootcount(const sensorRES_t *pRec, const lookup_t *pTable, const char *value) { return set_sensor_dbus_state_y(pRec->sensor_number, "setValue", pRec->assert_state7_0); } int set_sensor_dbus_state_system_event(const sensorRES_t *pRec, const lookup_t *pTable, const char *value) { char valuestring[128]; char* p = valuestring; switch (pTable->offset) { case 0x00 : snprintf(p, sizeof(valuestring), "System Reconfigured"); break; case 0x01 : snprintf(p, sizeof(valuestring), "OEM Boot Event"); break; case 0x02 : snprintf(p, sizeof(valuestring), "Undetermined System Hardware Failure"); break; case 0x03 : snprintf(p, sizeof(valuestring), "System Failure see error log for more details (0x%02x)", pRec->event_data2); break; case 0x04 : snprintf(p, sizeof(valuestring), "System Failure see PEF error log for more details (0x%02x)", pRec->event_data2); break; default : snprintf(p, sizeof(valuestring), "Internal warning, system_event offset unknown (0x%02x)", pTable->offset); break; } return set_sensor_dbus_state_s(pRec->sensor_number, pTable->member, p); } // This table lists only senors we care about telling dbus about. // Offset definition cab be found in section 42.2 of the IPMI 2.0 // spec. Add more if/when there are more items of interest. lookup_t g_ipmidbuslookup[] = { {0xe9, 0x00, set_sensor_dbus_state_simple, "setValue", "Disabled", ""}, // OCC Inactive 0 {0xe9, 0x01, set_sensor_dbus_state_simple, "setValue", "Enabled", ""}, // OCC Active 1 // Turbo Allowed {0xda, 0x00, set_sensor_dbus_state_simple, "setValue", "True", "False"}, // Power Supply Derating {0xb4, 0x00, set_sensor_dbus_state_simple, "setValue", "", ""}, // Power Cap {0xC2, 0x00, set_sensor_dbus_state_simple, "setValue", "", ""}, {0x07, 0x07, set_sensor_dbus_state_simple, "setPresent", "True", "False"}, {0x07, 0x08, set_sensor_dbus_state_simple, "setFault", "True", "False"}, {0x0C, 0x06, set_sensor_dbus_state_simple, "setPresent", "True", "False"}, {0x0C, 0x04, set_sensor_dbus_state_simple, "setFault", "True", "False"}, {0x0F, 0x02, set_sensor_dbus_state_fwprogress, "setValue", "True", "False"}, {0x0F, 0x01, set_sensor_dbus_state_fwprogress, "setValue", "True", "False"}, {0x0F, 0x00, set_sensor_dbus_state_fwprogress, "setValue", "True", "False"}, {0xC7, 0x01, set_sensor_dbus_state_simple, "setFault", "True", "False"}, {0xc3, 0x00, set_sensor_dbus_state_osbootcount, "setValue", "" ,""}, {0x1F, 0x00, set_sensor_dbus_state_simple, "setValue", "Boot completed (00)", ""}, {0x1F, 0x01, set_sensor_dbus_state_simple, "setValue", "Boot completed (01)", ""}, {0x1F, 0x02, set_sensor_dbus_state_simple, "setValue", "PXE boot completed", ""}, {0x1F, 0x03, set_sensor_dbus_state_simple, "setValue", "Diagnostic boot completed", ""}, {0x1F, 0x04, set_sensor_dbus_state_simple, "setValue", "CD-ROM boot completed", ""}, {0x1F, 0x05, set_sensor_dbus_state_simple, "setValue", "ROM boot completed", ""}, {0x1F, 0x06, set_sensor_dbus_state_simple, "setValue", "Boot completed (06)", ""}, {0x12, 0x00, set_sensor_dbus_state_system_event, "setValue", "", ""}, {0x12, 0x01, set_sensor_dbus_state_system_event, "setValue", "", ""}, {0x12, 0x02, set_sensor_dbus_state_system_event, "setValue", "", ""}, {0x12, 0x03, set_sensor_dbus_state_system_event, "setValue", "", ""}, {0x12, 0x04, set_sensor_dbus_state_system_event, "setValue", "", ""}, {0xD8, 0x00, set_sensor_dbus_state_simple, "setValue", "Disabled", ""}, {0xFF, 0xFF, NULL, "", "", ""} }; void reportSensorEventAssert(sensorRES_t *pRec, int index) { lookup_t *pTable = &g_ipmidbuslookup[index]; (*pTable->func)(pRec, pTable, pTable->assertion); } void reportSensorEventDeassert(sensorRES_t *pRec, int index) { lookup_t *pTable = &g_ipmidbuslookup[index]; (*pTable->func)(pRec, pTable, pTable->deassertion); } int findindex(const uint8_t sensor_type, int offset, int *index) { int i=0, rc=0; lookup_t *pTable = g_ipmidbuslookup; do { if ( ((pTable+i)->sensor_type == sensor_type) && ((pTable+i)->offset == offset) ) { rc = 1; *index = i; break; } i++; } while ((pTable+i)->sensor_type != 0xFF); return rc; } void debug_print_ok_to_dont_care(uint8_t stype, int offset) { printf("LOOKATME: Sensor should not be reported: Type 0x%02x, Offset 0x%02x\n", stype, offset); } bool shouldReport(uint8_t sensorType, int offset, int *index) { bool rc = false; if (findindex(sensorType, offset, index)) { rc = true; } if (rc==false) { debug_print_ok_to_dont_care(sensorType, offset); } return rc; } int updateSensorRecordFromSSRAESC(const void *record) { sensorRES_t *pRec = (sensorRES_t *) record; uint8_t stype; int index, i=0; stype = find_type_for_sensor_number(pRec->sensor_number); // 0xC3 types use the assertion7_0 for the value to be set // so skip the reseach and call the correct event reporting // function if (stype == 0xC3) { shouldReport(stype, 0x00, &index); reportSensorEventAssert(pRec, index); } else { // Scroll through each bit position . Determine // if any bit is either asserted or Deasserted. for(i=0;i<8;i++) { if ((ISBITSET(pRec->assert_state7_0,i)) && (shouldReport(stype, i, &index))) { reportSensorEventAssert(pRec, index); } if ((ISBITSET(pRec->assert_state14_8,i)) && (shouldReport(stype, i+8, &index))) { reportSensorEventAssert(pRec, index); } if ((ISBITSET(pRec->deassert_state7_0,i)) && (shouldReport(stype, i, &index))) { reportSensorEventDeassert(pRec, index); } if ((ISBITSET(pRec->deassert_state14_8,i)) && (shouldReport(stype, i+8, &index))) { reportSensorEventDeassert(pRec, index); } } } 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. #include "chrome/browser/autofill/autofill_manager.h" #include <string> #include "base/command_line.h" #include "chrome/browser/autofill/autofill_dialog.h" #include "chrome/browser/autofill/autofill_infobar_delegate.h" #include "chrome/browser/autofill/form_structure.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "webkit/glue/form_field_values.h" AutoFillManager::AutoFillManager(TabContents* tab_contents) : tab_contents_(tab_contents), infobar_(NULL) { personal_data_ = tab_contents_->profile()->GetPersonalDataManager(); } AutoFillManager::~AutoFillManager() { } // static void AutoFillManager::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kAutoFillInfoBarShown, false); prefs->RegisterBooleanPref(prefs::kAutoFillEnabled, false); } void AutoFillManager::FormFieldValuesSubmitted( const webkit_glue::FormFieldValues& form) { // TODO(jhawkins): Remove this switch when AutoFill++ is fully implemented. if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableNewAutoFill)) return; // Grab a copy of the form data. upload_form_structure_.reset(new FormStructure(form)); if (!upload_form_structure_->IsAutoFillable()) return; // Determine the possible field types. DeterminePossibleFieldTypes(upload_form_structure_.get()); PrefService* prefs = tab_contents_->profile()->GetPrefs(); bool autofill_enabled = prefs->GetBoolean(prefs::kAutoFillEnabled); bool infobar_shown = prefs->GetBoolean(prefs::kAutoFillInfoBarShown); if (!infobar_shown) { // Ask the user for permission to save form information. infobar_.reset(new AutoFillInfoBarDelegate(tab_contents_, this)); } else if (autofill_enabled) { HandleSubmit(); } } void AutoFillManager::OnAutoFillDialogApply( std::vector<AutoFillProfile>* profiles, std::vector<CreditCard>* credit_cards) { // Save the personal data. personal_data_->SetProfiles(profiles); personal_data_->SetCreditCards(credit_cards); HandleSubmit(); } void AutoFillManager::OnPersonalDataLoaded() { // We might have been alerted that the PersonalDataManager has loaded, so // remove ourselves as observer. personal_data_->RemoveObserver(this); ShowAutoFillDialog( this, personal_data_->profiles(), personal_data_->credit_cards()); } void AutoFillManager::DeterminePossibleFieldTypes( FormStructure* form_structure) { // TODO(jhawkins): Update field text. form_structure->GetHeuristicAutoFillTypes(); for (size_t i = 0; i < form_structure->field_count(); i++) { const AutoFillField* field = form_structure->field(i); FieldTypeSet field_types; personal_data_->GetPossibleFieldTypes(field->value(), &field_types); form_structure->set_possible_types(i, field_types); } } void AutoFillManager::HandleSubmit() { // If there wasn't enough data to import then we don't want to send an upload // to the server. if (!personal_data_->ImportFormData(form_structures_, this)) return; UploadFormData(); } void AutoFillManager::OnInfoBarAccepted() { PrefService* prefs = tab_contents_->profile()->GetPrefs(); prefs->SetBoolean(prefs::kAutoFillEnabled, true); // If the personal data manager has not loaded the data yet, set ourselves as // its observer so that we can listen for the OnPersonalDataLoaded signal. if (!personal_data_->IsDataLoaded()) personal_data_->SetObserver(this); else OnPersonalDataLoaded(); } void AutoFillManager::SaveFormData() { // TODO(jhawkins): Save the form data to the web database. } void AutoFillManager::UploadFormData() { std::string xml; bool ok = upload_form_structure_->EncodeUploadRequest(false, &xml); DCHECK(ok); // TODO(jhawkins): Initiate the upload request thread. } void AutoFillManager::Reset() { upload_form_structure_.reset(); } <commit_msg>Remove the AutoFillManager as an observer of the PersonalDataManager in the constructor. In rare circumtances, the user can close the browser (and shutdown the AutoFillManager) after we've set ourselves as observers of the PersonalDataManager and before the PersonalDataManager has called us back.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_manager.h" #include <string> #include "base/command_line.h" #include "chrome/browser/autofill/autofill_dialog.h" #include "chrome/browser/autofill/autofill_infobar_delegate.h" #include "chrome/browser/autofill/form_structure.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "webkit/glue/form_field_values.h" AutoFillManager::AutoFillManager(TabContents* tab_contents) : tab_contents_(tab_contents), infobar_(NULL) { personal_data_ = tab_contents_->profile()->GetPersonalDataManager(); } AutoFillManager::~AutoFillManager() { personal_data_->RemoveObserver(this); } // static void AutoFillManager::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kAutoFillInfoBarShown, false); prefs->RegisterBooleanPref(prefs::kAutoFillEnabled, false); } void AutoFillManager::FormFieldValuesSubmitted( const webkit_glue::FormFieldValues& form) { // TODO(jhawkins): Remove this switch when AutoFill++ is fully implemented. if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableNewAutoFill)) return; // Grab a copy of the form data. upload_form_structure_.reset(new FormStructure(form)); if (!upload_form_structure_->IsAutoFillable()) return; // Determine the possible field types. DeterminePossibleFieldTypes(upload_form_structure_.get()); PrefService* prefs = tab_contents_->profile()->GetPrefs(); bool autofill_enabled = prefs->GetBoolean(prefs::kAutoFillEnabled); bool infobar_shown = prefs->GetBoolean(prefs::kAutoFillInfoBarShown); if (!infobar_shown) { // Ask the user for permission to save form information. infobar_.reset(new AutoFillInfoBarDelegate(tab_contents_, this)); } else if (autofill_enabled) { HandleSubmit(); } } void AutoFillManager::OnAutoFillDialogApply( std::vector<AutoFillProfile>* profiles, std::vector<CreditCard>* credit_cards) { // Save the personal data. personal_data_->SetProfiles(profiles); personal_data_->SetCreditCards(credit_cards); HandleSubmit(); } void AutoFillManager::OnPersonalDataLoaded() { // We might have been alerted that the PersonalDataManager has loaded, so // remove ourselves as observer. personal_data_->RemoveObserver(this); ShowAutoFillDialog( this, personal_data_->profiles(), personal_data_->credit_cards()); } void AutoFillManager::DeterminePossibleFieldTypes( FormStructure* form_structure) { // TODO(jhawkins): Update field text. form_structure->GetHeuristicAutoFillTypes(); for (size_t i = 0; i < form_structure->field_count(); i++) { const AutoFillField* field = form_structure->field(i); FieldTypeSet field_types; personal_data_->GetPossibleFieldTypes(field->value(), &field_types); form_structure->set_possible_types(i, field_types); } } void AutoFillManager::HandleSubmit() { // If there wasn't enough data to import then we don't want to send an upload // to the server. if (!personal_data_->ImportFormData(form_structures_, this)) return; UploadFormData(); } void AutoFillManager::OnInfoBarAccepted() { PrefService* prefs = tab_contents_->profile()->GetPrefs(); prefs->SetBoolean(prefs::kAutoFillEnabled, true); // If the personal data manager has not loaded the data yet, set ourselves as // its observer so that we can listen for the OnPersonalDataLoaded signal. if (!personal_data_->IsDataLoaded()) personal_data_->SetObserver(this); else OnPersonalDataLoaded(); } void AutoFillManager::SaveFormData() { // TODO(jhawkins): Save the form data to the web database. } void AutoFillManager::UploadFormData() { std::string xml; bool ok = upload_form_structure_->EncodeUploadRequest(false, &xml); DCHECK(ok); // TODO(jhawkins): Initiate the upload request thread. } void AutoFillManager::Reset() { upload_form_structure_.reset(); } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <libcellml> /** * @todo Need a way to have resources which can be used in tests, such as the * source models used in these tests. But I guess not until we start validating * models... * * While this is needed eventually, for now we are not instantiating the imports * so don't need it just yet. */ TEST(ComponentImport, singleImport01) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">" "<import xlink:href=\"some-other-model.xml\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\">" "<component component_ref=\"a_component_in_that_model\" " "name=\"component_in_this_model\"/>" "</import>" "</model>"; libcellml::Model m; libcellml::Import imp("some-other-model.xml"); m.addImport(imp); libcellml::ComponentPtr importedComponent = std::make_shared<libcellml::Component>(); importedComponent->setName("component_in_this_model"); importedComponent->setSourceComponent("a_component_in_that_model"); imp.addComponent(importedComponent); std::string a = m.serialise(libcellml::CELLML_FORMAT_XML); EXPECT_EQ(e, a); } TEST(ComponentImport, singleImport02) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">" "<import xlink:href=\"some-other-model.xml\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\">" "<component component_ref=\"a_component_in_that_model\" " "name=\"component_in_this_model\"/>" "</import>" "</model>"; libcellml::Model m; libcellml::Import imp("some-other-model.xml"); libcellml::ComponentPtr importedComponent = std::make_shared<libcellml::Component>(); importedComponent->setName("component_in_this_model"); importedComponent->setSourceComponent(imp, "a_component_in_that_model"); m.addComponent(importedComponent); std::string a = m.serialise(libcellml::CELLML_FORMAT_XML); EXPECT_EQ(e, a); } TEST(ComponentImport, multipleImport02) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">" "<import xlink:href=\"some-other-model.xml\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\">" "<component component_ref=\"cc1\" " "name=\"c1"/>" "<component component_ref=\"cc2\" " "name=\"c2\"/>" "</import>" "<import xlink:href=\"some-other-model.xml\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\">" "<component component_ref=\"cc1\" " "name=\"c3\"/>" "</import>" "</model>"; libcellml::Model m; libcellml::Import imp("some-other-model.xml"); m.addImport(imp); libcellml::ComponentPtr c1 = std::make_shared<libcellml::Component>(); c1->setName("c1"); c1->setSourceComponent("cc1"); imp.addComponent(c1); libcellml::ComponentPtr c2 = std::make_shared<libcellml::Component>(); c2->setName("c2"); c2->setSourceComponent("cc2"); imp.addComponent(c2); libcellml::Import imp2("some-other-model.xml"); m.addImport(imp2); libcellml::ComponentPtr c3 = std::make_shared<libcellml::Component>(); c3->setName("c3"); c3->setSourceComponent("cc1"); imp.addComponent(c3); std::string a = m.serialise(libcellml::CELLML_FORMAT_XML); EXPECT_EQ(e, a); } TEST(ComponentImport, multipleImport01) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">" "<import xlink:href=\"some-other-model.xml\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\">" "<component component_ref=\"cc1\" " "name=\"c1"/>" "<component component_ref=\"cc2\" " "name=\"c2\"/>" "</import>" "<import xlink:href=\"some-other-model.xml\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\">" "<component component_ref=\"cc1\" " "name=\"c3\"/>" "</import>" "</model>"; libcellml::Model m; libcellml::Import imp("some-other-model.xml"); libcellml::ComponentPtr c1 = std::make_shared<libcellml::Component>(); c1->setName("c1"); c1->setSourceComponent(imp, "cc1"); m.addComponent(c1); libcellml::ComponentPtr c2 = std::make_shared<libcellml::Component>(); c2->setName("c2"); c2->setSourceComponent(imp, "cc2"); m.addComponent(c2); libcellml::Import imp2("some-other-model.xml"); libcellml::ComponentPtr c3 = std::make_shared<libcellml::Component>(); c3->setName("c3"); c3->setSourceComponent(imp2, "cc1"); m.addComponent(c3); std::string a = m.serialise(libcellml::CELLML_FORMAT_XML); EXPECT_EQ(e, a); } <commit_msg>correct typo in the test names to clarify which ones belong together<commit_after>#include "gtest/gtest.h" #include <libcellml> /** * @todo Need a way to have resources which can be used in tests, such as the * source models used in these tests. But I guess not until we start validating * models... * * While this is needed eventually, for now we are not instantiating the imports * so don't need it just yet. */ TEST(ComponentImport, singleImport01) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">" "<import xlink:href=\"some-other-model.xml\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\">" "<component component_ref=\"a_component_in_that_model\" " "name=\"component_in_this_model\"/>" "</import>" "</model>"; libcellml::Model m; libcellml::Import imp("some-other-model.xml"); m.addImport(imp); libcellml::ComponentPtr importedComponent = std::make_shared<libcellml::Component>(); importedComponent->setName("component_in_this_model"); importedComponent->setSourceComponent("a_component_in_that_model"); imp.addComponent(importedComponent); std::string a = m.serialise(libcellml::CELLML_FORMAT_XML); EXPECT_EQ(e, a); } TEST(ComponentImport, singleImport02) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">" "<import xlink:href=\"some-other-model.xml\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\">" "<component component_ref=\"a_component_in_that_model\" " "name=\"component_in_this_model\"/>" "</import>" "</model>"; libcellml::Model m; libcellml::Import imp("some-other-model.xml"); libcellml::ComponentPtr importedComponent = std::make_shared<libcellml::Component>(); importedComponent->setName("component_in_this_model"); importedComponent->setSourceComponent(imp, "a_component_in_that_model"); m.addComponent(importedComponent); std::string a = m.serialise(libcellml::CELLML_FORMAT_XML); EXPECT_EQ(e, a); } TEST(ComponentImport, multipleImport01) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">" "<import xlink:href=\"some-other-model.xml\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\">" "<component component_ref=\"cc1\" " "name=\"c1"/>" "<component component_ref=\"cc2\" " "name=\"c2\"/>" "</import>" "<import xlink:href=\"some-other-model.xml\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\">" "<component component_ref=\"cc1\" " "name=\"c3\"/>" "</import>" "</model>"; libcellml::Model m; libcellml::Import imp("some-other-model.xml"); m.addImport(imp); libcellml::ComponentPtr c1 = std::make_shared<libcellml::Component>(); c1->setName("c1"); c1->setSourceComponent("cc1"); imp.addComponent(c1); libcellml::ComponentPtr c2 = std::make_shared<libcellml::Component>(); c2->setName("c2"); c2->setSourceComponent("cc2"); imp.addComponent(c2); libcellml::Import imp2("some-other-model.xml"); m.addImport(imp2); libcellml::ComponentPtr c3 = std::make_shared<libcellml::Component>(); c3->setName("c3"); c3->setSourceComponent("cc1"); imp.addComponent(c3); std::string a = m.serialise(libcellml::CELLML_FORMAT_XML); EXPECT_EQ(e, a); } TEST(ComponentImport, multipleImport02) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/1.2#\">" "<import xlink:href=\"some-other-model.xml\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\">" "<component component_ref=\"cc1\" " "name=\"c1"/>" "<component component_ref=\"cc2\" " "name=\"c2\"/>" "</import>" "<import xlink:href=\"some-other-model.xml\" " "xmlns:xlink=\"http://www.w3.org/1999/xlink\">" "<component component_ref=\"cc1\" " "name=\"c3\"/>" "</import>" "</model>"; libcellml::Model m; libcellml::Import imp("some-other-model.xml"); libcellml::ComponentPtr c1 = std::make_shared<libcellml::Component>(); c1->setName("c1"); c1->setSourceComponent(imp, "cc1"); m.addComponent(c1); libcellml::ComponentPtr c2 = std::make_shared<libcellml::Component>(); c2->setName("c2"); c2->setSourceComponent(imp, "cc2"); m.addComponent(c2); libcellml::Import imp2("some-other-model.xml"); libcellml::ComponentPtr c3 = std::make_shared<libcellml::Component>(); c3->setName("c3"); c3->setSourceComponent(imp2, "cc1"); m.addComponent(c3); std::string a = m.serialise(libcellml::CELLML_FORMAT_XML); EXPECT_EQ(e, a); } <|endoftext|>
<commit_before> #include <stdint.h> #include <stdio.h> #include <memory.h> namespace mm { #pragma pack(push, 1) struct smap_entry_t { uint64_t base; uint64_t length; uint32_t type; uint32_t acpi; } __attribute__((packed)); #pragma pack(pop) static int entries_count; static smap_entry_t *entries; void detect(void) { entries_count = (int) *(uint32_t *)0x8000; entries = (smap_entry_t *)0x8004; printf("entries = %d\n", entries_count); int sum = 0; for (int i = 0; i < entries_count; ++i) { printf("base = %x, length = %x, type = %d, acpi = %d\n", (int) entries[i].base, (int) entries[i].length, entries[i].type, entries[i].acpi); sum += entries[i].length; } printf("total memory = %dMB\n", sum / 1024 / 1024); } } /* mm */ <commit_msg>prettify memory detect<commit_after> #include <stdint.h> #include <stdio.h> #include <memory.h> #include <algorithm> using std::sort; namespace mm { #pragma pack(push, 1) struct smap_entry_t { uint64_t base; uint64_t length; uint32_t type; uint32_t acpi; } __attribute__((packed)); #pragma pack(pop) static int entries_count; static smap_entry_t *entries; void detect(void) { const char *spearate_l1 = "+------------+------------+------+------+"; const char *spearate_l2 = "+============+============+======+======+"; entries_count = (int) *(uint32_t *) 0x8000; entries = (smap_entry_t *) 0x8004; printf("Total memory entries = %d.\n", entries_count); /* std::sort doesn't rely on memory allocation. So it is guaranteed to be safe. */ sort(entries, entries + entries_count, [&](const smap_entry_t &a, const smap_entry_t &b) -> bool { return a.base < b.base; }); int sum = 0; puts(spearate_l1); puts("| base | length | type | free |"); puts(spearate_l2); for (int i = 0; i < entries_count; ++i) { bool free = (entries[i].type == 1); printf("| 0x%08x | 0x%08x | %d | %c |\n", (int) entries[i].base, (int) entries[i].length, entries[i].type, free ? 'Y' : 'N'); sum += entries[i].length; } puts(spearate_l1); printf("Total memory = %dM.\n", sum / 1024 / 1024); } } /* mm */ <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/debugger/devtools_manager.h" #include <vector> #include "base/auto_reset.h" #include "base/message_loop.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browsing_instance.h" #include "chrome/browser/child_process_security_policy.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/devtools_messages.h" #include "chrome/common/pref_names.h" #include "googleurl/src/gurl.h" // static DevToolsManager* DevToolsManager::GetInstance() { return g_browser_process->devtools_manager(); } // static void DevToolsManager::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kDevToolsOpenDocked, true); } DevToolsManager::DevToolsManager() : inspected_rvh_for_reopen_(NULL), in_initial_show_(false), last_orphan_cookie_(0) { } DevToolsManager::~DevToolsManager() { DCHECK(inspected_rvh_to_client_host_.empty()); DCHECK(client_host_to_inspected_rvh_.empty()); // By the time we destroy devtools manager, all orphan client hosts should // have been delelted, no need to notify them upon tab closing. DCHECK(orphan_client_hosts_.empty()); } DevToolsClientHost* DevToolsManager::GetDevToolsClientHostFor( RenderViewHost* inspected_rvh) { InspectedRvhToClientHostMap::iterator it = inspected_rvh_to_client_host_.find(inspected_rvh); if (it != inspected_rvh_to_client_host_.end()) return it->second; return NULL; } void DevToolsManager::RegisterDevToolsClientHostFor( RenderViewHost* inspected_rvh, DevToolsClientHost* client_host) { DCHECK(!GetDevToolsClientHostFor(inspected_rvh)); RuntimeFeatures initial_features; BindClientHost(inspected_rvh, client_host, initial_features); client_host->set_close_listener(this); SendAttachToAgent(inspected_rvh); } void DevToolsManager::ForwardToDevToolsAgent( RenderViewHost* client_rvh, const IPC::Message& message) { DevToolsClientHost* client_host = FindOnwerDevToolsClientHost(client_rvh); if (client_host) ForwardToDevToolsAgent(client_host, message); } void DevToolsManager::ForwardToDevToolsAgent(DevToolsClientHost* from, const IPC::Message& message) { RenderViewHost* inspected_rvh = GetInspectedRenderViewHost(from); if (!inspected_rvh) { // TODO(yurys): notify client that the agent is no longer available NOTREACHED(); return; } IPC::Message* m = new IPC::Message(message); m->set_routing_id(inspected_rvh->routing_id()); inspected_rvh->Send(m); } void DevToolsManager::ForwardToDevToolsClient(RenderViewHost* inspected_rvh, const IPC::Message& message) { DevToolsClientHost* client_host = GetDevToolsClientHostFor(inspected_rvh); if (!client_host) { // Client window was closed while there were messages // being sent to it. return; } client_host->SendMessageToClient(message); } void DevToolsManager::ActivateWindow(RenderViewHost* client_rvh) { DevToolsClientHost* client_host = FindOnwerDevToolsClientHost(client_rvh); if (!client_host) return; DevToolsWindow* window = client_host->AsDevToolsWindow(); DCHECK(window); window->Activate(); } void DevToolsManager::CloseWindow(RenderViewHost* client_rvh) { DevToolsClientHost* client_host = FindOnwerDevToolsClientHost(client_rvh); if (client_host) { RenderViewHost* inspected_rvh = GetInspectedRenderViewHost(client_host); DCHECK(inspected_rvh); UnregisterDevToolsClientHostFor(inspected_rvh); } } void DevToolsManager::RequestDockWindow(RenderViewHost* client_rvh) { ReopenWindow(client_rvh, true); } void DevToolsManager::RequestUndockWindow(RenderViewHost* client_rvh) { ReopenWindow(client_rvh, false); } void DevToolsManager::OpenDevToolsWindow(RenderViewHost* inspected_rvh) { ToggleDevToolsWindow(inspected_rvh, true, false); } void DevToolsManager::ToggleDevToolsWindow(RenderViewHost* inspected_rvh, bool open_console) { ToggleDevToolsWindow(inspected_rvh, false, open_console); } void DevToolsManager::RuntimeFeatureStateChanged(RenderViewHost* inspected_rvh, const std::string& feature, bool enabled) { RuntimeFeaturesMap::iterator it = runtime_features_map_.find(inspected_rvh); if (it == runtime_features_map_.end()) { std::pair<RenderViewHost*, std::set<std::string> > value( inspected_rvh, std::set<std::string>()); it = runtime_features_map_.insert(value).first; } if (enabled) it->second.insert(feature); else it->second.erase(feature); } void DevToolsManager::InspectElement(RenderViewHost* inspected_rvh, int x, int y) { OpenDevToolsWindow(inspected_rvh); IPC::Message* m = new DevToolsAgentMsg_InspectElement(x, y); m->set_routing_id(inspected_rvh->routing_id()); inspected_rvh->Send(m); } void DevToolsManager::ClientHostClosing(DevToolsClientHost* host) { RenderViewHost* inspected_rvh = GetInspectedRenderViewHost(host); if (!inspected_rvh) { // It might be in the list of orphan client hosts, remove it from there. for (OrphanClientHosts::iterator it = orphan_client_hosts_.begin(); it != orphan_client_hosts_.end(); ++it) { if (it->second.first == host) { orphan_client_hosts_.erase(it->first); return; } } return; } NotificationService::current()->Notify( NotificationType::DEVTOOLS_WINDOW_CLOSING, Source<Profile>(inspected_rvh->site_instance()->GetProcess()->profile()), Details<RenderViewHost>(inspected_rvh)); SendDetachToAgent(inspected_rvh); UnbindClientHost(inspected_rvh, host); } RenderViewHost* DevToolsManager::GetInspectedRenderViewHost( DevToolsClientHost* client_host) { ClientHostToInspectedRvhMap::iterator it = client_host_to_inspected_rvh_.find(client_host); if (it != client_host_to_inspected_rvh_.end()) return it->second; return NULL; } void DevToolsManager::UnregisterDevToolsClientHostFor( RenderViewHost* inspected_rvh) { DevToolsClientHost* host = GetDevToolsClientHostFor(inspected_rvh); if (!host) return; SendDetachToAgent(inspected_rvh); UnbindClientHost(inspected_rvh, host); if (inspected_rvh_for_reopen_ == inspected_rvh) inspected_rvh_for_reopen_ = NULL; // Issue tab closing event post unbound. host->InspectedTabClosing(); int process_id = inspected_rvh->process()->id(); for (InspectedRvhToClientHostMap::iterator it = inspected_rvh_to_client_host_.begin(); it != inspected_rvh_to_client_host_.end(); ++it) { if (it->first->process()->id() == process_id) return; } // We've disconnected from the last renderer -> revoke cookie permissions. ChildProcessSecurityPolicy::GetInstance()->RevokeReadRawCookies(process_id); } void DevToolsManager::OnNavigatingToPendingEntry(RenderViewHost* rvh, RenderViewHost* dest_rvh, const GURL& gurl) { if (in_initial_show_) { // Mute this even in case it is caused by the initial show routines. return; } int cookie = DetachClientHost(rvh); if (cookie != -1) { // Navigating to URL in the inspected window. AttachClientHost(cookie, dest_rvh); return; } // Iterate over client hosts and if there is one that has render view host // changing, reopen entire client window (this must be caused by the user // manually refreshing its content). for (ClientHostToInspectedRvhMap::iterator it = client_host_to_inspected_rvh_.begin(); it != client_host_to_inspected_rvh_.end(); ++it) { DevToolsWindow* window = it->first->AsDevToolsWindow(); if (window && window->GetRenderViewHost() == rvh) { inspected_rvh_for_reopen_ = it->second; MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this, &DevToolsManager::ForceReopenWindow)); return; } } } int DevToolsManager::DetachClientHost(RenderViewHost* from_rvh) { DevToolsClientHost* client_host = GetDevToolsClientHostFor(from_rvh); if (!client_host) return -1; int cookie = last_orphan_cookie_++; orphan_client_hosts_[cookie] = std::pair<DevToolsClientHost*, RuntimeFeatures>( client_host, runtime_features_map_[from_rvh]); UnbindClientHost(from_rvh, client_host); return cookie; } void DevToolsManager::AttachClientHost(int client_host_cookie, RenderViewHost* to_rvh) { OrphanClientHosts::iterator it = orphan_client_hosts_.find( client_host_cookie); if (it == orphan_client_hosts_.end()) return; DevToolsClientHost* client_host = (*it).second.first; BindClientHost(to_rvh, client_host, (*it).second.second); SendAttachToAgent(to_rvh); orphan_client_hosts_.erase(client_host_cookie); } void DevToolsManager::SendAttachToAgent(RenderViewHost* inspected_rvh) { if (inspected_rvh) { ChildProcessSecurityPolicy::GetInstance()->GrantReadRawCookies( inspected_rvh->process()->id()); std::vector<std::string> features; RuntimeFeaturesMap::iterator it = runtime_features_map_.find(inspected_rvh); if (it != runtime_features_map_.end()) { features = std::vector<std::string>(it->second.begin(), it->second.end()); } IPC::Message* m = new DevToolsAgentMsg_Attach(features); m->set_routing_id(inspected_rvh->routing_id()); inspected_rvh->Send(m); } } void DevToolsManager::SendDetachToAgent(RenderViewHost* inspected_rvh) { if (inspected_rvh) { IPC::Message* m = new DevToolsAgentMsg_Detach(); m->set_routing_id(inspected_rvh->routing_id()); inspected_rvh->Send(m); } } void DevToolsManager::ForceReopenWindow() { if (inspected_rvh_for_reopen_) { RenderViewHost* inspected_rvn = inspected_rvh_for_reopen_; UnregisterDevToolsClientHostFor(inspected_rvn); OpenDevToolsWindow(inspected_rvn); } } DevToolsClientHost* DevToolsManager::FindOnwerDevToolsClientHost( RenderViewHost* client_rvh) { for (InspectedRvhToClientHostMap::iterator it = inspected_rvh_to_client_host_.begin(); it != inspected_rvh_to_client_host_.end(); ++it) { DevToolsWindow* win = it->second->AsDevToolsWindow(); if (!win) continue; if (client_rvh == win->GetRenderViewHost()) return it->second; } return NULL; } void DevToolsManager::ReopenWindow(RenderViewHost* client_rvh, bool docked) { DevToolsClientHost* client_host = FindOnwerDevToolsClientHost(client_rvh); if (!client_host) return; RenderViewHost* inspected_rvh = GetInspectedRenderViewHost(client_host); DCHECK(inspected_rvh); inspected_rvh->process()->profile()->GetPrefs()->SetBoolean( prefs::kDevToolsOpenDocked, docked); DevToolsWindow* window = client_host->AsDevToolsWindow(); DCHECK(window); window->SetDocked(docked); } void DevToolsManager::ToggleDevToolsWindow(RenderViewHost* inspected_rvh, bool force_open, bool open_console) { bool do_open = force_open; DevToolsClientHost* host = GetDevToolsClientHostFor(inspected_rvh); if (!host) { bool docked = inspected_rvh->process()->profile()->GetPrefs()-> GetBoolean(prefs::kDevToolsOpenDocked); host = new DevToolsWindow( inspected_rvh->site_instance()->browsing_instance()->profile(), inspected_rvh, docked); RegisterDevToolsClientHostFor(inspected_rvh, host); do_open = true; } DevToolsWindow* window = host->AsDevToolsWindow(); if (!window) return; // If window is docked and visible, we hide it on toggle. If window is // undocked, we show (activate) it. if (!window->is_docked() || do_open) { AutoReset<bool> auto_reset_in_initial_show(&in_initial_show_, true); window->Show(open_console); } else UnregisterDevToolsClientHostFor(inspected_rvh); } void DevToolsManager::BindClientHost(RenderViewHost* inspected_rvh, DevToolsClientHost* client_host, const RuntimeFeatures& runtime_features) { DCHECK(inspected_rvh_to_client_host_.find(inspected_rvh) == inspected_rvh_to_client_host_.end()); DCHECK(client_host_to_inspected_rvh_.find(client_host) == client_host_to_inspected_rvh_.end()); inspected_rvh_to_client_host_[inspected_rvh] = client_host; client_host_to_inspected_rvh_[client_host] = inspected_rvh; runtime_features_map_[inspected_rvh] = runtime_features; } void DevToolsManager::UnbindClientHost(RenderViewHost* inspected_rvh, DevToolsClientHost* client_host) { DCHECK(inspected_rvh_to_client_host_.find(inspected_rvh)->second == client_host); DCHECK(client_host_to_inspected_rvh_.find(client_host)->second == inspected_rvh); inspected_rvh_to_client_host_.erase(inspected_rvh); client_host_to_inspected_rvh_.erase(client_host); runtime_features_map_.erase(inspected_rvh); } <commit_msg>Check that BrowserProcess still exists before accessing its methods from DevToolsManager::GetInstance<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/debugger/devtools_manager.h" #include <vector> #include "base/auto_reset.h" #include "base/message_loop.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browsing_instance.h" #include "chrome/browser/child_process_security_policy.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/devtools_messages.h" #include "chrome/common/pref_names.h" #include "googleurl/src/gurl.h" // static DevToolsManager* DevToolsManager::GetInstance() { // http://crbug.com/47806 this method may be called when BrowserProcess // has already been destroyed. if (!g_browser_process) return NULL; return g_browser_process->devtools_manager(); } // static void DevToolsManager::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kDevToolsOpenDocked, true); } DevToolsManager::DevToolsManager() : inspected_rvh_for_reopen_(NULL), in_initial_show_(false), last_orphan_cookie_(0) { } DevToolsManager::~DevToolsManager() { DCHECK(inspected_rvh_to_client_host_.empty()); DCHECK(client_host_to_inspected_rvh_.empty()); // By the time we destroy devtools manager, all orphan client hosts should // have been delelted, no need to notify them upon tab closing. DCHECK(orphan_client_hosts_.empty()); } DevToolsClientHost* DevToolsManager::GetDevToolsClientHostFor( RenderViewHost* inspected_rvh) { InspectedRvhToClientHostMap::iterator it = inspected_rvh_to_client_host_.find(inspected_rvh); if (it != inspected_rvh_to_client_host_.end()) return it->second; return NULL; } void DevToolsManager::RegisterDevToolsClientHostFor( RenderViewHost* inspected_rvh, DevToolsClientHost* client_host) { DCHECK(!GetDevToolsClientHostFor(inspected_rvh)); RuntimeFeatures initial_features; BindClientHost(inspected_rvh, client_host, initial_features); client_host->set_close_listener(this); SendAttachToAgent(inspected_rvh); } void DevToolsManager::ForwardToDevToolsAgent( RenderViewHost* client_rvh, const IPC::Message& message) { DevToolsClientHost* client_host = FindOnwerDevToolsClientHost(client_rvh); if (client_host) ForwardToDevToolsAgent(client_host, message); } void DevToolsManager::ForwardToDevToolsAgent(DevToolsClientHost* from, const IPC::Message& message) { RenderViewHost* inspected_rvh = GetInspectedRenderViewHost(from); if (!inspected_rvh) { // TODO(yurys): notify client that the agent is no longer available NOTREACHED(); return; } IPC::Message* m = new IPC::Message(message); m->set_routing_id(inspected_rvh->routing_id()); inspected_rvh->Send(m); } void DevToolsManager::ForwardToDevToolsClient(RenderViewHost* inspected_rvh, const IPC::Message& message) { DevToolsClientHost* client_host = GetDevToolsClientHostFor(inspected_rvh); if (!client_host) { // Client window was closed while there were messages // being sent to it. return; } client_host->SendMessageToClient(message); } void DevToolsManager::ActivateWindow(RenderViewHost* client_rvh) { DevToolsClientHost* client_host = FindOnwerDevToolsClientHost(client_rvh); if (!client_host) return; DevToolsWindow* window = client_host->AsDevToolsWindow(); DCHECK(window); window->Activate(); } void DevToolsManager::CloseWindow(RenderViewHost* client_rvh) { DevToolsClientHost* client_host = FindOnwerDevToolsClientHost(client_rvh); if (client_host) { RenderViewHost* inspected_rvh = GetInspectedRenderViewHost(client_host); DCHECK(inspected_rvh); UnregisterDevToolsClientHostFor(inspected_rvh); } } void DevToolsManager::RequestDockWindow(RenderViewHost* client_rvh) { ReopenWindow(client_rvh, true); } void DevToolsManager::RequestUndockWindow(RenderViewHost* client_rvh) { ReopenWindow(client_rvh, false); } void DevToolsManager::OpenDevToolsWindow(RenderViewHost* inspected_rvh) { ToggleDevToolsWindow(inspected_rvh, true, false); } void DevToolsManager::ToggleDevToolsWindow(RenderViewHost* inspected_rvh, bool open_console) { ToggleDevToolsWindow(inspected_rvh, false, open_console); } void DevToolsManager::RuntimeFeatureStateChanged(RenderViewHost* inspected_rvh, const std::string& feature, bool enabled) { RuntimeFeaturesMap::iterator it = runtime_features_map_.find(inspected_rvh); if (it == runtime_features_map_.end()) { std::pair<RenderViewHost*, std::set<std::string> > value( inspected_rvh, std::set<std::string>()); it = runtime_features_map_.insert(value).first; } if (enabled) it->second.insert(feature); else it->second.erase(feature); } void DevToolsManager::InspectElement(RenderViewHost* inspected_rvh, int x, int y) { OpenDevToolsWindow(inspected_rvh); IPC::Message* m = new DevToolsAgentMsg_InspectElement(x, y); m->set_routing_id(inspected_rvh->routing_id()); inspected_rvh->Send(m); } void DevToolsManager::ClientHostClosing(DevToolsClientHost* host) { RenderViewHost* inspected_rvh = GetInspectedRenderViewHost(host); if (!inspected_rvh) { // It might be in the list of orphan client hosts, remove it from there. for (OrphanClientHosts::iterator it = orphan_client_hosts_.begin(); it != orphan_client_hosts_.end(); ++it) { if (it->second.first == host) { orphan_client_hosts_.erase(it->first); return; } } return; } NotificationService::current()->Notify( NotificationType::DEVTOOLS_WINDOW_CLOSING, Source<Profile>(inspected_rvh->site_instance()->GetProcess()->profile()), Details<RenderViewHost>(inspected_rvh)); SendDetachToAgent(inspected_rvh); UnbindClientHost(inspected_rvh, host); } RenderViewHost* DevToolsManager::GetInspectedRenderViewHost( DevToolsClientHost* client_host) { ClientHostToInspectedRvhMap::iterator it = client_host_to_inspected_rvh_.find(client_host); if (it != client_host_to_inspected_rvh_.end()) return it->second; return NULL; } void DevToolsManager::UnregisterDevToolsClientHostFor( RenderViewHost* inspected_rvh) { DevToolsClientHost* host = GetDevToolsClientHostFor(inspected_rvh); if (!host) return; SendDetachToAgent(inspected_rvh); UnbindClientHost(inspected_rvh, host); if (inspected_rvh_for_reopen_ == inspected_rvh) inspected_rvh_for_reopen_ = NULL; // Issue tab closing event post unbound. host->InspectedTabClosing(); int process_id = inspected_rvh->process()->id(); for (InspectedRvhToClientHostMap::iterator it = inspected_rvh_to_client_host_.begin(); it != inspected_rvh_to_client_host_.end(); ++it) { if (it->first->process()->id() == process_id) return; } // We've disconnected from the last renderer -> revoke cookie permissions. ChildProcessSecurityPolicy::GetInstance()->RevokeReadRawCookies(process_id); } void DevToolsManager::OnNavigatingToPendingEntry(RenderViewHost* rvh, RenderViewHost* dest_rvh, const GURL& gurl) { if (in_initial_show_) { // Mute this even in case it is caused by the initial show routines. return; } int cookie = DetachClientHost(rvh); if (cookie != -1) { // Navigating to URL in the inspected window. AttachClientHost(cookie, dest_rvh); return; } // Iterate over client hosts and if there is one that has render view host // changing, reopen entire client window (this must be caused by the user // manually refreshing its content). for (ClientHostToInspectedRvhMap::iterator it = client_host_to_inspected_rvh_.begin(); it != client_host_to_inspected_rvh_.end(); ++it) { DevToolsWindow* window = it->first->AsDevToolsWindow(); if (window && window->GetRenderViewHost() == rvh) { inspected_rvh_for_reopen_ = it->second; MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this, &DevToolsManager::ForceReopenWindow)); return; } } } int DevToolsManager::DetachClientHost(RenderViewHost* from_rvh) { DevToolsClientHost* client_host = GetDevToolsClientHostFor(from_rvh); if (!client_host) return -1; int cookie = last_orphan_cookie_++; orphan_client_hosts_[cookie] = std::pair<DevToolsClientHost*, RuntimeFeatures>( client_host, runtime_features_map_[from_rvh]); UnbindClientHost(from_rvh, client_host); return cookie; } void DevToolsManager::AttachClientHost(int client_host_cookie, RenderViewHost* to_rvh) { OrphanClientHosts::iterator it = orphan_client_hosts_.find( client_host_cookie); if (it == orphan_client_hosts_.end()) return; DevToolsClientHost* client_host = (*it).second.first; BindClientHost(to_rvh, client_host, (*it).second.second); SendAttachToAgent(to_rvh); orphan_client_hosts_.erase(client_host_cookie); } void DevToolsManager::SendAttachToAgent(RenderViewHost* inspected_rvh) { if (inspected_rvh) { ChildProcessSecurityPolicy::GetInstance()->GrantReadRawCookies( inspected_rvh->process()->id()); std::vector<std::string> features; RuntimeFeaturesMap::iterator it = runtime_features_map_.find(inspected_rvh); if (it != runtime_features_map_.end()) { features = std::vector<std::string>(it->second.begin(), it->second.end()); } IPC::Message* m = new DevToolsAgentMsg_Attach(features); m->set_routing_id(inspected_rvh->routing_id()); inspected_rvh->Send(m); } } void DevToolsManager::SendDetachToAgent(RenderViewHost* inspected_rvh) { if (inspected_rvh) { IPC::Message* m = new DevToolsAgentMsg_Detach(); m->set_routing_id(inspected_rvh->routing_id()); inspected_rvh->Send(m); } } void DevToolsManager::ForceReopenWindow() { if (inspected_rvh_for_reopen_) { RenderViewHost* inspected_rvn = inspected_rvh_for_reopen_; UnregisterDevToolsClientHostFor(inspected_rvn); OpenDevToolsWindow(inspected_rvn); } } DevToolsClientHost* DevToolsManager::FindOnwerDevToolsClientHost( RenderViewHost* client_rvh) { for (InspectedRvhToClientHostMap::iterator it = inspected_rvh_to_client_host_.begin(); it != inspected_rvh_to_client_host_.end(); ++it) { DevToolsWindow* win = it->second->AsDevToolsWindow(); if (!win) continue; if (client_rvh == win->GetRenderViewHost()) return it->second; } return NULL; } void DevToolsManager::ReopenWindow(RenderViewHost* client_rvh, bool docked) { DevToolsClientHost* client_host = FindOnwerDevToolsClientHost(client_rvh); if (!client_host) return; RenderViewHost* inspected_rvh = GetInspectedRenderViewHost(client_host); DCHECK(inspected_rvh); inspected_rvh->process()->profile()->GetPrefs()->SetBoolean( prefs::kDevToolsOpenDocked, docked); DevToolsWindow* window = client_host->AsDevToolsWindow(); DCHECK(window); window->SetDocked(docked); } void DevToolsManager::ToggleDevToolsWindow(RenderViewHost* inspected_rvh, bool force_open, bool open_console) { bool do_open = force_open; DevToolsClientHost* host = GetDevToolsClientHostFor(inspected_rvh); if (!host) { bool docked = inspected_rvh->process()->profile()->GetPrefs()-> GetBoolean(prefs::kDevToolsOpenDocked); host = new DevToolsWindow( inspected_rvh->site_instance()->browsing_instance()->profile(), inspected_rvh, docked); RegisterDevToolsClientHostFor(inspected_rvh, host); do_open = true; } DevToolsWindow* window = host->AsDevToolsWindow(); if (!window) return; // If window is docked and visible, we hide it on toggle. If window is // undocked, we show (activate) it. if (!window->is_docked() || do_open) { AutoReset<bool> auto_reset_in_initial_show(&in_initial_show_, true); window->Show(open_console); } else UnregisterDevToolsClientHostFor(inspected_rvh); } void DevToolsManager::BindClientHost(RenderViewHost* inspected_rvh, DevToolsClientHost* client_host, const RuntimeFeatures& runtime_features) { DCHECK(inspected_rvh_to_client_host_.find(inspected_rvh) == inspected_rvh_to_client_host_.end()); DCHECK(client_host_to_inspected_rvh_.find(client_host) == client_host_to_inspected_rvh_.end()); inspected_rvh_to_client_host_[inspected_rvh] = client_host; client_host_to_inspected_rvh_[client_host] = inspected_rvh; runtime_features_map_[inspected_rvh] = runtime_features; } void DevToolsManager::UnbindClientHost(RenderViewHost* inspected_rvh, DevToolsClientHost* client_host) { DCHECK(inspected_rvh_to_client_host_.find(inspected_rvh)->second == client_host); DCHECK(client_host_to_inspected_rvh_.find(client_host)->second == inspected_rvh); inspected_rvh_to_client_host_.erase(inspected_rvh); client_host_to_inspected_rvh_.erase(client_host); runtime_features_map_.erase(inspected_rvh); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_dialog_gtk.h" #include <gtk/gtkprintjob.h> #include <gtk/gtkprintunixdialog.h> #include <gtk/gtkpagesetupunixdialog.h> #include "base/file_util.h" #include "base/logging.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/tab_contents/infobar_delegate.h" #include "chrome/browser/tab_contents/tab_contents.h" namespace { // This is a temporary infobar designed to help gauge how many users are trying // to print to printers that don't support PDF. class PdfUnsupportedInfoBarDelegate : public LinkInfoBarDelegate { public: explicit PdfUnsupportedInfoBarDelegate(Browser* browser) : LinkInfoBarDelegate(NULL), browser_(browser) { } virtual ~PdfUnsupportedInfoBarDelegate() {} virtual std::wstring GetMessageTextWithOffset(size_t* link_offset) const { std::wstring message(L"Oops! Your printer does not support PDF. Please " L"report this to us ."); *link_offset = message.length() - 1; return message; } virtual std::wstring GetLinkText() const { return std::wstring(L"here"); } virtual Type GetInfoBarType() { return ERROR_TYPE; } virtual bool LinkClicked(WindowOpenDisposition disposition) { browser_->OpenURL( GURL("http://code.google.com/p/chromium/issues/detail?id=22027"), GURL(), NEW_FOREGROUND_TAB, PageTransition::TYPED); return true; } private: Browser* browser_; }; } // namespace // static void PrintDialogGtk::CreatePrintDialogForPdf(const FilePath& path) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&PrintDialogGtk::CreateDialogImpl, path)); } // static void PrintDialogGtk::CreateDialogImpl(const FilePath& path) { new PrintDialogGtk(path); } PrintDialogGtk::PrintDialogGtk(const FilePath& path_to_pdf) : path_to_pdf_(path_to_pdf), browser_(BrowserList::GetLastActive()) { GtkWindow* parent = browser_->window()->GetNativeHandle(); // TODO(estade): We need a window title here. dialog_ = gtk_print_unix_dialog_new(NULL, parent); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this); gtk_widget_show_all(dialog_); } PrintDialogGtk::~PrintDialogGtk() { } void PrintDialogGtk::OnResponse(gint response_id) { gtk_widget_hide(dialog_); switch (response_id) { case GTK_RESPONSE_OK: { GtkPrinter* printer = gtk_print_unix_dialog_get_selected_printer( GTK_PRINT_UNIX_DIALOG(dialog_)); if (!gtk_printer_accepts_pdf(printer)) { browser_->GetSelectedTabContents()->AddInfoBar( new PdfUnsupportedInfoBarDelegate(browser_)); break; } GtkPrintSettings* settings = gtk_print_unix_dialog_get_settings( GTK_PRINT_UNIX_DIALOG(dialog_)); GtkPageSetup* setup = gtk_print_unix_dialog_get_page_setup( GTK_PRINT_UNIX_DIALOG(dialog_)); GtkPrintJob* job = gtk_print_job_new(path_to_pdf_.value().c_str(), printer, settings, setup); gtk_print_job_set_source_file(job, path_to_pdf_.value().c_str(), NULL); gtk_print_job_send(job, OnJobCompletedThunk, this, NULL); g_object_unref(settings); // Success; return early. return; } case GTK_RESPONSE_DELETE_EVENT: // Fall through. case GTK_RESPONSE_CANCEL: { break; } case GTK_RESPONSE_APPLY: default: { NOTREACHED(); } } // Delete this dialog. OnJobCompleted(NULL, NULL); } void PrintDialogGtk::OnJobCompleted(GtkPrintJob* job, GError* error) { gtk_widget_destroy(dialog_); if (error) LOG(ERROR) << "Printing failed: " << error->message; if (job) g_object_unref(job); file_util::Delete(path_to_pdf_, false); delete this; } <commit_msg>Linux: Don't show all of the print dialog's children, including widgets normally not displayed.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_dialog_gtk.h" #include <gtk/gtkprintjob.h> #include <gtk/gtkprintunixdialog.h> #include <gtk/gtkpagesetupunixdialog.h> #include "base/file_util.h" #include "base/logging.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/tab_contents/infobar_delegate.h" #include "chrome/browser/tab_contents/tab_contents.h" namespace { // This is a temporary infobar designed to help gauge how many users are trying // to print to printers that don't support PDF. class PdfUnsupportedInfoBarDelegate : public LinkInfoBarDelegate { public: explicit PdfUnsupportedInfoBarDelegate(Browser* browser) : LinkInfoBarDelegate(NULL), browser_(browser) { } virtual ~PdfUnsupportedInfoBarDelegate() {} virtual std::wstring GetMessageTextWithOffset(size_t* link_offset) const { std::wstring message(L"Oops! Your printer does not support PDF. Please " L"report this to us ."); *link_offset = message.length() - 1; return message; } virtual std::wstring GetLinkText() const { return std::wstring(L"here"); } virtual Type GetInfoBarType() { return ERROR_TYPE; } virtual bool LinkClicked(WindowOpenDisposition disposition) { browser_->OpenURL( GURL("http://code.google.com/p/chromium/issues/detail?id=22027"), GURL(), NEW_FOREGROUND_TAB, PageTransition::TYPED); return true; } private: Browser* browser_; }; } // namespace // static void PrintDialogGtk::CreatePrintDialogForPdf(const FilePath& path) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&PrintDialogGtk::CreateDialogImpl, path)); } // static void PrintDialogGtk::CreateDialogImpl(const FilePath& path) { new PrintDialogGtk(path); } PrintDialogGtk::PrintDialogGtk(const FilePath& path_to_pdf) : path_to_pdf_(path_to_pdf), browser_(BrowserList::GetLastActive()) { GtkWindow* parent = browser_->window()->GetNativeHandle(); // TODO(estade): We need a window title here. dialog_ = gtk_print_unix_dialog_new(NULL, parent); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this); gtk_widget_show(dialog_); } PrintDialogGtk::~PrintDialogGtk() { } void PrintDialogGtk::OnResponse(gint response_id) { gtk_widget_hide(dialog_); switch (response_id) { case GTK_RESPONSE_OK: { GtkPrinter* printer = gtk_print_unix_dialog_get_selected_printer( GTK_PRINT_UNIX_DIALOG(dialog_)); if (!gtk_printer_accepts_pdf(printer)) { browser_->GetSelectedTabContents()->AddInfoBar( new PdfUnsupportedInfoBarDelegate(browser_)); break; } GtkPrintSettings* settings = gtk_print_unix_dialog_get_settings( GTK_PRINT_UNIX_DIALOG(dialog_)); GtkPageSetup* setup = gtk_print_unix_dialog_get_page_setup( GTK_PRINT_UNIX_DIALOG(dialog_)); GtkPrintJob* job = gtk_print_job_new(path_to_pdf_.value().c_str(), printer, settings, setup); gtk_print_job_set_source_file(job, path_to_pdf_.value().c_str(), NULL); gtk_print_job_send(job, OnJobCompletedThunk, this, NULL); g_object_unref(settings); // Success; return early. return; } case GTK_RESPONSE_DELETE_EVENT: // Fall through. case GTK_RESPONSE_CANCEL: { break; } case GTK_RESPONSE_APPLY: default: { NOTREACHED(); } } // Delete this dialog. OnJobCompleted(NULL, NULL); } void PrintDialogGtk::OnJobCompleted(GtkPrintJob* job, GError* error) { gtk_widget_destroy(dialog_); if (error) LOG(ERROR) << "Printing failed: " << error->message; if (job) g_object_unref(job); file_util::Delete(path_to_pdf_, false); delete this; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkArcParallelEdgeStrategy.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ #include "vtkArcParallelEdgeStrategy.h" #include "vtkCellArray.h" #include "vtkDirectedGraph.h" #include "vtkEdgeListIterator.h" #include "vtkGraph.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPoints.h" #include "vtkSmartPointer.h" #include <vtksys/stl/utility> #include <vtksys/stl/vector> #include <vtksys/stl/map> vtkStandardNewMacro(vtkArcParallelEdgeStrategy); vtkCxxRevisionMacro(vtkArcParallelEdgeStrategy, "1.4"); vtkArcParallelEdgeStrategy::vtkArcParallelEdgeStrategy() { this->NumberOfSubdivisions = 10; } vtkArcParallelEdgeStrategy::~vtkArcParallelEdgeStrategy() { } void vtkArcParallelEdgeStrategy::Layout() { bool directed = vtkDirectedGraph::SafeDownCast(this->Graph) != 0; vtksys_stl::map<vtksys_stl::pair<vtkIdType, vtkIdType>, int> edgeCount; vtksys_stl::map<vtksys_stl::pair<vtkIdType, vtkIdType>, int> edgeNumber; vtksys_stl::vector<vtkEdgeType> edgeVector(this->Graph->GetNumberOfEdges()); vtkSmartPointer<vtkEdgeListIterator> it = vtkSmartPointer<vtkEdgeListIterator>::New(); this->Graph->GetEdges(it); double avgEdgeLength = 0.0; while (it->HasNext()) { vtkEdgeType e = it->Next(); vtkIdType src, tgt; if (directed || e.Source < e.Target) { src = e.Source; tgt = e.Target; } else { src = e.Target; tgt = e.Source; } edgeCount[vtksys_stl::pair<vtkIdType, vtkIdType>(src, tgt)]++; edgeVector[e.Id] = e; // Compute edge length double sourcePt[3]; double targetPt[3]; this->Graph->GetPoint(e.Source, sourcePt); this->Graph->GetPoint(e.Target, targetPt); avgEdgeLength += sqrt(vtkMath::Distance2BetweenPoints(sourcePt, targetPt)); } vtkIdType numEdges = this->Graph->GetNumberOfEdges(); if (numEdges > 0) { avgEdgeLength /= numEdges; } else { avgEdgeLength = 1.0; } double maxLoopHeight = avgEdgeLength / 10.0; double* pts = new double[this->NumberOfSubdivisions*3]; for (vtkIdType eid = 0; eid < numEdges; ++eid) { vtkEdgeType e = edgeVector[eid]; vtkIdType src, tgt; if (directed || e.Source < e.Target) { src = e.Source; tgt = e.Target; } else { src = e.Target; tgt = e.Source; } // Lookup the total number of edges with this source // and target, as well as how many times this pair // has been found so far. vtksys_stl::pair<vtkIdType,vtkIdType> p(src, tgt); edgeNumber[p]++; int cur = edgeNumber[p]; int total = edgeCount[p]; vtksys_stl::pair<vtkIdType,vtkIdType> revP(tgt, src); int revTotal = edgeCount[revP]; double sourcePt[3]; double targetPt[3]; this->Graph->GetPoint(e.Source, sourcePt); this->Graph->GetPoint(e.Target, targetPt); // If only one edge between source and target, // just draw a straight line. if (total + revTotal == 1) { double pt[6]; pt[0] = sourcePt[0]; pt[1] = sourcePt[1]; pt[2] = sourcePt[2]; pt[3] = targetPt[0]; pt[4] = targetPt[1]; pt[5] = targetPt[2]; this->Graph->SetEdgePoints(e.Id, 2, pt); continue; } // Find vector from source to target double delta[3]; for (int c = 0; c < 3; ++c) { delta[c] = targetPt[c] - sourcePt[c]; } double dist = vtkMath::Norm(delta); // If the distance is zero, draw a loop. if (dist == 0) { double radius = maxLoopHeight*cur/total; double u[3] = {1.0, 0.0, 0.0}; double v[3] = {0.0, 1.0, 0.0}; double center[3] = {sourcePt[0] - radius, sourcePt[1], sourcePt[2]}; // Use the general equation for a circle in three dimensions // to draw a loop. for (int s = 0; s < this->NumberOfSubdivisions; ++s) { double angle = 2.0*vtkMath::Pi() *s/(this->NumberOfSubdivisions-1); for (int c = 0; c < 3; ++c) { pts[3*s + c] = center[c] + radius*cos(angle)*u[c] + radius/2.0*sin(angle)*v[c]; } } this->Graph->SetEdgePoints(e.Id, this->NumberOfSubdivisions, pts); continue; } // Find vector perpendicular to delta // and (0,0,1). double z[3] = {0.0, 0.0, 1.0}; double w[3]; vtkMath::Cross(delta, z, w); vtkMath::Normalize(w); // Really bad ascii art: // ___-------___ // / |height\ <-- the drawn arc // src----dist-----tgt // \ | / // \ |offset // \ | / // u \ | / x // \ | / // \ | / // \|/ // center // The center of the circle used to draw the arc is a // point along the vector w a certain distance (offset) // from the midpoint of sourcePt and targetPt. // The offset is computed to give a certain arc height // based on cur and total. double maxHeight = dist/8.0; double height; int sign = 1; if (directed) { // Directed edges will go on one side or the other // automatically based on the order of source and target. height = (static_cast<double>(cur)/total)*maxHeight; } else { // For undirected edges, place every other edge on one // side or the other. height = (static_cast<double>((cur+1)/2)/(total/2))*maxHeight; if (cur % 2) { sign = -1; } } // This formula computes offset given dist and height. // You can pull out your trig formulas and verify it :) double offset = (dist*dist/4.0 - height*height)/(2.0*height); double center[3]; for (int c = 0; c < 3; ++c) { center[c] = (targetPt[c] + sourcePt[c])/2.0 + sign*offset*w[c]; } // The vectors u and x are unit vectors pointing from the // center of the circle to the two endpoints of the arc, // sourcePt and targetPt, respectively. double u[3], x[3]; for (int c = 0; c < 3; ++c) { u[c] = sourcePt[c] - center[c]; x[c] = targetPt[c] - center[c]; } double radius = vtkMath::Norm(u); vtkMath::Normalize(u); vtkMath::Normalize(x); // Find the angle that the arc spans. double theta = acos(vtkMath::Dot(u, x)); // We need two perpendicular vectors on the plane of the circle // in order to draw the circle. First we calculate n, a vector // normal to the circle, by crossing u and w. Next, we cross // n and u in order to get a vector v in the plane of the circle // that is perpendicular to u. double n[3]; vtkMath::Cross(u, w, n); vtkMath::Normalize(n); double v[3]; vtkMath::Cross(n, u, v); vtkMath::Normalize(v); // Use the general equation for a circle in three dimensions // to draw an arc from the last point to the current point. for (int s = 0; s < this->NumberOfSubdivisions; ++s) { double angle = -sign*s*theta/(this->NumberOfSubdivisions - 1.0); for (int c = 0; c < 3; ++c) { pts[3*s + c] = center[c] + radius*cos(angle)*u[c] + radius*sin(angle)*v[c]; } } this->Graph->SetEdgePoints(e.Id, this->NumberOfSubdivisions, pts); } delete [] pts; } void vtkArcParallelEdgeStrategy::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "NumberOfSubdivisions: " << this->NumberOfSubdivisions << endl; } <commit_msg>ENH: Add progress events.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkArcParallelEdgeStrategy.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ #include "vtkArcParallelEdgeStrategy.h" #include "vtkCellArray.h" #include "vtkCommand.h" #include "vtkDirectedGraph.h" #include "vtkEdgeListIterator.h" #include "vtkGraph.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPoints.h" #include "vtkSmartPointer.h" #include <vtksys/stl/utility> #include <vtksys/stl/vector> #include <vtksys/stl/map> vtkStandardNewMacro(vtkArcParallelEdgeStrategy); vtkCxxRevisionMacro(vtkArcParallelEdgeStrategy, "1.5"); vtkArcParallelEdgeStrategy::vtkArcParallelEdgeStrategy() { this->NumberOfSubdivisions = 10; } vtkArcParallelEdgeStrategy::~vtkArcParallelEdgeStrategy() { } void vtkArcParallelEdgeStrategy::Layout() { bool directed = vtkDirectedGraph::SafeDownCast(this->Graph) != 0; vtksys_stl::map<vtksys_stl::pair<vtkIdType, vtkIdType>, int> edgeCount; vtksys_stl::map<vtksys_stl::pair<vtkIdType, vtkIdType>, int> edgeNumber; vtksys_stl::vector<vtkEdgeType> edgeVector(this->Graph->GetNumberOfEdges()); vtkSmartPointer<vtkEdgeListIterator> it = vtkSmartPointer<vtkEdgeListIterator>::New(); this->Graph->GetEdges(it); double avgEdgeLength = 0.0; while (it->HasNext()) { vtkEdgeType e = it->Next(); vtkIdType src, tgt; if (directed || e.Source < e.Target) { src = e.Source; tgt = e.Target; } else { src = e.Target; tgt = e.Source; } edgeCount[vtksys_stl::pair<vtkIdType, vtkIdType>(src, tgt)]++; edgeVector[e.Id] = e; // Compute edge length double sourcePt[3]; double targetPt[3]; this->Graph->GetPoint(e.Source, sourcePt); this->Graph->GetPoint(e.Target, targetPt); avgEdgeLength += sqrt(vtkMath::Distance2BetweenPoints(sourcePt, targetPt)); } vtkIdType numEdges = this->Graph->GetNumberOfEdges(); if (numEdges > 0) { avgEdgeLength /= numEdges; } else { avgEdgeLength = 1.0; } double maxLoopHeight = avgEdgeLength / 10.0; double* pts = new double[this->NumberOfSubdivisions*3]; for (vtkIdType eid = 0; eid < numEdges; ++eid) { vtkEdgeType e = edgeVector[eid]; vtkIdType src, tgt; if (directed || e.Source < e.Target) { src = e.Source; tgt = e.Target; } else { src = e.Target; tgt = e.Source; } // Lookup the total number of edges with this source // and target, as well as how many times this pair // has been found so far. vtksys_stl::pair<vtkIdType,vtkIdType> p(src, tgt); edgeNumber[p]++; int cur = edgeNumber[p]; int total = edgeCount[p]; vtksys_stl::pair<vtkIdType,vtkIdType> revP(tgt, src); int revTotal = edgeCount[revP]; double sourcePt[3]; double targetPt[3]; this->Graph->GetPoint(e.Source, sourcePt); this->Graph->GetPoint(e.Target, targetPt); // If only one edge between source and target, // just draw a straight line. if (total + revTotal == 1) { double pt[6]; pt[0] = sourcePt[0]; pt[1] = sourcePt[1]; pt[2] = sourcePt[2]; pt[3] = targetPt[0]; pt[4] = targetPt[1]; pt[5] = targetPt[2]; this->Graph->SetEdgePoints(e.Id, 2, pt); continue; } // Find vector from source to target double delta[3]; for (int c = 0; c < 3; ++c) { delta[c] = targetPt[c] - sourcePt[c]; } double dist = vtkMath::Norm(delta); // If the distance is zero, draw a loop. if (dist == 0) { double radius = maxLoopHeight*cur/total; double u[3] = {1.0, 0.0, 0.0}; double v[3] = {0.0, 1.0, 0.0}; double center[3] = {sourcePt[0] - radius, sourcePt[1], sourcePt[2]}; // Use the general equation for a circle in three dimensions // to draw a loop. for (int s = 0; s < this->NumberOfSubdivisions; ++s) { double angle = 2.0*vtkMath::Pi() *s/(this->NumberOfSubdivisions-1); for (int c = 0; c < 3; ++c) { pts[3*s + c] = center[c] + radius*cos(angle)*u[c] + radius/2.0*sin(angle)*v[c]; } } this->Graph->SetEdgePoints(e.Id, this->NumberOfSubdivisions, pts); continue; } // Find vector perpendicular to delta // and (0,0,1). double z[3] = {0.0, 0.0, 1.0}; double w[3]; vtkMath::Cross(delta, z, w); vtkMath::Normalize(w); // Really bad ascii art: // ___-------___ // / |height\ <-- the drawn arc // src----dist-----tgt // \ | / // \ |offset // \ | / // u \ | / x // \ | / // \ | / // \|/ // center // The center of the circle used to draw the arc is a // point along the vector w a certain distance (offset) // from the midpoint of sourcePt and targetPt. // The offset is computed to give a certain arc height // based on cur and total. double maxHeight = dist/8.0; double height; int sign = 1; if (directed) { // Directed edges will go on one side or the other // automatically based on the order of source and target. height = (static_cast<double>(cur)/total)*maxHeight; } else { // For undirected edges, place every other edge on one // side or the other. height = (static_cast<double>((cur+1)/2)/(total/2))*maxHeight; if (cur % 2) { sign = -1; } } // This formula computes offset given dist and height. // You can pull out your trig formulas and verify it :) double offset = (dist*dist/4.0 - height*height)/(2.0*height); double center[3]; for (int c = 0; c < 3; ++c) { center[c] = (targetPt[c] + sourcePt[c])/2.0 + sign*offset*w[c]; } // The vectors u and x are unit vectors pointing from the // center of the circle to the two endpoints of the arc, // sourcePt and targetPt, respectively. double u[3], x[3]; for (int c = 0; c < 3; ++c) { u[c] = sourcePt[c] - center[c]; x[c] = targetPt[c] - center[c]; } double radius = vtkMath::Norm(u); vtkMath::Normalize(u); vtkMath::Normalize(x); // Find the angle that the arc spans. double theta = acos(vtkMath::Dot(u, x)); // We need two perpendicular vectors on the plane of the circle // in order to draw the circle. First we calculate n, a vector // normal to the circle, by crossing u and w. Next, we cross // n and u in order to get a vector v in the plane of the circle // that is perpendicular to u. double n[3]; vtkMath::Cross(u, w, n); vtkMath::Normalize(n); double v[3]; vtkMath::Cross(n, u, v); vtkMath::Normalize(v); // Use the general equation for a circle in three dimensions // to draw an arc from the last point to the current point. for (int s = 0; s < this->NumberOfSubdivisions; ++s) { double angle = -sign*s*theta/(this->NumberOfSubdivisions - 1.0); for (int c = 0; c < 3; ++c) { pts[3*s + c] = center[c] + radius*cos(angle)*u[c] + radius*sin(angle)*v[c]; } } this->Graph->SetEdgePoints(e.Id, this->NumberOfSubdivisions, pts); if (eid % 1000 == 0) { double progress = eid / static_cast<double>(numEdges); this->InvokeEvent(vtkCommand::ProgressEvent, static_cast<void*>(&progress)); } } double progress = 1.0; this->InvokeEvent(vtkCommand::ProgressEvent, static_cast<void*>(&progress)); delete [] pts; } void vtkArcParallelEdgeStrategy::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "NumberOfSubdivisions: " << this->NumberOfSubdivisions << endl; } <|endoftext|>
<commit_before>// Time: O(n) // Space: O(1) /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { ListNode dummy(-1); dummy.next = head; ListNode *prev = &dummy; for(int i = 0; i < m - 1; ++i) { prev = prev->next; } ListNode *const head2 = prev; prev = prev->next; ListNode *cur = prev->next; for(int i = m; i < n; ++i) { prev->next = cur->next; // remove cur from the list cur->next = head2->next; // add cur to the head head2->next = cur; // add cur to the head cur = prev->next; // get next cur } return dummy.next; } }; <commit_msg>Update reverse-linked-list-ii.cpp<commit_after>// Time: O(n) // Space: O(1) /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { ListNode dummy{0}; dummy.next = head; auto *prev = &dummy; for (int i = 0; i < m - 1; ++i) { prev = prev->next; } auto *head2 = prev; prev = prev->next; auto *cur = prev->next; for (int i = m; i < n; ++i) { prev->next = cur->next; // Remove cur from the list. cur->next = head2->next; // Add cur to the head. head2->next = cur; // Add cur to the head. cur = prev->next; // Get next cur. } return dummy.next; } }; <|endoftext|>
<commit_before>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <fstream> #include <string> #include <cstring> #include <vector> #include <iomanip> #include <configuration.hpp> #include <ArgumentList.hpp> #include <Observation.hpp> #include <ReadData.hpp> #include <Shifts.hpp> #include <Dedispersion.hpp> int main(int argc, char * argv[]) { // Command line arguments isa::utils::ArgumentList args(argc, argv); // Observation AstroData::Observation observation; unsigned int padding = 0; uint8_t inputBits = 0; // Files std::string dataFile; std::string headerFile; std::string outputFile; std::vector< std::ofstream > output; // LOFAR bool dataLOFAR = false; bool limit = false; // SIGPROC bool dataSIGPROC = false; unsigned int bytesToSkip = 0; // PSRDada bool dataPSRDada = false; key_t dadaKey; dada_hdu_t * ringBuffer; try { padding = args.getSwitchArgument< unsigned int >("-padding"); dataLOFAR = args.getSwitch("-lofar"); dataSIGPROC = args.getSwitch("-sigproc"); dataPSRDada = args.getSwitch("-dada"); if ( !((((!(dataLOFAR && dataSIGPROC) && dataPSRDada) || (!(dataLOFAR && dataPSRDada) && dataSIGPROC)) || (!(dataSIGPROC && dataPSRDada) && dataLOFAR)) || ((!dataLOFAR && !dataSIGPROC) && !dataPSRDada)) ) { std::cerr << "-lofar -sigproc and -dada are mutually exclusive." << std::endl; throw std::exception(); } else if ( dataLOFAR ) { observation.setNrBeams(1); headerFile = args.getSwitchArgument< std::string >("-header"); dataFile = args.getSwitchArgument< std::string >("-data"); limit = args.getSwitch("-limit"); if ( limit ) { observation.setNrSeconds(args.getSwitchArgument< unsigned int >("-seconds")); } } else if ( dataSIGPROC ) { observation.setNrBeams(1); bytesToSkip = args.getSwitchArgument< unsigned int >("-header"); dataFile = args.getSwitchArgument< std::string >("-data"); observation.setNrSeconds(args.getSwitchArgument< unsigned int >("-seconds")); observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth")); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); } else if ( dataPSRDada ) { dadaKey = args.getSwitchArgument< key_t >("-dada_key"); observation.setNrBeams(args.getSwitchArgument< unsigned int >("-beams")); observation.setNrSeconds(args.getSwitchArgument< unsigned int >("-seconds")); } inputBits = args.getSwitchArgument< unsigned int >("-input_bits"); outputFile = args.getSwitchArgument< std::string >("-output"); observation.setDMRange(1, args.getSwitchArgument< float >("-dm"), 0.0f); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << args.getName() << " -padding ... [-lofar] [-sigproc] [-dada] -input_bits ... -output ... -dm ..." << std::endl; std::cerr << "\t -lofar -header ... -data ... [-limit]" << std::endl; std::cerr << "\t\t -limit -seconds ..." << std::endl; std::cerr << "\t -sigproc -header ... -data ... -seconds ... -channels ... -min_freq ... -channel_bandwidth ... -samples ..." << std::endl; std::cerr << "\t -dada -dada_key ... -beams ... -seconds ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Load observation data std::vector< std::vector< std::vector< inputDataType > * > * > input(observation.getNrBeams()); if ( dataLOFAR ) { input[0] = new std::vector< std::vector< inputDataType > * >(observation.getNrSeconds()); if ( limit ) { AstroData::readLOFAR(headerFile, dataFile, observation, padding, *(input[0]), observation.getNrSeconds()); } else { AstroData::readLOFAR(headerFile, dataFile, observation, padding, *(input[0])); } } else if ( dataSIGPROC ) { input[0] = new std::vector< std::vector< inputDataType > * >(observation.getNrSeconds()); AstroData::readSIGPROC(observation, padding, inputBits, bytesToSkip, dataFile, *(input[0])); } else if ( dataPSRDada ) { ringBuffer = dada_hdu_create(0); dada_hdu_set_key(ringBuffer, dadaKey); dada_hdu_connect(ringBuffer); dada_hdu_lock_read(ringBuffer); } output = std::vector< std::ofstream >(observation.getNrBeams()); // Host memory allocation std::vector< float > * shifts = PulsarSearch::getShifts(observation); observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * observation.getFirstDM())); observation.setNrDelaySeconds(static_cast< unsigned int >(std::ceil(static_cast< double >(observation.getNrSamplesPerDispersedChannel()) / observation.getNrSamplesPerSecond()))); std::vector< std::vector< inputDataType > > dispersedData(observation.getNrBeams()); std::vector< std::vector< outputDataType > > dedispersedData(observation.getNrBeams()); for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { if ( inputBits >= 8 ) { dispersedData[beam] = std::vector< inputDataType >(observation.getNrChannels() * observation.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))); } else { dispersedData[beam] = std::vector< inputDataType >(observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))); } dedispersedData[beam] = std::vector< outputDataType >(observation.getNrSamplesPerPaddedSecond(padding / sizeof(outputDataType))); } // Open output files for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { output[beam].open(outputFile + "_B" + isa::utils::toString(beam) + ".tim"); output[beam] << std::fixed << std::setprecision(6); } // Dedispersion loop for ( unsigned int second = 0; second < observation.getNrSeconds() - observation.getNrDelaySeconds(); second++ ) { for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { for ( unsigned int chunk = 0; chunk < observation.getNrDelaySeconds() - 1; chunk++ ) { if ( inputBits >= 8 ) { std::memcpy(reinterpret_cast< void * >(&(dispersedData[beam].data()[(channel * observation.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + (chunk * observation.getNrSamplesPerSecond())])), reinterpret_cast< void * >(&((input[beam]->at(second + chunk))->at(channel * observation.getNrSamplesPerPaddedSecond(padding / sizeof(inputDataType))))), observation.getNrSamplesPerSecond() * sizeof(inputDataType)); } else { std::memcpy(reinterpret_cast< void * >(&(dispersedData[beam].data()[(channel * isa::utils::pad(observation.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + (chunk * (observation.getNrSamplesPerSecond() / (8 / inputBits)))])), reinterpret_cast< void * >(&((input[beam]->at(second + chunk))->at(channel * isa::utils::pad(observation.getNrSamplesPerSecond() / (8 / inputBits), padding / sizeof(inputDataType))))), (observation.getNrSamplesPerSecond() / (8 / inputBits)) * sizeof(inputDataType)); } } if ( observation.getNrSamplesPerDispersedChannel() % observation.getNrSamplesPerSecond() == 0 ) { if ( inputBits >= 8 ) { std::memcpy(reinterpret_cast< void * >(&(dispersedData[beam].data()[(channel * observation.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + ((observation.getNrDelaySeconds() - 1) * observation.getNrSamplesPerSecond())])), reinterpret_cast< void * >(&((input[beam]->at(second + (observation.getNrDelaySeconds() - 1)))->at(channel * observation.getNrSamplesPerPaddedSecond(padding / sizeof(inputDataType))))), observation.getNrSamplesPerDispersedChannel() * sizeof(inputDataType)); } else { std::memcpy(reinterpret_cast< void * >(&(dispersedData[beam].data()[(channel * isa::utils::pad(observation.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + ((observation.getNrDelaySeconds() - 1) * (observation.getNrSamplesPerSecond() / (8 / inputBits)))])), reinterpret_cast< void * >(&((input[beam]->at(second + (observation.getNrDelaySeconds() - 1)))->at(channel * isa::utils::pad(observation.getNrSamplesPerSecond() / (8 / inputBits), padding / sizeof(inputDataType))))), (observation.getNrSamplesPerDispersedChannel() / (8 / inputBits)) * sizeof(inputDataType)); } } else { if ( inputBits >= 8 ) { std::memcpy(reinterpret_cast< void * >(&(dispersedData[beam].data()[(channel * observation.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + ((observation.getNrDelaySeconds() - 1) * observation.getNrSamplesPerSecond())])), reinterpret_cast< void * >(&((input[beam]->at(second + (observation.getNrDelaySeconds() - 1)))->at(channel * observation.getNrSamplesPerPaddedSecond(padding / sizeof(inputDataType))))), (observation.getNrSamplesPerDispersedChannel() % observation.getNrSamplesPerSecond()) * sizeof(inputDataType)); } else { std::memcpy(reinterpret_cast< void * >(&(dispersedData[beam].data()[(channel * isa::utils::pad(observation.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + ((observation.getNrDelaySeconds() - 1) * (observation.getNrSamplesPerSecond() / (8 / inputBits)))])), reinterpret_cast< void * >(&((input[beam]->at(second + (observation.getNrDelaySeconds() - 1)))->at(channel * isa::utils::pad(observation.getNrSamplesPerSecond() / (8 / inputBits), padding / sizeof(inputDataType))))), ((observation.getNrSamplesPerDispersedChannel() % observation.getNrSamplesPerSecond()) / (8 / inputBits)) * sizeof(inputDataType)); } } } PulsarSearch::dedispersion< inputDataType, intermediateDataType, outputDataType >(observation, dispersedData[beam], dedispersedData[beam], *shifts, padding, inputBits); for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { output[beam] << static_cast< uint64_t >((second * observation.getNrSamplesPerSecond()) + sample) * observation.getSamplingRate() << " " << dedispersedData[beam][sample] << std::endl; } } } if ( dataPSRDada ) { dada_hdu_unlock_read(ringBuffer); dada_hdu_disconnect(ringBuffer); } // Close output files for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { output[beam].close(); } return 0; } <commit_msg>Added padding to getShifts.<commit_after>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <fstream> #include <string> #include <cstring> #include <vector> #include <iomanip> #include <configuration.hpp> #include <ArgumentList.hpp> #include <Observation.hpp> #include <ReadData.hpp> #include <Shifts.hpp> #include <Dedispersion.hpp> int main(int argc, char * argv[]) { // Command line arguments isa::utils::ArgumentList args(argc, argv); // Observation AstroData::Observation observation; unsigned int padding = 0; uint8_t inputBits = 0; // Files std::string dataFile; std::string headerFile; std::string outputFile; std::vector< std::ofstream > output; // LOFAR bool dataLOFAR = false; bool limit = false; // SIGPROC bool dataSIGPROC = false; unsigned int bytesToSkip = 0; // PSRDada bool dataPSRDada = false; key_t dadaKey; dada_hdu_t * ringBuffer; try { padding = args.getSwitchArgument< unsigned int >("-padding"); dataLOFAR = args.getSwitch("-lofar"); dataSIGPROC = args.getSwitch("-sigproc"); dataPSRDada = args.getSwitch("-dada"); if ( !((((!(dataLOFAR && dataSIGPROC) && dataPSRDada) || (!(dataLOFAR && dataPSRDada) && dataSIGPROC)) || (!(dataSIGPROC && dataPSRDada) && dataLOFAR)) || ((!dataLOFAR && !dataSIGPROC) && !dataPSRDada)) ) { std::cerr << "-lofar -sigproc and -dada are mutually exclusive." << std::endl; throw std::exception(); } else if ( dataLOFAR ) { observation.setNrBeams(1); headerFile = args.getSwitchArgument< std::string >("-header"); dataFile = args.getSwitchArgument< std::string >("-data"); limit = args.getSwitch("-limit"); if ( limit ) { observation.setNrSeconds(args.getSwitchArgument< unsigned int >("-seconds")); } } else if ( dataSIGPROC ) { observation.setNrBeams(1); bytesToSkip = args.getSwitchArgument< unsigned int >("-header"); dataFile = args.getSwitchArgument< std::string >("-data"); observation.setNrSeconds(args.getSwitchArgument< unsigned int >("-seconds")); observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth")); observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples")); } else if ( dataPSRDada ) { dadaKey = args.getSwitchArgument< key_t >("-dada_key"); observation.setNrBeams(args.getSwitchArgument< unsigned int >("-beams")); observation.setNrSeconds(args.getSwitchArgument< unsigned int >("-seconds")); } inputBits = args.getSwitchArgument< unsigned int >("-input_bits"); outputFile = args.getSwitchArgument< std::string >("-output"); observation.setDMRange(1, args.getSwitchArgument< float >("-dm"), 0.0f); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << args.getName() << " -padding ... [-lofar] [-sigproc] [-dada] -input_bits ... -output ... -dm ..." << std::endl; std::cerr << "\t -lofar -header ... -data ... [-limit]" << std::endl; std::cerr << "\t\t -limit -seconds ..." << std::endl; std::cerr << "\t -sigproc -header ... -data ... -seconds ... -channels ... -min_freq ... -channel_bandwidth ... -samples ..." << std::endl; std::cerr << "\t -dada -dada_key ... -beams ... -seconds ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Load observation data std::vector< std::vector< std::vector< inputDataType > * > * > input(observation.getNrBeams()); if ( dataLOFAR ) { input[0] = new std::vector< std::vector< inputDataType > * >(observation.getNrSeconds()); if ( limit ) { AstroData::readLOFAR(headerFile, dataFile, observation, padding, *(input[0]), observation.getNrSeconds()); } else { AstroData::readLOFAR(headerFile, dataFile, observation, padding, *(input[0])); } } else if ( dataSIGPROC ) { input[0] = new std::vector< std::vector< inputDataType > * >(observation.getNrSeconds()); AstroData::readSIGPROC(observation, padding, inputBits, bytesToSkip, dataFile, *(input[0])); } else if ( dataPSRDada ) { ringBuffer = dada_hdu_create(0); dada_hdu_set_key(ringBuffer, dadaKey); dada_hdu_connect(ringBuffer); dada_hdu_lock_read(ringBuffer); } output = std::vector< std::ofstream >(observation.getNrBeams()); // Host memory allocation std::vector< float > * shifts = PulsarSearch::getShifts(observation, padding); observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * observation.getFirstDM())); observation.setNrDelaySeconds(static_cast< unsigned int >(std::ceil(static_cast< double >(observation.getNrSamplesPerDispersedChannel()) / observation.getNrSamplesPerSecond()))); std::vector< std::vector< inputDataType > > dispersedData(observation.getNrBeams()); std::vector< std::vector< outputDataType > > dedispersedData(observation.getNrBeams()); for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { if ( inputBits >= 8 ) { dispersedData[beam] = std::vector< inputDataType >(observation.getNrChannels() * observation.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))); } else { dispersedData[beam] = std::vector< inputDataType >(observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))); } dedispersedData[beam] = std::vector< outputDataType >(observation.getNrSamplesPerPaddedSecond(padding / sizeof(outputDataType))); } // Open output files for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { output[beam].open(outputFile + "_B" + isa::utils::toString(beam) + ".tim"); output[beam] << std::fixed << std::setprecision(6); } // Dedispersion loop for ( unsigned int second = 0; second < observation.getNrSeconds() - observation.getNrDelaySeconds(); second++ ) { for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { for ( unsigned int chunk = 0; chunk < observation.getNrDelaySeconds() - 1; chunk++ ) { if ( inputBits >= 8 ) { std::memcpy(reinterpret_cast< void * >(&(dispersedData[beam].data()[(channel * observation.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + (chunk * observation.getNrSamplesPerSecond())])), reinterpret_cast< void * >(&((input[beam]->at(second + chunk))->at(channel * observation.getNrSamplesPerPaddedSecond(padding / sizeof(inputDataType))))), observation.getNrSamplesPerSecond() * sizeof(inputDataType)); } else { std::memcpy(reinterpret_cast< void * >(&(dispersedData[beam].data()[(channel * isa::utils::pad(observation.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + (chunk * (observation.getNrSamplesPerSecond() / (8 / inputBits)))])), reinterpret_cast< void * >(&((input[beam]->at(second + chunk))->at(channel * isa::utils::pad(observation.getNrSamplesPerSecond() / (8 / inputBits), padding / sizeof(inputDataType))))), (observation.getNrSamplesPerSecond() / (8 / inputBits)) * sizeof(inputDataType)); } } if ( observation.getNrSamplesPerDispersedChannel() % observation.getNrSamplesPerSecond() == 0 ) { if ( inputBits >= 8 ) { std::memcpy(reinterpret_cast< void * >(&(dispersedData[beam].data()[(channel * observation.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + ((observation.getNrDelaySeconds() - 1) * observation.getNrSamplesPerSecond())])), reinterpret_cast< void * >(&((input[beam]->at(second + (observation.getNrDelaySeconds() - 1)))->at(channel * observation.getNrSamplesPerPaddedSecond(padding / sizeof(inputDataType))))), observation.getNrSamplesPerDispersedChannel() * sizeof(inputDataType)); } else { std::memcpy(reinterpret_cast< void * >(&(dispersedData[beam].data()[(channel * isa::utils::pad(observation.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + ((observation.getNrDelaySeconds() - 1) * (observation.getNrSamplesPerSecond() / (8 / inputBits)))])), reinterpret_cast< void * >(&((input[beam]->at(second + (observation.getNrDelaySeconds() - 1)))->at(channel * isa::utils::pad(observation.getNrSamplesPerSecond() / (8 / inputBits), padding / sizeof(inputDataType))))), (observation.getNrSamplesPerDispersedChannel() / (8 / inputBits)) * sizeof(inputDataType)); } } else { if ( inputBits >= 8 ) { std::memcpy(reinterpret_cast< void * >(&(dispersedData[beam].data()[(channel * observation.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + ((observation.getNrDelaySeconds() - 1) * observation.getNrSamplesPerSecond())])), reinterpret_cast< void * >(&((input[beam]->at(second + (observation.getNrDelaySeconds() - 1)))->at(channel * observation.getNrSamplesPerPaddedSecond(padding / sizeof(inputDataType))))), (observation.getNrSamplesPerDispersedChannel() % observation.getNrSamplesPerSecond()) * sizeof(inputDataType)); } else { std::memcpy(reinterpret_cast< void * >(&(dispersedData[beam].data()[(channel * isa::utils::pad(observation.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + ((observation.getNrDelaySeconds() - 1) * (observation.getNrSamplesPerSecond() / (8 / inputBits)))])), reinterpret_cast< void * >(&((input[beam]->at(second + (observation.getNrDelaySeconds() - 1)))->at(channel * isa::utils::pad(observation.getNrSamplesPerSecond() / (8 / inputBits), padding / sizeof(inputDataType))))), ((observation.getNrSamplesPerDispersedChannel() % observation.getNrSamplesPerSecond()) / (8 / inputBits)) * sizeof(inputDataType)); } } } PulsarSearch::dedispersion< inputDataType, intermediateDataType, outputDataType >(observation, dispersedData[beam], dedispersedData[beam], *shifts, padding, inputBits); for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) { output[beam] << static_cast< uint64_t >((second * observation.getNrSamplesPerSecond()) + sample) * observation.getSamplingRate() << " " << dedispersedData[beam][sample] << std::endl; } } } if ( dataPSRDada ) { dada_hdu_unlock_read(ringBuffer); dada_hdu_disconnect(ringBuffer); } // Close output files for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) { output[beam].close(); } return 0; } <|endoftext|>