Dataset Viewer
Auto-converted to Parquet
text
stringlengths
500
20k
source
stringclasses
27 values
lang
stringclasses
3 values
char_count
int64
500
20k
word_count
int64
4
19.8k
// Copyright 2011 the V8 project authors. 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Features shared by parsing and pre-parsing scanners. #include "scanner.h" #include "../include/v8stdint.h" #include "char-predicates-inl.h" namespace v8 { namespace internal { // ---------------------------------------------------------------------------- // Scanner Scanner::Scanner(UnicodeCache* unicode_cache) : unicode_cache_(unicode_cache), octal_pos_(Location::invalid()), harmony_scoping_(false), harmony_modules_(false) { } void Scanner::Initialize(Utf16CharacterStream* source) { source_ = source; // Need to capture identifiers in order to recognize "get" and "set" // in object literals. Init(); // Skip initial whitespace allowing HTML comment ends just like // after a newline and scan first token. has_line_terminator_before_next_ = true; SkipWhiteSpace(); Scan(); } uc32 Scanner::ScanHexNumber(int expected_length) { ASSERT(expected_length <= 4); // prevent overflow uc32 digits[4] = { 0, 0, 0, 0 }; uc32 x = 0; for (int i = 0; i < expected_length; i++) { digits[i] = c0_; int d = HexValue(c0_); if (d < 0) { // According to ECMA-262, 3rd, 7.8.4, page 18, these hex escapes // should be illegal, but other JS VMs just return the // non-escaped version of the original character. // Push back digits that we have advanced past. for (int j = i-1; j >= 0; j--) { PushBack(digits[j]); } return -1; } x = x * 16 + d; Advance(); } return x; } // Ensure that tokens can be stored in a byte. STATIC_ASSERT(Token::NUM_TOKENS <= 0x100); // Table of one-character tokens, by character (0x00..0x7f only). static const byte one_char_tokens[] = { Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::LPAREN, // 0x28 Token::RPAREN, // 0x29 Token::ILLEGAL, Token::ILLEGAL, Token::COMMA, // 0x2c Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::COLON, // 0x3a Token::SEMICOLON, // 0x3b Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::CONDITIONAL, // 0x3f Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::LBRACK, // 0x5b Token::ILLEGAL, Token::RBRACK, // 0x5d Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::ILLEGAL, Token::LBRACE, // 0x7b Token::ILLEGAL, Token::RBRACE, // 0x7d Token::BIT_NOT, // 0x7e Token::ILLEGAL }; Token::Value Scanner::Next() { current_ = next_; has_line_terminator_before_next_ = false; has_multiline_comment_before_next_ = false; if (static_cast<unsigned>(c0_) <= 0x7f) { Token::Value token = static_cast<Token::Value>(one_char_tokens[c0_]); if (token != Token::ILLEGAL) { int pos = source_pos(); next_.token = token; next_.location.beg_pos = pos; next_.location.end_pos = pos + 1; Advance(); return current_.token; } } Scan(); return current_.token; } static inline bool IsByteOrderMark(uc32 c) { // The Unicode value U+FFFE is guaranteed never to be assigned as a // Unicode character; this implies that in a Unicode context the // 0xFF, 0xFE byte pattern can only be interpreted as the U+FEFF // character expressed in little-endian byte order (since it could // not be a U+FFFE character expressed in big-endian byte // order). Nevertheless, we check for it to be compatible with // Spidermonkey. return c == 0xFEFF || c == 0xFFFE; } bool Scanner::SkipWhiteSpace() { int start_position = source_pos(); while (true) { // We treat byte-order marks (BOMs) as whitespace for better // compatibility with Spidermonkey and other JavaScript engines. while (unicode_cache_->IsWhiteSpace(c0_) || IsByteOrderMark(c0_)) { // IsWhiteSpace() includes line terminators! if (unicode_cache_->IsLineTerminator(c0_)) { // Ignore line terminators, but remember them. This is necessary // for automatic semicolon insertion. has_line_terminator_before_next_ = true; } Advance(); } // If there is an HTML comment end '-->' at the beginning of a // line (with only whitespace in front of it), we treat the rest // of the line as a comment. This is in line with the way // SpiderMonkey handles it. if (c0_ == '-' && has_line_terminator_before_next_) { Advance(); if (c0_ == '-') { Advance(); if (c0_ == '>') { // Treat the rest of the line as a comment. SkipSingleLineComment(); // Continue skipping white space after the comment. continue; } PushBack('-'); // undo Advance() } PushBack('-'); // undo Advance() } // Return whether or not we skipped any characters. return source_pos() != start_position; } } Token::Value Scanner::SkipSingleLineComment() { Advance(); // The line terminator at the end of the line is not considered // to be part of the single-line comment; it is recognized // separately by the lexical grammar and becomes part of the // stream of input elements for the syntactic grammar (see // ECMA-262, section 7.4). while (c0_ >= 0 && !unicode_cache_->IsLineTerminator(c0_)) { Advance(); } return Token::WHITESPACE; } Token::Value Scanner::SkipMultiLineComment() { ASSERT(c0_ == '*'); Advance(); while (c0_ >= 0) { uc32 ch = c0_; Advance(); if (unicode_cache_->IsLineTerminator(ch)) { // Following ECMA-262, section 7.4, a comment containing // a newline will make the comment count as a line-terminator. has_multiline_comment_before_next_ = true; } // If we have reached the end of the multi-line comment, we // consume the '/' and insert a whitespace. This way all // multi-line comments are treated as whitespace. if (ch == '*' && c0_ == '/') { c0_ = ' '; return Token::WHITESPACE; } } // Unterminated multi-line comment. return Token::ILLEGAL; } Token::Value Scanner::ScanHtmlComment() { // Check for <!-- comments. ASSERT(c0_ == '!'); Advance(); if (c0_ == '-') { Advance(); if (c0_ == '-') return SkipSingleLineComment(); PushBack('-'); // undo Advance() } PushBack('!'); // undo Advance() ASSERT(c0_ == '!'); return Token::LT; } void Scanner::Scan() { next_.literal_chars = NULL; Token::Value token; do { // Remember the position of the next token next_.location.beg_pos = source_pos(); switch (c0_) { case ' ': case '\t': Advance(); token = Token::WHITESPACE; break; case '\n': Advance(); has_line_terminator_before_next_ = true; token = Token::WHITESPACE; break; case '"': case '\'': token = ScanString(); break; case '<': // < <= << <<= <!-- Advance(); if (c0_ == '=') { token = Select(Token::LTE); } else if (c0_ == '<') { token = Select('=', Token::ASSIGN_SHL, Token::SHL); } else if (c0_ == '!') { token = ScanHtmlComment(); } else { token = Token::LT; } break; case '>': // > >= >> >>= >>> >>>= Advance(); if (c0_ == '=') { token = Select(Token::GTE); } else if (c0_ == '>') { // >> >>= >>> >>>= Advance(); if (c0_ == '=') { token = Select(Token::ASSIGN_SAR); } else if (c0_ == '>') { token = Select('=', Token::ASSIGN_SHR, Token::SHR); } else { token = Token::SAR; } } else { token = Token::GT; } break; case '=': // = == === Advance(); if (c0_ == '=') { token = Select('=', Token::EQ_STRICT, Token::EQ); } else { token = Token::ASSIGN; } break; case '!': // ! != !== Advance(); if (c0_ == '=') { token = Select('=', Token::NE_STRICT, Token::NE); } else { token = Token::NOT; } break; case '+': // + ++ += Advance(); if (c0_ == '+') { token = Select(Token::INC); } else if (c0_ == '=') { token = Select(Token::ASSIGN_ADD); } else { token = Token::ADD; } break; case '-': // - -- --> -= Advance(); if (c0_ == '-') { Advance(); if (c0_ == '>' && has_line_terminator_before_next_) { // For compatibility with SpiderMonkey, we skip lines that // start with an HTML comment end '-->'. token = SkipSingleLineComment(); } else { token = Token::DEC; } } else if (c0_ == '=') { token = Select(Token::ASSIGN_SUB); } else { token = Token::SUB; } break; case '*': // * *= token = Select('=', Token::ASSIGN_MUL, Token::MUL); break; case '%': // % %= token = Select('=', Token::ASSIGN_MOD, Token::MOD); break; case '/': // / // /* /= Advance(); if (c0_ == '/') { token = SkipSingleLineComment(); } else if (c0_ == '*') { token = SkipMultiLineComment(); } else if (c0_ == '=') { token = Select(Token::ASSIGN_DIV); } else { token = Token::DIV; } break; case '&': // & && &= Advance(); if (c0_ == '&') { token = Select(Token::AND); } else if (c0_ == '=') { token = Select(Token::ASSIGN_BIT_AND); } else { token = Token::BIT_AND; } break; case '|': // | || |= Advance(); if (c0_ == '|') { token = Select(Token::OR); } else if (c0_ == '=') { token = Select(Token::ASSIGN_BIT_OR); } else { token = Token::BIT_OR; } break; case '^': // ^ ^= token = Select('=', Token::ASSIGN_BIT_XOR, Token::BIT_XOR); break; case '.': // . Number Advance(); if (IsDecimalDigit(c0_)) { token = ScanNumber(true); } else { token = Token::PERIOD; } break; case ':': token = Select(Token::COLON); break; case ';': token = Select(Token::SEMICOLON); break; case ',': token = Select(Token::COMMA); break; case '(': token = Select(Token::LPAREN); break; case ')': token = Select(Token::RPAREN); break; case '[': token = Select(Token::LBRACK); break; case ']': token = Select(Token::RBRACK); break; case '{': token = Select(Token::LBRACE); break; case '}': token = Select(Token::RBRACE); break; case '?': token = Select(Token::CONDITIONAL); break; case '~': token = Select(Token::BIT_NOT); break; default: if (unicode_cache_->IsIdentifierStart(c0_)) { token = ScanIdentifierOrKeyword(); } else if (IsDecimalDigit(c0_)) { token = ScanNumber(false); } else if (SkipWhiteSpace()) { token = Token::WHITESPACE; } else if (c0_ < 0) { token = Token::EOS; } else { token = Select(Token::ILLEGAL); } break; } // Continue scanning for tokens as long as we're just skipping // whitespace. } while (token == Token::WHITESPACE); next_.location.end_pos = source_pos(); next_.token = token; } void Scanner::SeekForward(int pos) { // After this call, we will have the token at the given position as // the "next" token. The "current" token will be invalid. if (pos == next_.location.beg_pos) return; int current_pos = source_pos(); ASSERT_EQ(next_.location.end_pos, current_pos); // Positions inside the lookahead token aren't supported. ASSERT(pos >= current_pos); if (pos != current_pos) { source_->SeekForward(pos - source_->pos()); Advance(); // This function is only called to seek to the location // of the end of a function (at the "}" token). It doesn't matter // whether there was a line terminator in the part we skip. has_line_terminator_before_next_ = false; has_multiline_comment_before_next_ = false; } Scan(); } void Scanner::ScanEscape() { uc32 c = c0_; Advance(); // Skip escaped newlines. if (unicode_cache_->IsLineTerminator(c)) { // Allow CR+LF newlines in multiline string literals. if (IsCarriageReturn(c) && IsLineFeed(c0_)) Advance(); // Allow LF+CR newlines in multiline string literals. if (IsLineFeed(c) && IsCarriageReturn(c0_)) Advance(); return; } switch (c) { case '\'': // fall through case '"' : // fall through case '\\': break; case 'b' : c = '\b'; break; case 'f' : c = '\f'; break; case 'n' : c = '\n'; break; case 'r' : c = '\r'; break; case 't' : c = '\t'; break; case 'u' : { c = ScanHexNumber(4); if (c < 0) c = 'u'; break; } case 'v' : c = '\v'; break; case 'x' : { c = ScanHexNumber(2); if (c < 0) c = 'x'; break; } case '0' : // fall through case '1' : // fall through case '2' : // fall through case '3' : // fall through case '4' : // fall through case '5' : // fall through case '6' : // fall through case '7' : c = ScanOctalEscape(c, 2); break; } // According to ECMA-262, 3rd, 7.8.4 (p 18ff) these // should be illegal, but they are commonly handled // as non-escaped characters by JS VMs. AddLiteralChar(c); } // Octal escapes of the forms '\0xx' and '\xxx' are not a part of // ECMA-262. Other JS VMs support them. uc32 Scanner::ScanOctalEscape(uc32 c, int length) { uc32 x = c - '0'; int i = 0; for (; i < length; i++) { int d = c0_ - '0'; if (d < 0 || d > 7) break; int nx = x * 8 + d; if (nx >= 256) break; x = nx; Advance(); } // Anything except '\0' is an octal escape sequence, illegal in strict mode. // Remember the position of octal escape sequences so that an error // can be reported later (in strict mode). // We don't report the error immediately, because the octal escape can // occur before the "use strict" directive. if (c != '0' || i > 0) { octal_pos_ = Location(source_pos() - i - 1, source_pos() - 1); } return x; } Token::Value Scanner::ScanString() { uc32 quote = c0_; Advance(); // consume quote LiteralScope literal(this); while (c0_ != quote && c0_ >= 0 && !unicode_cache_->IsLineTerminator(c0_)) { uc32 c = c0_; Advance(); if (c == '\\') { if (c0_ < 0) return Token::ILLEGAL; ScanEscape(); } else { AddLiteralChar(c); } } if (c0_ != quote) return Token::ILLEGAL; literal.Complete(); Advance(); // consume quote return Token::STRING; } void Scanner::ScanDecimalDigits() { while (IsDecimalDigit(c0_)) AddLiteralCharAdvance(); } Token::Value Scanner::ScanNumber(bool seen_period) { ASSERT(IsDecimalDigit(c0_)); // the first digit of the number or the fraction enum { DECIMAL, HEX, OCTAL } kind = DECIMAL; LiteralScope literal(this); if (seen_period) { // we have already seen a decimal point of the float AddLiteralChar('.'); ScanDecimalDigits(); // we know we have at least one digit } else { // if the first character is '0' we must check for octals and hex if (c0_ == '0') { int start_pos = source_pos(); // For reporting octal positions. AddLiteralCharAdvance(); // either 0, 0exxx, 0Exxx, 0.xxx, an octal number, or a hex number if (c0_ == 'x' || c0_ == 'X') { // hex number kind = HEX; AddLiteralCharAdvance(); if (!IsHexDigit(c0_)) { // we must have at least one hex digit after 'x'/'X' return Token::ILLEGAL; } while (IsHexDigit(c0_)) { AddLiteralCharAdvance(); } } else if ('0' <= c0_ && c0_ <= '7') { // (possible) octal number kind = OCTAL; while (true) { if (c0_ == '8' || c0_ == '9') { kind = DECIMAL; break; } if (c0_ < '0' || '7' < c0_) { // Octal literal finished. octal_pos_ = Location(start_pos, source_pos()); break; } AddLiteralCharAdvance(); } }
c++
code
19,998
4,708
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "tools/ToolUtils.h" #include <string> #include "include/core/SkBitmap.h" #include "include/core/SkCanvas.h" #include "include/core/SkFontMgr.h" #include "include/core/SkGraphics.h" #include "include/core/SkPaint.h" #include "include/core/SkPoint.h" #include "include/core/SkSurface.h" #include "include/core/SkTextBlob.h" #include "include/core/SkTypeface.h" #include "include/gpu/GrDirectContext.h" #include "src/core/SkGlyphRun.h" #include "src/gpu/GrDirectContextPriv.h" #include "tools/fonts/RandomScalerContext.h" #ifdef SK_BUILD_FOR_WIN #include "include/ports/SkTypeface_win.h" #endif #include "tests/Test.h" #include "src/gpu/GrDirectContextPriv.h" #include "src/gpu/text/GrAtlasManager.h" #include "src/gpu/text/GrTextBlobCache.h" static void draw(SkCanvas* canvas, int redraw, const SkTArray<sk_sp<SkTextBlob>>& blobs) { int yOffset = 0; for (int r = 0; r < redraw; r++) { for (int i = 0; i < blobs.count(); i++) { const auto& blob = blobs[i]; const SkRect& bounds = blob->bounds(); yOffset += SkScalarCeilToInt(bounds.height()); SkPaint paint; canvas->drawTextBlob(blob, 0, SkIntToScalar(yOffset), paint); } } } static const int kWidth = 1024; static const int kHeight = 768; static void setup_always_evict_atlas(GrDirectContext* dContext) { dContext->priv().getAtlasManager()->setAtlasDimensionsToMinimum_ForTesting(); } class GrTextBlobTestingPeer { public: static void SetBudget(GrTextBlobCache* cache, size_t budget) { SkAutoSpinlock lock{cache->fSpinLock}; cache->fSizeBudget = budget; cache->internalCheckPurge(); } }; // This test hammers the GPU textblobcache and font atlas static void text_blob_cache_inner(skiatest::Reporter* reporter, GrDirectContext* dContext, int maxTotalText, int maxGlyphID, int maxFamilies, bool normal, bool stressTest) { // setup surface uint32_t flags = 0; SkSurfaceProps props(flags, kRGB_H_SkPixelGeometry); // configure our context for maximum stressing of cache and atlas if (stressTest) { setup_always_evict_atlas(dContext); GrTextBlobTestingPeer::SetBudget(dContext->priv().getTextBlobCache(), 0); } SkImageInfo info = SkImageInfo::Make(kWidth, kHeight, kRGBA_8888_SkColorType, kPremul_SkAlphaType); auto surface(SkSurface::MakeRenderTarget(dContext, SkBudgeted::kNo, info, 0, &props)); REPORTER_ASSERT(reporter, surface); if (!surface) { return; } SkCanvas* canvas = surface->getCanvas(); sk_sp<SkFontMgr> fm(SkFontMgr::RefDefault()); int count = std::min(fm->countFamilies(), maxFamilies); // make a ton of text SkAutoTArray<uint16_t> text(maxTotalText); for (int i = 0; i < maxTotalText; i++) { text[i] = i % maxGlyphID; } // generate textblobs SkTArray<sk_sp<SkTextBlob>> blobs; for (int i = 0; i < count; i++) { SkFont font; font.setSize(48); // draw big glyphs to really stress the atlas SkString familyName; fm->getFamilyName(i, &familyName); sk_sp<SkFontStyleSet> set(fm->createStyleSet(i)); for (int j = 0; j < set->count(); ++j) { SkFontStyle fs; set->getStyle(j, &fs, nullptr); // We use a typeface which randomy returns unexpected mask formats to fuzz sk_sp<SkTypeface> orig(set->createTypeface(j)); if (normal) { font.setTypeface(orig); } else { font.setTypeface(sk_make_sp<SkRandomTypeface>(orig, SkPaint(), true)); } SkTextBlobBuilder builder; for (int aa = 0; aa < 2; aa++) { for (int subpixel = 0; subpixel < 2; subpixel++) { for (int lcd = 0; lcd < 2; lcd++) { font.setEdging(SkFont::Edging::kAlias); if (aa) { font.setEdging(SkFont::Edging::kAntiAlias); if (lcd) { font.setEdging(SkFont::Edging::kSubpixelAntiAlias); } } font.setSubpixel(SkToBool(subpixel)); if (!SkToBool(lcd)) { font.setSize(160); } const SkTextBlobBuilder::RunBuffer& run = builder.allocRun(font, maxTotalText, 0, 0, nullptr); memcpy(run.glyphs, text.get(), maxTotalText * sizeof(uint16_t)); } } } blobs.emplace_back(builder.make()); } } // create surface where LCD is impossible info = SkImageInfo::Make(kWidth, kHeight, kRGBA_8888_SkColorType, kPremul_SkAlphaType); SkSurfaceProps propsNoLCD(0, kUnknown_SkPixelGeometry); auto surfaceNoLCD(canvas->makeSurface(info, &propsNoLCD)); REPORTER_ASSERT(reporter, surface); if (!surface) { return; } SkCanvas* canvasNoLCD = surfaceNoLCD->getCanvas(); // test redraw draw(canvas, 2, blobs); draw(canvasNoLCD, 2, blobs); // test draw after free dContext->freeGpuResources(); draw(canvas, 1, blobs); dContext->freeGpuResources(); draw(canvasNoLCD, 1, blobs); // test draw after abandon dContext->abandonContext(); draw(canvas, 1, blobs); } DEF_GPUTEST_FOR_MOCK_CONTEXT(TextBlobCache, reporter, ctxInfo) { text_blob_cache_inner(reporter, ctxInfo.directContext(), 1024, 256, 30, true, false); } DEF_GPUTEST_FOR_MOCK_CONTEXT(TextBlobStressCache, reporter, ctxInfo) { text_blob_cache_inner(reporter, ctxInfo.directContext(), 256, 256, 10, true, true); } DEF_GPUTEST_FOR_MOCK_CONTEXT(TextBlobAbnormal, reporter, ctxInfo) { text_blob_cache_inner(reporter, ctxInfo.directContext(), 256, 256, 10, false, false); } DEF_GPUTEST_FOR_MOCK_CONTEXT(TextBlobStressAbnormal, reporter, ctxInfo) { text_blob_cache_inner(reporter, ctxInfo.directContext(), 256, 256, 10, false, true); } static const int kScreenDim = 160; static SkBitmap draw_blob(SkTextBlob* blob, SkSurface* surface, SkPoint offset) { SkPaint paint; SkCanvas* canvas = surface->getCanvas(); canvas->save(); canvas->drawColor(SK_ColorWHITE, SkBlendMode::kSrc); canvas->translate(offset.fX, offset.fY); canvas->drawTextBlob(blob, 0, 0, paint); SkBitmap bitmap; bitmap.allocN32Pixels(kScreenDim, kScreenDim); surface->readPixels(bitmap, 0, 0); canvas->restore(); return bitmap; } static bool compare_bitmaps(const SkBitmap& expected, const SkBitmap& actual) { SkASSERT(expected.width() == actual.width()); SkASSERT(expected.height() == actual.height()); for (int i = 0; i < expected.width(); ++i) { for (int j = 0; j < expected.height(); ++j) { SkColor expectedColor = expected.getColor(i, j); SkColor actualColor = actual.getColor(i, j); if (expectedColor != actualColor) { return false; } } } return true; } static sk_sp<SkTextBlob> make_blob() { auto tf = SkTypeface::MakeFromName("Roboto2-Regular", SkFontStyle()); SkFont font; font.setTypeface(tf); font.setSubpixel(false); font.setEdging(SkFont::Edging::kAlias); font.setSize(24); static char text[] = "HekpqB"; static const int maxGlyphLen = sizeof(text) * 4; SkGlyphID glyphs[maxGlyphLen]; int glyphCount = font.textToGlyphs(text, sizeof(text), SkTextEncoding::kUTF8, glyphs, maxGlyphLen); SkTextBlobBuilder builder; const auto& runBuffer = builder.allocRun(font, glyphCount, 0, 0); for (int i = 0; i < glyphCount; i++) { runBuffer.glyphs[i] = glyphs[i]; } return builder.make(); } // Turned off to pass on android and ios devices, which were running out of memory.. #if 0 static sk_sp<SkTextBlob> make_large_blob() { auto tf = SkTypeface::MakeFromName("Roboto2-Regular", SkFontStyle()); SkFont font; font.setTypeface(tf); font.setSubpixel(false); font.setEdging(SkFont::Edging::kAlias); font.setSize(24); const int mallocSize = 0x3c3c3bd; // x86 size std::unique_ptr<char[]> text{new char[mallocSize + 1]}; if (text == nullptr) { return nullptr; } for (int i = 0; i < mallocSize; i++) { text[i] = 'x'; } text[mallocSize] = 0; static const int maxGlyphLen = mallocSize; std::unique_ptr<SkGlyphID[]> glyphs{new SkGlyphID[maxGlyphLen]}; int glyphCount = font.textToGlyphs( text.get(), mallocSize, SkTextEncoding::kUTF8, glyphs.get(), maxGlyphLen); SkTextBlobBuilder builder; const auto& runBuffer = builder.allocRun(font, glyphCount, 0, 0); for (int i = 0; i < glyphCount; i++) { runBuffer.glyphs[i] = glyphs[i]; } return builder.make(); } DEF_GPUTEST_FOR_RENDERING_CONTEXTS(TextBlobIntegerOverflowTest, reporter, ctxInfo) { auto dContext = ctxInfo.directContext(); const SkImageInfo info = SkImageInfo::Make(kScreenDim, kScreenDim, kN32_SkColorType, kPremul_SkAlphaType); auto surface = SkSurface::MakeRenderTarget(dContext, SkBudgeted::kNo, info); auto blob = make_large_blob(); int y = 40; SkBitmap base = draw_blob(blob.get(), surface.get(), {40, y + 0.0f}); } #endif static const bool kDumpPngs = true; // dump pngs needs a "good" and a "bad" directory to put the results in. This allows the use of the // skdiff tool to visualize the differences. void write_png(const std::string& filename, const SkBitmap& bitmap) { auto data = SkEncodeBitmap(bitmap, SkEncodedImageFormat::kPNG, 0); SkFILEWStream w{filename.c_str()}; w.write(data->data(), data->size()); w.fsync(); } DEF_GPUTEST_FOR_RENDERING_CONTEXTS(TextBlobJaggedGlyph, reporter, ctxInfo) { auto direct = ctxInfo.directContext(); const SkImageInfo info = SkImageInfo::Make(kScreenDim, kScreenDim, kN32_SkColorType, kPremul_SkAlphaType); auto surface = SkSurface::MakeRenderTarget(direct, SkBudgeted::kNo, info); auto blob = make_blob(); for (int y = 40; y < kScreenDim - 40; y++) { SkBitmap base = draw_blob(blob.get(), surface.get(), {40, y + 0.0f}); SkBitmap half = draw_blob(blob.get(), surface.get(), {40, y + 0.5f}); SkBitmap unit = draw_blob(blob.get(), surface.get(), {40, y + 1.0f}); bool isOk = compare_bitmaps(base, half) || compare_bitmaps(unit, half); REPORTER_ASSERT(reporter, isOk); if (!isOk) { if (kDumpPngs) { { std::string filename = "bad/half-y" + std::to_string(y) + ".png"; write_png(filename, half); } { std::string filename = "good/half-y" + std::to_string(y) + ".png"; write_png(filename, base); } } break; } } // Testing the x direction across all platforms does not workout, because letter spacing can // change based on non-integer advance widths, but this has been useful for diagnosing problems. #if 0 blob = make_blob(); for (int x = 40; x < kScreenDim - 40; x++) { SkBitmap base = draw_blob(blob.get(), surface.get(), {x + 0.0f, 40}); SkBitmap half = draw_blob(blob.get(), surface.get(), {x + 0.5f, 40}); SkBitmap unit = draw_blob(blob.get(), surface.get(), {x + 1.0f, 40}); bool isOk = compare_bitmaps(base, half) || compare_bitmaps(unit, half); REPORTER_ASSERT(reporter, isOk); if (!isOk) { if (kDumpPngs) { { std::string filename = "bad/half-x" + std::to_string(x) + ".png"; write_png(filename, half); } { std::string filename = "good/half-x" + std::to_string(x) + ".png"; write_png(filename, base); } } break; } } #endif } DEF_GPUTEST_FOR_RENDERING_CONTEXTS(TextBlobSmoothScroll, reporter, ctxInfo) { auto direct = ctxInfo.directContext(); const SkImageInfo info = SkImageInfo::Make(kScreenDim, kScreenDim, kN32_SkColorType, kPremul_SkAlphaType); auto surface = SkSurface::MakeRenderTarget(direct, SkBudgeted::kNo, info); auto movingBlob = make_blob(); for (SkScalar y = 40; y < 50; y += 1.0/8.0) { auto expectedBlob = make_blob(); auto expectedBitMap = draw_blob(expectedBlob.get(), surface.get(), {40, y}); auto movingBitmap = draw_blob(movingBlob.get(), surface.get(), {40, y}); bool isOk = compare_bitmaps(expectedBitMap, movingBitmap); REPORTER_ASSERT(reporter, isOk); if (!isOk) { if (kDumpPngs) { { std::string filename = "bad/scroll-y" + std::to_string(y) + ".png"; write_png(filename, movingBitmap); } { std::string filename = "good/scroll-y" + std::to_string(y) + ".png"; write_png(filename, expectedBitMap); } } break; } } }
c++
code
13,774
2,793
// Copyright (c) 2011-2018 The ton Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/receiverequestdialog.h> #include <qt/forms/ui_receiverequestdialog.h> #include <qt/tonunits.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <QClipboard> #include <QPixmap> #if defined(HAVE_CONFIG_H) #include <config/ton-config.h> /* for USE_QRCODE */ #endif ReceiveRequestDialog::ReceiveRequestDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ReceiveRequestDialog), model(nullptr) { ui->setupUi(this); #ifndef USE_QRCODE ui->btnSaveAs->setVisible(false); ui->lblQRCode->setVisible(false); #endif connect(ui->btnSaveAs, &QPushButton::clicked, ui->lblQRCode, &QRImageWidget::saveImage); } ReceiveRequestDialog::~ReceiveRequestDialog() { delete ui; } void ReceiveRequestDialog::setModel(WalletModel *_model) { this->model = _model; if (_model) connect(_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &ReceiveRequestDialog::update); // update the display unit if necessary update(); } void ReceiveRequestDialog::setInfo(const SendCoinsRecipient &_info) { this->info = _info; update(); } void ReceiveRequestDialog::update() { if(!model) return; QString target = info.label; if(target.isEmpty()) target = info.address; setWindowTitle(tr("Request payment to %1").arg(target)); QString uri = GUIUtil::formattonURI(info); ui->btnSaveAs->setEnabled(false); QString html; html += "<html><font face='verdana, arial, helvetica, sans-serif'>"; html += "<b>"+tr("Payment information")+"</b><br>"; html += "<b>"+tr("URI")+"</b>: "; html += "<a href=\""+uri+"\">" + GUIUtil::HtmlEscape(uri) + "</a><br>"; html += "<b>"+tr("Address")+"</b>: " + GUIUtil::HtmlEscape(info.address) + "<br>"; if(info.amount) html += "<b>"+tr("Amount")+"</b>: " + tonUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), info.amount) + "<br>"; if(!info.label.isEmpty()) html += "<b>"+tr("Label")+"</b>: " + GUIUtil::HtmlEscape(info.label) + "<br>"; if(!info.message.isEmpty()) html += "<b>"+tr("Message")+"</b>: " + GUIUtil::HtmlEscape(info.message) + "<br>"; if(model->isMultiwallet()) { html += "<b>"+tr("Wallet")+"</b>: " + GUIUtil::HtmlEscape(model->getWalletName()) + "<br>"; } ui->outUri->setText(html); if (ui->lblQRCode->setQR(uri, info.address)) { ui->btnSaveAs->setEnabled(true); } } void ReceiveRequestDialog::on_btnCopyURI_clicked() { GUIUtil::setClipboard(GUIUtil::formattonURI(info)); } void ReceiveRequestDialog::on_btnCopyAddress_clicked() { GUIUtil::setClipboard(info.address); }
c++
code
2,843
785
/* Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. 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 Sony Pictures Imageworks 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 <cstring> #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <OpenImageIO/filesystem.h> #include <OpenImageIO/sysutil.h> #include <OpenImageIO/thread.h> #include <OSL/oslcomp.h> #include <OSL/oslexec.h> using namespace OSL; static void usage () { std::cout << "oslc -- Open Shading Language compiler " OSL_LIBRARY_VERSION_STRING "\n" OSL_COPYRIGHT_STRING "\n" "Usage: oslc [options] file\n" " Options:\n" "\t--help Print this usage message\n" "\t-o filename Specify output filename\n" "\t-v Verbose mode\n" "\t-q Quiet mode\n" "\t-Ipath Add path to the #include search path\n" "\t-Dsym[=val] Define preprocessor symbol\n" "\t-Usym Undefine preprocessor symbol\n" "\t-O0, -O1, -O2 Set optimization level (default=1)\n" "\t-d Debug mode\n" "\t-E Only preprocess the input and output to stdout\n" "\t-Werror Treat all warnings as errors\n" ; } namespace { // anonymous // Subclass ErrorHandler because we want our messages to appear somewhat // differant than the default ErrorHandler base class, in order to match // typical compiler command line messages. class OSLC_ErrorHandler : public ErrorHandler { public: virtual void operator () (int errcode, const std::string &msg) { static OIIO::mutex err_mutex; OIIO::lock_guard guard (err_mutex); switch (errcode & 0xffff0000) { case EH_INFO : if (verbosity() >= VERBOSE) std::cout << msg << std::endl; break; case EH_WARNING : if (verbosity() >= NORMAL) std::cerr << msg << std::endl; break; case EH_ERROR : std::cerr << msg << std::endl; break; case EH_SEVERE : std::cerr << msg << std::endl; break; case EH_DEBUG : #ifdef NDEBUG break; #endif default : if (verbosity() > QUIET) std::cout << msg; break; } } }; static OSLC_ErrorHandler default_oslc_error_handler; } // anonymous namespace int main (int argc, const char *argv[]) { // Globally force classic "C" locale, and turn off all formatting // internationalization, for the entire oslc application. std::locale::global (std::locale::classic()); OIIO::Filesystem::convert_native_arguments (argc, (const char **)argv); if (argc <= 1) { usage (); return EXIT_SUCCESS; } std::vector<std::string> args; bool quiet = false; std::string shader_path; // Parse arguments from command line for (int a = 1; a < argc; ++a) { if (! strcmp (argv[a], "--help") | ! strcmp (argv[a], "-h")) { usage (); return EXIT_SUCCESS; } else if (! strcmp (argv[a], "-v") || ! strcmp (argv[a], "-q") || ! strcmp (argv[a], "-d") || ! strcmp (argv[a], "-E") || ! strcmp (argv[a], "-O") || ! strcmp (argv[a], "-O0") || ! strcmp (argv[a], "-O1") || ! strcmp (argv[a], "-O2") || ! strcmp (argv[a], "-Werror") ) { // Valid command-line argument args.emplace_back(argv[a]); quiet |= (strcmp (argv[a], "-q") == 0); } else if (! strcmp (argv[a], "-o") && a < argc-1) { // Output filepath args.emplace_back(argv[a]); ++a; args.emplace_back(argv[a]); } else if (argv[a][0] == '-' && (argv[a][1] == 'D' || argv[a][1] == 'U' || argv[a][1] == 'I')) { args.emplace_back(argv[a]); } else { // Shader to compile shader_path = argv[a]; } } if (shader_path.empty ()) { std::cout << "ERROR: Missing shader path" << "\n\n"; usage (); return EXIT_FAILURE; } OSLCompiler compiler (&default_oslc_error_handler); bool ok = compiler.compile (shader_path, args); if (ok) { if (!quiet) std::cout << "Compiled " << shader_path << " -> " << compiler.output_filename() << "\n"; } else { std::cout << "FAILED " << shader_path << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
c++
code
6,022
1,302
// // @author [email protected] // #include <op_boilerplate.h> #if NOT_EXCLUDED(OP_cumsum) #include <ops/declarable/helpers/prefix.h> #include <ops/declarable/CustomOperations.h> namespace nd4j { namespace ops { CONFIGURABLE_OP_IMPL(cumsum, 1, 1, true, 0, 2) { auto input = INPUT_VARIABLE(0); auto output = OUTPUT_VARIABLE(0); const bool exclusive = INT_ARG(0) == 1; const bool reverse = INT_ARG(1) == 1; if (block.getIArguments()->size() == 2 && block.width() == 1) { // all at once case nd4j::ops::helpers::_prefix<T, simdOps::Add<T>>(input->buffer(), input->shapeInfo(), output->buffer(), output->shapeInfo(), exclusive, reverse); } else { std::vector<int> dims(block.numI() - 2); if (block.width() == 1) { for (int e = 0; e < block.numI() - 2; e++) dims[e] = INT_ARG(e + 2); } else { auto ax = INPUT_VARIABLE(1); dims = ax->template asVectorT<int>(); } for (int e = 0; e < dims.size(); e++) if (dims[e] < 0) dims[e] += input->rankOf(); nd4j::ops::helpers::_prefix<T, simdOps::Add<T>>(input, output, dims, exclusive, reverse); } return ND4J_STATUS_OK; } } } #endif
c++
code
1,279
351
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "gtest/gtest.h" #include "mozilla/DataStorage.h" #include "nsAppDirectoryServiceDefs.h" #include "nsDirectoryServiceUtils.h" #include "nsNetUtil.h" #include "nsPrintfCString.h" #include "nsStreamUtils.h" #include "prtime.h" using namespace mozilla; class psm_DataStorageTest : public ::testing::Test { protected: void SetUp() override { const ::testing::TestInfo* const testInfo = ::testing::UnitTest::GetInstance()->current_test_info(); NS_ConvertUTF8toUTF16 testName(testInfo->name()); storage = DataStorage::GetFromRawFileName(testName); storage->Init(nullptr); } RefPtr<DataStorage> storage; }; constexpr auto testKey = "test"_ns; constexpr auto testValue = "value"_ns; constexpr auto privateTestValue = "private"_ns; TEST_F(psm_DataStorageTest, GetPutRemove) { // Test Put/Get on Persistent data EXPECT_EQ(NS_OK, storage->Put(testKey, testValue, DataStorage_Persistent)); // Don't re-use testKey / testValue here, to make sure that this works as // expected with objects that have the same semantic value but are not // literally the same object. nsCString result = storage->Get("test"_ns, DataStorage_Persistent); EXPECT_STREQ("value", result.get()); // Get on Temporary/Private data with the same key should give nothing result = storage->Get(testKey, DataStorage_Temporary); EXPECT_TRUE(result.IsEmpty()); result = storage->Get(testKey, DataStorage_Private); EXPECT_TRUE(result.IsEmpty()); // Put with Temporary/Private data shouldn't affect Persistent data constexpr auto temporaryTestValue = "temporary"_ns; EXPECT_EQ(NS_OK, storage->Put(testKey, temporaryTestValue, DataStorage_Temporary)); EXPECT_EQ(NS_OK, storage->Put(testKey, privateTestValue, DataStorage_Private)); result = storage->Get(testKey, DataStorage_Temporary); EXPECT_STREQ("temporary", result.get()); result = storage->Get(testKey, DataStorage_Private); EXPECT_STREQ("private", result.get()); result = storage->Get(testKey, DataStorage_Persistent); EXPECT_STREQ("value", result.get()); // Put of a previously-present key overwrites it (if of the same type) constexpr auto newValue = "new"_ns; EXPECT_EQ(NS_OK, storage->Put(testKey, newValue, DataStorage_Persistent)); result = storage->Get(testKey, DataStorage_Persistent); EXPECT_STREQ("new", result.get()); // Removal should work storage->Remove(testKey, DataStorage_Temporary); result = storage->Get(testKey, DataStorage_Temporary); EXPECT_TRUE(result.IsEmpty()); // But removing one type shouldn't affect the others result = storage->Get(testKey, DataStorage_Private); EXPECT_STREQ("private", result.get()); result = storage->Get(testKey, DataStorage_Persistent); EXPECT_STREQ("new", result.get()); // Test removing the other types as well storage->Remove(testKey, DataStorage_Private); result = storage->Get(testKey, DataStorage_Private); EXPECT_TRUE(result.IsEmpty()); storage->Remove(testKey, DataStorage_Persistent); result = storage->Get(testKey, DataStorage_Persistent); EXPECT_TRUE(result.IsEmpty()); } TEST_F(psm_DataStorageTest, InputValidation) { // Keys may not have tabs or newlines EXPECT_EQ(NS_ERROR_INVALID_ARG, storage->Put("key\thas tab"_ns, testValue, DataStorage_Persistent)); nsCString result = storage->Get("key\thas tab"_ns, DataStorage_Persistent); EXPECT_TRUE(result.IsEmpty()); EXPECT_EQ(NS_ERROR_INVALID_ARG, storage->Put("key has\nnewline"_ns, testValue, DataStorage_Persistent)); result = storage->Get("keyhas\nnewline"_ns, DataStorage_Persistent); EXPECT_TRUE(result.IsEmpty()); // Values may not have newlines EXPECT_EQ(NS_ERROR_INVALID_ARG, storage->Put(testKey, "value\nhas newline"_ns, DataStorage_Persistent)); result = storage->Get(testKey, DataStorage_Persistent); // Values may have tabs EXPECT_TRUE(result.IsEmpty()); EXPECT_EQ(NS_OK, storage->Put(testKey, "val\thas tab; this is ok"_ns, DataStorage_Persistent)); result = storage->Get(testKey, DataStorage_Persistent); EXPECT_STREQ("val\thas tab; this is ok", result.get()); nsCString longKey("a"); for (int i = 0; i < 8; i++) { longKey.Append(longKey); } // A key of length 256 will work EXPECT_EQ(NS_OK, storage->Put(longKey, testValue, DataStorage_Persistent)); result = storage->Get(longKey, DataStorage_Persistent); EXPECT_STREQ("value", result.get()); longKey.AppendLiteral("a"); // A key longer than that will not work EXPECT_EQ(NS_ERROR_INVALID_ARG, storage->Put(longKey, testValue, DataStorage_Persistent)); result = storage->Get(longKey, DataStorage_Persistent); EXPECT_TRUE(result.IsEmpty()); nsCString longValue("a"); for (int i = 0; i < 10; i++) { longValue.Append(longValue); } // A value of length 1024 will work EXPECT_EQ(NS_OK, storage->Put(testKey, longValue, DataStorage_Persistent)); result = storage->Get(testKey, DataStorage_Persistent); EXPECT_STREQ(longValue.get(), result.get()); longValue.AppendLiteral("a"); // A value longer than that will not work storage->Remove(testKey, DataStorage_Persistent); EXPECT_EQ(NS_ERROR_INVALID_ARG, storage->Put(testKey, longValue, DataStorage_Persistent)); result = storage->Get(testKey, DataStorage_Persistent); EXPECT_TRUE(result.IsEmpty()); } TEST_F(psm_DataStorageTest, Eviction) { // Eviction is on a per-table basis. Tables shouldn't affect each other. EXPECT_EQ(NS_OK, storage->Put(testKey, testValue, DataStorage_Persistent)); for (int i = 0; i < 1025; i++) { EXPECT_EQ(NS_OK, storage->Put(nsPrintfCString("%d", i), nsPrintfCString("%d", i), DataStorage_Temporary)); nsCString result = storage->Get(nsPrintfCString("%d", i), DataStorage_Temporary); EXPECT_STREQ(nsPrintfCString("%d", i).get(), result.get()); } // We don't know which entry got evicted, but we can count them. int entries = 0; for (int i = 0; i < 1025; i++) { nsCString result = storage->Get(nsPrintfCString("%d", i), DataStorage_Temporary); if (!result.IsEmpty()) { entries++; } } EXPECT_EQ(entries, 1024); nsCString result = storage->Get(testKey, DataStorage_Persistent); EXPECT_STREQ("value", result.get()); } TEST_F(psm_DataStorageTest, ClearPrivateData) { EXPECT_EQ(NS_OK, storage->Put(testKey, privateTestValue, DataStorage_Private)); nsCString result = storage->Get(testKey, DataStorage_Private); EXPECT_STREQ("private", result.get()); storage->Observe(nullptr, "last-pb-context-exited", nullptr); result = storage->Get(testKey, DataStorage_Private); EXPECT_TRUE(result.IsEmpty()); } TEST_F(psm_DataStorageTest, Shutdown) { EXPECT_EQ(NS_OK, storage->Put(testKey, testValue, DataStorage_Persistent)); nsCString result = storage->Get(testKey, DataStorage_Persistent); EXPECT_STREQ("value", result.get()); // Get "now" (in days) close to when the data was last touched, so we won't // get intermittent failures with the day not matching. int64_t microsecondsPerDay = 24 * 60 * 60 * int64_t(PR_USEC_PER_SEC); int32_t nowInDays = int32_t(PR_Now() / microsecondsPerDay); // Simulate shutdown. storage->Observe(nullptr, "profile-before-change", nullptr); nsCOMPtr<nsIFile> backingFile; EXPECT_EQ(NS_OK, NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(backingFile))); const ::testing::TestInfo* const testInfo = ::testing::UnitTest::GetInstance()->current_test_info(); NS_ConvertUTF8toUTF16 testName(testInfo->name()); EXPECT_EQ(NS_OK, backingFile->Append(testName)); nsCOMPtr<nsIInputStream> fileInputStream; EXPECT_EQ(NS_OK, NS_NewLocalFileInputStream(getter_AddRefs(fileInputStream), backingFile)); nsCString data; EXPECT_EQ(NS_OK, NS_ConsumeStream(fileInputStream, UINT32_MAX, data)); // The data will be of the form 'test\t0\t<days since the epoch>\tvalue' EXPECT_STREQ(nsPrintfCString("test\t0\t%d\tvalue\n", nowInDays).get(), data.get()); }
c++
code
8,544
1,878
#include <dirent.h> #include <unistd.h> #include <sstream> #include <string> #include <vector> #include <math.h> #include "linux_parser.h" using std::stof; using std::string; using std::to_string; using std::vector; // Done: An example of how to read data from the filesystem string LinuxParser::OperatingSystem() { string line; string key; string value; std::ifstream filestream(kOSPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ' ', '_'); std::replace(line.begin(), line.end(), '=', ' '); std::replace(line.begin(), line.end(), '"', ' '); std::istringstream linestream(line); while (linestream >> key >> value) { if (key == kPreNamKey) { std::replace(value.begin(), value.end(), '_', ' '); return value; } } } } filestream.close(); return value; } // Done: An example of how to read data from the filesystem string LinuxParser::Kernel() { string os; string kernel; string version; string line; std::ifstream stream(kProcDirectory + kVersionFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> os >> version >> kernel; } stream.close(); return kernel; } // BONUS: Update this to use std::filesystem vector<int> LinuxParser::Pids() { vector<int> pids; DIR* directory = opendir(kProcDirectory.c_str()); struct dirent* file; while ((file = readdir(directory)) != nullptr) { // Is this a directory? if (file->d_type == DT_DIR) { // Is every character of the name a digit? string filename(file->d_name); if (std::all_of(filename.begin(), filename.end(), isdigit)) { int pid = stoi(filename); pids.push_back(pid); } } } closedir(directory); return pids; } // Done: Read and return the system memory utilization float LinuxParser::MemoryUtilization() { string line; string key; string value; string trash; float memtotal; float memfree; std::ifstream filestream(kProcDirectory + kMeminfoFilename); if (filestream.is_open()){ while (std::getline(filestream, line)) { std::istringstream linestream(line); while (linestream >> key >> value >> trash){ if (key == kMemTotKey){ memtotal = std::stof(value); } if (key == kMemFreeKey){ memfree = std::stof(value); break; } } } } filestream.close(); return (memtotal - memfree)/memtotal; } // Done: Read and return the system uptime long int LinuxParser::UpTime() { string uptime; long int uptimel; string line; std::ifstream stream(kProcDirectory + kUptimeFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> uptime; uptimel = std::stol(uptime); } stream.close(); return uptimel; } //Added manually: CPU utilization of process ID float LinuxParser::CpuUtilization(int pid) { string value; string line; long int utime; long int stime; long int cutime; long int cstime; long int uptime; int pos = 0; int utime_pos = 13; int stime_pos = 14; int cutime_pos =15; int cstime_pos = 16; float cpu_util = 0; std::ifstream filestream(kProcDirectory + std::to_string(pid) + kStatFilename); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::istringstream linestream(line); while (linestream >> value && pos < 22) { if (pos == utime_pos) {utime = (std::stol(value));} if (pos == stime_pos) {stime = (std::stol(value));} if (pos == cutime_pos) {cutime = (std::stol(value));} if (pos == cstime_pos) {cstime = (std::stol(value));} pos++; } break; } //Problem is that sys uptime is in secs uptime = LinuxParser::UpTime(pid); // I used the given Stackoverflow-Link for this calculation // total = utime + stime long total_time = utime + stime; //total with wait = total + cu +cs long total_time_with_wait = total_time + cutime + cstime; long total_tww_secs = total_time_with_wait / sysconf(_SC_CLK_TCK); //Utilization = total with wait / uptime cpu_util = static_cast<float>(total_tww_secs) / static_cast<float>(uptime); } filestream.close(); return cpu_util; } int LinuxParser::TotalProcesses() { string line; string key; string value; int tot_process; std::ifstream filestream(kProcDirectory + kStatFilename); if (filestream.is_open()){ while (std::getline(filestream, line)) { std::istringstream linestream(line); while (linestream >> key >> value){ if (key == kProcKey){ tot_process = std::stoi(value); break; } } } } filestream.close(); return tot_process; } // Done: Read and return the number of running processes int LinuxParser::RunningProcesses() { string line; string key; string value; std::ifstream filestream(kProcDirectory + kStatFilename); if (filestream.is_open()){ while (std::getline(filestream, line)) { std::istringstream linestream(line); while (linestream >> key >> value){ if (key == kProRunKey){ return std::stoi(value); } } } } filestream.close(); return std::stoi(value); } // Done: Read and return the command associated with a process string LinuxParser::Command(int pid) { string pidpath = kProcDirectory + to_string(pid) + kCmdlineFilename; string line; std::ifstream stream(pidpath); if (stream.is_open()) { std::getline(stream, line); return line; } stream.close(); return line; } // Done: Read and return the memory used by a process string LinuxParser::Ram(int pid) { string pidpath = kProcDirectory + to_string(pid) + kStatusFilename; string line; string key; string value; string value_MB_str; int value_kB; std::ifstream filestream(pidpath); if (filestream.is_open()){ while (std::getline(filestream, line)) { std::istringstream linestream(line); while (linestream >> key >> value){ if (key == kVmKey){ value_kB = std::stoi(value); value_MB_str = to_string(value_kB / 1000); return value_MB_str; } } } } filestream.close(); return value_MB_str; } // Done: Read and return the user ID associated with a process string LinuxParser::Uid(int pid) { string pidpath = kProcDirectory + to_string(pid) + kStatusFilename; string line; string key; string value; std::ifstream filestream(pidpath); if (filestream.is_open()){ while (std::getline(filestream, line)) { std::istringstream linestream(line); while (linestream >> key >> value){ if (key == kUidKey){ return value; } } } } filestream.close(); return value; } // Done: Read and return the user associated with a process string LinuxParser::User(int pid) { string uid = Uid(pid); string line; string key; string value; std::ifstream filestream(kPasswordPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), 'x', ' '); std::replace(line.begin(), line.end(), ':', ' '); std::istringstream linestream(line); while (linestream >> value >> key) { if (key == uid ) { return value; } } } } filestream.close(); return value; } // Done: Read and return the uptime of a process long LinuxParser::UpTime(int pid) { string pidpath = kProcDirectory + to_string(pid) + kStatFilename; string line, value; vector<string> values; std::ifstream stream(pidpath); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); while (linestream >> value) { values.push_back(value); } } stream.close(); return UpTime() - stol(values[21])/sysconf(_SC_CLK_TCK); }
c++
code
8,054
1,931
#include <gtest/gtest.h> #include <platform.h> #include <stdio.h> #include <ast/ast.h> #include <ast/id_internal.h> #include <ast/id.h> #include "util.h" static void test_id(const char* id, bool expect_pass, int spec) { ast_t* node = ast_blank(TK_ID); ast_set_name(node, id); pass_opt_t opt; pass_opt_init(&opt); bool r = check_id(&opt, node, "test", spec); pass_opt_done(&opt); ast_free(node); if(r != expect_pass) { printf("Expected [0x%x] \"%s\" to %s but it %s\n", spec, id, expect_pass ? "pass" : "fail", r ? "passed" : "failed"); ASSERT_TRUE(false); } } class IdTest : public testing::Test {}; TEST_F(IdTest, LeadingUnderscore) { DO(test_id("foo", true, 0)); DO(test_id("_foo", false, 0)); DO(test_id("foo", true, ALLOW_LEADING_UNDERSCORE)); DO(test_id("_foo", true, ALLOW_LEADING_UNDERSCORE)); } TEST_F(IdTest, StartUpperCase) { DO(test_id("foo", false, START_UPPER)); DO(test_id("Foo", true, START_UPPER)); DO(test_id("_foo", false, START_UPPER)); DO(test_id("_Foo", false, START_UPPER)); DO(test_id("foo", false, START_UPPER | ALLOW_LEADING_UNDERSCORE)); DO(test_id("Foo", true, START_UPPER | ALLOW_LEADING_UNDERSCORE)); DO(test_id("_foo", false, START_UPPER | ALLOW_LEADING_UNDERSCORE)); DO(test_id("_Foo", true, START_UPPER | ALLOW_LEADING_UNDERSCORE)); } TEST_F(IdTest, StartLowerCase) { DO(test_id("foo", true, START_LOWER)); DO(test_id("Foo", false, START_LOWER)); DO(test_id("_foo", false, START_LOWER)); DO(test_id("_Foo", false, START_LOWER)); DO(test_id("foo", true, START_LOWER | ALLOW_LEADING_UNDERSCORE)); DO(test_id("Foo", false, START_LOWER | ALLOW_LEADING_UNDERSCORE)); DO(test_id("_foo", true, START_LOWER | ALLOW_LEADING_UNDERSCORE)); DO(test_id("_Foo", false, START_LOWER | ALLOW_LEADING_UNDERSCORE)); } TEST_F(IdTest, StartAnyCase) { DO(test_id("foo", true, 0)); DO(test_id("Foo", true, 0)); DO(test_id("_foo", false, 0)); DO(test_id("_Foo", false, 0)); DO(test_id("foo", true, ALLOW_LEADING_UNDERSCORE)); DO(test_id("Foo", true, ALLOW_LEADING_UNDERSCORE)); DO(test_id("_foo", true, ALLOW_LEADING_UNDERSCORE)); DO(test_id("_Foo", true, ALLOW_LEADING_UNDERSCORE)); } TEST_F(IdTest, ContainUnderscore) { DO(test_id("foo_bar", false, 0)); DO(test_id("_foo_bar", false, 0)); DO(test_id("foo_bar", false, ALLOW_LEADING_UNDERSCORE)); DO(test_id("_foo_bar", false, ALLOW_LEADING_UNDERSCORE)); DO(test_id("foo_bar", true, ALLOW_UNDERSCORE)); DO(test_id("_foo_bar", false, ALLOW_UNDERSCORE)); DO(test_id("foo_bar", true, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE)); DO(test_id("_foo_bar", true, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE)); } TEST_F(IdTest, DoubleUnderscore) { DO(test_id("foo__bar", false, 0)); DO(test_id("__foobar", false, 0)); DO(test_id("__foo__bar", false, 0)); DO(test_id("foo__bar", false, ALLOW_UNDERSCORE)); DO(test_id("__foobar", false, ALLOW_UNDERSCORE)); DO(test_id("__foo__bar", false, ALLOW_UNDERSCORE)); DO(test_id("foo__bar", false, ALLOW_LEADING_UNDERSCORE)); DO(test_id("__foobar", false, ALLOW_LEADING_UNDERSCORE)); DO(test_id("__foo__bar", false, ALLOW_LEADING_UNDERSCORE)); DO(test_id("foo__bar", false, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE)); DO(test_id("__foobar", false, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE)); DO(test_id("__foo__bar", false, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE)); } TEST_F(IdTest, TripleUnderscore) { DO(test_id("foo___bar", false, 0)); DO(test_id("___foobar", false, 0)); DO(test_id("___foo___bar", false, 0)); DO(test_id("foo___bar", false, ALLOW_UNDERSCORE)); DO(test_id("___foobar", false, ALLOW_UNDERSCORE)); DO(test_id("___foo___bar", false, ALLOW_UNDERSCORE)); DO(test_id("foo___bar", false, ALLOW_LEADING_UNDERSCORE)); DO(test_id("___foobar", false, ALLOW_LEADING_UNDERSCORE)); DO(test_id("___foo___bar", false, ALLOW_LEADING_UNDERSCORE)); DO(test_id("foo___bar", false, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE)); DO(test_id("___foobar", false, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE)); DO(test_id("___foo___bar", false, ALLOW_LEADING_UNDERSCORE | ALLOW_UNDERSCORE)); } TEST_F(IdTest, TrailingUnderscore) { DO(test_id("foo_bar", false, 0)); DO(test_id("foobar_", false, 0)); DO(test_id("foo_bar_", false, 0)); DO(test_id("foobar_'", false, 0)); DO(test_id("foo_bar", true, ALLOW_UNDERSCORE)); DO(test_id("foobar_", false, ALLOW_UNDERSCORE)); DO(test_id("foo_bar_", false, ALLOW_UNDERSCORE)); DO(test_id("foobar_'", false, ALLOW_UNDERSCORE)); DO(test_id("foo_bar", true, ALLOW_UNDERSCORE | ALLOW_TICK)); DO(test_id("foobar_", false, ALLOW_UNDERSCORE | ALLOW_TICK)); DO(test_id("foo_bar_", false, ALLOW_UNDERSCORE | ALLOW_TICK)); DO(test_id("foobar_'", false, ALLOW_UNDERSCORE | ALLOW_TICK)); } TEST_F(IdTest, Prime) { DO(test_id("foo", true, 0)); DO(test_id("fo'o", false, 0)); DO(test_id("fo''o", false, 0)); DO(test_id("foo'", false, 0)); DO(test_id("foo''", false, 0)); DO(test_id("foo'''", false, 0)); DO(test_id("foo", true, ALLOW_TICK)); DO(test_id("fo'o", false, ALLOW_TICK)); DO(test_id("fo''o", false, ALLOW_TICK)); DO(test_id("foo'", true, ALLOW_TICK)); DO(test_id("foo''", true, ALLOW_TICK)); DO(test_id("foo'''", true, ALLOW_TICK)); } TEST_F(IdTest, PrivateName) { ASSERT_TRUE(is_name_private("_foo")); ASSERT_TRUE(is_name_private("_Foo")); ASSERT_TRUE(is_name_private("$_foo")); ASSERT_TRUE(is_name_private("$_Foo")); ASSERT_FALSE(is_name_private("foo")); ASSERT_FALSE(is_name_private("Foo")); ASSERT_FALSE(is_name_private("$foo")); ASSERT_FALSE(is_name_private("$Foo")); } TEST_F(IdTest, TypeName) { ASSERT_TRUE(is_name_type("Foo")); ASSERT_TRUE(is_name_type("_Foo")); ASSERT_TRUE(is_name_type("$Foo")); ASSERT_TRUE(is_name_type("$_Foo")); ASSERT_FALSE(is_name_type("foo")); ASSERT_FALSE(is_name_type("_foo")); ASSERT_FALSE(is_name_type("$foo")); ASSERT_FALSE(is_name_type("$_foo")); } TEST_F(IdTest, FFIType) { ASSERT_TRUE(is_name_ffi("@foo")); ASSERT_FALSE(is_name_ffi("foo")); } TEST_F(IdTest, InternalTypeName) { ASSERT_TRUE(is_name_internal_test("$foo")); ASSERT_TRUE(is_name_internal_test("$_foo")); ASSERT_TRUE(is_name_internal_test("$Foo")); ASSERT_TRUE(is_name_internal_test("$_Foo")); ASSERT_FALSE(is_name_internal_test("foo")); ASSERT_FALSE(is_name_internal_test("_foo")); ASSERT_FALSE(is_name_internal_test("Foo")); ASSERT_FALSE(is_name_internal_test("_Foo")); }
c++
code
6,513
1,792
#include "graphics/impl/bitmap_loader/stb_bitmap_loader.h" #ifdef ARK_USE_STB_IMAGE #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include "core/inf/array.h" #include "core/inf/readable.h" #include "core/util/log.h" #include "graphics/base/bitmap.h" namespace ark { namespace { struct STBUserCallback { sp<Readable> _readable; bool _eof; STBUserCallback(const sp<Readable>& readable) : _readable(readable), _eof(false) { } }; static int _stb_read_callback(void* user, char *data,int size) { STBUserCallback* u = reinterpret_cast<STBUserCallback*>(user); return static_cast<int>(u->_readable->read(data, static_cast<uint32_t>(size))); } static void _stb_skip_callback(void* user, int n) { STBUserCallback* u = reinterpret_cast<STBUserCallback*>(user); u->_readable->seek(n, SEEK_CUR); } static int _stb_eof_callback(void *user) { STBUserCallback* u = reinterpret_cast<STBUserCallback*>(user); return static_cast<int>(u->_eof); } class STBImageByteArray : public Array<uint8_t> { public: STBImageByteArray(void* array, size_t length) : _array(array), _length(length) { } ~STBImageByteArray() { stbi_image_free(_array); } virtual uint8_t* buf() override { return reinterpret_cast<uint8_t*>(_array); } virtual size_t length() override { return _length; } private: void* _array; size_t _length; }; } STBBitmapLoader::STBBitmapLoader(bool justDecodeBounds) : _just_decode_bounds(justDecodeBounds) { } bitmap STBBitmapLoader::load(const sp<Readable>& readable) { stbi_io_callbacks callback; callback.read = _stb_read_callback; callback.skip = _stb_skip_callback; callback.eof = _stb_eof_callback; STBUserCallback user(readable); int width, height, channels; if(_just_decode_bounds) { int ret = stbi_info_from_callbacks(&callback, &user, &width, &height, &channels); DCHECK(ret, "stbi_info_from_callbacks failure: %s", stbi_failure_reason()); return bitmap::make(width, height, 0, channels, false); } uint32_t componentSize = stbi_is_hdr_from_callbacks(&callback, &user) ? 4 : 1; readable->seek(0, SEEK_SET); void* bytes = componentSize == 1 ? reinterpret_cast<void*>(stbi_load_from_callbacks(&callback, &user, &width, &height, &channels, 0)) : reinterpret_cast<void*>(stbi_loadf_from_callbacks(&callback, &user, &width, &height, &channels, 0)); DCHECK(bytes, "stbi_load_from_callbacks failure: %s", stbi_failure_reason()); uint32_t stride = width * channels * componentSize; return bitmap::make(width, height, stride, static_cast<uint8_t>(channels), sp<STBImageByteArray>::make(bytes, stride * height)); } } #endif
c++
code
2,786
572
/**************************************************************************** * * This is a part of CTPPS offline software. * Authors: * Jan Kašpar ([email protected]) * Nicola Minafra * Laurent Forthomme * ****************************************************************************/ #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/InputTag.h" #include "FWCore/Framework/interface/Run.h" #include "DQMServices/Core/interface/DQMOneEDAnalyzer.h" #include "DQMServices/Core/interface/DQMStore.h" #include "DataFormats/Provenance/interface/EventRange.h" #include "DataFormats/CTPPSDigi/interface/TotemVFATStatus.h" #include "DataFormats/CTPPSDigi/interface/TotemFEDInfo.h" #include "DataFormats/Common/interface/DetSetVector.h" #include "DataFormats/CTPPSDetId/interface/CTPPSDiamondDetId.h" #include "DataFormats/CTPPSDigi/interface/CTPPSDiamondDigi.h" #include "DataFormats/CTPPSReco/interface/CTPPSPixelLocalTrack.h" #include "DataFormats/CTPPSDetId/interface/CTPPSPixelDetId.h" #include "DataFormats/CTPPSReco/interface/CTPPSDiamondRecHit.h" #include "DataFormats/CTPPSReco/interface/CTPPSDiamondLocalTrack.h" #include "Geometry/VeryForwardGeometryBuilder/interface/CTPPSGeometry.h" #include "Geometry/Records/interface/VeryForwardRealGeometryRecord.h" #include <string> //---------------------------------------------------------------------------------------------------- // Utility for efficiency computations bool channelAlignedWithTrack(const CTPPSGeometry* geom, const CTPPSDiamondDetId& detid, const CTPPSDiamondLocalTrack& localTrack, const float tolerance = 1) { const DetGeomDesc* det = geom->getSensor(detid); const float x_pos = det->translation().x(), x_width = 2.0 * det->params().at(0); // parameters stand for half the size return ((x_pos + 0.5 * x_width > localTrack.getX0() - localTrack.getX0Sigma() - tolerance && x_pos + 0.5 * x_width < localTrack.getX0() + localTrack.getX0Sigma() + tolerance) || (x_pos - 0.5 * x_width > localTrack.getX0() - localTrack.getX0Sigma() - tolerance && x_pos - 0.5 * x_width < localTrack.getX0() + localTrack.getX0Sigma() + tolerance) || (x_pos - 0.5 * x_width < localTrack.getX0() - localTrack.getX0Sigma() - tolerance && x_pos + 0.5 * x_width > localTrack.getX0() + localTrack.getX0Sigma() + tolerance)); } namespace dds { struct Cache { std::unordered_map<unsigned int, std::unique_ptr<TH2F>> hitDistribution2dMap; std::unordered_map<unsigned int, unsigned long> hitsCounterMap; }; } // namespace dds class CTPPSDiamondDQMSource : public DQMOneEDAnalyzer<edm::LuminosityBlockCache<dds::Cache>> { public: CTPPSDiamondDQMSource(const edm::ParameterSet&); ~CTPPSDiamondDQMSource() override; protected: void dqmBeginRun(const edm::Run&, const edm::EventSetup&) override; void bookHistograms(DQMStore::IBooker&, const edm::Run&, const edm::EventSetup&) override; void analyze(const edm::Event&, const edm::EventSetup&) override; std::shared_ptr<dds::Cache> globalBeginLuminosityBlock(const edm::LuminosityBlock&, const edm::EventSetup&) const override; void globalEndLuminosityBlock(const edm::LuminosityBlock&, const edm::EventSetup&) override; void dqmEndRun(const edm::Run&, const edm::EventSetup&) override; private: // Constants static const double SEC_PER_LUMI_SECTION; // Number of seconds per lumisection: used to compute hit rates in Hz static const int CHANNEL_OF_VFAT_CLOCK; // Channel ID of the VFAT that contains clock data static const double DISPLAY_RESOLUTION_FOR_HITS_MM; // Bin width of histograms showing hits and tracks (in mm) static const double INV_DISPLAY_RESOLUTION_FOR_HITS_MM; static const double HPTDC_BIN_WIDTH_NS; // ns per HPTDC bin static const int CTPPS_NUM_OF_ARMS; static const int CTPPS_DIAMOND_STATION_ID; static const int CTPPS_DIAMOND_RP_ID; static const int CTPPS_PIXEL_STATION_ID; static const int CTPPS_NEAR_RP_ID; static const int CTPPS_FAR_RP_ID; static const int CTPPS_DIAMOND_NUM_OF_PLANES; static const int CTPPS_DIAMOND_NUM_OF_CHANNELS; static const int CTPPS_FED_ID_45; static const int CTPPS_FED_ID_56; edm::EDGetTokenT<edm::DetSetVector<TotemVFATStatus>> tokenStatus_; edm::EDGetTokenT<edm::DetSetVector<CTPPSPixelLocalTrack>> tokenPixelTrack_; edm::EDGetTokenT<edm::DetSetVector<CTPPSDiamondDigi>> tokenDigi_; edm::EDGetTokenT<edm::DetSetVector<CTPPSDiamondRecHit>> tokenDiamondHit_; edm::EDGetTokenT<edm::DetSetVector<CTPPSDiamondLocalTrack>> tokenDiamondTrack_; edm::EDGetTokenT<std::vector<TotemFEDInfo>> tokenFEDInfo_; bool excludeMultipleHits_; double horizontalShiftBwDiamondPixels_; double horizontalShiftOfDiamond_; std::vector<std::pair<edm::EventRange, int>> runParameters_; int centralOOT_; unsigned int verbosity_; /// plots related to the whole system struct GlobalPlots { GlobalPlots() {} GlobalPlots(DQMStore::IBooker& ibooker); }; GlobalPlots globalPlot_; /// plots related to one Diamond detector package struct PotPlots { std::unordered_map<unsigned int, MonitorElement*> activity_per_bx; MonitorElement* hitDistribution2d = nullptr; MonitorElement* hitDistribution2d_lumisection = nullptr; MonitorElement* hitDistribution2dOOT = nullptr; MonitorElement* hitDistribution2dOOT_le = nullptr; MonitorElement *activePlanes = nullptr, *activePlanesInclusive = nullptr; MonitorElement* trackDistribution = nullptr; MonitorElement* trackDistributionOOT = nullptr; std::unordered_map<unsigned int, MonitorElement*> pixelTomographyAll; MonitorElement *leadingEdgeCumulative_both = nullptr, *leadingEdgeCumulative_all = nullptr, *leadingEdgeCumulative_le = nullptr, *trailingEdgeCumulative_te = nullptr; MonitorElement *timeOverThresholdCumulativePot = nullptr, *leadingTrailingCorrelationPot = nullptr; MonitorElement* leadingWithoutTrailingCumulativePot = nullptr; MonitorElement* ECCheck = nullptr; MonitorElement* HPTDCErrorFlags_2D = nullptr; MonitorElement* MHComprensive = nullptr; // MonitorElement* clock_Digi1_le = nullptr; // MonitorElement* clock_Digi1_te = nullptr; // MonitorElement* clock_Digi3_le = nullptr; // MonitorElement* clock_Digi3_te = nullptr; unsigned int HitCounter, MHCounter, LeadingOnlyCounter, TrailingOnlyCounter, CompleteCounter; std::map<int, int> effTriplecountingChMap; std::map<int, int> effDoublecountingChMap; MonitorElement* EfficiencyOfChannelsInPot = nullptr; TH2F pixelTracksMap; PotPlots() {} PotPlots(DQMStore::IBooker& ibooker, unsigned int id); }; std::unordered_map<unsigned int, PotPlots> potPlots_; int EC_difference_56_, EC_difference_45_; /// plots related to one Diamond plane struct PlanePlots { MonitorElement* digiProfileCumulativePerPlane = nullptr; MonitorElement* hitProfile = nullptr; MonitorElement* hit_multiplicity = nullptr; MonitorElement* pixelTomography_far = nullptr; MonitorElement* EfficiencyWRTPixelsInPlane = nullptr; TH2F pixelTracksMapWithDiamonds; PlanePlots() {} PlanePlots(DQMStore::IBooker& ibooker, unsigned int id); }; std::unordered_map<unsigned int, PlanePlots> planePlots_; /// plots related to one Diamond channel struct ChannelPlots { std::unordered_map<unsigned int, MonitorElement*> activity_per_bx; MonitorElement* HPTDCErrorFlags = nullptr; MonitorElement *leadingEdgeCumulative_both = nullptr, *leadingEdgeCumulative_le = nullptr, *trailingEdgeCumulative_te = nullptr; MonitorElement* TimeOverThresholdCumulativePerChannel = nullptr; MonitorElement* LeadingTrailingCorrelationPerChannel = nullptr; MonitorElement* leadingWithoutTrailing = nullptr; MonitorElement* pixelTomography_far = nullptr; MonitorElement* hit_rate = nullptr; unsigned int HitCounter, MHCounter, LeadingOnlyCounter, TrailingOnlyCounter, CompleteCounter; ChannelPlots() {} ChannelPlots(DQMStore::IBooker& ibooker, unsigned int id); }; std::unordered_map<unsigned int, ChannelPlots> channelPlots_; }; //---------------------------------------------------------------------------------------------------- // Values for all constants const double CTPPSDiamondDQMSource::SEC_PER_LUMI_SECTION = 23.31; const int CTPPSDiamondDQMSource::CHANNEL_OF_VFAT_CLOCK = 30; const double CTPPSDiamondDQMSource::DISPLAY_RESOLUTION_FOR_HITS_MM = 0.1; const double CTPPSDiamondDQMSource::INV_DISPLAY_RESOLUTION_FOR_HITS_MM = 1. / DISPLAY_RESOLUTION_FOR_HITS_MM; const double CTPPSDiamondDQMSource::HPTDC_BIN_WIDTH_NS = 25. / 1024; const int CTPPSDiamondDQMSource::CTPPS_NUM_OF_ARMS = 2; const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_STATION_ID = 1; const int CTPPSDiamondDQMSource::CTPPS_PIXEL_STATION_ID = 2; const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_RP_ID = 6; const int CTPPSDiamondDQMSource::CTPPS_NEAR_RP_ID = 2; const int CTPPSDiamondDQMSource::CTPPS_FAR_RP_ID = 3; const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_NUM_OF_PLANES = 4; const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_NUM_OF_CHANNELS = 12; const int CTPPSDiamondDQMSource::CTPPS_FED_ID_56 = 582; const int CTPPSDiamondDQMSource::CTPPS_FED_ID_45 = 583; //---------------------------------------------------------------------------------------------------- CTPPSDiamondDQMSource::GlobalPlots::GlobalPlots(DQMStore::IBooker& ibooker) { ibooker.setCurrentFolder("CTPPS"); } //---------------------------------------------------------------------------------------------------- CTPPSDiamondDQMSource::PotPlots::PotPlots(DQMStore::IBooker& ibooker, unsigned int id) : HitCounter(0), MHCounter(0), LeadingOnlyCounter(0), TrailingOnlyCounter(0), CompleteCounter(0), pixelTracksMap("Pixel track maps for efficiency", "Pixel track maps for efficiency", 25, 0, 25, 12, -2, 10) { std::string path, title; CTPPSDiamondDetId(id).rpName(path, CTPPSDiamondDetId::nPath); ibooker.setCurrentFolder(path); CTPPSDiamondDetId(id).rpName(title, CTPPSDiamondDetId::nFull); activity_per_bx[0] = ibooker.book1D("activity per BX 0 25", title + " Activity per BX 0 - 25 ns;Event.BX", 3600, -1.5, 3598. + 0.5); activity_per_bx[1] = ibooker.book1D("activity per BX 25 50", title + " Activity per BX 25 - 50 ns;Event.BX", 3600, -1.5, 3598. + 0.5); activity_per_bx[2] = ibooker.book1D("activity per BX 50 75", title + " Activity per BX 50 - 75 ns;Event.BX", 3600, -1.5, 3598. + 0.5); hitDistribution2d = ibooker.book2D("hits in planes", title + " hits in planes;plane number;x (mm)", 10, -0.5, 4.5, 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5); hitDistribution2d_lumisection = ibooker.book2D("hits in planes lumisection", title + " hits in planes in the last lumisection;plane number;x (mm)", 10, -0.5, 4.5, 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5); hitDistribution2dOOT = ibooker.book2D("hits with OOT in planes", title + " hits with OOT in planes;plane number + 0.25 OOT;x (mm)", 17, -0.25, 4, 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5); hitDistribution2dOOT_le = ibooker.book2D("hits with OOT in planes (le only)", title + " hits with OOT in planes (le only);plane number + 0.25 OOT;x (mm)", 17, -0.25, 4, 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5); activePlanes = ibooker.book1D("active planes", title + " active planes (per event);number of active planes", 6, -0.5, 5.5); activePlanesInclusive = ibooker.book1D("active planes inclusive", title + " active planes, MH and le only included (per event);number of active planes", 6, -0.5, 5.5); trackDistribution = ibooker.book1D("tracks", title + " tracks;x (mm)", 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5); trackDistributionOOT = ibooker.book2D("tracks with OOT", title + " tracks with OOT;plane number;x (mm)", 9, -0.5, 4, 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5); pixelTomographyAll[0] = ibooker.book2D("tomography pixel 0 25", title + " tomography with pixel 0 - 25 ns (all planes);x + 25*plane(mm);y (mm)", 100, 0, 100, 8, 0, 8); pixelTomographyAll[1] = ibooker.book2D("tomography pixel 25 50", title + " tomography with pixel 25 - 50 ns (all planes);x + 25*plane(mm);y (mm)", 100, 0, 100, 8, 0, 8); pixelTomographyAll[2] = ibooker.book2D("tomography pixel 50 75", title + " tomography with pixel 50 - 75 ns (all planes);x + 25*plane(mm);y (mm)", 100, 0, 100, 8, 0, 8); leadingEdgeCumulative_both = ibooker.book1D( "leading edge (le and te)", title + " leading edge (le and te) (recHits); leading edge (ns)", 75, 0, 75); leadingEdgeCumulative_all = ibooker.book1D( "leading edge (all)", title + " leading edge (with or without te) (DIGIs); leading edge (ns)", 75, 0, 75); leadingEdgeCumulative_le = ibooker.book1D("leading edge (le only)", title + " leading edge (le only) (DIGIs); leading edge (ns)", 75, 0, 75); trailingEdgeCumulative_te = ibooker.book1D( "trailing edge (te only)", title + " trailing edge (te only) (DIGIs); trailing edge (ns)", 75, 0, 75); timeOverThresholdCumulativePot = ibooker.book1D("time over threshold", title + " time over threshold;time over threshold (ns)", 250, -25, 100); leadingTrailingCorrelationPot = ibooker.book2D("leading trailing correlation", title + " leading trailing correlation;leading edge (ns);trailing edge (ns)", 75, 0, 75, 75, 0, 75); leadingWithoutTrailingCumulativePot = ibooker.book1D("event category", title + " leading edges without trailing;;%", 3, 0.5, 3.5); leadingWithoutTrailingCumulativePot->getTH1F()->GetXaxis()->SetBinLabel(1, "Leading only"); leadingWithoutTrailingCumulativePot->getTH1F()->GetXaxis()->SetBinLabel(2, "Trailing only"); leadingWithoutTrailingCumulativePot->getTH1F()->GetXaxis()->SetBinLabel(3, "Both"); ECCheck = ibooker.book1D("optorxEC(8bit) - vfatEC", title + " EC Error;optorxEC-vfatEC", 50, -25, 25); HPTDCErrorFlags_2D = ibooker.book2D("HPTDC Errors", title + " HPTDC Errors", 16, -0.5, 16.5, 9, -0.5, 8.5); for (unsigned short error_index = 1; error_index < 16; ++error_index) HPTDCErrorFlags_2D->getTH2F()->GetXaxis()->SetBinLabel(error_index, HPTDCErrorFlags::getHPTDCErrorName(error_index - 1).c_str()); HPTDCErrorFlags_2D->getTH2F()->GetXaxis()->SetBinLabel(16, "Wrong EC"); int tmpIndex = 0; HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 0 TDC 18"); HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 0 TDC 17"); HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 0 TDC 16"); HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 0 TDC 15"); HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 1 TDC 18"); HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 1 TDC 17"); HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 1 TDC 16"); HPTDCErrorFlags_2D->getTH2F()->GetYaxis()->SetBinLabel(++tmpIndex, "DB 1 TDC 15"); MHComprensive = ibooker.book2D("MH in channels", title + " MH (%) in channels;plane number;ch number", 10, -0.5, 4.5, 14, -1, 13); EfficiencyOfChannelsInPot = ibooker.book2D("Efficiency in channels", title + " Efficiency (%) in channels (diamonds only);plane number;ch number", 10, -0.5, 4.5, 14, -1, 13); // ibooker.setCurrentFolder( path+"/clock/" ); // clock_Digi1_le = ibooker.book1D( "clock1 leading edge", title+" clock1;leading edge (ns)", 250, 0, 25 ); // clock_Digi1_te = ibooker.book1D( "clock1 trailing edge", title+" clock1;trailing edge (ns)", 75, 0, 75 ); // clock_Digi3_le = ibooker.book1D( "clock3 leading edge", title+" clock3;leading edge (ns)", 250, 0, 25 ); // clock_Digi3_te = ibooker.book1D( "clock3 trailing edge", title+" clock3;trailing edge (ns)", 75, 0, 75 ); } //---------------------------------------------------------------------------------------------------- CTPPSDiamondDQMSource::PlanePlots::PlanePlots(DQMStore::IBooker& ibooker, unsigned int id) : pixelTracksMapWithDiamonds("Pixel track maps for efficiency with coincidence", "Pixel track maps for efficiency with coincidence", 25, 0, 25, 12, -2, 10) { std::string path, title; CTPPSDiamondDetId(id).planeName(path, CTPPSDiamondDetId::nPath); ibooker.setCurrentFolder(path); CTPPSDiamondDetId(id).planeName(title, CTPPSDiamondDetId::nFull); digiProfileCumulativePerPlane = ibooker.book1D("digi profile", title + " digi profile; ch number", 12, -0.5, 11.5); hitProfile = ibooker.book1D( "hit profile", title + " hit profile;x (mm)", 19. * INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -0.5, 18.5); hit_multiplicity = ibooker.book1D("channels per plane", title + " channels per plane; ch per plane", 13, -0.5, 12.5); pixelTomography_far = ibooker.book2D("tomography pixel", title + " tomography with pixel;x + 25 OOT (mm);y (mm)", 75, 0, 75, 8, 0, 8); EfficiencyWRTPixelsInPlane = ibooker.book2D("Efficiency wrt pixels
c++
code
20,000
3,796
/** * @file ac_controller_software.cpp * @author Vinicius Pimenta Bernardo ([email protected]) * @brief Host PC software. * @version 0.1 * @date 2021-04-18 * * @copyright Copyright (c) 2021 * */ #include <iostream> #include <fstream> #include <string> #include <stdio.h> #include <string.h> #include "Serial.h" #include "cJSON.h" #define COM_PORT "COM3" // #define TERMINAL_DEBUG using namespace std; int main() { bool leave = false; // Serial buffer and params char incomingData[256] = ""; int dataLength = 255; int readResult = 0; // Terminal command issued by user int userInput = 0; // Flag to wait for serial comms to end current transaction int serialWaitingResponse = 0; // File class and file name ofstream logFile; char fileName[9] = ""; // Start and connect to serial port Serial *SP = new Serial(COM_PORT); if (SP->IsConnected()) { cout << "Serial connected" << endl; } // User menu on terminal cout << "--- Host PC (Windows) ---" << endl; cout << "--- Possible actions:" << endl; cout << "--- 0. Leave" << endl; cout << "--- 1. Download events from device" << endl; cout << "--- 2. List all events" << endl; cout << "--- 3. Start AC (Remote start button)" << endl; // Main loop while (!leave) { if (!serialWaitingResponse) { // Prompt for user command cout << "Action: "; cin >> userInput; switch (userInput) { case 0: leave = true; case 1: // Upload log from board event queue if (SP->IsConnected()) { SP->WriteData("u", strlen("u")); serialWaitingResponse = 1; cout << "Upload started" << endl; } break; case 2: cout << "--- 1. Last connected device" << endl; cout << "--- 2. Enter device id" << endl; cout << "Option: "; cin >> userInput; if (userInput == 1) { // See if any device recently uploaded (if fileName already exists) if (strstr(fileName, ".txt") != NULL) { string line; ifstream myfile; myfile.open(fileName); if (myfile.is_open()) { while (getline(myfile, line)) { cout << line << '\n'; } myfile.close(); } else { cout << "Unable to open file" << endl; } } else { cout << "No device found" << endl; } } else if (userInput == 2) { int id = 0; cout << "Type device id (xxxx): "; cin >> id; sprintf_s(fileName, "%d.txt", id); string line; ifstream myfile; myfile.open(fileName); if (myfile.is_open()) { while (getline(myfile, line)) { cout << line << '\n'; } myfile.close(); } else { cout << "Unable to open file" << endl; } } break; case 3: // Simulate button via serial if (SP->IsConnected()) { SP->WriteData("b", strlen("b")); } break; default: break; } } else if (serialWaitingResponse) { if (SP->IsConnected()) { // Read from serial if waiting for response readResult = SP->ReadData(incomingData, dataLength); #ifdef TERMINAL_DEBUG cout << "Bytes read: " << readResult << endl; #endif incomingData[readResult] = 0; // Process response if (readResult > 0) { #ifdef TERMINAL_DEBUG cout << incomingData << endl; #endif if (strstr(incomingData, "isEmpty") != NULL) { serialWaitingResponse = 0; cout << "Upload ended" << endl; } else if (strstr(incomingData, "\"id\"") != NULL) { // Parse incoming json string cJSON *dataJSON = cJSON_Parse(incomingData); cJSON *idJSON = cJSON_GetObjectItem(dataJSON, "id"); cJSON *eventJSON = cJSON_GetObjectItem(dataJSON, "event"); cJSON *stateJSON = cJSON_GetObjectItem(dataJSON, "state"); cJSON *timestampJSON = cJSON_GetObjectItem(dataJSON, "timestamp"); #ifdef TERMINAL_DEBUG cout << cJSON_Print(dataJSON) << endl; #endif // Print in one line cout << "{"; cout << "\"id\": \"" << idJSON->valuestring << "\""; cout << ", \"event\": \"" << eventJSON->valuestring << "\""; cout << ", \"state\": \"" << stateJSON->valuestring << "\""; cout << ", \"timestamp\": " << timestampJSON->valueint; cout << "}" << endl; // Generate file name with device id (xxxx.txt) sprintf_s(fileName, "%s.txt", idJSON->valuestring); #ifdef TERMINAL_DEBUG cout << fileName << endl; #endif // Write to file (http://www.cplusplus.com/reference/fstream/ofstream/open/) logFile.open(fileName, ios_base::app); if (logFile.is_open()) { logFile << "{"; logFile << "\"id\": \"" << idJSON->valuestring << "\""; logFile << ", \"event\": \"" << eventJSON->valuestring << "\""; logFile << ", \"state\": \"" << stateJSON->valuestring << "\""; logFile << ", \"timestamp\": " << timestampJSON->valueint; logFile << "}\n"; logFile.close(); } else { cout << "Failed to open log file" << endl; } // Keep uploading until queue is empty SP->WriteData("u", strlen("u")); } } } } Sleep(100); } return 0; }
c++
code
7,389
1,324
/* ============================================================================== This file is part of the juce_core module of the JUCE library. Copyright (c) 2013 - Raw Material Software Ltd. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ------------------------------------------------------------------------------ NOTE! This permissive ISC license applies ONLY to files within the juce_core module! All other JUCE modules are covered by a dual GPL/commercial license, so if you are using any other modules, be sure to check that you also comply with their license. For more details, visit www.juce.com ============================================================================== */ StringPairArray::StringPairArray (const bool ignoreCase_) : ignoreCase (ignoreCase_) { } StringPairArray::StringPairArray (const StringPairArray& other) : keys (other.keys), values (other.values), ignoreCase (other.ignoreCase) { } StringPairArray::~StringPairArray() { } StringPairArray& StringPairArray::operator= (const StringPairArray& other) { keys = other.keys; values = other.values; return *this; } bool StringPairArray::operator== (const StringPairArray& other) const { for (int i = keys.size(); --i >= 0;) if (other [keys[i]] != values[i]) return false; return true; } bool StringPairArray::operator!= (const StringPairArray& other) const { return ! operator== (other); } const String& StringPairArray::operator[] (StringRef key) const { return values [keys.indexOf (key, ignoreCase)]; } String StringPairArray::getValue (StringRef key, const String& defaultReturnValue) const { const int i = keys.indexOf (key, ignoreCase); if (i >= 0) return values[i]; return defaultReturnValue; } void StringPairArray::set (const String& key, const String& value) { const int i = keys.indexOf (key, ignoreCase); if (i >= 0) { values.set (i, value); } else { keys.add (key); values.add (value); } } void StringPairArray::addArray (const StringPairArray& other) { for (int i = 0; i < other.size(); ++i) set (other.keys[i], other.values[i]); } void StringPairArray::clear() { keys.clear(); values.clear(); } void StringPairArray::remove (StringRef key) { remove (keys.indexOf (key, ignoreCase)); } void StringPairArray::remove (const int index) { keys.remove (index); values.remove (index); } void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase) { ignoreCase = shouldIgnoreCase; } String StringPairArray::getDescription() const { String s; for (int i = 0; i < keys.size(); ++i) { s << keys[i] << " = " << values[i]; if (i < keys.size()) s << ", "; } return s; } void StringPairArray::minimiseStorageOverheads() { keys.minimiseStorageOverheads(); values.minimiseStorageOverheads(); }
c++
code
3,781
791
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2020 Scientific Computing and Imaging Institute, University of Utah. 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. */ /// ///@file Pstreams.cc ///@brief Reading/writing persistent objects /// ///@authors /// Steven G. Parker, /// Modified by: /// Michelle Miller /// Department of Computer Science /// University of Utah ///@date April 1994 Modified: /// Thu Feb 19 17:04:59 MST 1998 /// #include <Core/Persistent/Pstreams.h> #include <Core/Logging/LoggerInterface.h> #include <Core/Utils/Legacy/StringUtil.h> #ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER #include <teem/air.h> #include <teem/nrrd.h> #include <zlib.h> #endif #include <string.h> #include <stdio.h> #include <fstream> #include <iostream> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #ifdef _WIN32 # include <io.h> #endif using namespace SCIRun::Core::Logging; namespace SCIRun { // BinaryPiostream -- portable BinaryPiostream::BinaryPiostream(const std::string& filename, Direction dir, const int& v, LoggerHandle pr) : Piostream(dir, v, filename, pr), fp_(nullptr) { if (v == -1) // no version given so use PERSISTENT_VERSION version_ = PERSISTENT_VERSION; else version_ = v; if (dir==Read) { fp_ = fopen (filename.c_str(), "rb"); if (!fp_) { reporter_->error("Error opening file: " + filename + " for reading."); err = true; return; } // Old versions had headers of size 12. if (version() == 1) { char hdr[12]; if (!fread(hdr, 1, 12, fp_)) { reporter_->error("Header read failed."); err = true; return; } } else { // Versions > 1 have size of 16 to account for endianness in // header (LIT | BIG). char hdr[16]; if (!fread(hdr, 1, 16, fp_)) { reporter_->error("Header read failed."); err = true; return; } } } else { fp_ = fopen(filename.c_str(), "wb"); if (!fp_) { reporter_->error("Error opening file '" + filename + "' for writing."); err = true; return; } if (version() > 1) { // write out 16 bytes, but we need 17 for \0 char hdr[17]; sprintf(hdr, "SCI\nBIN\n%03d\n%s", version_, endianness()); if (!fwrite(hdr, 1, 16, fp_)) { reporter_->error("Header write failed."); err = true; return; } } else { // write out 12 bytes, but we need 13 for \0 char hdr[13]; sprintf(hdr, "SCI\nBIN\n%03d\n", version_); if (!fwrite(hdr, 1, 13, fp_)) { reporter_->error("Header write failed."); err = true; return; } } } } BinaryPiostream::BinaryPiostream(int fd, Direction dir, const int& v, LoggerHandle pr) : Piostream(dir, v, "", pr), fp_(nullptr) { if (v == -1) // No version given so use PERSISTENT_VERSION. version_ = PERSISTENT_VERSION; else version_ = v; if (dir == Read) { fp_ = fdopen (fd, "rb"); if (!fp_) { reporter_->error("Error opening socket " + to_string(fd) + " for reading."); err = true; return; } // Old versions had headers of size 12. if (version() == 1) { char hdr[12]; // read header if (!fread(hdr, 1, 12, fp_)) { reporter_->error("Header read failed."); err = true; return; } } else { // Versions > 1 have size of 16 to account for endianness in // header (LIT | BIG). char hdr[16]; if (!fread(hdr, 1, 16, fp_)) { reporter_->error("Header read failed."); err = true; return; } } } else { fp_ = fdopen(fd, "wb"); if (!fp_) { reporter_->error("Error opening socket " + to_string(fd) + " for writing."); err = true; return; } if (version() > 1) { char hdr[16]; sprintf(hdr, "SCI\nBIN\n%03d\n%s", version_, endianness()); if (!fwrite(hdr, 1, 16, fp_)) { reporter_->error("Header write failed."); err = true; return; } } else { char hdr[12]; sprintf(hdr, "SCI\nBIN\n%03d\n", version_); if (!fwrite(hdr, 1, 12, fp_)) { reporter_->error("Header write failed."); err = true; return; } } } } BinaryPiostream::~BinaryPiostream() { if (fp_) fclose(fp_); } void BinaryPiostream::reset_post_header() { if (! reading()) return; fseek(fp_, 0, SEEK_SET); if (version() == 1) { // Old versions had headers of size 12. char hdr[12]; // read header fread(hdr, 1, 12, fp_); } else { // Versions > 1 have size of 16 to account for endianness in // header (LIT | BIG). char hdr[16]; // read header fread(hdr, 1, 16, fp_); } } const char * BinaryPiostream::endianness() { /// @todo SCIRUN4_CODE_TO_BE_ENABLED_LATER //if (airMyEndian == airEndianLittle) return "LIT\n"; //else //return "BIG\n"; } template <class T> inline void BinaryPiostream::gen_io(T& data, const char *iotype) { if (err) return; if (dir==Read) { if (!fread(&data, sizeof(data), 1, fp_)) { err = true; reporter_->error(std::string("BinaryPiostream error reading ") + iotype + "."); } } else { if (!fwrite(&data, sizeof(data), 1, fp_)) { err = true; reporter_->error(std::string("BinaryPiostream error writing ") + iotype + "."); } } } void BinaryPiostream::io(char& data) { if (version() == 1) { // xdr_char int tmp; tmp = data; io(tmp); data = tmp; } else { gen_io(data, "char"); } } void BinaryPiostream::io(signed char& data) { if (version() == 1) { // Wrote as short, still xdr int eventually. short tmp = data; io(tmp); data = tmp; } else { gen_io(data, "signed char"); } } void BinaryPiostream::io(unsigned char& data) { if (version() == 1) { // xdr_u_char unsigned int tmp; tmp = data; io(tmp); data = tmp; } else { gen_io(data, "unsigned char"); } } void BinaryPiostream::io(short& data) { if (version() == 1) { // xdr_short int tmp; tmp = data; io(tmp); data = tmp; } else { gen_io(data, "short"); } } void BinaryPiostream::io(unsigned short& data) { if (version() == 1) { // xdr_u_short unsigned int tmp; tmp = data; io(tmp); data = tmp; } else { gen_io(data, "unsigned short"); } } void BinaryPiostream::io(int& data) { gen_io(data, "int"); // xdr_int } void BinaryPiostream::io(unsigned int& data) { gen_io(data, "unsigned int"); // xdr_u_int } void BinaryPiostream::io(long& data) { if (version() == 1) { // xdr_long // Note that xdr treats longs as 4 byte numbers. int tmp; tmp = data; io(tmp); data = tmp; } else { // For 32bits for now (we need to update this later in the next // version of Pio) int tmp = data; gen_io(tmp, "long"); data = tmp; } } void BinaryPiostream::io(unsigned long& data) { if (version() == 1) { // xdr_u_long // Note that xdr treats longs as 4 byte numbers. unsigned int tmp; tmp = data; io(tmp); data = tmp; } else { // For 32bits for now (we need to update this later in the next // version of Pio) unsigned int tmp = data; gen_io(tmp, "unsigned long"); data = tmp; } } void BinaryPiostream::io(long long& data) { gen_io(data, "long long"); // xdr_longlong_t } void BinaryPiostream::io(unsigned long long& data) { gen_io(data, "unsigned long long"); //xdr_u_longlong_t } void BinaryPiostream::io(double& data) { gen_io(data, "double"); // xdr_double } void BinaryPiostream::io(float& data) { gen_io(data, "float"); // xdr_float } void BinaryPiostream::io(std::string& data) { // xdr_wrapstring if (err) return; unsigned int chars = 0; if (dir == Write) { if (version() == 1) { // An xdr string is 4 byte int for string size, followed by the // characters without the null termination, then padded back out // to the 4 byte boundary with zeros. chars = data.size(); io(chars); if (!fwrite(data.c_str(), sizeof(char), chars, fp_)) err = true; // Pad data out to 4 bytes. int extra = chars % 4; if (extra) { static const char pad[4] = {0, 0, 0, 0}; if (!fwrite(pad, sizeof(char), 4 - extra, fp_)) err = true; } } else { const char* p = data.c_str(); chars = static_cast<int>(strlen(p)) + 1; io(chars); if (!fwrite(p, sizeof(char), chars, fp_)) err = true; } } if (dir == Read) { // Read in size. io(chars); if (version() == 1) { // Create buffer which is multiple of 4. int extra = 4 - (chars%4); if (extra == 4) extra = 0; unsigned int buf_size = chars + extra; data = ""; if (buf_size) { char* buf = new char[buf_size]; // Read in data plus padding. if (!fread(buf, sizeof(char), buf_size, fp_)) { err = true; delete [] buf; return; } // Only use actual size of string. for (unsigned int i=0; i<chars; i++) data += buf[i]; delete [] buf; } } else { char* buf = new char[chars]; fread(buf, sizeof(char), chars, fp_); data = std::string(buf); delete[] buf; } } } bool BinaryPiostream::block_io(void *data, size_t s, size_t nmemb) { if (err || version() == 1) { return false; } if (dir == Read) { const size_t did = fread(data, s, nmemb, fp_); if (did != nmemb) { err = true; reporter_->error("BinaryPiostream error reading block io."); } } else { const size_t did = fwrite(data, s, nmemb, fp_); if (did != nmemb) { err = true; reporter_->error("BinaryPiostream error writing block io."); } } return true; } //// // BinarySwapPiostream -- portable // Piostream used when endianness of machine and file don't match BinarySwapPiostream::BinarySwapPiostream(const std::string& filename, Direction dir, const int& v, LoggerHandle pr) : BinaryPiostream(filename, dir, v, pr) { } BinarySwapPiostream::BinarySwapPiostream(int fd, Direction dir, const int& v, LoggerHandle pr) : BinaryPiostream(fd, dir, v, pr) { } BinarySwapPiostream::~BinarySwapPiostream() { } const char * BinarySwapPiostream::endianness() { /// @todo SCIRUN4_CODE_TO_BE_ENABLED_LATER //if (airMyEndian == airEndianLittle) return "LIT\n"; //else //return "BIG\n"; } template <class T> inline void BinarySwapPiostream::gen_io(T& data, const char *iotype) { if (err) return; if (dir==Read) { unsigned char tmp[sizeof(data)]; if (!fread(tmp, sizeof(data), 1, fp_)) { err = true; reporter_->error(std::string("BinaryPiostream error reading ") + iotype + "."); return; } unsigned char *cdata = reinterpret_cast<unsigned char *>(&data); for (unsigned int i = 0; i < sizeof(data); i++) { cdata[i] = tmp[sizeof(data)-i-1]; } } else { #if 0 unsigned char tmp[sizeof(data)]; unsigned char *cdata = reinterpret_cast<unsigned char *>(&data); for (unsigned int i = 0; i < sizeof(data); i++) { tmp[i] = cdata[sizeof(data)-i-1]; } if (!fwrite(tmp, sizeof(data), 1, fp_)) { err = true; reporter_->error(std::string("BinaryPiostream error writing ") + iotype + "."); } #else if (!fwrite(&data, sizeof(data), 1, fp_)) { err = true; reporter_->error(std::string("BinaryPiostream error writing ") + iotype + "."); } #endif } } void BinarySwapPiostream::io(short& data) { if (version() == 1) { // xdr_short int tmp; tmp = data; io(tmp); data = tmp; } else { gen_io(data, "short"); } } void BinarySwapPiostream::io(unsigned short& data) { if (version() == 1) { // xdr_u_short unsigned int tmp; tmp = data; io(tmp); data = tmp; } else { gen_io(data, "unsigned short"); } } void BinarySwapPiostream::io(int& data) { gen_io(data, "int"); } void BinarySwapPiostream::io(unsigned int& data) { gen_io(data, "unsigned int"); } void BinarySwapPiostream::io(long& data) { if (version() == 1) { // xdr_long // Note that xdr treats longs as 4 byte numbers. int tmp; tmp = data; io(tmp); data = tmp; } else { gen_io(data, "long"); } } void BinarySwapPiostream::io(unsigned long& data) { if (version() == 1) { // xdr_u_long // Note that xdr treats longs as 4 byte numbers. unsigned int tmp; tmp = data; io(tmp); data = tmp; } else { gen_io(data, "unsigned long"); } } void BinarySwapPiostream::io(long long& data) { gen_io(data, "long long"); } void BinarySwapPiostream::io(unsigned long long& data) { gen_io(data, "unsigned long long"); } void BinarySwapPiostream::io(double& data) { gen_io(data, "double"); } void BinarySwapPiostream::io(float& data) { gen_io(data, "float"); } TextPiostream::TextPiostream(const std::string& filename, Direction dir, LoggerHandle pr) : Piostream(dir, -1, filename, pr), ownstreams_p_(true) { if (dir==Read) { ostr=nullptr; istr=new std::ifstream(filename.c_str()); if (!istr) { reporter_->error("Error opening file: " + filename + " for reading."); err = true; return; } char hdr[12]; istr->read(hdr, 8); if (!*istr) { reporter_->error("Error reading header of file: " + filename); err = true; return; } int c=8; while (*istr && c < 12) { hdr[c]=istr->get(); if (hdr[c] == '\n') break; c++; } if (!readHeader(reporter_, filename, hdr, "ASC", version_, file_endian)) { reporter_->error("Error parsing header of file: " + filename); err = true; return; } } else { istr=nullptr; ostr = new std::ofstream(filename.c_str(), std::ios_base::binary | std::ios_base::out); std::ostream& out=*ostr; if (!out) { reporter_->error("Error opening file: " + filename + " for writing."); err = true; return; } out << "SCI\nASC\n" << PERSISTENT_VERSION << "\n"; version_ = PERSISTENT_VERSION; } } TextPiostream::TextPiostream(std::istream *strm, LoggerHandle pr) : Piostream(Read, -1, "", pr), istr(strm), ostr(nullptr), ownstreams_p_(false) { char hdr[12]; istr->read(hdr, 8); if (!*istr) { reporter_->error("Error reading header of istream."); err = true; return; } int c=8; while (*istr && c < 12) { hdr[c]=istr->get(); if (hdr[c] == '\n') break; c++; } if (!readHeader(reporter_, "istream", hdr, "ASC", version_, file_endian)) { reporter_->error("Error parsing header of istream."); err = true; return; } } TextPiostream::TextPiostream(std::ostream *strm, LoggerHandle pr) : Piostream(Write, -1, "", pr), istr(nullptr), ostr(strm), ownstreams_p_(false) { std::ostream& out=*ostr; out << "SCI\nASC\n" << PERSISTENT_VERSION << "\n"; version_ = PERSISTENT_VERSION; } TextPiostream::~TextPiostream() { if (ownstreams_p_) { delete istr; delete ostr; } } void TextPiostream::reset_post_header() { if (! reading()) return; istr->seekg(0, std::ios::beg); char hdr[12]; istr->read(hdr, 8); int c=8; while (*istr && c < 12) { hdr[c]=istr->get(); if (hdr[c] == '\n') break; c++; } } void TextPiostream::ioString(bool do_quotes, std::string& str) { if (do_quotes) { io(str); } else { if (dir==Read) { char buf[1000]; char* p=buf; int n=0; std::istream& in=*istr; for(;;) { char c; in.get(c); if (!in) { reporter_->error("String input failed."); char buf[100]; in.clear(); in.getline(buf, 100); reporter_->error(std::string("Rest of line is: ") + buf); err = true; break; } if (c == ' ') break; else *p++=c; if (n++ > 998) { reporter_->error("String too long."); char buf[100]; in.clear(); in.getline(buf, 100); reporter_->error(std::string("Rest of line is: ") + buf); err = true; break; } } *p=0; str = std::string(buf); } else { *ostr << str << " "; } } } std::string TextPiostream::peek_class() { // if we have the name already do nothing if (have_peekname_) { return peekname_; } else { expect('{'); ioString(false, peekname_); have_peekname_ = true; return peekname_; } } int TextPiostream::begin_class(const std::string& classname, int current_version) { if (err) return -1; int version = current_version; std::string gname; if (dir==Write) { gname=classname; *ostr << '{'; ioString(false, gname); } else if (dir==Read && have_peekname_) { gname = peekname_; } else { expect('{'); ioString(false, gname); } have_peekname_ = false; if (dir==Read) { } io(version); if (dir == Read && version > current_version) { err = true; reporter_->error("File too new. " + classname + " has version " + to_string(version) + ", but this scirun build is at version " + to_string(current_version) + "."); } return version; } void TextPiostream::end_class() { if (err) return; if (dir==Read) { expect('}'); expect('\n'); } else { *ostr << "}\n"; } } void TextPiostream::begin_cheap_delim() { if (err) return; if (dir==Read) { expect('{'); } else { *ostr << "{"; } } void TextPiostream::end_cheap_delim() { if (err) return; if (dir==Read) { expect('}'); } else { *ostr << "}"; } } void TextPiostream::io(bool& data) { if (err) return; if (dir==Read) { std::istream& in=*istr; in >> data; if (!in) { reporter_->error("Error reading bool."); char buf[100]; in.clear(); in.getline(buf, 100); reporter_->error(std::string("Rest of line is: ") + buf); err = true; return; } next_entry(); } else {
c++
code
19,995
5,051
#pragma once #include <graphene/chain/protocol/operations.hpp> #include <graphene/chain/protocol/lua_types.hpp> #include <graphene/db/generic_index.hpp> #include <boost/multi_index/composite_key.hpp> #include <graphene/chain/hardfork.hpp> #include <graphene/chain/database.hpp> #include <lua_extern.hpp> #include <graphene/chain/protocol/lua_scheduler.hpp> #include <graphene/chain/protocol/memo.hpp> #include <graphene/utilities/words.hpp> #include <fc/crypto/aes.hpp> #include <graphene/process_encryption/process_encryption_helper.hpp> namespace graphene { namespace chain { using namespace process_encryption; struct register_scheduler; //nico lua Key_Special static const std::string Key_Special[] = {"table", "_G", "_VERSION", "coroutine", "debug", "math", "io", "utf8", "bit", "package", "string", "os", "cjson","baseENV" #if !defined(LUA_COMPAT_GRAPHENE) , "require" #endif }; struct contract_base_info; class contract_object : public graphene::db::abstract_object<contract_object> { public: static const uint8_t space_id = protocol_ids; static const uint8_t type_id = contract_object_type; time_point_sec creation_date; account_id_type owner; string name; uint32_t user_invoke_share_percent; bool is_release=false; tx_hash_type current_version; bool check_contract_authority = false; public_key_type contract_authority; lua_map contract_data; lua_map contract_ABI; contract_bin_code_id_type lua_code_b_id; public: contract_object(){}; contract_object(string name):name(name){id=contract_id_type(1);} void compiling_contract(lua_State *bL, string lua_code,bool is_baseENV=false); contract_id_type get_id() const { return id; } optional<lua_types> parse_function_summary(lua_scheduler &context, int index); lua_table do_contract(string lua_code,lua_State *L=nullptr); void do_contract_function(account_id_type caller, string function_name, vector<lua_types> value_list, lua_map &account_data, graphene::chain::database &db, const flat_set<public_key_type> &sigkeys, contract_result &apply_result); void do_contract_function(account_id_type caller, string function_name, vector<lua_types> value_list, lua_map &account_data, graphene::chain::database &db, const flat_set<public_key_type> &sigkeys, contract_result &apply_result,contract_id_type contract_id); void do_actual_contract_function(account_id_type caller, string function_name, vector<lua_types> value_list, lua_map &account_data, graphene::chain::database &db, const flat_set<public_key_type> &sigkeys, contract_result &apply_result,contract_id_type contract_id); void set_mode(const transaction_evaluation_state * tx_mode) { trx_state = tx_mode; } contract_result get_result() { return this->result; } struct process_variable &get_process_variable() { return _process_value; } void set_process_value(vector<char> process_value); vector<char> set_result_process_value(); bool check_contract_authority_falg() { return check_contract_authority; } void set_process_encryption_helper(const process_encryption_helper helper) {encryption_helper=helper; } void register_function(lua_scheduler &context, register_scheduler *fc_register,graphene::chain::contract_base_info*base_info)const; optional<lua_types> get_lua_data(lua_scheduler &context, int index, bool check_fc = false); void push_global_parameters(lua_scheduler &context, lua_map &global_variable_list, string tablename = ""); void push_table_parameters(lua_scheduler &context, lua_map &table_variable, string tablename); void push_function_actual_parameters(lua_State *L, vector<lua_types> &value_list); void get_code(vector<char>&target){target=lua_code_b;lua_code_b.clear();} void set_code(vector<char>source){FC_ASSERT(source.size()>0); lua_code_b=source;} private: process_encryption_helper encryption_helper; vector<char> lua_code_b; contract_result result; const transaction_evaluation_state * trx_state; struct process_variable _process_value; }; struct boost_lua_variant_visitor : public boost::static_visitor<lua_types> { template <typename T> lua_types operator()(T t) const { return t; } }; class account_contract_data : public graphene::db::abstract_object<account_contract_data> { public: static const uint8_t space_id = protocol_ids; static const uint8_t type_id = contract_data_type; account_id_type owner; contract_id_type contract_id; lua_map contract_data; account_contract_data(){}; contract_data_id_type get_id() const { return id; } }; struct contract_base_info { string name; string id; string owner; string caller; string creation_date; string contract_authority; string invoker_contract_id; contract_base_info(const contract_object &co, account_id_type caller,object_id_type contract_id) { this->name = co.name; this->id = string(co.id); object_id_type temp=co.owner; this->owner =string(temp); temp=caller; this->caller = string(temp); this->creation_date = string(co.creation_date); this->contract_authority = string(co.contract_authority); this->invoker_contract_id = string(contract_id); } }; /* class contract_runing_stata : public graphene::db::abstract_object<contract_runing_stata> { contract_id_type contract_id; bool isruning; fc::time_point_sec last_call_time; }; */ #ifdef INCREASE_CONTRACT /*********************************************合约索引�?**********************************************/ struct by_name; struct by_owner; typedef multi_index_container< contract_object, indexed_by< ordered_unique< tag<by_id>, member<object, object_id_type, &object::id>>, ordered_unique< tag<by_name>, member<contract_object, string, &contract_object::name>>, ordered_non_unique< tag<by_owner>,member<contract_object,account_id_type,&contract_object::owner>> > > contract_multi_index_type; /** * @ingroup object_index */ typedef generic_index<contract_object, contract_multi_index_type> contract_index; /*********************************************合约数据索引�?**********************************************/ struct by_account_contract { }; typedef multi_index_container< account_contract_data, indexed_by< ordered_unique< tag<by_id>, member<object, object_id_type, &object::id>>, ordered_unique< tag<by_account_contract>, composite_key< account_contract_data, member<account_contract_data, account_id_type, &account_contract_data ::owner>, member<account_contract_data, contract_id_type, &account_contract_data ::contract_id>>>>> account_contract_data_multi_index_type; /** * @ingroup object_index */ typedef generic_index<account_contract_data, account_contract_data_multi_index_type> account_contract_data_index; class contract_bin_code_object: public graphene::db::abstract_object<contract_bin_code_object> { public: static const uint8_t space_id = implementation_ids; static const uint8_t type_id = impl_contract_bin_code_type; contract_id_type contract_id; vector<char> lua_code_b; }; struct by_contract_id{}; typedef multi_index_container< contract_bin_code_object, indexed_by< ordered_unique< tag<by_id>, member<object, object_id_type, &object::id>>, ordered_unique< tag<by_contract_id>,member<contract_bin_code_object,contract_id_type,&contract_bin_code_object::contract_id>> > > contract_bin_code_multi_index_type; typedef generic_index<contract_bin_code_object, contract_bin_code_multi_index_type> contract_bin_code_index; #endif } // namespace chain } // namespace graphene FC_REFLECT_DERIVED(graphene::chain::contract_object, (graphene::db::object), (creation_date)(owner)(name)(user_invoke_share_percent)(current_version)(contract_authority)(is_release)(check_contract_authority)(contract_data)(contract_ABI)(lua_code_b_id)) FC_REFLECT_DERIVED(graphene::chain::account_contract_data, (graphene::db::object), (owner)(contract_id)(contract_data)) FC_REFLECT_DERIVED(graphene::chain::contract_bin_code_object,(graphene::db::object),(contract_id)(lua_code_b))
c++
code
8,671
1,543
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // Please do not modify this file. It will be re-generated // running the code generator. //-------------------------------------------------------------------------- #ifndef _RGB2GRAY_OBSERVER_INTERFACE_HH #define _RGB2GRAY_OBSERVER_INTERFACE_HH // forward declaration class Rgb2gray; class Rgb2grayObserverInterface { public: virtual ~Rgb2grayObserverInterface() { } virtual void on_update_from(const Rgb2gray *subject) = 0; }; #endif
c++
code
844
188
/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/collective/recv_v2_op.h" #if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL) #include "paddle/fluid/platform/collective_helper.h" #include "paddle/fluid/platform/nccl_helper.h" #endif namespace paddle { namespace operators { template <typename T> class RecvOpV2CUDAKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext &ctx) const override { #if (defined(PADDLE_WITH_RCCL) || defined(PADDLE_WITH_NCCL)) && \ NCCL_VERSION_CODE >= 2703 int rid = ctx.Attr<int>("ring_id"); PADDLE_ENFORCE_GE( rid, 0, platform::errors::InvalidArgument( "The ring_id (%d) for recv_v2 op must be non-negative.", rid)); int peer = ctx.Attr<int>("peer"); PADDLE_ENFORCE_GE( peer, 0, platform::errors::InvalidArgument( "The peer (%d) for recv_v2 op must be non-negative.", peer)); auto out = ctx.Output<framework::LoDTensor>("Out"); auto out_dims = out->dims(); auto numel = out->numel(); int data_type = ctx.Attr<int>("dtype"); framework::proto::VarType::Type type = framework::proto::VarType::Type(data_type); gpuStream_t stream = nullptr; auto place = ctx.GetPlace(); auto comm = platform::NCCLCommContext::Instance().Get(rid, place); if (ctx.Attr<bool>("use_calc_stream")) { auto dev_ctx = platform::DeviceContextPool::Instance().Get(place); stream = static_cast<platform::CUDADeviceContext *>(dev_ctx)->stream(); } else { stream = comm->stream(); } PADDLE_ENFORCE_LT( peer, comm->nranks(), platform::errors::InvalidArgument("The value of peer (%d) you set must " "be less than comm->nranks (%d).", peer, comm->nranks())); out->mutable_data<T>(out_dims, place); ncclDataType_t dtype = platform::ToNCCLDataType(type); PADDLE_ENFORCE_CUDA_SUCCESS(platform::dynload::ncclRecv( out->data<T>(), numel, dtype, peer, comm->comm(), stream)); VLOG(3) << "rank " << comm->rank() << " recv " << framework::product(out->dims()) << " from " << peer; #else PADDLE_THROW(platform::errors::Unavailable( "PaddlePaddle should be compiled with NCCL and " "NCCL version >= 2.7.3 is needed.")); #endif } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; namespace plat = paddle::platform; REGISTER_OP_CUDA_KERNEL(recv_v2, ops::RecvOpV2CUDAKernel<float>, ops::RecvOpV2CUDAKernel<double>, ops::RecvOpV2CUDAKernel<int>, ops::RecvOpV2CUDAKernel<int64_t>, ops::RecvOpV2CUDAKernel<plat::float16>);
c++
code
3,378
747
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // 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 "async.h" #include "debug.h" #include "vector.h" #include "threadlocal.h" #include <exception> #include <map> #if KJ_USE_FUTEX #include <unistd.h> #include <sys/syscall.h> #include <linux/futex.h> #endif #if !KJ_NO_RTTI #include <typeinfo> #if __GNUC__ #include <cxxabi.h> #include <stdlib.h> #endif #endif namespace kj { namespace { KJ_THREADLOCAL_PTR(EventLoop) threadLocalEventLoop = nullptr; #define _kJ_ALREADY_READY reinterpret_cast< ::kj::_::Event*>(1) EventLoop& currentEventLoop() { EventLoop* loop = threadLocalEventLoop; KJ_REQUIRE(loop != nullptr, "No event loop is running on this thread."); return *loop; } class BoolEvent: public _::Event { public: bool fired = false; Maybe<Own<_::Event>> fire() override { fired = true; return nullptr; } }; class YieldPromiseNode final: public _::PromiseNode { public: void onReady(_::Event& event) noexcept override { event.armBreadthFirst(); } void get(_::ExceptionOrValue& output) noexcept override { output.as<_::Void>() = _::Void(); } }; class NeverDonePromiseNode final: public _::PromiseNode { public: void onReady(_::Event& event) noexcept override { // ignore } void get(_::ExceptionOrValue& output) noexcept override { KJ_FAIL_REQUIRE("Not ready."); } }; } // namespace namespace _ { // private class TaskSetImpl { public: inline TaskSetImpl(TaskSet::ErrorHandler& errorHandler) : errorHandler(errorHandler) {} ~TaskSetImpl() noexcept(false) { // std::map doesn't like it when elements' destructors throw, so carefully disassemble it. if (!tasks.empty()) { Vector<Own<Task>> deleteMe(tasks.size()); for (auto& entry: tasks) { deleteMe.add(kj::mv(entry.second)); } } } class Task final: public Event { public: Task(TaskSetImpl& taskSet, Own<_::PromiseNode>&& nodeParam) : taskSet(taskSet), node(kj::mv(nodeParam)) { node->setSelfPointer(&node); node->onReady(*this); } protected: Maybe<Own<Event>> fire() override { // Get the result. _::ExceptionOr<_::Void> result; node->get(result); // Delete the node, catching any exceptions. KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() { node = nullptr; })) { result.addException(kj::mv(*exception)); } // Call the error handler if there was an exception. KJ_IF_MAYBE(e, result.exception) { taskSet.errorHandler.taskFailed(kj::mv(*e)); } // Remove from the task map. auto iter = taskSet.tasks.find(this); KJ_ASSERT(iter != taskSet.tasks.end()); Own<Event> self = kj::mv(iter->second); taskSet.tasks.erase(iter); return mv(self); } _::PromiseNode* getInnerForTrace() override { return node; } private: TaskSetImpl& taskSet; kj::Own<_::PromiseNode> node; }; void add(Promise<void>&& promise) { auto task = heap<Task>(*this, kj::mv(promise.node)); Task* ptr = task; tasks.insert(std::make_pair(ptr, kj::mv(task))); } kj::String trace() { kj::Vector<kj::String> traces; for (auto& entry: tasks) { traces.add(entry.second->trace()); } return kj::strArray(traces, "\n============================================\n"); } private: TaskSet::ErrorHandler& errorHandler; // TODO(perf): Use a linked list instead. std::map<Task*, Own<Task>> tasks; }; class LoggingErrorHandler: public TaskSet::ErrorHandler { public: static LoggingErrorHandler instance; void taskFailed(kj::Exception&& exception) override { KJ_LOG(ERROR, "Uncaught exception in daemonized task.", exception); } }; LoggingErrorHandler LoggingErrorHandler::instance = LoggingErrorHandler(); class NullEventPort: public EventPort { public: bool wait() override { KJ_FAIL_REQUIRE("Nothing to wait for; this thread would hang forever."); } bool poll() override { return false; } void wake() const override { // TODO(someday): Implement using condvar. kj::throwRecoverableException(KJ_EXCEPTION(UNIMPLEMENTED, "Cross-thread events are not yet implemented for EventLoops with no EventPort.")); } static NullEventPort instance; }; NullEventPort NullEventPort::instance = NullEventPort(); } // namespace _ (private) // ======================================================================================= void EventPort::setRunnable(bool runnable) {} void EventPort::wake() const { kj::throwRecoverableException(KJ_EXCEPTION(UNIMPLEMENTED, "cross-thread wake() not implemented by this EventPort implementation")); } EventLoop::EventLoop() : port(_::NullEventPort::instance), daemons(kj::heap<_::TaskSetImpl>(_::LoggingErrorHandler::instance)) {} EventLoop::EventLoop(EventPort& port) : port(port), daemons(kj::heap<_::TaskSetImpl>(_::LoggingErrorHandler::instance)) {} EventLoop::~EventLoop() noexcept(false) { // Destroy all "daemon" tasks, noting that their destructors might try to access the EventLoop // some more. daemons = nullptr; // The application _should_ destroy everything using the EventLoop before destroying the // EventLoop itself, so if there are events on the loop, this indicates a memory leak. KJ_REQUIRE(head == nullptr, "EventLoop destroyed with events still in the queue. Memory leak?", head->trace()) { // Unlink all the events and hope that no one ever fires them... _::Event* event = head; while (event != nullptr) { _::Event* next = event->next; event->next = nullptr; event->prev = nullptr; event = next; } break; } KJ_REQUIRE(threadLocalEventLoop != this, "EventLoop destroyed while still current for the thread.") { threadLocalEventLoop = nullptr; break; } } void EventLoop::run(uint maxTurnCount) { running = true; KJ_DEFER(running = false); for (uint i = 0; i < maxTurnCount; i++) { if (!turn()) { break; } } setRunnable(isRunnable()); } bool EventLoop::turn() { _::Event* event = head; if (event == nullptr) { // No events in the queue. return false; } else { head = event->next; if (head != nullptr) { head->prev = &head; } depthFirstInsertPoint = &head; if (tail == &event->next) { tail = &head; } event->next = nullptr; event->prev = nullptr; Maybe<Own<_::Event>> eventToDestroy; { event->firing = true; KJ_DEFER(event->firing = false); eventToDestroy = event->fire(); } depthFirstInsertPoint = &head; return true; } } bool EventLoop::isRunnable() { return head != nullptr; } void EventLoop::setRunnable(bool runnable) { if (runnable != lastRunnableState) { port.setRunnable(runnable); lastRunnableState = runnable; } } void EventLoop::enterScope() { KJ_REQUIRE(threadLocalEventLoop == nullptr, "This thread already has an EventLoop."); threadLocalEventLoop = this; } void EventLoop::leaveScope() { KJ_REQUIRE(threadLocalEventLoop == this, "WaitScope destroyed in a different thread than it was created in.") { break; } threadLocalEventLoop = nullptr; } namespace _ { // private void waitImpl(Own<_::PromiseNode>&& node, _::ExceptionOrValue& result, WaitScope& waitScope) { EventLoop& loop = waitScope.loop; KJ_REQUIRE(&loop == threadLocalEventLoop, "WaitScope not valid for this thread."); KJ_REQUIRE(!loop.running, "wait() is not allowed from within event callbacks."); BoolEvent doneEvent; node->setSelfPointer(&node); node->onReady(doneEvent); loop.running = true; KJ_DEFER(loop.running = false); while (!doneEvent.fired) { if (!loop.turn()) { // No events in the queue. Wait for callback. loop.port.wait(); } } loop.setRunnable(loop.isRunnable()); node->get(result); KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() { node = nullptr; })) { result.addException(kj::mv(*exception)); } } Promise<void> yield() { return Promise<void>(false, kj::heap<YieldPromiseNode>()); } Own<PromiseNode> neverDone() { return kj::heap<NeverDonePromiseNode>(); } void NeverDone::wait(WaitScope& waitScope) const { ExceptionOr<Void> dummy; waitImpl(neverDone(), dummy, waitScope); KJ_UNREACHABLE; } void detach(kj::Promise<void>&& promise) { EventLoop& loop = currentEventLoop(); KJ_REQUIRE(loop.daemons.get() != nullptr, "EventLoop is shutting down.") { return; } loop.daemons->add(kj::mv(promise)); } Event::Event() : loop(currentEventLoop()), next(nullptr), prev(nullptr) {} Event::~Event() noexcept(false) { if (prev != nullptr) { if (loop.tail == &next) { loop.tail = prev; } if (loop.depthFirstInsertPoint == &next) { loop.depthFirstInsertPoint = prev; } *prev = next; if (next != nullptr) { next->prev = prev; } } KJ_REQUIRE(!firing, "Promise callback destroyed itself."); KJ_REQUIRE(threadLocalEventLoop == &loop || threadLocalEventLoop == nullptr, "Promise destroyed from a different thread than it was created in."); } void Event::armDepthFirst() { KJ_REQUIRE(threadLocalEventLoop == &loop || threadLocalEventLoop == nullptr, "Event armed from different thread than it was created in. You must use " "the thread-safe work queue to queue events cross-thread."); if (prev == nullptr) { next = *loop.depthFirstInsertPoint; prev = loop.depthFirstInsertPoint; *prev = this; if (next != nullptr) { next->prev = &next; } loop.depthFirstInsertPoint = &next; if (loop.tail == prev) { loop.tail = &next; } loop.setRunnable(true); } } void Event::armBreadthFirst() { KJ_REQUIRE(threadLocalEventLoop == &loop || threadLocalEventLoop == nullptr, "Event armed from different thread than it was created in. You must use " "the thread-safe work queue to queue events cross-thread."); if (prev == nullptr) { next = *loop.tail; prev = loop.tail; *prev = this; if (next != nullptr) { next->prev = &next; } loop.tail = &next; loop.setRunnable(true); } } _::PromiseNode* Event::getInnerForTrace() { return nullptr; } #if !KJ_NO_RTTI #if __GNUC__ static kj::String demangleTypeName(const char* name) { int status; char* buf = abi::__cxa_demangle(name, nullptr, nullptr, &status); kj::String result = kj::heapString(buf == nullptr ? name : buf); free(buf); return kj::mv(result); } #else static kj::String demangleTypeName(const char* name) { return kj::heapString(name); } #endif #endif static kj::String traceImpl(Event* event, _::PromiseNode* node) { #if KJ_NO_RTTI return heapString("Trace not available because RTTI is disabled."); #else kj::Vector<kj::String> trace; if (event != nullptr) { trace.add(demangleTypeName(typeid(*event).name())); } while (node != nullptr) { trace.add(demangleTypeName(typeid(*node).name())); node = node->getInnerForTrace(); } return strArray(trace, "\n"); #endif } kj::String Event::trace() { return traceImpl(this, getInnerForTrace()); } } // namespace _ (private) // ======================================================================================= TaskSet::TaskSet(ErrorHandler& errorHandler) : impl(heap<_::TaskSetImpl>(errorHandler)) {} TaskSet::~TaskSet() noexcept(false) {} void TaskSet::add(Promise<void>&& promise) { impl->add(kj::mv(promise)); } kj::String TaskSet::trace() { return impl->trace(); } namespace _ { // private kj::String PromiseBase::trace() { return traceImpl(nullptr, node); } void PromiseNode::setSelfPointer(Own<PromiseNode>* selfPtr) noexcept {} PromiseNode* PromiseNode::getInnerForTrace() { return nullptr; } void PromiseNode::OnReadyEvent::init(Event& newEvent) { if (event == _kJ_ALREADY_READY) { // A new continuation was added to a promise that was already ready. In this case, we schedule // breadth-first, to make it difficult for applications to accidentally starve the event loop // by repeatedly waiting on immediate promises. newEvent.armBreadthFirst(); } else { event = &newEvent; } } void PromiseNode::OnReadyEvent::arm() { if (event == nullptr) { event = _kJ_ALREADY_READY; } else { // A promise resolved and an event is already waiting on it. In this case, arm in depth-first // order so that the event runs immediately after the current one. This way, chained promises // execute together for better cache locality and lower latency. event->armDepthFirst(); } } // ------------------------------------------------------------------- ImmediatePromiseNodeBase::ImmediatePromiseNodeBase() {} ImmediatePromiseNodeBase::~ImmediatePromiseNodeBase() noexcept(false) {} void ImmediatePromiseNodeBase::onReady(Event& event) noexcept { event.armBreadthFirst(); } ImmediateBrokenPromiseNode::ImmediateBrokenPromiseNode(Exception&& exception) : exception(kj::mv(exception)) {} void ImmediateBrokenPromiseNode::get(ExceptionOrValue& output) noexcept { output.exception = kj::mv(exception); } // ------------------------------------------------------------------- AttachmentPromiseNodeBase::AttachmentPromiseNodeBase(Own<PromiseNode>&& dependencyParam) : dependency(kj::mv(dependencyParam)) { dependency->setSelfPointer(&dependency); } void AttachmentPromiseNodeBase::onReady(Event& event) noexcept { dependency->onReady(event); } void AttachmentPromiseNodeBase::get(ExceptionOrValue& output) noexcept { dependency->get(output); } PromiseNode* AttachmentPromiseNodeBase::getInnerForTrace() { return dependency; } void AttachmentPromiseNodeBase::dropDependency() { dependency = nullptr; } // ------------------------------------------------------------------- TransformPromiseNodeBase::TransformPromiseNodeBase( Own<PromiseNode>&& dependencyParam, void* continuationTracePtr) : dependency(kj::mv(dependencyParam)), continuationTracePtr(continuationTracePtr) { dependency->setSelfPointer(&dependency); } void TransformPromiseNodeBase::onReady(Event& event) noexcept { dependency->onReady(event); } void TransformPromiseNodeBase::get(ExceptionOrValue& output) noexcept { KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() { getImpl(output); dropDependency(); })) { output.addException(kj::mv(*exception)); } } PromiseNode* TransformPromiseNodeBase::getInnerForTrace() { return dependency; } void TransformPromiseNodeBase::dropDependency() { dependency = nullptr; } void TransformPromiseNodeBase::getDepResult(ExceptionOrValue& output) { dependency->get(output); KJ_IF_MAYBE(exception, kj::runCatchingExceptions([&]() { dependency = nullptr; })) { output.addException(kj::mv(*exception)); } KJ_IF_MAYBE(e, output.exception) { e->addTrace(continuationTracePtr); } } // ------------------------------------------------------------------- ForkBranchBase::ForkBranchBase(Own<ForkHubBase>&& hubParam): hub(kj::mv(hubParam)) { if (hub->tailBranch == nullptr) { onReadyEvent.arm(); } else { // Insert into hub's linked list of branches. prevPtr = hub->tailBranch; *prevPtr = this; next = nullptr; hub->tailBranch = &next; } } ForkBranchBase::~ForkBranchBase() noexcept(false) { if (prevPtr != nullptr) { // Remove from hub's linked list of branches. *prevPtr = next; (next == nullptr ? hub->tailBranch : next->prevPtr) = prevPtr; } } void ForkBranchBase::hubReady() noexcept { onReadyEvent.arm(); } void ForkBranchBase::releaseHub(ExceptionOrValue& output) { KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() { hub = nullptr; })) { output.addException(kj::mv(*exception)); } } void ForkBranchBase::onReady(Event& event) noexcept { onReadyEvent.init(event); } PromiseNode* ForkBranchBase::getInnerForTrace() { return hub->getInnerForTrace(); } // ------------------------------------------------------------------- ForkHubBase::ForkHubBase(Own<PromiseNode>&& innerParam, ExceptionOrValue& resultRef) : inner(kj::mv(innerParam)), resultRef(resultRef) { inner->setSelfPointer(&inner); inner->onReady(*this); } Maybe<Own<Event>> ForkHubBase::fire() { // Dependency is ready. Fetch its result and then delete the node. inner->get(resultRef); KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() { inner = nullptr; })) { resultRef.addException(kj::mv(*exception)); } for (auto branch = headBranch; branch != nullptr; branch = branch->next) { branch->hubReady(); *branch->prevPtr = nullptr; branch->prevPtr = nullptr; } *tailBranch = nullptr; // Indicate that the list is no longer active. tailBranch = nullptr; return nullptr; } _::PromiseNode* ForkHubBase::getInnerForTrace() { return inner; } // ------------------------------------------------------------------- ChainPromiseNode::ChainPromiseNode(Own<PromiseNode> innerParam) : state(STEP1), inner(kj::mv(innerParam)) { inner->setSelfPointer(&inner); inner->onReady(*this); } ChainPromiseNode::~ChainPromiseNode() noexcept(false) {} void ChainPromiseNode::onReady(Event& event) noexcept { switch (state) { case STEP1: KJ_REQUIRE(onReadyEvent == nullptr, "onReady() can only be called once."); onReadyEvent = &event; return; case STEP2: inner->onReady(event); return; } KJ_UNREACHABLE; } void ChainPromiseNode::setSelfPointer(Own<PromiseNode>* selfPtr) noexcept { if (state == STEP2) { *selfPtr = kj::mv(inner); // deletes this! selfPtr->get()->setSelfPointer(selfPtr); } else { this->selfPtr = selfPtr; } } void ChainPromiseNode::get(ExceptionOrValue& output) noexcept { KJ_REQUIRE(state == STEP2); return inner->get(output); } PromiseNode* ChainPromiseNode::getInnerForTrace() { return inner; } Maybe<Own<Event>> ChainPromiseNode::fire() { KJ_REQUIRE(state != STEP2); static_assert(sizeof(Promise<int>) == sizeof(PromiseBase), "This code assumes Promise<T> does not add any new members to PromiseBase."); ExceptionOr<PromiseBase> intermediate; inner->get(intermediate); KJ_IF_MAYBE(exception, kj::runCatchingExceptions([this]() { inner = nullptr; })) { intermediate.addException(kj::mv(*exception)); } KJ_IF_MAYBE(exception, intermediate.exception) { // There is an exception. If there is also a value, delete it. kj::runCatchingExceptions([&]() { intermediate.value = nullptr; }); // Now set step2 to a rejected promise. inner = heap<ImmediateBrokenPromiseNode>(kj::mv(*exception)); } else KJ_IF_MAYBE(value, intermediate.value) { // There is a value and no exception. The value is itself a promise. Adopt it as our // step2. inner = kj::
c++
code
20,000
4,733
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cdb/v20170320/model/SellConfig.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cdb::V20170320::Model; using namespace std; SellConfig::SellConfig() : m_deviceHasBeenSet(false), m_typeHasBeenSet(false), m_cdbTypeHasBeenSet(false), m_memoryHasBeenSet(false), m_cpuHasBeenSet(false), m_volumeMinHasBeenSet(false), m_volumeMaxHasBeenSet(false), m_volumeStepHasBeenSet(false), m_connectionHasBeenSet(false), m_qpsHasBeenSet(false), m_iopsHasBeenSet(false), m_infoHasBeenSet(false), m_statusHasBeenSet(false), m_tagHasBeenSet(false), m_deviceTypeHasBeenSet(false), m_deviceTypeNameHasBeenSet(false), m_engineTypeHasBeenSet(false) { } CoreInternalOutcome SellConfig::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Device") && !value["Device"].IsNull()) { if (!value["Device"].IsString()) { return CoreInternalOutcome(Core::Error("response `SellConfig.Device` IsString=false incorrectly").SetRequestId(requestId)); } m_device = string(value["Device"].GetString()); m_deviceHasBeenSet = true; } if (value.HasMember("Type") && !value["Type"].IsNull()) { if (!value["Type"].IsString()) { return CoreInternalOutcome(Core::Error("response `SellConfig.Type` IsString=false incorrectly").SetRequestId(requestId)); } m_type = string(value["Type"].GetString()); m_typeHasBeenSet = true; } if (value.HasMember("CdbType") && !value["CdbType"].IsNull()) { if (!value["CdbType"].IsString()) { return CoreInternalOutcome(Core::Error("response `SellConfig.CdbType` IsString=false incorrectly").SetRequestId(requestId)); } m_cdbType = string(value["CdbType"].GetString()); m_cdbTypeHasBeenSet = true; } if (value.HasMember("Memory") && !value["Memory"].IsNull()) { if (!value["Memory"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `SellConfig.Memory` IsInt64=false incorrectly").SetRequestId(requestId)); } m_memory = value["Memory"].GetInt64(); m_memoryHasBeenSet = true; } if (value.HasMember("Cpu") && !value["Cpu"].IsNull()) { if (!value["Cpu"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `SellConfig.Cpu` IsInt64=false incorrectly").SetRequestId(requestId)); } m_cpu = value["Cpu"].GetInt64(); m_cpuHasBeenSet = true; } if (value.HasMember("VolumeMin") && !value["VolumeMin"].IsNull()) { if (!value["VolumeMin"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `SellConfig.VolumeMin` IsInt64=false incorrectly").SetRequestId(requestId)); } m_volumeMin = value["VolumeMin"].GetInt64(); m_volumeMinHasBeenSet = true; } if (value.HasMember("VolumeMax") && !value["VolumeMax"].IsNull()) { if (!value["VolumeMax"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `SellConfig.VolumeMax` IsInt64=false incorrectly").SetRequestId(requestId)); } m_volumeMax = value["VolumeMax"].GetInt64(); m_volumeMaxHasBeenSet = true; } if (value.HasMember("VolumeStep") && !value["VolumeStep"].IsNull()) { if (!value["VolumeStep"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `SellConfig.VolumeStep` IsInt64=false incorrectly").SetRequestId(requestId)); } m_volumeStep = value["VolumeStep"].GetInt64(); m_volumeStepHasBeenSet = true; } if (value.HasMember("Connection") && !value["Connection"].IsNull()) { if (!value["Connection"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `SellConfig.Connection` IsInt64=false incorrectly").SetRequestId(requestId)); } m_connection = value["Connection"].GetInt64(); m_connectionHasBeenSet = true; } if (value.HasMember("Qps") && !value["Qps"].IsNull()) { if (!value["Qps"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `SellConfig.Qps` IsInt64=false incorrectly").SetRequestId(requestId)); } m_qps = value["Qps"].GetInt64(); m_qpsHasBeenSet = true; } if (value.HasMember("Iops") && !value["Iops"].IsNull()) { if (!value["Iops"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `SellConfig.Iops` IsInt64=false incorrectly").SetRequestId(requestId)); } m_iops = value["Iops"].GetInt64(); m_iopsHasBeenSet = true; } if (value.HasMember("Info") && !value["Info"].IsNull()) { if (!value["Info"].IsString()) { return CoreInternalOutcome(Core::Error("response `SellConfig.Info` IsString=false incorrectly").SetRequestId(requestId)); } m_info = string(value["Info"].GetString()); m_infoHasBeenSet = true; } if (value.HasMember("Status") && !value["Status"].IsNull()) { if (!value["Status"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `SellConfig.Status` IsInt64=false incorrectly").SetRequestId(requestId)); } m_status = value["Status"].GetInt64(); m_statusHasBeenSet = true; } if (value.HasMember("Tag") && !value["Tag"].IsNull()) { if (!value["Tag"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `SellConfig.Tag` IsInt64=false incorrectly").SetRequestId(requestId)); } m_tag = value["Tag"].GetInt64(); m_tagHasBeenSet = true; } if (value.HasMember("DeviceType") && !value["DeviceType"].IsNull()) { if (!value["DeviceType"].IsString()) { return CoreInternalOutcome(Core::Error("response `SellConfig.DeviceType` IsString=false incorrectly").SetRequestId(requestId)); } m_deviceType = string(value["DeviceType"].GetString()); m_deviceTypeHasBeenSet = true; } if (value.HasMember("DeviceTypeName") && !value["DeviceTypeName"].IsNull()) { if (!value["DeviceTypeName"].IsString()) { return CoreInternalOutcome(Core::Error("response `SellConfig.DeviceTypeName` IsString=false incorrectly").SetRequestId(requestId)); } m_deviceTypeName = string(value["DeviceTypeName"].GetString()); m_deviceTypeNameHasBeenSet = true; } if (value.HasMember("EngineType") && !value["EngineType"].IsNull()) { if (!value["EngineType"].IsString()) { return CoreInternalOutcome(Core::Error("response `SellConfig.EngineType` IsString=false incorrectly").SetRequestId(requestId)); } m_engineType = string(value["EngineType"].GetString()); m_engineTypeHasBeenSet = true; } return CoreInternalOutcome(true); } void SellConfig::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_deviceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Device"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_device.c_str(), allocator).Move(), allocator); } if (m_typeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Type"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_type.c_str(), allocator).Move(), allocator); } if (m_cdbTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CdbType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_cdbType.c_str(), allocator).Move(), allocator); } if (m_memoryHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Memory"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_memory, allocator); } if (m_cpuHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Cpu"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_cpu, allocator); } if (m_volumeMinHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VolumeMin"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_volumeMin, allocator); } if (m_volumeMaxHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VolumeMax"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_volumeMax, allocator); } if (m_volumeStepHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VolumeStep"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_volumeStep, allocator); } if (m_connectionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Connection"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_connection, allocator); } if (m_qpsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Qps"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_qps, allocator); } if (m_iopsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Iops"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_iops, allocator); } if (m_infoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Info"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_info.c_str(), allocator).Move(), allocator); } if (m_statusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Status"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_status, allocator); } if (m_tagHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Tag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_tag, allocator); } if (m_deviceTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DeviceType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_deviceType.c_str(), allocator).Move(), allocator); } if (m_deviceTypeNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DeviceTypeName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_deviceTypeName.c_str(), allocator).Move(), allocator); } if (m_engineTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EngineType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_engineType.c_str(), allocator).Move(), allocator); } } string SellConfig::GetDevice() const { return m_device; } void SellConfig::SetDevice(const string& _device) { m_device = _device; m_deviceHasBeenSet = true; } bool SellConfig::DeviceHasBeenSet() const { return m_deviceHasBeenSet; } string SellConfig::GetType() const { return m_type; } void SellConfig::SetType(const string& _type) { m_type = _type; m_typeHasBeenSet = true; } bool SellConfig::TypeHasBeenSet() const { return m_typeHasBeenSet; } string SellConfig::GetCdbType() const { return m_cdbType; } void SellConfig::SetCdbType(const string& _cdbType) { m_cdbType = _cdbType; m_cdbTypeHasBeenSet = true; } bool SellConfig::CdbTypeHasBeenSet() const { return m_cdbTypeHasBeenSet; } int64_t SellConfig::GetMemory() const { return m_memory; } void SellConfig::SetMemory(const int64_t& _memory) { m_memory = _memory; m_memoryHasBeenSet = true; } bool SellConfig::MemoryHasBeenSet() const { return m_memoryHasBeenSet; } int64_t SellConfig::GetCpu() const { return m_cpu; } void SellConfig::SetCpu(const int64_t& _cpu) { m_cpu = _cpu; m_cpuHasBeenSet = true; } bool SellConfig::CpuHasBeenSet() const { return m_cpuHasBeenSet; } int64_t SellConfig::GetVolumeMin() const { return m_volumeMin; } void SellConfig::SetVolumeMin(const int64_t& _volumeMin) { m_volumeMin = _volumeMin; m_volumeMinHasBeenSet = true; } bool SellConfig::VolumeMinHasBeenSet() const { return m_volumeMinHasBeenSet; } int64_t SellConfig::GetVolumeMax() const { return m_volumeMax; } void SellConfig::SetVolumeMax(const int64_t& _volumeMax) { m_volumeMax = _volumeMax; m_volumeMaxHasBeenSet = true; } bool SellConfig::VolumeMaxHasBeenSet() const { return m_volumeMaxHasBeenSet; } int64_t SellConfig::GetVolumeStep() const { return m_volumeStep; } void SellConfig::SetVolumeStep(const int64_t& _volumeStep) { m_volumeStep = _volumeStep; m_volumeStepHasBeenSet = true; } bool SellConfig::VolumeStepHasBeenSet() const { return m_volumeStepHasBeenSet; } int64_t SellConfig::GetConnection() const { return m_connection; } void SellConfig::SetConnection(const int64_t& _connection) { m_connection = _connection; m_connectionHasBeenSet = true; } bool SellConfig::ConnectionHasBeenSet() const { return m_connectionHasBeenSet; } int64_t SellConfig::GetQps() const { return m_qps; } void SellConfig::SetQps(const int64_t& _qps) { m_qps = _qps; m_qpsHasBeenSet = true; } bool SellConfig::QpsHasBeenSet() const { return m_qpsHasBeenSet; } int64_t SellConfig::GetIops() const { return m_iops; } void SellConfig::SetIops(const int64_t& _iops) { m_iops = _iops; m_iopsHasBeenSet = true; } bool SellConfig::IopsHasBeenSet() const { return m_iopsHasBeenSet; } string SellConfig::GetInfo() const { return m_info; } void SellConfig::SetInfo(const string& _info) { m_info = _info; m_infoHasBeenSet = true; } bool SellConfig::InfoHasBeenSet() const { return m_infoHasBeenSet; } int64_t SellConfig::GetStatus() const { return m_status; } void SellConfig::SetStatus(const int64_t& _status) { m_status = _status; m_statusHasBeenSet = true; } bool SellConfig::StatusHasBeenSet() const { return m_statusHasBeenSet; } int64_t SellConfig::GetTag() const { return m_tag; } void SellConfig::SetTag(const int64_t& _tag) { m_tag = _tag; m_tagHasBeenSet = true; } bool SellConfig::TagHasBeenSet() const { return m_tagHasBeenSet; } string SellConfig::GetDeviceType() const { return m_deviceType; } void SellConfig::SetDeviceType(const string& _deviceType) { m_deviceType = _deviceType; m_deviceTypeHasBeenSet = true; } bool SellConfig::DeviceTypeHasBeenSet() const { return m_deviceTypeHasBeenSet; } string SellConfig::GetDeviceTypeName() const { return m_deviceTypeName; } void SellConfig::SetDeviceTypeName(const string& _deviceTypeName) { m_deviceTypeName = _deviceTypeName; m_deviceTypeNameHasBeenSet = true; } bool SellConfig::DeviceTypeNameHasBeenSet() const { return m_deviceTypeNameHasBeenSet; } string SellConfig::GetEngineType() const { return m_engineType; } void SellConfig::SetEngineType(const string& _engineType) { m_engineType = _engineType; m_engineTypeHasBeenSet = true; } bool SellConfig::EngineTypeHasBeenSet() const { return m_engineTypeHasBeenSet; }
c++
code
16,511
3,479
#include "datastore.h" #include "datastore_p.h" #include "defaults_p.h" #include <QtJsonSerializer/QJsonSerializer> #include "signal_private_connect_p.h" using namespace QtDataSync; using std::function; DataStore::DataStore(QObject *parent) : DataStore{DefaultSetup, parent} {} DataStore::DataStore(const QString &setupName, QObject *parent) : QObject{parent}, d{nullptr} { initStore(setupName); } DataStore::DataStore(QObject *parent, void *) : QObject{parent}, d{nullptr} {} void DataStore::initStore(const QString &setupName) { d.reset(new DataStorePrivate(this, setupName)); connect(d->store, &LocalStore::dataChanged, this, [this](const ObjectKey &key, bool deleted) { emit dataChanged(QMetaType::type(key.typeName), key.id, deleted, {}); }); connect(d->store, &LocalStore::dataResetted, this, PSIG(&DataStore::dataResetted)); } DataStore::~DataStore() = default; qint64 DataStore::count(int metaTypeId) const //MAJOR change to uint { return static_cast<qint64>(d->store->count(d->typeName(metaTypeId))); } QStringList DataStore::keys(int metaTypeId) const { return d->store->keys(d->typeName(metaTypeId)); } QVariantList DataStore::loadAll(int metaTypeId) const { const auto allData = d->store->loadAll(d->typeName(metaTypeId)); QVariantList resList; resList.reserve(allData.size()); for(const auto &val : allData) resList.append(d->serializer->deserialize(val, metaTypeId)); return resList; } QVariant DataStore::load(int metaTypeId, const QString &key) const { auto data = d->store->load({d->typeName(metaTypeId), key}); return d->serializer->deserialize(data, metaTypeId); } void DataStore::save(int metaTypeId, QVariant value) { auto typeName = d->typeName(metaTypeId); if(!value.convert(metaTypeId)) throw InvalidDataException(d->defaults, typeName, QStringLiteral("Failed to convert passed variant to the target type")); auto meta = QMetaType::metaObjectForType(metaTypeId); if(!meta) throw InvalidDataException(d->defaults, typeName, QStringLiteral("Type does not have a meta object")); auto userProp = meta->userProperty(); if(!userProp.isValid()) throw InvalidDataException(d->defaults, typeName, QStringLiteral("Type does not have a user property")); QString key; auto flags = QMetaType::typeFlags(metaTypeId); if(flags.testFlag(QMetaType::IsGadget)) key = userProp.readOnGadget(value.data()).toString(); else if(flags.testFlag(QMetaType::PointerToQObject)) key = userProp.read(value.value<QObject*>()).toString(); else if(flags.testFlag(QMetaType::SharedPointerToQObject)) key = userProp.read(value.value<QSharedPointer<QObject>>().data()).toString(); else if(flags.testFlag(QMetaType::WeakPointerToQObject)) key = userProp.read(value.value<QWeakPointer<QObject>>().data()).toString(); else if(flags.testFlag(QMetaType::TrackingPointerToQObject)) key = userProp.read(value.value<QPointer<QObject>>().data()).toString(); else throw InvalidDataException(d->defaults, typeName, QStringLiteral("Type is neither a gadget nor a pointer to an object")); if(key.isEmpty()) throw InvalidDataException(d->defaults, typeName, QStringLiteral("Failed to convert USER property to a string")); auto json = d->serializer->serialize(value); if(!json.isObject()) throw InvalidDataException(d->defaults, typeName, QStringLiteral("Serialization converted to invalid json type. Only json objects are allowed")); d->store->save({typeName, key}, json.toObject()); } bool DataStore::remove(int metaTypeId, const QString &key) { return d->store->remove({d->typeName(metaTypeId), key}); } void DataStore::update(int metaTypeId, QObject *object) const { auto typeName = d->typeName(metaTypeId); auto meta = QMetaType::metaObjectForType(metaTypeId); if(!meta) throw InvalidDataException(d->defaults, typeName, QStringLiteral("Type does not have a meta object")); auto userProp = meta->userProperty(); if(!userProp.isValid()) throw InvalidDataException(d->defaults, typeName, QStringLiteral("Type does not have a user property")); auto key = userProp.read(object).toString(); if(key.isEmpty()) throw InvalidDataException(d->defaults, typeName, QStringLiteral("Failed to convert user property value to a string")); if(!object->metaObject()->inherits(meta)) { throw InvalidDataException(d->defaults, typeName, QStringLiteral("Passed object of type %1 does not inherit the given meta type") .arg(QString::fromUtf8(object->metaObject()->className()))); } auto nObj = load(metaTypeId, key).value<QObject*>(); for(auto i = 0; i < meta->propertyCount(); i++) { auto prop = meta->property(i); prop.write(object, prop.read(nObj)); } nObj->deleteLater(); } QVariantList DataStore::search(int metaTypeId, const QString &query, SearchMode mode) const { const auto dataList= d->store->find(d->typeName(metaTypeId), query, mode); QVariantList resList; resList.reserve(dataList.size()); for(const auto &val : dataList) resList.append(d->serializer->deserialize(val, metaTypeId)); return resList; } void DataStore::iterate(int metaTypeId, const function<bool (QVariant)> &iterator) const { for(const auto &key : keys(metaTypeId)) { if(!iterator(load(metaTypeId, key))) break; } } void DataStore::clear(int metaTypeId) { d->store->clear(d->typeName(metaTypeId)); } // ------------- PRIVATE IMPLEMENTATION ------------- DataStorePrivate::DataStorePrivate(DataStore *q, const QString &setupName) : defaults{DefaultsPrivate::obtainDefaults(setupName)}, logger{defaults.createLogger("datastore", q)}, serializer{defaults.serializer()}, store{new LocalStore(defaults, q)} {} QByteArray DataStorePrivate::typeName(int metaTypeId) const { auto name = QMetaType::typeName(metaTypeId); if(name) return name; else throw InvalidDataException(defaults, "type_" + QByteArray::number(metaTypeId), QStringLiteral("Not a valid metatype id")); } // ------------- Exceptions ------------- DataStoreException::DataStoreException(const Defaults &defaults, const QString &message) : Exception(defaults, message) {} DataStoreException::DataStoreException(const DataStoreException * const other) : Exception(other) {} LocalStoreException::LocalStoreException(const Defaults &defaults, const ObjectKey &key, const QString &context, const QString &message) : DataStoreException(defaults, message), _key(key), _context(context) {} LocalStoreException::LocalStoreException(const LocalStoreException * const other) : DataStoreException(other), _key(other->_key), _context(other->_context) {} ObjectKey LocalStoreException::key() const { return _key; } QString LocalStoreException::context() const { return _context; } QByteArray LocalStoreException::className() const noexcept { return QTDATASYNC_EXCEPTION_NAME(LocalStoreException); } QString LocalStoreException::qWhat() const { QString msg = Exception::qWhat() + QStringLiteral("\n\tContext: %1" "\n\tTypeName: %2") .arg(_context, QString::fromUtf8(_key.typeName)); if(!_key.id.isNull()) msg += QStringLiteral("\n\tKey: %1").arg(_key.id); return msg; } void LocalStoreException::raise() const { throw (*this); } QException *LocalStoreException::clone() const { return new LocalStoreException(this); } NoDataException::NoDataException(const Defaults &defaults, const ObjectKey &key) : DataStoreException(defaults, QStringLiteral("The requested data does not exist")), _key(key) {} NoDataException::NoDataException(const NoDataException * const other) : DataStoreException(other), _key(other->_key) {} ObjectKey NoDataException::key() const { return _key; } QByteArray NoDataException::className() const noexcept { return QTDATASYNC_EXCEPTION_NAME(NoDataException); } QString NoDataException::qWhat() const { return Exception::qWhat() + QStringLiteral("\n\tTypeName: %1" "\n\tKey: %2") .arg(QString::fromUtf8(_key.typeName), _key.id); } void NoDataException::raise() const { throw (*this); } QException *NoDataException::clone() const { return new NoDataException(this); } InvalidDataException::InvalidDataException(const Defaults &defaults, const QByteArray &typeName, const QString &message) : DataStoreException(defaults, message), _typeName(typeName) {} InvalidDataException::InvalidDataException(const InvalidDataException * const other) : DataStoreException(other), _typeName(other->_typeName) {} QByteArray InvalidDataException::typeName() const { return _typeName; } QByteArray InvalidDataException::className() const noexcept { return QTDATASYNC_EXCEPTION_NAME(InvalidDataException); } QString InvalidDataException::qWhat() const { return Exception::qWhat() + QStringLiteral("\n\tTypeName: %1") .arg(QString::fromUtf8(_typeName)); } void InvalidDataException::raise() const { throw (*this); } QException *InvalidDataException::clone() const { return new InvalidDataException(this); }
c++
code
8,876
2,198
#include "robot_localization/ros_filter_types.h" #include <limits> #include <gtest/gtest.h> using namespace RobotLocalization; class RosEkfPassThrough : public RosEkf { public: RosEkfPassThrough() { } Ekf getFilter() { return filter_; } }; TEST (EkfTest, Measurements) { RosEkfPassThrough ekf; Eigen::VectorXd measurement(STATE_SIZE); for(size_t i = 0; i < STATE_SIZE; ++i) { measurement[i] = i; } Eigen::MatrixXd measurementCovariance(STATE_SIZE, STATE_SIZE); for(size_t i = 0; i < STATE_SIZE; ++i) { measurementCovariance(i, i) = 0.5; } std::vector<int> updateVector(STATE_SIZE, true); // Ensure that measurements are being placed in the queue correctly ros::Time time; time.fromSec(1000); ekf.enqueueMeasurement("odom0", measurement, measurementCovariance, updateVector, std::numeric_limits<double>::max(), time); std::map<std::string, Eigen::VectorXd> postUpdateStates; ekf.integrateMeasurements(1001); EXPECT_EQ(ekf.getFilter().getState(), measurement); EXPECT_EQ(ekf.getFilter().getEstimateErrorCovariance(), measurementCovariance); // Now fuse another measurement and check the output. // We know what the filter's state should be when // this is complete, so we'll check the difference and // make sure it's suitably small. Eigen::VectorXd measurement2 = measurement; measurement2 *= 2.0; time.fromSec(1002); ekf.enqueueMeasurement("odom0", measurement2, measurementCovariance, updateVector, std::numeric_limits<double>::max(), time); ekf.integrateMeasurements(1003); measurement[0] = -4.5198; measurement[1] = 0.14655; measurement[2] = 9.4514; measurement[3] = -2.8688; measurement[4] = -2.2672; measurement[5] = 0.12861; measurement[6] = 15.481; measurement[7] = 17.517; measurement[8] = 19.587; measurement[9] = 9.8351; measurement[10] = 12.73; measurement[11] = 13.87; measurement[12] = 10.978; measurement[13] = 12.008; measurement[14] = 13.126; measurement = measurement.eval() - ekf.getFilter().getState(); for(size_t i = 0; i < STATE_SIZE; ++i) { EXPECT_LT(::fabs(measurement[i]), 0.001); } } int main(int argc, char **argv) { ros::init(argc, argv, "ekf"); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
c++
code
2,548
542
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
23