text
stringlengths
8
6.88M
#pragma once #include "GameObject.h" class Particle: public GameObject { public: int r; int g; int b; int a; int deathtime; Particle(int width, int height, Physics physics, SDL_Texture* texture, int r, int g, int b, int a, int deathtime); Particle(GameObject go, int r, int g, int b, int a, int deathtime); ~Particle(); };
// Lexer for Python. #include <string.h> #include <assert.h> #include <ctype.h> #include <algorithm> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" using namespace Scintilla; #define LEX_PY 32 // Python #define LEX_BOO 55 // Boo /*static const char *const pythonWordListDesc[] = { "Keywords", "Type Keywords", "Built-in Constants", "Decorator", "Build-in Functions", "Attribute", "object Method" "global class", 0 };*/ #define PY_DEF_CLASS 1 #define PY_DEF_FUNC 2 #define PY_DEF_ENUM 3 // Boo static inline bool IsPyStringPrefix(int ch) { ch |= 32; return ch == 'r' || ch == 'u' || ch == 'b' || ch == 'f'; } static inline bool IsPyTripleStyle(int style) { return style == SCE_PY_TRIPLE_STRING1 || style == SCE_PY_TRIPLE_STRING2 || style == SCE_PY_TRIPLE_BYTES1 || style == SCE_PY_TRIPLE_BYTES2 || style == SCE_PY_TRIPLE_FMT_STRING1 || style == SCE_PY_TRIPLE_FMT_STRING2; } static inline bool IsPyStringStyle(int style) { return style == SCE_PY_STRING1 || style == SCE_PY_STRING2 || style == SCE_PY_BYTES1 || style == SCE_PY_BYTES2 || style == SCE_PY_RAW_STRING1 || style == SCE_PY_RAW_STRING2 || style == SCE_PY_RAW_BYTES1 || style == SCE_PY_RAW_BYTES2 || style == SCE_PY_FMT_STRING1 || style == SCE_PY_FMT_STRING2; } static inline bool IsSpaceEquiv(int state) { // including SCE_PY_DEFAULT, SCE_PY_COMMENTLINE, SCE_PY_COMMENTBLOCK return (state <= SCE_PY_COMMENTLINE) || (state == SCE_PY_COMMENTBLOCK); } #define PyStringPrefix_Empty 0 #define PyStringPrefix_Raw 1 // 'r' #define PyStringPrefix_Unicode 2 // 'u' #define PyStringPrefix_Bytes 4 // 'b' #define PyStringPrefix_Formatted 8 // 'f' // r, u, b, f // ru, rb, rf // ur, br, fr static inline int GetPyStringPrefix(int ch) { switch ((ch | 32)) { case 'r': return PyStringPrefix_Raw; case 'u': return PyStringPrefix_Unicode; case 'b': return PyStringPrefix_Bytes; case 'f': return PyStringPrefix_Formatted; default: return PyStringPrefix_Empty; } } static inline int GetPyStringStyle(int quote, bool is_raw, bool is_bytes, bool is_fmt) { switch (quote) { case 1: if (is_bytes) return is_raw? SCE_PY_RAW_BYTES1 : SCE_PY_BYTES1; if (is_fmt) return SCE_PY_FMT_STRING1; return is_raw? SCE_PY_RAW_STRING1 : SCE_PY_STRING1; case 2: if (is_bytes) return is_raw? SCE_PY_RAW_BYTES2 : SCE_PY_BYTES2; if (is_fmt) return SCE_PY_FMT_STRING2; return is_raw? SCE_PY_RAW_STRING2 : SCE_PY_STRING2; case 3: if (is_bytes) return SCE_PY_TRIPLE_BYTES1; if (is_fmt) return SCE_PY_TRIPLE_FMT_STRING1; return SCE_PY_TRIPLE_STRING1; case 6: if (is_bytes) return SCE_PY_TRIPLE_BYTES2; if (is_fmt) return SCE_PY_TRIPLE_FMT_STRING2; return SCE_PY_TRIPLE_STRING2; default: return SCE_PY_DEFAULT; } } static void ColourisePyDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, LexerWordList keywordLists, Accessor &styler) { const WordList &keywords = *keywordLists[0]; const WordList &keywords2 = *keywordLists[1]; const WordList &keywords_const = *keywordLists[2]; //const WordList &keywords4 = *keywordLists[3]; const WordList &keywords_func = *keywordLists[4]; const WordList &keywords_attr = *keywordLists[5]; const WordList &keywords_objm = *keywordLists[6]; const WordList &keywords_class = *keywordLists[7]; int defType = 0; int visibleChars = 0; bool continuationLine = false; //const int lexType = styler.GetPropertyInt("lexer.lang.type", LEX_PY); StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.atLineStart) { if (IsPyTripleStyle(sc.state) || IsPyStringStyle(sc.state)) { sc.SetState(sc.state); } defType = 0; visibleChars = 0; } // Determine if the current state should terminate. switch (sc.state) { case SCE_PY_OPERATOR: sc.SetState(SCE_PY_DEFAULT); break; case SCE_PY_NUMBER: if (!iswordstart(sc.ch)) { if ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E')) { sc.Forward(); } else if (sc.ch == '.' && sc.chNext != '.') { sc.ForwardSetState(SCE_PY_DEFAULT); } else { sc.SetState(SCE_PY_DEFAULT); } } break; case SCE_PY_IDENTIFIER: _label_identifier: if (!iswordstart(sc.ch)) { char s[128]; sc.GetCurrent(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_PY_WORD); if (strcmp(s, "def") == 0) defType = PY_DEF_FUNC; else if (strcmp(s, "class") == 0 || strcmp(s, "raise") == 0 || strcmp(s, "except") == 0) defType = PY_DEF_CLASS; //else if (strcmp(s, "enum") == 0) // defType = PY_DEF_ENUM; } else if (keywords2.InList(s)) { sc.ChangeState(SCE_PY_WORD2); } else if (keywords_const.InList(s)) { sc.ChangeState(SCE_PY_BUILDIN_CONST); } else if (keywords_func.InListAbbreviated(s, '(')) { sc.ChangeState(SCE_PY_BUILDIN_FUNC); } else if (keywords_attr.InList(s)) { sc.ChangeState(SCE_PY_ATTR); } else if (keywords_objm.InList(s)) { sc.ChangeState(SCE_PY_OBJ_FUNC); } else if (defType == PY_DEF_CLASS) { defType = 0; sc.ChangeState(SCE_PY_CLASSNAME); } else if (defType == PY_DEF_FUNC) { defType = 0; sc.ChangeState(SCE_PY_DEFNAME); } else if (keywords_class.InList(s)) { defType = 0; sc.ChangeState(SCE_PY_CLASSNAME); } else if (LexGetNextChar(sc.currentPos, styler) == '(') { sc.ChangeState(SCE_PY_FUNCTION); } sc.SetState(SCE_PY_DEFAULT); } break; case SCE_PY_DECORATOR: if (!iswordchar(sc.ch)) sc.SetState(SCE_PY_DEFAULT); break; case SCE_PY_COMMENTLINE: if (sc.atLineStart) { sc.SetState(SCE_PY_DEFAULT); } break; case SCE_PY_STRING1: case SCE_PY_BYTES1: case SCE_PY_RAW_STRING1: case SCE_PY_RAW_BYTES1: case SCE_PY_FMT_STRING1: if (sc.atLineStart&& !continuationLine) { sc.SetState(SCE_PY_DEFAULT); } else if (sc.ch == '\\' && (sc.chNext == '\\' || sc.chNext == '\"' || sc.chNext == '\'')) { sc.Forward(); } else if (sc.ch == '\'') { sc.ForwardSetState(SCE_PY_DEFAULT); } break; case SCE_PY_STRING2: case SCE_PY_BYTES2: case SCE_PY_RAW_STRING2: case SCE_PY_RAW_BYTES2: case SCE_PY_FMT_STRING2: if (sc.atLineStart && !continuationLine) { sc.SetState(SCE_PY_DEFAULT); } else if (sc.ch == '\\' && (sc.chNext == '\\' || sc.chNext == '\"' || sc.chNext == '\'')) { sc.Forward(); } else if (sc.ch == '\"') { sc.ForwardSetState(SCE_PY_DEFAULT); } break; case SCE_PY_TRIPLE_STRING1: case SCE_PY_TRIPLE_BYTES1: case SCE_PY_TRIPLE_FMT_STRING1: if (sc.ch == '\\') { sc.Forward(); } else if (sc.Match("\'\'\'")) { sc.Forward(2); sc.ForwardSetState(SCE_PY_DEFAULT); } break; case SCE_PY_TRIPLE_STRING2: case SCE_PY_TRIPLE_BYTES2: case SCE_PY_TRIPLE_FMT_STRING2: if (sc.ch == '\\') { sc.Forward(); } else if (sc.Match("\"\"\"")) { sc.Forward(2); sc.ForwardSetState(SCE_PY_DEFAULT); } break; } // Determine if a new state should be entered. if (sc.state == SCE_PY_DEFAULT) { if (sc.ch == '#') { sc.SetState(SCE_PY_COMMENTLINE); } else if (sc.Match("\'\'\'")) { sc.SetState(SCE_PY_TRIPLE_STRING1); sc.Forward(2); } else if (sc.Match("\"\"\"")) { sc.SetState(SCE_PY_TRIPLE_STRING2); sc.Forward(2); } else if (sc.ch == '\'') { sc.SetState(SCE_PY_STRING1); } else if (sc.ch == '\"') { sc.SetState(SCE_PY_STRING2); } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_PY_NUMBER); } else if (IsPyStringPrefix(sc.ch)) { int offset = 0; int prefix = GetPyStringPrefix(sc.ch); bool is_bytes = prefix == PyStringPrefix_Bytes; bool is_fmt = prefix == PyStringPrefix_Formatted; bool is_raw = prefix == PyStringPrefix_Raw; if (sc.chNext == '\"' || sc.chNext == '\'') { offset = 1; } else if (IsPyStringPrefix(sc.chNext) && (sc.GetRelative(2) == '\"' || sc.GetRelative(2) == '\'')) { prefix = GetPyStringPrefix(sc.chNext); offset = 2; is_bytes = (is_bytes && prefix == PyStringPrefix_Raw) || (is_raw && prefix == PyStringPrefix_Bytes); is_fmt = (is_fmt && prefix == PyStringPrefix_Raw) || (is_raw && prefix == PyStringPrefix_Formatted); is_raw = (is_raw && prefix != PyStringPrefix_Raw) || (!is_raw && prefix == PyStringPrefix_Raw); if (!(is_bytes || is_fmt || is_raw)) { --offset; sc.ForwardSetState(SCE_PY_IDENTIFIER); } } if (!offset) { sc.SetState(SCE_PY_IDENTIFIER); } else { sc.Forward(offset); if (sc.Match("\'\'\'")) { sc.ChangeState(GetPyStringStyle(3, is_raw, is_bytes, is_fmt)); sc.Forward(2); } else if (sc.Match("\"\"\"")) { sc.ChangeState(GetPyStringStyle(6, is_raw, is_bytes, is_fmt)); sc.Forward(2); } else if (sc.ch == '\'') { sc.ChangeState(GetPyStringStyle(1, is_raw, is_bytes, is_fmt)); } else if (sc.ch == '\"') { sc.ChangeState(GetPyStringStyle(2, is_raw, is_bytes, is_fmt)); } } } else if (iswordstart(sc.ch)) { sc.SetState(SCE_PY_IDENTIFIER); } else if (sc.ch == '@') { if (visibleChars == 1 && iswordstart(sc.chNext)) sc.SetState(SCE_PY_OPERATOR); else sc.SetState(SCE_PY_DECORATOR); } else if (isoperator(static_cast<char>(sc.ch)) || sc.ch == '`') { sc.SetState(SCE_PY_OPERATOR); if (defType > 0 && (sc.ch == '(' || sc.ch == ':')) defType = 0; } } // Handle line continuation generically. if (sc.ch == '\\') { if (sc.chNext == '\n' || sc.chNext == '\r') { sc.Forward(); if (sc.ch == '\r' && sc.chNext == '\n') { sc.Forward(); } continuationLine = true; continue; } } if (!(isspacechar(sc.ch) || IsSpaceEquiv(sc.state))) { visibleChars++; } continuationLine = false; } if (sc.state == SCE_PY_IDENTIFIER) goto _label_identifier; sc.Complete(); } #define IsCommentLine(line) IsLexCommentLine(line, styler, MultiStyle(SCE_PY_COMMENTLINE, SCE_PY_COMMENTBLOCK)) static inline bool IsQuoteLine(Sci_Position line, Accessor &styler) { int style = styler.StyleAt(styler.LineStart(line)); return IsPyTripleStyle(style); } static void FoldPyDoc(Sci_PositionU startPos, Sci_Position length, int, LexerWordList, Accessor &styler) { if (styler.GetPropertyInt("fold") == 0) return; const Sci_Position maxPos = startPos + length; const Sci_Position maxLines = (maxPos == styler.Length()) ? styler.GetLine(maxPos) : styler.GetLine(maxPos - 1); // Requested last line const Sci_Position docLines = styler.GetLine(styler.Length()); // Available last line // property fold.quotes.python // This option enables folding multi-line quoted strings when using the Python lexer. const bool foldQuotes = styler.GetPropertyInt("fold.quotes.python", 1) != 0; const bool foldCompact = styler.GetPropertyInt("fold.compact") != 0; // Backtrack to previous non-blank line so we can determine indent level // for any white space lines (needed esp. within triple quoted strings) // and so we can fix any preceding fold level (which is why we go back // at least one line in all cases) int spaceFlags = 0; Sci_Position lineCurrent = styler.GetLine(startPos); int indentCurrent = Accessor::LexIndentAmount(styler, lineCurrent, &spaceFlags, NULL); while (lineCurrent > 0) { lineCurrent--; indentCurrent = Accessor::LexIndentAmount(styler, lineCurrent, &spaceFlags, NULL); if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG) && (!IsCommentLine(lineCurrent)) && (!IsQuoteLine(lineCurrent, styler))) break; } int indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK; // Set up initial loop state startPos = styler.LineStart(lineCurrent); int prev_state = SCE_PY_DEFAULT; if (lineCurrent >= 1) prev_state = styler.StyleAt(startPos - 1); int prevQuote = foldQuotes && IsPyTripleStyle(prev_state); // Process all characters to end of requested range or end of any triple quote //that hangs over the end of the range. Cap processing in all cases // to end of document (in case of unclosed quote at end). while ((lineCurrent <= docLines) && ((lineCurrent <= maxLines) || prevQuote)) { // Gather info int lev = indentCurrent; Sci_Position lineNext = lineCurrent + 1; int indentNext = indentCurrent; int quote = false; if (lineNext <= docLines) { // Information about next line is only available if not at end of document indentNext = Accessor::LexIndentAmount(styler, lineNext, &spaceFlags, NULL); Sci_Position lookAtPos = (styler.LineStart(lineNext) == styler.Length()) ? styler.Length() - 1 : styler.LineStart(lineNext); int style = styler.StyleAt(lookAtPos); quote = foldQuotes && IsPyTripleStyle(style); } const int quote_start = (quote && !prevQuote); const int quote_continue = (quote && prevQuote); if (!quote || !prevQuote) indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK; if (quote) indentNext = indentCurrentLevel; if (indentNext & SC_FOLDLEVELWHITEFLAG) indentNext = SC_FOLDLEVELWHITEFLAG | indentCurrentLevel; if (quote_start) { // Place fold point at start of triple quoted string lev |= SC_FOLDLEVELHEADERFLAG; } else if (quote_continue || prevQuote) { // Add level to rest of lines in the string lev = lev + 1; } // Skip past any blank lines for next indent level info; we skip also // comments (all comments, not just those starting in column 0) // which effectively folds them into surrounding code rather // than screwing up folding. If comments end file, use the min // comment indent as the level after int minCommentLevel = indentCurrentLevel; while (!quote && (lineNext < docLines) && ((indentNext & SC_FOLDLEVELWHITEFLAG) || (lineNext <= docLines && IsCommentLine(lineNext)))) { if (IsCommentLine(lineNext) && indentNext < minCommentLevel) { minCommentLevel = indentNext; } lineNext++; indentNext = Accessor::LexIndentAmount(styler, lineNext, &spaceFlags, NULL); } const int levelAfterComments = ((lineNext < docLines) ? indentNext & SC_FOLDLEVELNUMBERMASK : minCommentLevel); const int levelBeforeComments = std::max(indentCurrentLevel, levelAfterComments); // Now set all the indent levels on the lines we skipped // Do this from end to start. Once we encounter one line // which is indented more than the line after the end of // the comment-block, use the level of the block before Sci_Position skipLine = lineNext; int skipLevel = levelAfterComments; while (--skipLine > lineCurrent) { int skipLineIndent = Accessor::LexIndentAmount(styler, skipLine, &spaceFlags, NULL); if (foldCompact) { if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments) skipLevel = levelBeforeComments; int whiteFlag = skipLineIndent & SC_FOLDLEVELWHITEFLAG; styler.SetLevel(skipLine, skipLevel | whiteFlag); } else { if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments && !(skipLineIndent & SC_FOLDLEVELWHITEFLAG) && !IsCommentLine(skipLine)) skipLevel = levelBeforeComments; styler.SetLevel(skipLine, skipLevel); } } // Set fold header on non-quote line if (!quote && !(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) lev |= SC_FOLDLEVELHEADERFLAG; } // Keep track of triple quote state of previous line prevQuote = quote; // Set fold level for this line and move to next line styler.SetLevel(lineCurrent, foldCompact ? lev : lev & ~SC_FOLDLEVELWHITEFLAG); indentCurrent = indentNext; lineCurrent = lineNext; } // NOTE: Cannot set level of last line here because indentCurrent doesn't have // header flag set; the loop above is crafted to take care of this case! //styler.SetLevel(lineCurrent, indentCurrent); } LexerModule lmPython(SCLEX_PYTHON, ColourisePyDoc, "python", FoldPyDoc);
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Manuela Hutter (manuelah) */ #include "core/pch.h" #include "adjunct/quick_toolkit/widgets/QuickDropDown.h" /*virtual*/ QuickDropDown::~QuickDropDown() { GetOpWidget()->SetItemAddedHandler(NULL); } /*virtual*/ OP_STATUS QuickDropDown::Init() { RETURN_IF_ERROR(QuickEditableTextWidgetWrapper<DesktopOpDropDown>::Init()); GetOpWidget()->SetItemAddedHandler( MAKE_DELEGATE(*this, &QuickDropDown::OnItemAdded)); return OpStatus::OK; }
#pragma once #include "entity/entity.h" #include "component/component.h" namespace component { struct PosComponentDesc : public ComponentDesc { D3DXVECTOR3 position; D3DXVECTOR3 rotation; D3DXVECTOR3 scale; string parentName; PosComponentDesc() : position(0.0, 0.0, 0.0), rotation(0.0, 0.0, 0.0), scale(1.0, 1.0, 1.0) {} }; class PosComponent : public Component { public: // typedefs typedef PosComponentDesc desc_type; typedef function<void(D3DXMATRIX&, const D3DXMATRIX&)> get_set_type; // constructor/destructor PosComponent(entity::Entity* entity, const string& name, const desc_type& desc); ~PosComponent(); // overloads int getType() { return POSCOMPONENT; } void acquire(); void release(); // methods virtual void setPos(const D3DXVECTOR3& new_pos); virtual D3DXVECTOR3 getPos(); virtual void setRot(const D3DXVECTOR3& new_rot); virtual void setRot(const D3DXQUATERNION& new_rot); virtual D3DXVECTOR3 getRot(); virtual D3DXQUATERNION getRotQuat(); virtual void setScale(const D3DXVECTOR3& new_scale); virtual D3DXVECTOR3 getScale(); virtual void setTransform(const D3DXMATRIX& new_transform); virtual D3DXMATRIX getTransform(); get_set_type setSetFunction(const get_set_type& setter); get_set_type setGetFunction(const get_set_type& getter); // properties ComponentLink<PosComponent> parent; static ScriptedObject::ScriptClass m_scriptClass; protected: // script functions JSObject* createScriptObject(); void destroyScriptObject(); // members D3DXMATRIX m_transform; get_set_type m_getter; get_set_type m_setter; }; }
#include <iostream> #include <cmath> #include <emscripten.h> #include <emscripten/bind.h> #include <emscripten/val.h> #include "vendor/entt/entt.hpp" #include "main.h" #include "scene/Scene.cpp" EMSCRIPTEN_KEEPALIVE int add(int a, int b) { return a + b; } EMSCRIPTEN_KEEPALIVE int sub(int a, int b) { return a - b; } EMSCRIPTEN_KEEPALIVE int mul(int a, int b) { return a * b; } EMSCRIPTEN_KEEPALIVE int divi(int a, int b) { return a / b; } EMSCRIPTEN_KEEPALIVE int mod(int a, int b) { return a % b; } struct Player { float xpos; float ypos; void moveUp() { ypos--; } void moveDown() { ypos++; } void moveLeft() { xpos--; } void moveRight() { xpos++; } // move up right void moveUpRight() { xpos++; ypos--; } // move up left void moveUpLeft() { xpos--; ypos--; } // move down right void moveDownRight() { xpos++; ypos++; } // move down left void moveDownLeft() { xpos--; ypos++; } }; enum class Move{ STATIONARY = 0, UP, DOWN, LEFT, RIGHT, UP_RIGHT, UP_LEFT, DOWN_RIGHT, DOWN_LEFT }; struct GameState { Player player{100, 100}; Move move = Move::STATIONARY; }; struct Vector2 { float x; float y; }; //generate middle point between two vectors Vector2 middlePoint(Vector2 a, Vector2 b) { Vector2 result; result.x = (a.x + b.x) / 2; result.y = (a.y + b.y) / 2; return result; } //generate distance between two vectors float distance(Vector2 a, Vector2 b) { float x = a.x - b.x; float y = a.y - b.y; return sqrt(x * x + y * y); } GameState createInitialGameState(){ DrawMe(600, 800, 10, 10); return GameState{}; } GameState updatePosition(GameState gameState) { if (gameState.move == Move::UP) { gameState.player.moveUp(); } if (gameState.move == Move::DOWN) { gameState.player.moveDown(); } if (gameState.move == Move::LEFT) { gameState.player.moveLeft(); } if (gameState.move == Move::RIGHT) { gameState.player.moveRight(); } if (gameState.move == Move::UP_RIGHT) { gameState.player.moveUpRight(); } if (gameState.move == Move::UP_LEFT) { gameState.player.moveUpLeft(); } if (gameState.move == Move::DOWN_RIGHT) { gameState.player.moveDownRight(); } if (gameState.move == Move::DOWN_LEFT) { gameState.player.moveDownLeft(); } return gameState; } int main() { Scene scene; std::cout << "Scene is here: Player: "<< scene.player.Transform.x << " - " << scene.player.Transform.y <<std::endl; printMeSoldo(1000, false, 2.0f); CallMe(true); // EM_ASM(Loaded()); Stringolo(65); return 0; } EMSCRIPTEN_BINDINGS(gameState) { emscripten::value_object<Player>("Player") .field("xpos", &Player::xpos) .field("ypos", &Player::ypos) ; emscripten::enum_<Move>("Move") .value("STATIONARY", Move::STATIONARY) .value("UP", Move::UP) .value("DOWN", Move::DOWN) .value("LEFT", Move::LEFT) .value("RIGHT", Move::RIGHT) .value("UP_RIGHT", Move::UP_RIGHT) .value("UP_LEFT", Move::UP_LEFT) .value("DOWN_RIGHT", Move::DOWN_RIGHT) .value("DOWN_LEFT", Move::DOWN_LEFT); emscripten::value_object<GameState>("GameState") .field("player", &GameState::player) .field("move", &GameState::move); emscripten::value_object<Vector2>("Vector2") .field("x", &Vector2::x) .field("y", &Vector2::y); emscripten::function("distance", &distance); emscripten::function("middlePoint", &middlePoint); emscripten::function("updatePosition", &updatePosition); emscripten::function("createInitialGameState", &createInitialGameState); }
#pragma once #include <string> #include <algorithm> using namespace std; string longestPalindrome_violence(string s) { int maxlen = 0; string maxstr; int len = s.size(); for (int i = 0; i < len; ++i) { for (int j = i; j < len; ++j) { bool is_palindrome = true; int sub_len = j - i + 1; for (int k = 0; k < sub_len / 2; ++k) { if (s[i + k] != s[i + sub_len - k - 1]) { is_palindrome = false; break; } } if (is_palindrome) { if (sub_len > maxlen) { maxstr = s.substr(i, j - i + 1); maxlen = sub_len; } } } } return maxstr; } int palindrome_expand(string& s, int left, int right) { int len = s.size(); while (left >= 0 && right < len && s[left] == s[right]) { left--; right++; } return right - left - 1; } string longestPalindrome_middleExpand(string s) { int str_len = s.size(); int max_len = 0; int max_start = 0; int max_end = 0; for (int i = 0; i < str_len; ++i) { int palindrome_len1 = palindrome_expand(s, i, i); int palindrome_len2 = palindrome_expand(s, i, i + 1); int len = std::max(palindrome_len1, palindrome_len2); if (len > max_len) { max_len = len; if (len % 2 == 0) max_start = i - len / 2 + 1; else max_start = i - len / 2; max_end = i + len / 2; } } return s.substr(max_start, max_end - max_start + 1); }
#include <iostream> #include<string> #include<stdio.h> #include<vector> #include<conio.h> using namespace std; class Ngay { private: int ngay,thang,nam; public: void Input_ngay(); void out_ngay(); }; void Ngay::Input_ngay() { do { cout<"\n Nhap Ngay:"; cin>>ngay; if(ngay<0||ngay>31) { cout<<"\n Ngay Khong Hop Le!"; } } while(ngay<0||ngay>31); do { cout<<"\n Nhap Thang:"; cin>>thang; if(thang<0||thang>12) { cout<<"\n Thang Khong Hop LE!"; } } while(thang<0||thang>12); do { cout<<"\n Nhap Nam:\t"; cin>>nam; if(nam<0) { cout<<"\n Nam Khong HOp LE!"; } } while(nam<0); } void Ngay::out_ngay() { cout<<" Ngay "<<ngay<<" Thang "<<thang<<" Nam "<<nam; } class sinhvien { private: string Maso,Hoten,Lop; Ngay Ngaysinh; int SCMND; double DiemChuyenNganh; public: void Input_sv(); void Out_sv(); double DiemCN(); string Ten() { return Hoten; } }; double sinhvien::DiemCN() { return DiemChuyenNganh; } void sinhvien::Input_sv() { fflush(stdin); cout<<"\n Nhap vao Ho Ten:"; getline(cin,Hoten); fflush(stdin); cout<<"\n Nhap vao Ma so:"; getline(cin,Maso); fflush(stdin); cout<<"\n Nhap vao Lop Hoc:"; getline(cin,Lop); cout<<"\n Nhap So CMND:"; cin>>SCMND; cout<<"\n------ Ngay Sinh-----\n"; Ngaysinh.Input_ngay(); do { cout<<"\n Nhap Diem Chuyen Nganh IT:"; cin>>DiemChuyenNganh; if(DiemChuyenNganh<0||DiemChuyenNganh>10) { cout<<"\n Diem Chuyen Nganh Khong Hop LE!"; } }while(DiemChuyenNganh<0||DiemChuyenNganh>10); } void sinhvien::Out_sv() { cout<<"\n Ho Ten:"<<Hoten; cout<<"\n Ma so:"<<Maso; cout<<"\n LOP :"<<Lop; cout<<"\n So CMND:"<<SCMND; cout<<"\n Sinh Ngay:"; Ngaysinh.out_ngay(); cout<<"\n Diem Chuyen Nganh:\t"<<DiemChuyenNganh; } class Lop { private: vector<sinhvien> arr; vector<sinhvien> Mangnew; public: void Input_Lop(); void Out_Lop(); double Max_Chuyennganh(); void Sinhvien_Good(); }; void Lop::Input_Lop() { char Kitu; do { cout<<"\n **********Menu***********\n"; cout<<"\n Keydown ('0') To sTop"; cout<<"\n------------------------------\n"; Kitu=getch(); if(Kitu!='0') { sinhvien x; x.Input_sv(); arr.push_back(x); cout<<"\n OK!"; } }while(Kitu!='0'); } void Lop::Out_Lop() { int Size=arr.size(); for(int i=0;i<Size;i++) { cout<<"\n***Sinh vien "<<i+1<<"*****\n"; arr[i].Out_sv(); } } double Lop::Max_Chuyennganh() { double Max=arr[0].DiemCN(); for(int i=1;i<arr.size();i++) { double Temp=arr[i].DiemCN(); if(Temp>Max) { Max=Temp; } } return Max; } //Ham Hoan vi O ngoai template<class T> void Hoanvi(T &a, T &b ) { T Temp=a; a=b; b=Temp; } void Lop::Sinhvien_Good() { double Max_cn=Max_Chuyennganh(); int Size=arr.size(); for(int i=0;i<Size;i++) { if(Max_cn==arr.at(i).DiemCN()) { Mangnew.push_back(arr[i]); } } //Sap xep int Size_Mangnew=Mangnew.size(); if(Size_Mangnew==1) { Mangnew[0].Out_sv(); } else { for(int i=0;i<Size_Mangnew-1;i++) { for(int j=i+1;j<Size_Mangnew;j++) { if(Mangnew[i].Ten()>Mangnew[j].Ten()) { Hoanvi<sinhvien>(Mangnew[i],Mangnew[j]); } } } for(int i=0;i<Size_Mangnew;i++) { Mangnew[i].Out_sv(); } } } int main() { Lop lp; lp.Input_Lop(); lp.Out_Lop(); cout<<"\n***Sinh vien Uu Tu****\n"; lp.Sinhvien_Good(); return 0; } #include <iostream> #include<string> #include<stdio.h> #include<vector> #include<conio.h> using namespace std; class Ngay { private: int ngay,thang,nam; public: void Input_ngay(); void out_ngay(); }; void Ngay::Input_ngay() { do { cout<"\n Nhap Ngay:"; cin>>ngay; if(ngay<0||ngay>31) { cout<<"\n Ngay Khong Hop Le!"; } } while(ngay<0||ngay>31); do { cout<<"\n Nhap Thang:"; cin>>thang; if(thang<0||thang>12) { cout<<"\n Thang Khong Hop LE!"; } } while(thang<0||thang>12); do { cout<<"\n Nhap Nam:\t"; cin>>nam; if(nam<0) { cout<<"\n Nam Khong HOp LE!"; } } while(nam<0); } void Ngay::out_ngay() { cout<<" Ngay "<<ngay<<" Thang "<<thang<<" Nam "<<nam; } class sinhvien { private: string Maso,Hoten,Lop; Ngay Ngaysinh; int SCMND; double DiemChuyenNganh; public: void Input_sv(); void Out_sv(); double DiemCN(); string Ten() { return Hoten; } }; double sinhvien::DiemCN() { return DiemChuyenNganh; } void sinhvien::Input_sv() { fflush(stdin); cout<<"\n Nhap vao Ho Ten:"; getline(cin,Hoten); fflush(stdin); cout<<"\n Nhap vao Ma so:"; getline(cin,Maso); fflush(stdin); cout<<"\n Nhap vao Lop Hoc:"; getline(cin,Lop); cout<<"\n Nhap So CMND:"; cin>>SCMND; cout<<"\n------ Ngay Sinh-----\n"; Ngaysinh.Input_ngay(); do { cout<<"\n Nhap Diem Chuyen Nganh IT:"; cin>>DiemChuyenNganh; if(DiemChuyenNganh<0||DiemChuyenNganh>10) { cout<<"\n Diem Chuyen Nganh Khong Hop LE!"; } }while(DiemChuyenNganh<0||DiemChuyenNganh>10); } void sinhvien::Out_sv() { cout<<"\n Ho Ten:"<<Hoten; cout<<"\n Ma so:"<<Maso; cout<<"\n LOP :"<<Lop; cout<<"\n So CMND:"<<SCMND; cout<<"\n Sinh Ngay:"; Ngaysinh.out_ngay(); cout<<"\n Diem Chuyen Nganh:\t"<<DiemChuyenNganh; } class Lop { private: vector<sinhvien> arr; vector<sinhvien> Mangnew; public: void Input_Lop(); void Out_Lop(); double Max_Chuyennganh(); void Sinhvien_Good(); }; void Lop::Input_Lop() { char Kitu; do { cout<<"\n **********Menu***********\n"; cout<<"\n Keydown ('0') To sTop"; cout<<"\n------------------------------\n"; Kitu=getch(); if(Kitu!='0') { sinhvien x; x.Input_sv(); arr.push_back(x); cout<<"\n OK!"; } }while(Kitu!='0'); } void Lop::Out_Lop() { int Size=arr.size(); for(int i=0;i<Size;i++) { cout<<"\n***Sinh vien "<<i+1<<"*****\n"; arr[i].Out_sv(); } } double Lop::Max_Chuyennganh() { double Max=arr[0].DiemCN(); for(int i=1;i<arr.size();i++) { double Temp=arr[i].DiemCN(); if(Temp>Max) { Max=Temp; } } return Max; } //Ham Hoan vi O ngoai template<class T> void Hoanvi(T &a, T &b ) { T Temp=a; a=b; b=Temp; } void Lop::Sinhvien_Good() { double Max_cn=Max_Chuyennganh(); int Size=arr.size(); for(int i=0;i<Size;i++) { if(Max_cn==arr.at(i).DiemCN()) { Mangnew.push_back(arr[i]); } } //Sap xep int Size_Mangnew=Mangnew.size(); if(Size_Mangnew==1) { Mangnew[0].Out_sv(); } else { for(int i=0;i<Size_Mangnew-1;i++) { for(int j=i+1;j<Size_Mangnew;j++) { if(Mangnew[i].Ten()>Mangnew[j].Ten()) { Hoanvi<sinhvien>(Mangnew[i],Mangnew[j]); } } } for(int i=0;i<Size_Mangnew;i++) { Mangnew[i].Out_sv(); } } } int main() { Lop lp; lp.Input_Lop(); lp.Out_Lop(); cout<<"\n***Sinh vien Uu Tu****\n"; lp.Sinhvien_Good(); return 0; }
#ifndef _MSG_0X07_USEENTITY_CTS_H_ #define _MSG_0X07_USEENTITY_CTS_H_ #include "mcprotocol_base.h" namespace MC { namespace Protocol { namespace Msg { class UseEntity : public BaseMessage { public: UseEntity(); UseEntity(int32_t _user, int32_t _target, bool _button); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); int32_t getUser() const; int32_t getTarget() const; bool getButton() const; void setUser(int32_t _val); void setTarget(int32_t _val); void setButton(bool _val); private: int32_t _pf_user; int32_t _pf_target; bool _pf_button; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG_0X07_USEENTITY_CTS_H_
// Created on: 2001-12-20 // Created by: Pavel TELKOV // Copyright (c) 2001-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ShapeCustom_Curve2d_HeaderFile #define _ShapeCustom_Curve2d_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TColgp_Array1OfPnt2d.hxx> class Geom2d_Line; class Geom2d_Curve; class Geom2d_BSplineCurve; //! Converts curve2d to analytical form with given //! precision or simpify curve2d. class ShapeCustom_Curve2d { public: DEFINE_STANDARD_ALLOC //! Check if poleses is in the plane with given precision //! Returns false if no. Standard_EXPORT static Standard_Boolean IsLinear (const TColgp_Array1OfPnt2d& thePoles, const Standard_Real theTolerance, Standard_Real& theDeviation); //! Try to convert BSpline2d or Bezier2d to line 2d //! only if it is linear. Recalculate first and last parameters. //! Returns line2d or null curve2d. Standard_EXPORT static Handle(Geom2d_Line) ConvertToLine2d (const Handle(Geom2d_Curve)& theCurve, const Standard_Real theFirstIn, const Standard_Real theLastIn, const Standard_Real theTolerance, Standard_Real& theNewFirst, Standard_Real& theNewLast, Standard_Real& theDeviation); //! Try to remove knots from bspline where local derivatives are the same. //! Remove knots with given precision. //! Returns false if Bsplien was not modified Standard_EXPORT static Standard_Boolean SimplifyBSpline2d (Handle(Geom2d_BSplineCurve)& theBSpline2d, const Standard_Real theTolerance); protected: private: }; #endif // _ShapeCustom_Curve2d_HeaderFile
#include<stdio.h> int a,b,max=0; main() { scanf("%d",&a); while(a!=0) { b=a%10; a=a/10; if(b>max) { max=b; } } printf("%d",max); }
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; #define N 11111 #define M 222222 bool mark[N][33]; int kk, xx[N], yy[M], pp[M], ord[N], ordn = 0; bool was[N]; int n, m, k, vmark[N], x, y; char task[M]; bool superv[N]; vector<int> g[N]; void dfs(int x) { was[x] = true; for (int i = xx[x]; i; i = pp[i]) if ( (i & 1) == 1 && !was[yy[i]]) dfs(yy[i]); ord[ordn++] = x; } void dfs2(int x, int markx, int markb) { if (!mark[x][markb]) { superv[markx] = false; } vmark[x] = markx; was[x] = true; for (int i = xx[x]; i; i = pp[i]) if ( (i & 1) == 0 && !was[yy[i]]) dfs2(yy[i], markx, markb); } void dfs3(int x) { was[x] = true; // cerr << x << endl; for (int i = 0; i < g[x].size(); i++) { if (!was[g[x][i]]) { dfs3(g[x][i]); } // cerr << "\t" << g[x][i] << endl; superv[x] &= superv[ g[x][i] ]; } ord[ordn++] = x; } int main() { freopen("kripke.in", "r", stdin); freopen("kripke.out", "w", stdout); scanf("%d%d%d", &n, &m, &k); for (int i = 1; i <= n; i++) { int c; char ch; scanf("%d", &c); for (int j = 0; j < c; ++j) { scanf(" %c", &ch); mark[i][ch - 'a'] = true; } } for (int i = 0; i < m; i++) { scanf("%d%d\n", &x, &y); yy[++kk] = y; pp[kk] = xx[x]; xx[x] = kk; yy[++kk] = x; pp[kk] = xx[y]; xx[y] = kk; } int marka = -1, markb = -1; cin >> task; for (int j = 0; task[j]; ++j) if (task[j] >= 'a') { if (marka == -1) marka = task[j] - 'a';else markb = task[j] - 'a'; } memset(was, 0, sizeof(was)); for (int i = 1; i <= n; i++) if (!was[i]) dfs(i); memset(was, 0, sizeof(was)); memset(superv, 0, sizeof(superv)); int it = 0; for (int i = 1; i <= n; i++) if (!was[ ord[ordn - i] ]) { superv[++it] = true; dfs2(ord[ordn - i], it, markb); } // for (int i = 1; i <= n; i++) cerr << vmark[i] << " "; // cerr << endl; for (int i = 1; i <= n; i++) for (int j = xx[i]; j; j = pp[j]) if ( (j & 1) == 1 ) { if (vmark[i] != vmark[ yy[j] ]) { g[vmark[i]].push_back(vmark[ yy[j] ]); // cerr << vmark[i] << " " << vmark[yy[j]] << endl; } } ordn = 0; memset(was, 0, sizeof(was)); for (int i = 1; i <= it; i++) if (!was[i]) dfs3(i); memset(was, 0, sizeof(was)); queue<int> q; vector<int> ans; for (int i = 1; i <= n; i++) if (superv[vmark[i]]) { q.push(i); was[i] = true; } while (!q.empty()) { int x = q.front(); q.pop(); ans.push_back(x); for (int i = xx[x]; i; i = pp[i]) if ( (i&1) == 0 && !was[yy[i]] && mark[yy[i]][marka] == true) { q.push(yy[i]); was[yy[i]] = true; } } printf("%d\n", ans.size()); sort(ans.begin(), ans.end()); for (int i = 0; i < ans.size(); i++) printf("%d\n", ans[i]); return 0; }
 // DBServerDlg.cpp: 구현 파일 // #include "pch.h" #include "framework.h" #include "DBServer.h" #include "DBServerDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 응용 프로그램 정보에 사용되는 CAboutDlg 대화 상자입니다. class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 대화 상자 데이터입니다. #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다. // 구현입니다. protected: DECLARE_MESSAGE_MAP() // afx_msg LRESULT OnClientMsgRecv(WPARAM wParam, LPARAM lParam); // afx_msg LRESULT OnClientClose(WPARAM wParam, LPARAM lParam); }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) // ON_MESSAGE(WM_CLIENT_MSG_RECV, &CAboutDlg::OnClientMsgRecv) // ON_MESSAGE(WM_CLIENT_CLOSE, &CAboutDlg::OnClientClose) END_MESSAGE_MAP() // CDBServerDlg 대화 상자 CDBServerDlg::CDBServerDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DBSERVER_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CDBServerDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST_DBLIST, m_listDbAcc); DDX_Control(pDX, IDC_LIST_CLILIST, m_list_Client); DDX_Control(pDX, IDC_LIST_CLIMSG, m_list_MSG); } BEGIN_MESSAGE_MAP(CDBServerDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_MESSAGE(WM_ACCEPT_SOCKET, &CDBServerDlg::OnAcceptSocket) ON_MESSAGE(WM_CLIENT_MSG_RECV, &CDBServerDlg::OnClientMsgRecv) ON_MESSAGE(WM_CLIENT_CLOSE, &CDBServerDlg::OnClientClose) ON_MESSAGE(WM_CLIENT_LOGON, &CDBServerDlg::OnClientLogon) END_MESSAGE_MAP() // CDBServerDlg 메시지 처리기 BOOL CDBServerDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 시스템 메뉴에 "정보..." 메뉴 항목을 추가합니다. // IDM_ABOUTBOX는 시스템 명령 범위에 있어야 합니다. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 이 대화 상자의 아이콘을 설정합니다. 응용 프로그램의 주 창이 대화 상자가 아닐 경우에는 // 프레임워크가 이 작업을 자동으로 수행합니다. SetIcon(m_hIcon, TRUE); // 큰 아이콘을 설정합니다. SetIcon(m_hIcon, FALSE); // 작은 아이콘을 설정합니다. // TODO: 여기에 추가 초기화 작업을 추가합니다. CRect rect; m_listDbAcc.GetClientRect(rect); m_listDbAcc.InsertColumn(0, _T("사용자ID"), LVCFMT_CENTER, rect.Width() * 0.33); m_listDbAcc.InsertColumn(1, _T("사용자PW"), LVCFMT_CENTER, rect.Width() * 0.33); m_listDbAcc.InsertColumn(2, _T("닉 네 임"), LVCFMT_CENTER, rect.Width()*0.33 ); //DB_CONNECT MYSQL conn; CString szConnectMsg; const CString db_TableName = _T("user_account"); CString Query; MYSQL_RES * sqlResult; MYSQL_ROW sqlRow; mysql_init(&conn); if (mysql_real_connect(&conn, DB_HOST, DB_UID, DB_UPW, DB_SCHEMA, DB_PORT, NULL, 0) == NULL) { szConnectMsg.Format(_T("ERROR : DB CONNECT IS FAIL")); AfxMessageBox(szConnectMsg); TRACE(szConnectMsg); return FALSE; } else { //mysql_query(&conn, _T("set names euckr")); } Query.Format(_T("SELECT * FROM %s.%s;"),DB_SCHEMA,db_TableName); //int status = 0; if (mysql_query(&conn, Query) != 0) { szConnectMsg.Format(_T("ERROR(%d) : Query is Failed\nSEND>\n%s\nQUERY>\n"), mysql_errno(&conn),Query,mysql_error(&conn)); AfxMessageBox(szConnectMsg); TRACE(szConnectMsg); return FALSE; } sqlResult = mysql_store_result(&conn); int row = 0; while ((sqlRow = mysql_fetch_row(sqlResult)) != NULL) { m_listDbAcc.InsertItem(row,sqlRow[0]); m_listDbAcc.SetItemText(row, 1, sqlRow[1]); m_listDbAcc.SetItemText(row, 2, sqlRow[2]); row++; } m_pServerSock = new CServerSocket; m_pServerSock->SetWnd(this->m_hWnd); m_pServerSock->Create(SERVER_PORT_0); m_pServerSock->Listen(); mysql_free_result(sqlResult); mysql_close(&conn); return TRUE; // 포커스를 컨트롤에 설정하지 않으면 TRUE를 반환합니다. } void CDBServerDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 대화 상자에 최소화 단추를 추가할 경우 아이콘을 그리려면 // 아래 코드가 필요합니다. 문서/뷰 모델을 사용하는 MFC 애플리케이션의 경우에는 // 프레임워크에서 이 작업을 자동으로 수행합니다. void CDBServerDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 그리기를 위한 디바이스 컨텍스트입니다. SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 클라이언트 사각형에서 아이콘을 가운데에 맞춥니다. int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 아이콘을 그립니다. dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } // 사용자가 최소화된 창을 끄는 동안에 커서가 표시되도록 시스템에서 // 이 함수를 호출합니다. HCURSOR CDBServerDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } afx_msg LRESULT CDBServerDlg::OnAcceptSocket(WPARAM wParam, LPARAM lParam) { CString str; m_pClientSock = (CClientSocket*)lParam; m_ptrClientList.AddTail(m_pClientSock); str.Format(_T("Client (%d)"), int(m_pClientSock)); m_list_Client.InsertString(-1, str); m_pClientSock = NULL; delete m_pClientSock; return 0; } afx_msg LRESULT CDBServerDlg::OnClientMsgRecv(WPARAM wParam, LPARAM lParam) { CString message = (LPCSTR)lParam; POSITION pos = m_ptrClientList.GetHeadPosition(); while (pos != NULL) { CClientSocket* pClient = (CClientSocket*)m_ptrClientList.GetNext(pos); if (pClient != NULL) { #ifdef _UNICODE pClient->Send(message, message.GetLength() * 2); #else pClient->Send(message, message.GetLength() * 3); #endif } } m_list_MSG.InsertString(-1, message); m_list_MSG.SetCurSel(m_list_MSG.GetCurSel() - 1); return 0; } afx_msg LRESULT CDBServerDlg::OnClientClose(WPARAM wParam, LPARAM lParam) { CClientSocket* pClient = (CClientSocket*)lParam; CString str; UINT idx = 0; POSITION pos = m_ptrClientList.Find(pClient); if (pos != NULL) { str.Format(_T("Client (%d)"), (int)pClient); idx = m_list_Client.SelectString(-1, str); m_list_Client.DeleteString(idx); m_ptrClientList.RemoveAt(pos); } return 0; } afx_msg LRESULT CDBServerDlg::OnClientLogon(WPARAM wParam, LPARAM lParam) { CString UID; int UPW = 0; //"ID PW" LPCTSTR Msg = (LPCTSTR)lParam; _stscanf_s(Msg, _T("%[^\t]%*c%d"), UID ,1024,&UPW); CString form; CTime currTime = CTime::GetCurrentTime(); form.Format(_T("[%d-%02d-%02d %02d:%02d:%02d]::ID <%s> PW <%d> 가 로그인을 시도했습니다."), currTime.GetYear(), currTime.GetMonth(), currTime.GetDay(), currTime.GetHour(), currTime.GetMinute(), currTime.GetSecond(), UID, UPW ); m_list_MSG.InsertString(-1,form); m_list_MSG.SetCurSel(m_list_MSG.GetCurSel() - 1); return 0; }
#pragma once class GameCursor; class Fade; class ReturnButton; class DungeonSelect : public GameObject { public: bool Start() override; void Update() override; void OnDestroy() override; private: void CheckDungeonClearState(); void InitDungeonButtons(); void InitSideButtons(); void InitBackButton(); void PositionUpdate(); void NextSpAnimation(); void DungeonSelectClick(); void StartDungeon(); void BackToMenu(); int m_clearedDunNum = -1; std::map<SpriteRender*, int> m_dungeonButton; std::vector<SpriteRender*> m_sps; std::vector<FontRender*> m_fonts; SpriteRender* m_nextSp = nullptr; SpriteRender* m_backSp = nullptr; SpriteRender* m_rightSp = nullptr; SpriteRender* m_leftSp = nullptr; SpriteRender* m_wallpaper = nullptr; CVector2 m_fPivot = { 0.5f,0.5f }; GameCursor* m_cur = nullptr; FontRender* m_backTx = nullptr; CVector3 addPos = CVector3::Zero(); Fade* m_fade = nullptr; const CVector4 m_notYetClearCol = { 0.5,0.5f,0.5f,1.f }; const CVector4 m_ClearCol = CVector4::White; const int m_numDungeon = 8; const float m_spaceToNextSprite = 800.f; const float SPRITE_W = 400.f; const float SPRITE_H = 400.f; const CVector2 m_toFixMisalignment = { -150.f, -200.f }; bool m_isPositionUpdating = false; bool m_isfade = false; bool m_backfade = false; bool m_isChanged = false; int m_selectedNum = 1; int dunNum = 0; ReturnButton* m_returnButton = nullptr; //–ß‚éƒ{ƒ^ƒ“ };
#include "color.h" Color::Color() { } Color::Color(int _r, int _g, int _b, int _a) { r = _r; g = _g; b = _b; a = _a; } Color::Color(glm::vec4 color) { r = color.r; g = color.g; b = color.b; a = color.a; } Color::~Color(){ }
#include<iostream> #include<cstdlib> using namespace std; typedef struct node* ref; struct node{ int key; ref next; }; ref get(int k){ ref p; p=new node; if(p==NULL) exit(0); p->key=k; p->next=NULL; return p; } void addlast(ref &head, ref &tail, int k){ ref p=get(k); if(head==NULL){ head=tail=p; } else{ tail->next=p; tail=p; } } void nhap(ref &head, ref &tail, int n){ int k; for(int i = 0; i < n; i++){ cin>>k; addlast(head,tail,k); } } void xuly(ref &head, ref &tail, int t){ if(head==NULL) return; ref p; for(int i=0;i<t;i++){ p=head; head=head->next; tail->next=p; tail=p; tail->next=NULL; } } void duyet(ref head){ ref p; if(head==NULL) return; for(p = head; p ; p = p->next) cout<<p->key<<" "; } void destroy(ref &head){ ref p; while(head){ p=head; head=head->next; delete p; } } int main(){ ref head=NULL,tail=NULL; int n,t; cin>>n>>t; nhap(head,tail,n); // duyet(head);cout<<endl; xuly(head,tail,t); duyet(head); destroy(head); return 0; }
/** * @file adaptor.cpp * @brief * @author kevin20x2@gmail.com * @version 1.0 * @date 2018-12-17 */ #include "adaptor.hpp" #include "fs/inode.hpp" namespace kvfs{ using namespace rocksdb; const std::string RocksDBAdaptor ::default_DBpath = "/tmp/rocksdb"; RocksDBAdaptor :: RocksDBAdaptor(): inited_(false){ //default options } int RocksDBAdaptor::SetOptions(const Options & op){ options_ = op; return 0; } Status RocksDBAdaptor :: Init(const std::string & path){ Options option; option.IncreaseParallelism(); //option.OptimizeLevelStyleCompaction(); option.create_if_missing = true; if( path == "") { KVFS_LOG("RocksDBAdaptor : use default path\n"); Status s = DB::Open(option,default_DBpath,&db_); KVFS_LOG("status : %s",s.ToString().c_str()); assert(s.ok()); return s; } else { KVFS_LOG("RocksDBAdaptor : use path %s\n",path.c_str()); Status s = DB::Open(option,path,&db_); KVFS_LOG(s.ToString().c_str()); assert(s.ok()); return s; } } Status RocksDBAdaptor :: Delete(const std::string & key ) { auto s = db_->Delete(WriteOptions(),key); return s; } Status RocksDBAdaptor :: Put(const Slice & key , const Slice & value) { // default write options Status s = db_->Put(WriteOptions(),key,value); return s; } Status RocksDBAdaptor :: Get(const std::string & key,std::string * value) { Status s = db_->Get(ReadOptions(),key,value); return s; } Status RocksDBAdaptor ::Sync() { WriteOptions option; option.sync = true; Status s = db_->Put(option,"sync",""); return s; } Status RocksDBAdaptor :: PutFileMetaData(const char * path){ } }
// Created on: 2002-01-16 // Created by: Michael PONIKAROV // Copyright (c) 2002-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TDataStd_ExtStringArray_HeaderFile #define _TDataStd_ExtStringArray_HeaderFile #include <Standard.hxx> #include <TColStd_HArray1OfExtendedString.hxx> #include <TDF_Attribute.hxx> #include <Standard_Integer.hxx> #include <Standard_OStream.hxx> #include <Standard_GUID.hxx> class TDF_Label; class TCollection_ExtendedString; class TDF_RelocationTable; class TDF_DeltaOnModification; class TDataStd_ExtStringArray; DEFINE_STANDARD_HANDLE(TDataStd_ExtStringArray, TDF_Attribute) //! ExtStringArray Attribute. Handles an array of UNICODE strings (represented by the TCollection_ExtendedString class). class TDataStd_ExtStringArray : public TDF_Attribute { friend class TDataStd_DeltaOnModificationOfExtStringArray; DEFINE_STANDARD_RTTIEXT(TDataStd_ExtStringArray, TDF_Attribute) public: //! class methods //! ============= //! Returns the GUID for the attribute. Standard_EXPORT static const Standard_GUID& GetID(); //! Finds, or creates, an ExtStringArray attribute with <lower> //! and <upper> bounds on the specified label. //! If <isDelta> == False, DefaultDeltaOnModification is used. //! If <isDelta> == True, DeltaOnModification of the current attribute is used. //! If attribute is already set, all input parameters are refused and the found //! attribute is returned. Standard_EXPORT static Handle(TDataStd_ExtStringArray) Set (const TDF_Label& label, const Standard_Integer lower, const Standard_Integer upper, const Standard_Boolean isDelta = Standard_False); //! Finds, or creates, an ExtStringArray attribute with explicit user defined <guid>. //! The ExtStringArray attribute is returned. Standard_EXPORT static Handle(TDataStd_ExtStringArray) Set (const TDF_Label& label, const Standard_GUID& theGuid, const Standard_Integer lower, const Standard_Integer upper, const Standard_Boolean isDelta = Standard_False); //! Initializes the inner array with bounds from <lower> to <upper> Standard_EXPORT void Init (const Standard_Integer lower, const Standard_Integer upper); //! Sets the <Index>th element of the array to <Value> //! OutOfRange exception is raised if <Index> doesn't respect Lower and Upper bounds of the internal array. Standard_EXPORT void SetValue (const Standard_Integer Index, const TCollection_ExtendedString& Value); //! Sets the explicit GUID (user defined) for the attribute. Standard_EXPORT void SetID( const Standard_GUID& theGuid) Standard_OVERRIDE; //! Sets default GUID for the attribute. Standard_EXPORT void SetID() Standard_OVERRIDE; //! Returns the value of the <Index>th element of the array Standard_EXPORT const TCollection_ExtendedString& Value (const Standard_Integer Index) const; const TCollection_ExtendedString& operator () (const Standard_Integer Index) const { return Value(Index); } //! Return the lower bound. Standard_EXPORT Standard_Integer Lower() const; //! Return the upper bound Standard_EXPORT Standard_Integer Upper() const; //! Return the number of elements of <me>. Standard_EXPORT Standard_Integer Length() const; //! Sets the inner array <myValue> of the ExtStringArray attribute to <newArray>. //! If value of <newArray> differs from <myValue>, Backup performed and myValue //! refers to new instance of HArray1OfExtendedString that holds <newArray> values //! If <isCheckItems> equal True each item of <newArray> will be checked with each //! item of <myValue> for coincidence (to avoid backup). Standard_EXPORT void ChangeArray (const Handle(TColStd_HArray1OfExtendedString)& newArray, const Standard_Boolean isCheckItems = Standard_True); //! Return the inner array of the ExtStringArray attribute const Handle(TColStd_HArray1OfExtendedString)& Array() const { return myValue; } Standard_Boolean GetDelta() const { return myIsDelta; } //! for internal use only! void SetDelta (const Standard_Boolean isDelta) { myIsDelta = isDelta; } Standard_EXPORT TDataStd_ExtStringArray(); Standard_EXPORT const Standard_GUID& ID() const Standard_OVERRIDE; Standard_EXPORT void Restore (const Handle(TDF_Attribute)& With) Standard_OVERRIDE; Standard_EXPORT Handle(TDF_Attribute) NewEmpty() const Standard_OVERRIDE; Standard_EXPORT void Paste (const Handle(TDF_Attribute)& Into, const Handle(TDF_RelocationTable)& RT) const Standard_OVERRIDE; Standard_EXPORT virtual Standard_OStream& Dump (Standard_OStream& anOS) const Standard_OVERRIDE; //! Makes a DeltaOnModification between <me> and //! <anOldAttribute>. Standard_EXPORT virtual Handle(TDF_DeltaOnModification) DeltaOnModification (const Handle(TDF_Attribute)& anOldAttribute) const Standard_OVERRIDE; //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE; private: void RemoveArray() { myValue.Nullify(); } private: Handle(TColStd_HArray1OfExtendedString) myValue; Standard_Boolean myIsDelta; Standard_GUID myID; }; #endif // _TDataStd_ExtStringArray_HeaderFile
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2000 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #include "modules/logdoc/src/doc_tree.h" void DocTree::Under(DocTree* tree) { #ifdef DO_ASSERT OP_ASSERT(!m_parent); OP_ASSERT(tree); #endif /* * If the previous assertion is removed, we will have to * include an "Out();" here first. */ m_pred = tree->m_last_child; if (m_pred) m_pred->m_suc = this; else tree->m_first_child = this; #ifdef DO_ASSERT OP_ASSERT(!m_pred || m_pred != m_suc); OP_ASSERT(m_pred != this); OP_ASSERT(m_suc != this); #endif tree->m_last_child = this; m_parent = tree; } void DocTree::Out() { #ifdef DO_ASSERT OP_ASSERT(m_parent); #endif if (m_suc) // If we've a successor, unchain us m_suc->SetPred(m_pred); else // If we don't, we're the last in the list m_parent->SetLastChild(m_pred); if (m_pred) // If we've a predecessor, unchain us m_pred->SetSuc(m_suc); else // If we don't, we're the first in the list m_parent->SetFirstChild(m_suc); #ifdef DO_ASSERT OP_ASSERT(!m_pred || !m_pred->Suc() || m_pred->Suc() != m_pred->Pred()); OP_ASSERT(!m_suc || !m_suc->Suc() || m_suc->Suc() != m_suc->Pred()); OP_ASSERT(m_pred != this); OP_ASSERT(m_suc != this); OP_ASSERT(!m_pred || m_pred->Suc() != m_pred || m_pred->Pred() != m_pred); OP_ASSERT(!m_suc || m_suc->Suc() != m_suc || m_suc->Pred() != m_suc); #endif m_pred = NULL; m_suc = NULL; m_parent = NULL; } void DocTree::DetachChildren() { DocTree *tmp_child = m_first_child; while (tmp_child) { tmp_child->m_parent = NULL; tmp_child = tmp_child->m_suc; } m_first_child = NULL; m_last_child = NULL; } void DocTree::Follow(DocTree* tree) { #ifdef DO_ASSERT OP_ASSERT(tree); OP_ASSERT(!m_parent); #endif /* * If the previous assertion is removed, we will have to * include an "Out();" here first. */ m_parent = tree->Parent(); m_pred = tree; m_suc = tree->Suc(); if (m_suc) m_suc->SetPred(this); else m_parent->SetLastChild(this); tree->SetSuc(this); } void DocTree::Precede(DocTree* tree) { #ifdef DO_ASSERT OP_ASSERT(tree); OP_ASSERT(!m_parent); #endif /* * If the previous assertion is removed, we will have to * include an "Out();" here first. */ m_parent = tree->Parent(); m_suc = tree; m_pred = tree->Pred(); if (m_pred) m_pred->SetSuc(this); else m_parent->SetFirstChild(this); tree->SetPred(this); } DocTree* DocTree::LastLeaf() { // optimised for compilers that can't optimise recursive methods DocTree *leaf = this; while (leaf->LastChild()) leaf = leaf->LastChild(); return leaf; } DocTree* DocTree::FirstLeaf() { // optimised for compilers that can't optimise recursive methods DocTree *leaf = this; while (leaf->FirstChild()) leaf = leaf->FirstChild(); return leaf; } BOOL DocTree::Precedes(const DocTree* other_tree) const { if (other_tree == this) return FALSE; const DocTree* walk = this; UINT this_level = Level(); UINT other_level = other_tree->Level(); BOOL other_is_above = this_level < other_level; while (walk->Parent() != other_tree->Parent()) { if (this_level >= other_level) { walk = walk->Parent(); --this_level; } if (this_level < other_level) { other_tree = other_tree->Parent(); --other_level; } } if (walk == other_tree) // Special case; same branch return other_is_above; while ((other_tree = other_tree->Pred()) != NULL) if (walk == other_tree) return TRUE; return FALSE; } BOOL DocTree::IsAncestorOf(DocTree* tree) const { // optimised for compilers that can't optimise recursive methods while (tree) if (tree == this) return TRUE; else tree = tree->Parent(); return FALSE; } DocTree* DocTree::PrevLeaf() { DocTree* leaf = this; while (!leaf->Pred()) { // If leaf doesn't have a predecessor, go looking in parent leaf = leaf->Parent(); if (!leaf) return NULL; } leaf = leaf->Pred(); // Then, traverse down leaf to find last child, if it has any while (leaf->LastChild()) leaf = leaf->LastChild(); return leaf; } DocTree* DocTree::NextLeaf() { DocTree* leaf = this; while (!leaf->Suc()) { // If leaf doesn't have a successor, go looking in parent leaf = leaf->Parent(); if (!leaf) return NULL; } leaf = leaf->Suc(); // Then, traverse down leaf to find first child, if it has any while (leaf->FirstChild()) leaf = leaf->FirstChild(); return leaf; } DocTree* DocTree::Next() const { if (FirstChild()) return FirstChild(); for (const DocTree *leaf = this; leaf; leaf = leaf->Parent()) if (leaf->Suc()) return leaf->Suc(); return NULL; } DocTree* DocTree::NextSibling() const { for (const DocTree *leaf = this; leaf; leaf = leaf->Parent()) if (leaf->Suc()) return leaf->Suc(); return NULL; } DocTree* DocTree::Prev() const { if (Pred()) { DocTree* leaf = Pred(); while (leaf->LastChild()) leaf = leaf->LastChild(); return leaf; } return Parent(); } DocTree* DocTree::PrevSibling() const { for (const DocTree *leaf = this; leaf; leaf = leaf->Parent()) if (leaf->Pred()) return leaf->Pred(); return NULL; } void DocTree::AppendChildren(DocTree *list) { DocTree* first_added = list->m_first_child; if (!first_added) return; DocTree* last_added = list->m_last_child; list->m_first_child = NULL; list->m_last_child = NULL; if (m_last_child) { m_last_child->m_suc = first_added; first_added->m_pred = m_last_child; } else m_first_child = first_added; m_last_child = last_added; while (first_added) { first_added->m_parent = this; first_added = first_added->Suc(); } } void DocTree::InsertChildrenBefore(DocTree *list, DocTree *node) { if (!node) { // Insert at the end is the same as append AppendChildren(list); return; } #ifdef DO_ASSERT OP_ASSERT(node->parent == this); #endif DocTree* first_added = list->m_first_child; // inserting an empty list does not change this. if (!first_added) return; DocTree* last_added = list->m_last_child; list->m_first_child = NULL; list->m_last_child = NULL; // set the parent of the inserted elements to this list. DocTree* tmp = first_added; while (tmp) { tmp->m_parent = this; tmp = tmp->Suc(); } // insert the added list elements into the list. if (node->m_pred) { first_added->m_pred = node->m_pred; node->m_pred->m_suc = first_added; } else m_first_child = first_added; node->m_pred = last_added; last_added->m_suc = node; }
#ifndef VID_H #define VID_H #include <vector> using namespace std; vector<unsigned char> EncryptVidg(vector<unsigned char> data,vector<unsigned char> key); vector<unsigned char> DecryptVidg(vector<unsigned char> data,vector<unsigned char> key); #endif // VID_H
#ifndef _config_h #define _config_h #include <string> #include <cstdarg> #include <vector> #include <sstream> #include <limits> #include <cstring> #include <sys/stat.h> #include <opencv2/core/core.hpp> #include <opencv2/objdetect/objdetect.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #ifdef _WIN32 #include <ctime> #include <direct.h> #else #include<dirent.h> #include <time.h> #include <sys/types.h> #include <stdlib.h> #include <errno.h> #include <stdio.h> #endif //undefying dangerous macros if any #ifdef min #undef min #endif #ifdef max #undef max #endif /******************************************************************************************************************************* * Forward declarations, types, parameters, constants, exceptions and utility functions * *******************************************************************************************************************************/ namespace thesis { /******************* * DECLARATIONS * ******************** ---------------------------------------------------------------------------------------------------------------------------*/ class failure; //failure exception thrown by functions in the current module enum failure_type { UNDEFINED }; enum debug_level { NO_DEBUG, LEV1, LEV2, LEV3 }; enum axis { INVALID_AXIS, X, Y, Z }; /*-------------------------------------------------------------------------------------------------------------------------*/ /******************* * TYPES * ******************** ---------------------------------------------------------------------------------------------------------------------------*/ typedef signed char sint8; //8-bit signed integers (-128 -> +127) typedef short sint16; //16-bit signed integers (-32,768 -> +32,767) typedef int sint32; //32-bit signed integers (-2,147,483,648 -> +2,147,483,647) typedef long long sint64; //64-bit signed integers (�9,223,372,036,854,775,808 -> +9,223,372,036,854,775,807) typedef unsigned char uint8; //8-bit unsigned integers (0 -> +255) typedef unsigned short int uint16; //16-bit unsigned integers (0 -> +65,535) typedef unsigned int uint32; //32-bit unsigned integers (0 -> +4,294,967,295) typedef unsigned long long uint64; //64-bit unsigned integers (0 -> +18,446,744,073,709,551,615 typedef float real32; //real single precision typedef double real64; //real double precision /*-------------------------------------------------------------------------------------------------------------------------*/ /******************* * CONSTANTS * ******************** ---------------------------------------------------------------------------------------------------------------------------*/ const double PI = 3.14159265358979323846; //pi /*-------------------------------------------------------------------------------------------------------------------------*/ /******************* * PARAMETERS * ******************** ---------------------------------------------------------------------------------------------------------------------------*/ //extern int DEBUG; //debug level of current module extern int SCREEN_WIDTH; //screen width (in pixels) extern int SCREEN_HEIGHT; //screen height (in pixels) /*-------------------------------------------------------------------------------------------------------------------------*/ /******************************************** * Cross-platform UTILITY functions * ******************************************** ---------------------------------------------------------------------------------------------------------------------------*/ //infinity template<class T> T inf() { if (std::numeric_limits<T>::has_infinity) return std::numeric_limits<T>::infinity(); else return std::numeric_limits<T>::max(); } template<class T> T ninf() { if (std::numeric_limits<T>::has_infinity) return -std::numeric_limits<T>::infinity(); else return std::numeric_limits<T>::min(); } //the case insensitive version of C strstr() function inline const char* stristr(const char *str1, const char *str2) { if (!*str2) return str1; for (; *str1; ++str1) { if (toupper(*str1) == toupper(*str2)) { const char *h, *n; for (h = str1, n = str2; *h && *n; ++h, ++n) { if (toupper(*h) != toupper(*n)) { break; } } if (!*n) /* matched all of 'str2' to null termination */ return str1; /* return the start of the match */ } } return 0; } //the case insensitive version of C strcmp() function inline int stricmp(const char *s1, const char *s2) { if (s1 == 0) return s2 == 0 ? 0 : -(*s2); if (s2 == 0) return *s1; char c1, c2; while ((c1 = tolower(*s1)) == (c2 = tolower(*s2))) { if (*s1 == '\0') break; ++s1; ++s2; } return c1 - c2; } //stringstream-based integer-to-string conversion inline std::string int2str(const int& val) { std::stringstream ss; ss << val; return ss.str(); } //infinity-compliant string-to-double conversion inline double str2f(const char* str) { if (stristr(str, "1.#inf") == str) return std::numeric_limits<double>::infinity(); else if (stristr(str, "-1.#inf") == str) return -std::numeric_limits<double>::infinity(); else if (stristr(str, "-inf") == str) return -std::numeric_limits<double>::infinity(); else if (stristr(str, "inf") == str) return std::numeric_limits<double>::infinity(); else return atof(str); } //fgetstr() - mimics behavior of fgets(), but removes new-line character at end of line if it exists inline char *fgetstr(char *string, int n, FILE *stream) { char *result; result = fgets(string, n, stream); if (!result) return(result); char *nl = strrchr(string, '\r'); if (nl) *nl = '\0'; nl = strrchr(string, '\n'); if (nl) *nl = '\0'; return(string); } //string-based tokenization function inline void split(std::string& theString, std::string delim, std::vector<std::string>& tokens) { size_t start = 0, end = 0; while (end != std::string::npos) { end = theString.find(delim, start); // If at end, use length=maxLength. Else use length=end-start. tokens.push_back(theString.substr(start, (end == std::string::npos) ? std::string::npos : end - start)); // If at end, use start=maxSize. Else use start=end+delimiter. start = ((end > (std::string::npos - delim.size())) ? std::string::npos : end + delim.size()); } } //extracts the filename from the given path and stores it into <filename> inline std::string getFileName(std::string const & path, bool save_ext = true) { std::string filename = path; // Remove directory if present. // Do this before extension removal in case directory has a period character. const size_t last_slash_idx = filename.find_last_of("\\/"); if (std::string::npos != last_slash_idx) filename.erase(0, last_slash_idx + 1); // Remove extension if present. if (!save_ext) { const size_t period_idx = filename.rfind('.'); if (std::string::npos != period_idx) filename.erase(period_idx); } return filename; } //string-based sprintf function inline std::string strprintf(const std::string fmt, ...) { int size = 100; std::string str; va_list ap; while (1) { str.resize(size); va_start(ap, fmt); int n = vsnprintf((char *)str.c_str(), size, fmt.c_str(), ap); va_end(ap); if (n > -1 && n < size) { str.resize(n); return str; } if (n > -1) size = n + 1; else size *= 2; } return str; } //round functions inline int round(float x) { return static_cast<int>(x > 0.0f ? x + 0.5f : x - 0.5f); } inline int round(double x) { return static_cast<int>(x > 0.0 ? x + 0.5 : x - 0.5); } //returns true if the given path is a directory inline bool isDirectory(std::string path) { struct stat s; if (stat(path.c_str(), &s) == 0) { if (s.st_mode & S_IFDIR) return true; else if (s.st_mode & S_IFREG) return false; else return false; } else return false; } //returns true if the given path is a file inline bool isFile(std::string path) { struct stat s; if (stat(path.c_str(), &s) == 0) { if (s.st_mode & S_IFDIR) return false; else if (s.st_mode & S_IFREG) return true; else return false; } else return false; } //returns true if the given string <fullString> ends with <ending> inline bool hasEnding(std::string const &fullString, std::string const &ending) { if (fullString.length() >= ending.length()) { return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending)); } else { return false; } } //returns file extension, if any (otherwise returns "") inline std::string getFileExtension(const std::string& FileName) { if (FileName.find_last_of(".") != std::string::npos) return FileName.substr(FileName.find_last_of(".") + 1); return ""; } //number to string conversion function and vice versa template <typename T> std::string num2str(T Number) { std::stringstream ss; ss << Number; return ss.str(); } template <typename T> T str2num(const std::string &Text) { std::stringstream ss(Text); T result; return ss >> result ? result : 0; } //time computation #ifdef _WIN32 inline double getTimeSeconds() { return static_cast<double>(clock()) / CLOCKS_PER_SEC; } #else inline double getTimeSeconds() { timespec event; clock_gettime(CLOCK_REALTIME, &event); return (event.tv_sec*1000.0 + event.tv_nsec / 1000000.0) / 1000.0; } #endif //make dir #ifdef _WIN32 inline bool make_dir(const char* arg) { //printf("Creating directory \"%s\" ...", arg); bool done = _mkdir(arg) == 0; bool result = done || errno != ENOENT; //printf("%s\n", result? "DONE!" : "ERROR!"); return result; } #else inline bool make_dir(const char* arg) { //printf("Creating directory \"%s\" ...", arg); bool done = mkdir(arg, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0; bool result = done || errno == EEXIST; //printf("%s\n", result ? "DONE!" : "ERROR!"); return result; } #endif //file deleting #ifdef _WIN32 inline void delete_file(const char* arg) { //if(system(strprintf("del /F /Q /S \"%s\"", arg).c_str())!=0) // Se metto la /S mi stampa tutti i file eliminati.... /*if (system(strprintf("del /F /Q \"%s\"", arg).c_str()) != 0) fprintf(stderr,"Can't delete file \"%s\"\n", arg);*/ //system(strprintf("del /F /Q \"%s\"", arg).c_str()); //system("cls"); remove(arg); } #else inline void delete_file(const char* arg) { if (system(strprintf("rm -f \"%s\"", arg).c_str()) != 0) fprintf(stderr, "Can't delete file \"%s\"\n", arg); } #endif // folder Deleting (Only WIN) //file deleting #ifdef _WIN32 inline void delete_folder(const char* arg) { //if(system(strprintf("del /F /Q /S \"%s\"", arg).c_str())!=0) // Se metto la /S mi stampa tutti i file eliminati.... if (system(strprintf("rd /S /Q \"%s\"", arg).c_str()) != 0) fprintf(stderr, "Can't delete file \"%s\"\n", arg); } #else inline void delete_folder(const char *path) { struct dirent *entry = NULL; DIR *dir; dir = NULL; dir = opendir(path); while (entry = readdir(dir)) { DIR *sub_dir = NULL; FILE *file = NULL; char abs_path[100] = { 0 }; if (*(entry->d_name) != '.') { sprintf(abs_path, "%s/%s", path, entry->d_name); if (sub_dir = opendir(abs_path)) { closedir(sub_dir); delete_folder(abs_path); } else { if (file = fopen(abs_path, "r")) { fclose(file); remove(abs_path); } } } } remove(path); } #endif //cross-platform current function macro #if defined(__GNUC__) || (defined(__MWERKS__) && (__MWERKS__ >= 0x3000)) || (defined(__ICC) && (__ICC >= 600)) # define _eeid_current_function __PRETTY_FUNCTION__ #elif defined(__DMC__) && (__DMC__ >= 0x810) # define _eeid_current_function __PRETTY_FUNCTION__ #elif defined(__FUNCSIG__) # define _eeid_current_function __FUNCSIG__ #elif (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 600)) || (defined(__IBMCPP__) && (__IBMCPP__ >= 500)) # define _eeid_current_function __FUNCTION__ #elif defined(__BORLANDC__) && (__BORLANDC__ >= 0x550) # define _eeid_current_function __FUNC__ #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901) # define _eeid_current_function __func__ #else # define _eeid_current_function "(unknown)" #endif /*-------------------------------------------------------------------------------------------------------------------------*/ /******************************************* * OpenCV UTILITY functions * ******************************************** ---------------------------------------------------------------------------------------------------------------------------*/ inline void imshow(const std::string winname, const cv::InputArray& arr) { // create window cv::namedWindow(winname, CV_WINDOW_FREERATIO); // resize window so as to fit screen size while maintaining image aspect ratio int win_height = arr.size().height, win_width = arr.size().width; if (win_height > thesis::SCREEN_HEIGHT) { win_height = thesis::SCREEN_HEIGHT; win_width = round(win_height * static_cast<float>(arr.size().width) / arr.size().height); } if (win_width > thesis::SCREEN_WIDTH) { win_width = thesis::SCREEN_WIDTH; win_height = round(win_width * static_cast<float>(arr.size().height) / arr.size().width); } cv::resizeWindow(winname, win_width, win_height); // display image cv::imshow(winname, arr); // wait for key pressed cv::waitKey(0); } inline int depth(int ocv_depth) { switch (ocv_depth) { case CV_8U: return 8; case CV_8S: return 8; case CV_16U: return 16; case CV_16S: return 16; case CV_32S: return 32; case CV_32F: return 32; case CV_64F: return 64; default: return -1; } } } #endif /* _config_h */
#include "model/TokenID.h" using namespace BeeeOn; TokenID::TokenID() { }
#include<bits/stdc++.h> using namespace std; int main() { int n; long long l, p; cin>>l>>n; p=l*n; cout<<p<<"\n"; return 0; }
#include <bits/stdc++.h> using namespace std; void print(int n) { if (n == 0) return; print(n-1); cout << n << " "; } int main() { // only gravity will pull me down // Print 1 to n without using loops int t, n; cin >> t; while(t--) { cin >> n; print(n); cout << endl; } return 0; }
/* The ESP32 has four SPi buses, however as of right now only two of * them are available to use, HSPI and VSPI. Simply using the SPI API * as illustrated in Arduino examples will use VSPI, leaving HSPI unused. * * However if we simply intialise two instance of the SPI class for both * of these buses both can be used. However when just using these the Arduino * way only will actually be outputting at a time. * * Logic analyser capture is in the same folder as this example as * "multiple_bus_output.png" * * created 30/04/2018 by Alistair Symonds */ #include <SPI.h> static const int spiClk = 250000; // 250kHz //uninitalised pointers to SPI objects //SPIClass * vspi = NULL; //SPIClass * hspi = NULL; SPIClass vspi(VSPI); void setup() { //initialise two instances of the SPIClass attached to VSPI and HSPI respectively //vspi = new SPIClass(VSPI); //hspi = new SPIClass(HSPI); Serial.begin(115200); Serial.println("Hello from esp32 spi master"); //clock miso mosi ss //initialise vspi with default pins //SCLK = 18, MISO = 19, MOSI = 23, SS = 5 //vspi->begin(); vspi.begin(); pinMode(5, OUTPUT); //VSPI SS } // the loop function runs over and over again until power down or reset void loop() { //use the SPI buses vspiCommand(); //hspiCommand(); delay(1000); } void vspiCommand() { byte data = 0b01010101; // junk data to illustrate usage //use it as you would the regular arduino SPI API vspi.beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0)); digitalWrite(5, LOW); //pull SS slow to prep other end for transfer int res = vspi.transfer(data); digitalWrite(5, HIGH); //pull ss high to signify end of data transfer vspi.endTransaction(); Serial.print("esp32 master: slave returned: "); Serial.println(res); }
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno. // WARNING: Changes might be lost if you edit this file directly. #include <_root.app18_accessor_List_Items.h> #include <_root.List.h> #include <Uno.Bool.h> #include <Uno.Object.h> #include <Uno.String.h> #include <Uno.Type.h> #include <Uno.UX.IPropertyListener.h> #include <Uno.UX.PropertyObject.h> #include <Uno.UX.Selector.h> static uString* STRINGS[1]; static uType* TYPES[2]; namespace g{ // internal sealed class app18_accessor_List_Items :221 // { // static generated app18_accessor_List_Items() :221 static void app18_accessor_List_Items__cctor__fn(uType* __type) { ::g::Uno::UX::Selector_typeof()->Init(); app18_accessor_List_Items::Singleton_ = app18_accessor_List_Items::New1(); app18_accessor_List_Items::_name_ = ::g::Uno::UX::Selector__op_Implicit(::STRINGS[0/*"Items"*/]); } static void app18_accessor_List_Items_build(uType* type) { ::STRINGS[0] = uString::Const("Items"); ::TYPES[0] = ::g::List_typeof(); ::TYPES[1] = ::g::Uno::Type_typeof(); type->SetFields(0, ::g::Uno::UX::Selector_typeof(), (uintptr_t)&app18_accessor_List_Items::_name_, uFieldFlagsStatic, ::g::Uno::UX::PropertyAccessor_typeof(), (uintptr_t)&app18_accessor_List_Items::Singleton_, uFieldFlagsStatic); } ::g::Uno::UX::PropertyAccessor_type* app18_accessor_List_Items_typeof() { static uSStrong< ::g::Uno::UX::PropertyAccessor_type*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Uno::UX::PropertyAccessor_typeof(); options.FieldCount = 2; options.ObjectSize = sizeof(app18_accessor_List_Items); options.TypeSize = sizeof(::g::Uno::UX::PropertyAccessor_type); type = (::g::Uno::UX::PropertyAccessor_type*)uClassType::New("app18_accessor_List_Items", options); type->fp_build_ = app18_accessor_List_Items_build; type->fp_ctor_ = (void*)app18_accessor_List_Items__New1_fn; type->fp_cctor_ = app18_accessor_List_Items__cctor__fn; type->fp_GetAsObject = (void(*)(::g::Uno::UX::PropertyAccessor*, ::g::Uno::UX::PropertyObject*, uObject**))app18_accessor_List_Items__GetAsObject_fn; type->fp_get_Name = (void(*)(::g::Uno::UX::PropertyAccessor*, ::g::Uno::UX::Selector*))app18_accessor_List_Items__get_Name_fn; type->fp_get_PropertyType = (void(*)(::g::Uno::UX::PropertyAccessor*, uType**))app18_accessor_List_Items__get_PropertyType_fn; type->fp_SetAsObject = (void(*)(::g::Uno::UX::PropertyAccessor*, ::g::Uno::UX::PropertyObject*, uObject*, uObject*))app18_accessor_List_Items__SetAsObject_fn; type->fp_get_SupportsOriginSetter = (void(*)(::g::Uno::UX::PropertyAccessor*, bool*))app18_accessor_List_Items__get_SupportsOriginSetter_fn; return type; } // public generated app18_accessor_List_Items() :221 void app18_accessor_List_Items__ctor_1_fn(app18_accessor_List_Items* __this) { __this->ctor_1(); } // public override sealed object GetAsObject(Uno.UX.PropertyObject obj) :227 void app18_accessor_List_Items__GetAsObject_fn(app18_accessor_List_Items* __this, ::g::Uno::UX::PropertyObject* obj, uObject** __retval) { return *__retval = uPtr(uCast< ::g::List*>(obj, ::TYPES[0/*List*/]))->Items(), void(); } // public override sealed Uno.UX.Selector get_Name() :224 void app18_accessor_List_Items__get_Name_fn(app18_accessor_List_Items* __this, ::g::Uno::UX::Selector* __retval) { return *__retval = app18_accessor_List_Items::_name_, void(); } // public generated app18_accessor_List_Items New() :221 void app18_accessor_List_Items__New1_fn(app18_accessor_List_Items** __retval) { *__retval = app18_accessor_List_Items::New1(); } // public override sealed Uno.Type get_PropertyType() :226 void app18_accessor_List_Items__get_PropertyType_fn(app18_accessor_List_Items* __this, uType** __retval) { return *__retval = uObject_typeof(), void(); } // public override sealed void SetAsObject(Uno.UX.PropertyObject obj, object v, Uno.UX.IPropertyListener origin) :228 void app18_accessor_List_Items__SetAsObject_fn(app18_accessor_List_Items* __this, ::g::Uno::UX::PropertyObject* obj, uObject* v, uObject* origin) { uPtr(uCast< ::g::List*>(obj, ::TYPES[0/*List*/]))->SetItems(v, origin); } // public override sealed bool get_SupportsOriginSetter() :229 void app18_accessor_List_Items__get_SupportsOriginSetter_fn(app18_accessor_List_Items* __this, bool* __retval) { return *__retval = true, void(); } ::g::Uno::UX::Selector app18_accessor_List_Items::_name_; uSStrong< ::g::Uno::UX::PropertyAccessor*> app18_accessor_List_Items::Singleton_; // public generated app18_accessor_List_Items() [instance] :221 void app18_accessor_List_Items::ctor_1() { ctor_(); } // public generated app18_accessor_List_Items New() [static] :221 app18_accessor_List_Items* app18_accessor_List_Items::New1() { app18_accessor_List_Items* obj1 = (app18_accessor_List_Items*)uNew(app18_accessor_List_Items_typeof()); obj1->ctor_1(); return obj1; } // } } // ::g
/* ** EPITECH PROJECT, 2021 ** B-CPP-300-STG-3-1-CPPrush3-maxime.owaller ** File description: ** TitleSection */ #include "TitleSection.hpp" TitleSection::TitleSection(std::string const& title, sf::Color color, sf::Vector2f position) noexcept { _title = new Text{title, color, {100, 100}, 14}; _title->setPosition(position); } void TitleSection::DrawTitle(WindowManager& manager) const noexcept { manager._window.draw(_title->getText()); }
#include <iostream> #include <fstream> #include <string> #include <cstring> #include <sstream> #include <vector> #include <arpa/inet.h> #include <netinet/in.h> #include <unistd.h> #include <dirent.h> #include <map> #include <getopt.h> //#include <bits/regex.h> #include <regex> #include <sys/stat.h> using namespace std; # define IPV4 4 # define IPV6 6 struct net_info { string proto; string src_ip, dst_ip; string src_port, dst_port; string pid; string prg_name; }; struct prc_info { string pid, prg_name; map <string, bool> inode; }; // **global variable** vector<net_info> net_info_arr; vector<prc_info> prc_info_arr; vector<string> filter; // **...............** int HexToDec(char c) { return isalpha(c) ? c - 'A' + 10 : c - '0'; } void ipv4(const string &tmp1,const string &tmp2, string &ip, string &port) { // **ip** unsigned long tmp1_num = 0; for (int i = 0 ; i < tmp1.size() ; i ++) // hex to dec tmp1_num = tmp1_num * 16 + HexToDec(tmp1[i]); in_addr *in = new in_addr(); in->s_addr = tmp1_num; char buf[200]; inet_ntop(AF_INET, in, buf, sizeof(buf)); // dec to ip ip = buf; // **port** int pt = (HexToDec(tmp2[0]) * 16 + HexToDec(tmp2[1])) * 256 + HexToDec(tmp2[2]) * 16 + HexToDec(tmp2[3]); if (pt == 0) port = "*"; else { while(pt) { port = char((pt % 10) + '0') + port; pt /= 10; } } } void ipv6(const string &tmp1,const string &tmp2, string &ip, string &port) { // **ip** int i, j, k; in6_addr *in6 = new in6_addr(); int ip6[16] = {}; for (i = 0, j = 0; i < tmp1.size(); i += 2, j++) ip6[j] = HexToDec(tmp1[i]) * 16 + HexToDec(tmp1[i + 1]); for (i = 0 ; i < 4 ; i ++) for (j = 0 ; j < 4 ; j ++) { int lst = (i+1) * 4; in6->__in6_u.__u6_addr8[lst - j - 1] = ip6[i*4 + j]; } char buf[200]; inet_ntop(AF_INET6, in6, buf,sizeof(buf)); ip = buf; // **port** int pt = (HexToDec(tmp2[0]) * 16 + HexToDec(tmp2[1])) * 256 + HexToDec(tmp2[2]) * 16 + HexToDec(tmp2[3]); if (pt == 0) port = "*"; else { while(pt) { port = char((pt % 10) + '0') + port; pt /= 10; } } } void openNetFile(const string path, const string proto, int flag) { int i, j, k; ifstream net_file(path); if (net_file.is_open()) { string line, arg, arg_arr[200], tmp; getline(net_file, line); // first line is title while(getline(net_file, line)) { // read file for (i = 0 ; i < line.size() ; i ++) // replace ':' to ' ' if (line[i] == ':') line[i] = ' '; istringstream sin(line); for (i = 0, k = 0 ; sin >> arg ; i ++, k ++) // split by whitespace arg_arr[i] = arg; //if (arg_arr[5] != "01") continue; net_info ntif; ntif.proto = proto; if (flag == IPV4) { ipv4(arg_arr[1], arg_arr[2], ntif.src_ip, ntif.src_port); ipv4(arg_arr[3], arg_arr[4], ntif.dst_ip, ntif.dst_port); } else { ipv6(arg_arr[1], arg_arr[2], ntif.src_ip, ntif.src_port); ipv6(arg_arr[3], arg_arr[4], ntif.dst_ip, ntif.dst_port); } for (i = 0 ; i < prc_info_arr.size() ; i ++) // search inode in each pid if (prc_info_arr[i].inode[arg_arr[13]] == true) { ntif.pid = prc_info_arr[i].pid; ntif.prg_name = prc_info_arr[i].prg_name; break; } smatch sm; bool show = true; for (i = 0 ; i < filter.size() ; i ++) { string str_show = ntif.proto + " " + ntif.src_ip + ":" + ntif.src_port + " " + ntif.dst_ip + ":" + ntif.dst_port + " " + ntif.pid + "/" + ntif.prg_name; if ( !regex_search (str_show, sm, regex(filter[i]))) { show = false; break; } } if (!show) continue; printf("%-7s", ntif.proto.c_str()); char buf[200]; sprintf(buf, "%s:%s", ntif.src_ip.c_str(), ntif.src_port.c_str()); printf("%-24s", buf); sprintf(buf, "%s:%s", ntif.dst_ip.c_str(), ntif.dst_port.c_str()); printf("%-23s", buf); printf("%s/%s\n", ntif.pid.c_str(), ntif.prg_name.c_str()); } } else { cout << "open " << proto << "file failed:"; cout << strerror(errno) << endl; } } int main(int argc, char **argv) { // **store all pid's message** DIR *proc_dir = opendir("/proc"); dirent *proc_ptr; while((proc_ptr = readdir(proc_dir)) != NULL) { if (!isalpha(proc_ptr->d_name[0]) && proc_ptr->d_name[0] != '.') { // pid //cout << proc_ptr->d_name << endl; prc_info pif; pif.pid += proc_ptr->d_name; //cout << pif.pid << endl; string cmdline_path = "/proc/" + pif.pid + "/cmdline"; // find program name in stat ifstream cmdline_file(cmdline_path); string line; getline(cmdline_file, line); for (int i = 0 ; i < line.size() ; i ++) if (line[i] == 0) line[i] = ' '; pif.prg_name = line; bool start = false; //cout << pif.prg_name << endl; string fd_dir_path = "/proc/" + pif.pid + "/fd"; //cout << fd_dir_path << endl; DIR *fd_dir = opendir(fd_dir_path.c_str()); if (fd_dir == NULL) { cout << pif.pid << " of fd_dir open failed :"; cout << strerror(errno) << endl; continue; } dirent *fd_ptr; while((fd_ptr = readdir(fd_dir)) != NULL) { if (fd_ptr->d_name[0] != '.') { string fd_path = fd_dir_path + "/" + fd_ptr->d_name; struct stat status; if (stat(fd_path.c_str(), &status) == 0) if (S_ISSOCK(status.st_mode)) { // check is socket char buf[200] = {0}; int buf_len = readlink(fd_path.c_str(), buf, sizeof(buf)); string str_inode; start = false; for (int i = 1; buf[i] != ']' && i < strlen(buf); i++) { // store inode if (buf[i - 1] == '[') start = true; if (start) str_inode += buf[i]; } pif.inode[str_inode] = true; } prc_info_arr.push_back(pif); } } } } cout << "Proto Local Address Foreign Address PID/Program name and arguments" << endl; // --tcp -> -t, --udp -> -u struct option opts[] = { {"tcp", 0, NULL, 't'}, {"udp", 0, NULL, 'u'}, }; bool tcp = false, udp = false; const char *optstring = "tu"; // -t or -u char c; while ((c = getopt_long(argc, argv, optstring, opts, NULL)) != -1) { switch(c) { case 't': tcp = true; break; case 'u': udp = true; break; } } string filter_line = ""; int i, j; for (i = optind, j = 0 ; i < argc ; i ++, j ++) { if (j) filter_line += " "; filter_line += argv[i]; } filter.push_back(filter_line); if (tcp || !udp) { openNetFile("/proc/net/tcp", "tcp", IPV4); openNetFile("/proc/net/tcp6", "tcp6", IPV6); } if (udp || !tcp) { openNetFile("/proc/net/udp", "udp", IPV4); openNetFile("/proc/net/udp6", "udp6", IPV6); } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "modules/widgets/OpEdit.h" #include "modules/widgets/OpColorField.h" #include "modules/forms/piforms.h" #include "modules/logdoc/htm_elm.h" #include "modules/forms/formsuggestion.h" #include "modules/display/vis_dev.h" #include "modules/style/css.h" #include "modules/logdoc/htm_lex.h" #include "modules/widgets/CssWidgetPainter.h" #include "modules/widgets/WidgetWindow.h" #include "modules/widgets/WidgetContainer.h" #include "modules/locale/oplanguagemanager.h" #include "modules/locale/locale-enum.h" #include "modules/windowcommander/src/WindowCommander.h" // == Utilities ==================================================== OP_STATUS ParseColor(const uni_char *text, COLORREF &out_color) { if (!text || *text != '#' || !ParseColor(text, uni_strlen(text), out_color)) return OpStatus::ERR; // Workaround for something that might be a bug in ParseColor. It returns a COLORREF that has alpha calculated like a UINT32 color. // COLORREF is 7bit alpha and the full alpha value means it's a named color which it's not in this case. out_color = OP_RGB(GetRValue(out_color), GetGValue(out_color), GetBValue(out_color)); return OpStatus::OK; } // == OpColorMatrix ================================================ DEFINE_CONSTRUCT(OpColorMatrix) #define MAX_CELLS_PER_ROW 10 #define DEFAULT_CELL_SIZE 20 OpColorMatrix::OpColorMatrix() { m_active_cell_index = -1; m_cell_size = DEFAULT_CELL_SIZE; m_colors = m_default_colors; m_num_colors = 20; m_default_colors[0] = OP_RGB(0, 0, 0); m_default_colors[1] = OP_RGB(127, 127, 127); m_default_colors[2] = OP_RGB(136, 0, 21); m_default_colors[3] = OP_RGB(237, 28, 36); m_default_colors[4] = OP_RGB(255, 127, 39); m_default_colors[5] = OP_RGB(255, 242, 0); m_default_colors[6] = OP_RGB(34, 177, 76); m_default_colors[7] = OP_RGB(0, 162, 232); m_default_colors[8] = OP_RGB(63, 72, 204); m_default_colors[9] = OP_RGB(163, 73, 164); m_default_colors[10] = OP_RGB(255, 255, 255); m_default_colors[11] = OP_RGB(195, 195, 195); m_default_colors[12] = OP_RGB(185, 122, 87); m_default_colors[13] = OP_RGB(255, 174, 201); m_default_colors[14] = OP_RGB(255, 201, 14); m_default_colors[15] = OP_RGB(239, 228, 176); m_default_colors[16] = OP_RGB(181, 230, 29); m_default_colors[17] = OP_RGB(153, 217, 234); m_default_colors[18] = OP_RGB(112, 146, 190); m_default_colors[19] = OP_RGB(200, 191, 231); m_picked_color = m_default_colors[0]; SetTabStop(TRUE); } OpColorMatrix::~OpColorMatrix() { if (m_colors != m_default_colors) OP_DELETEA(m_colors); } void OpColorMatrix::SetPickedColor(COLORREF color) { if (color != m_picked_color) { m_picked_color = color; InvalidateAll(); } } OP_STATUS OpColorMatrix::SetColors(COLORREF *colors, int num_colors) { // Create new array and copy data to it COLORREF *new_colors = OP_NEWA(COLORREF, num_colors); if (!new_colors) return OpStatus::ERR_NO_MEMORY; op_memcpy(new_colors, colors, num_colors * sizeof(COLORREF)); // Unallocate old array if (m_colors != m_default_colors) OP_DELETEA(m_colors); // We're done m_active_cell_index = -1; m_colors = new_colors; m_num_colors = num_colors; InvalidateAll(); return OpStatus::OK; } int OpColorMatrix::CalculateWidth() { int row_count = (m_num_colors + MAX_CELLS_PER_ROW - 1) / MAX_CELLS_PER_ROW; int width = row_count > 1 ? MAX_CELLS_PER_ROW * m_cell_size : m_num_colors * m_cell_size; return width + 2; // Border } int OpColorMatrix::CalculateHeight() { int row_count = (m_num_colors + MAX_CELLS_PER_ROW - 1) / MAX_CELLS_PER_ROW; int height = row_count * m_cell_size; return height + 2; // Border } void OpColorMatrix::OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect) { OpRect view_rect = GetBounds(); VisualDevice *vd = GetVisualDevice(); vd->SetColor(GetColor().use_default_background_color ? OP_RGB(255, 255, 255) : GetColor().background_color); vd->FillRect(view_rect); vd->SetColor(0, 0, 0); vd->DrawRect(view_rect); view_rect = view_rect.InsetBy(1); // Border BOOL is_focused = IsFocused(); int x = 0, y = 0; for (int i = 0; i < m_num_colors; i++) { OpRect cell_rect(view_rect.x + x, view_rect.y + y, m_cell_size, m_cell_size); cell_rect = cell_rect.InsetBy(1); vd->SetColor(m_colors[i]); vd->FillRect(cell_rect); if (m_colors[i] == m_picked_color) { m_active_cell_index = i; vd->SetColor(OP_RGB(255, 255, 255)); vd->DrawRect(cell_rect); if (is_focused) vd->DrawFocusRect(cell_rect); cell_rect = cell_rect.InsetBy(-1); vd->SetColor(OP_RGB(0, 0, 0)); vd->DrawRect(cell_rect); } // Move to next grid position x += m_cell_size; if (x >= view_rect.width) { x = 0; y += m_cell_size; } } } int OpColorMatrix::GetColorIndexFromPoint(const OpPoint& point) { // Calculate picked color index. (-1 for border) int cellx = (point.x - 1) / m_cell_size; int celly = (point.y - 1) / m_cell_size; if (cellx >= 0 && cellx < MAX_CELLS_PER_ROW) { int cell_index = cellx + celly * MAX_CELLS_PER_ROW; if (cell_index >= 0 && cell_index < m_num_colors) return cell_index; } return -1; } #ifndef MOUSELESS void OpColorMatrix::OnMouseMove(const OpPoint &point) { if (hooked_widget == this) { int cell_index = GetColorIndexFromPoint(point); if (cell_index != -1) SetPickedColor(m_colors[cell_index]); } } void OpColorMatrix::OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks) { OnMouseMove(point); } void OpColorMatrix::OnMouseUp(const OpPoint &point, MouseButton button, UINT8 nclicks) { if (button == MOUSE_BUTTON_1 && GetColorIndexFromPoint(point) != -1) { if (listener) listener->OnClick(this); } } #endif // !MOUSELESS void OpColorMatrix::PopulateFromDatalist(OpWidget *widget_with_form) { FormObject *form_obj = widget_with_form->GetFormObject(TRUE); if (!form_obj) return; HTML_Element *he = form_obj->GetHTML_Element(); if (he->HasAttr(ATTR_LIST)) { // Get all items from the list in to a array FormSuggestion form_suggestion(form_obj->GetDocument(), he, FormSuggestion::AUTOMATIC); BOOL contains_private_data = TRUE; // Play it safe uni_char **items; int num_items = 0; int num_columns = 0; OP_STATUS ret_val = form_suggestion.GetItems(NULL, &items, &num_items, &num_columns, &contains_private_data); if (OpStatus::IsSuccess(ret_val)) { // Parse values as colors and feed the successful ones into a new color array COLORREF *colors = OP_NEWA(COLORREF, num_items); if (colors) { int num_colors = 0; for(int i = 0; i < num_items; i++) { COLORREF c; if (OpStatus::IsSuccess(ParseColor(items[i * num_columns], c))) colors[num_colors++] = c; } // We're done. Set it. SetColors(colors, num_colors); OP_DELETEA(colors); } // Clean up for(int i = 0; i < num_items * num_columns; i++) OP_DELETEA(items[i]); OP_DELETEA(items); } } } BOOL OpColorMatrix::IsParentInputContextAvailabilityRequired() { // Normally we don't allow focus to move to a different window, but // we really need focus in this one to make it usable. return CanHaveFocusInPopup() ? FALSE : TRUE; } BOOL OpColorMatrix::OnInputAction(OpInputAction* action) { switch (action->GetAction()) { case OpInputAction::ACTION_PREVIOUS_ITEM: case OpInputAction::ACTION_NEXT_ITEM: { int index = m_active_cell_index; if (index == -1) index = 0; else if (action->GetAction() == OpInputAction::ACTION_PREVIOUS_ITEM) index--; else if (action->GetAction() == OpInputAction::ACTION_NEXT_ITEM) index++; if (index >= 0 && index < m_num_colors) SetPickedColor(m_colors[index]); return TRUE; } break; case OpInputAction::ACTION_SELECT_ITEM: { if (listener) { listener->OnClick(this); return TRUE; } } break; } return FALSE; } // == OpColorBoxWindow ============================================= class OpColorBoxWindow : public WidgetWindow { public: OpColorBoxWindow(WidgetWindowHandler *handler) : WidgetWindow(handler), matrix(NULL), edit(NULL), button(NULL) {} OpColorMatrix *matrix; OpEdit *edit; OpButton *button; }; // == OpColorBoxColorSelectionCallback ============================= // Listen for the response from the platform/UI color picker. #ifdef WIDGETS_USE_NATIVECOLORSELECTOR class OpColorBoxColorSelectionCallback : public OpColorSelectionListener::ColorSelectionCallback { public: OpColorBoxColorSelectionCallback(OpColorBox *colorbox, COLORREF initial_color) : m_colorbox(colorbox) , m_initial_color(initial_color) { } ~OpColorBoxColorSelectionCallback() { m_colorbox->ResetColorSelectionCallback(); } void OnColorSelected(COLORREF color) { m_colorbox->SetColor(color, FALSE); OP_DELETE(this); } void OnCancel() { OP_DELETE(this); } COLORREF GetInitialColor() { return m_initial_color; } OpColorBox *m_colorbox; COLORREF m_initial_color; }; #endif // WIDGETS_USE_NATIVECOLORSELECTOR // == OpColorBox =================================================== DEFINE_CONSTRUCT(OpColorBox) OpColorBox::OpColorBox() : m_color(OP_RGB(0, 0, 0)) , m_is_readonly(FALSE) , m_is_hovering_button(FALSE) #ifdef WIDGETS_USE_NATIVECOLORSELECTOR , m_callback(NULL) #endif { #ifdef SKIN_SUPPORT SetSkinned(TRUE); GetBorderSkin()->SetImage("Dropdown Skin"); #endif } void OpColorBox::OnRemoving() { #ifdef WIDGETS_USE_NATIVECOLORSELECTOR if (m_callback) { // Tell the UI that we're going down and it should cancel dialog // or just unreference the callback. WindowCommander* wc = vis_dev->GetWindow()->GetWindowCommander(); OP_ASSERT(wc); if (wc) wc->GetColorSelectionListener()->OnColorSelectionCancel(wc); OP_DELETE(m_callback); } #endif } void OpColorBox::OnDeleted() { m_window_handler.OnOwnerDeleted(); } void OpColorBox::SetReadOnly(BOOL readonly) { if (m_is_readonly != readonly) { m_is_readonly = readonly; InvalidateAll(); } } void OpColorBox::SetColor(COLORREF color, bool force_no_onchange) { if (color != m_color) { m_color = color; InvalidateAll(); if (listener && !force_no_onchange) listener->OnChange(this); } } OP_STATUS OpColorBox::GetText(OpString &str) { if (!str.Reserve(10)) return OpStatus::ERR_NO_MEMORY; HTM_Lex::GetRGBStringFromVal(m_color, str.CStr(), TRUE); return OpStatus::OK; } OP_STATUS OpColorBox::SetText(const uni_char* text) { COLORREF c; RETURN_IF_ERROR(ParseColor(text, c)); SetColor(c, TRUE); return UpdateEditField(); } void OpColorBox::OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect) { widget_painter->DrawPopupableString(GetBounds(), m_is_hovering_button); UpdateWindow(); } #ifndef MOUSELESS void OpColorBox::OnMouseMove(const OpPoint &point) { BOOL is_inside = GetBounds().Contains(point) && !IsDead(); if (is_inside != m_is_hovering_button) { m_is_hovering_button = is_inside; InvalidateAll(); } } void OpColorBox::OnMouseLeave() { m_is_hovering_button = FALSE; InvalidateAll(); } void OpColorBox::OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks) { if (!m_is_readonly && IsEnabled()) { if (m_window_handler.GetWindow() || m_window_handler.IsClosingWindow()) CloseWindow(); else OpenWindow(); } } #endif // !MOUSELESS void OpColorBox::OpenWindow() { if (!m_window_handler.GetWindow()) { // Create window for color matrix if (OpColorBoxWindow *window = OP_NEW(OpColorBoxWindow, (&m_window_handler))) { OpWindow* parent_window = GetParentOpWindow(); OP_STATUS status = window->Init(OpWindow::STYLE_POPUP, parent_window); if (OpStatus::IsError(status)) { OP_DELETE(window); if (OpStatus::IsMemoryError(status)) ReportOOM(); } else { // Create color matrix and position it in the window. if (OpStatus::IsError(OpColorMatrix::Construct(&window->matrix))) OP_DELETE(window); else { OpWidget *root = window->GetWidgetContainer()->GetRoot(); root->SetParentInputContext(this); window->matrix->SetCanHaveFocusInPopup(TRUE); // Setup the color matrix window->matrix->PopulateFromDatalist(this); window->matrix->SetPickedColor(m_color); window->matrix->SetListener(this); window->GetWidgetContainer()->GetRoot()->AddChild(window->matrix, TRUE); // Setup edit field if (OpStatus::IsSuccess(OpEdit::Construct(&window->edit))) { window->edit->SetCanHaveFocusInPopup(TRUE); OpStatus::Ignore(window->edit->SetPattern(UNI_L("# "))); OpStatus::Ignore(window->edit->SetAllowedChars("0123456789abcdef")); window->edit->SetHasCssBackground(TRUE); window->edit->SetHasCssBorder(TRUE); window->edit->SetListener(this); window->matrix->AddChild(window->edit, FALSE); window->matrix->SetFocus(FOCUS_REASON_OTHER); } // Setup button for native color picker (if available) #ifdef WIDGETS_USE_NATIVECOLORSELECTOR if (OpStatus::IsSuccess(OpButton::Construct(&window->button))) { window->button->SetListener(this); OpString str; TRAPD(status, g_languageManager->GetStringL(Str::S_COLORPICKER_OTHER, str)); OpStatus::Ignore(status); OpStatus::Ignore(window->button->SetText(str.CStr())); window->matrix->AddChild(window->button, TRUE); } #endif // WIDGETS_USE_NATIVECOLORSELECTOR // Set background/foreground colors on matrix and editfield if (OpWidget::GetColor().use_default_foreground_color == FALSE) window->matrix->SetForegroundColor(OpWidget::GetColor().foreground_color); if (OpWidget::GetColor().use_default_background_color == FALSE) window->matrix->SetBackgroundColor(OpWidget::GetColor().background_color); m_window_handler.SetWindow(window); // Show window OpStatus::Ignore(UpdateEditField()); UpdateWindow(); } } } } } void OpColorBox::OnMove() { UpdateWindow(); } void OpColorBox::GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows) { *w = GetVisualDevice()->GetFontAveCharWidth() * 2 + GetInfo()->GetDropdownButtonWidth(this); *w += GetPaddingLeft() + GetPaddingRight(); if (!HasCssBorder()) *w += 4; } void OpColorBox::UpdateWindow() { OpColorBoxWindow *window = (OpColorBoxWindow *) m_window_handler.GetWindow(); if (!window) return; // Zoom cell size - based on font size and current zoom, but never smaller than DEFAULT_CELL_SIZE OpColorMatrix *matrix = window->matrix; matrix->SetCellSize(MAX(DEFAULT_CELL_SIZE, GetVisualDevice()->ScaleToScreen(font_info.size) + 4)); INT32 matrix_width = matrix->CalculateWidth(); INT32 matrix_height = matrix->CalculateHeight(); // Position editfield if (window->edit) { window->edit->SetFontInfo(font_info); window->edit->SetJustify(JUSTIFY_CENTER, FALSE); INT32 edit_width = 80, edit_height = 20; window->edit->GetPreferedSize(&edit_width, &edit_height, 0, 0); // Make sure there's room for it. matrix_width = MAX(matrix_width, edit_width); window->edit->SetRect(OpRect(1, matrix_height - 1, matrix_width - 2, edit_height)); // The edit lives in the matrix, extend its height: matrix_height += edit_height; } // Position button #ifdef WIDGETS_USE_NATIVECOLORSELECTOR if (window->button) { INT32 button_width, button_height = 20; window->button->GetPreferedSize(&button_width, &button_height, 0, 0); // Make sure there's room for the button. matrix_width = MAX(matrix_width, button_width); window->button->SetRect(OpRect(1, matrix_height - 1, matrix_width - 2, button_height)); // The button lives in the matrix, extend its height: matrix_height += button_height; } #endif // Position the matrix and window OpRect rect = AutoCompleteWindow::GetBestDropdownPosition(this, matrix_width, matrix_height); matrix->SetRect(OpRect(0, 0, matrix_width, matrix_height)); window->Show(TRUE, &rect); } OP_STATUS OpColorBox::UpdateEditField() { OpColorBoxWindow *window = (OpColorBoxWindow *) m_window_handler.GetWindow(); if (!window) return OpStatus::OK; OpString text; RETURN_IF_ERROR(GetText(text)); return window->edit->SetText(text, TRUE); } void OpColorBox::OnClick(OpWidget *widget, UINT32 id) { if (widget->GetType() == WIDGET_TYPE_COLOR_MATRIX) { OpColorMatrix *matrix = (OpColorMatrix *) widget; SetColor(matrix->GetPickedColor(), FALSE); m_window_handler.Close(); } #ifdef WIDGETS_USE_NATIVECOLORSELECTOR if (widget->GetType() == WIDGET_TYPE_BUTTON && !m_callback) { m_window_handler.Close(); // Request a color from the platform/UI WindowCommander* wc = vis_dev->GetWindow()->GetWindowCommander(); if (wc) { m_callback = OP_NEW(OpColorBoxColorSelectionCallback, (this, m_color)); if (m_callback) { wc->GetColorSelectionListener()->OnColorSelectionRequest(wc, m_callback); } } } #endif // WIDGETS_USE_NATIVECOLORSELECTOR } void OpColorBox::OnChange(OpWidget *widget, BOOL changed_by_mouse) { OpColorBoxWindow *window = (OpColorBoxWindow *) m_window_handler.GetWindow(); if (!window) return; if (widget == window->edit) { OpStatus::Ignore(SetText(window->edit->string.Get())); window->matrix->SetPickedColor(m_color); } } BOOL OpColorBox::OnInputAction(OpInputAction* action) { switch (action->GetAction()) { case OpInputAction::ACTION_PREVIOUS_ITEM: case OpInputAction::ACTION_NEXT_ITEM: case OpInputAction::ACTION_SELECT_ITEM: if (m_window_handler.GetWindow()) { OpColorBoxWindow *window = (OpColorBoxWindow *) m_window_handler.GetWindow(); return window->matrix->OnInputAction(action); } break; case OpInputAction::ACTION_FOCUS_NEXT_WIDGET: case OpInputAction::ACTION_FOCUS_PREVIOUS_WIDGET: if (m_window_handler.GetWindow()) { OpColorBoxWindow *window = (OpColorBoxWindow *) m_window_handler.GetWindow(); return window->GetWidgetContainer()->OnInputAction(action); } break; case OpInputAction::ACTION_CLOSE_DROPDOWN: { if (m_window_handler.GetWindow()) { CloseWindow(); return TRUE; } return FALSE; } case OpInputAction::ACTION_SHOW_DROPDOWN: { if (!m_window_handler.GetWindow()) { OpenWindow(); return TRUE; } break; } #ifdef _SPAT_NAV_SUPPORT_ case OpInputAction::ACTION_UNFOCUS_FORM: return g_input_manager->InvokeAction(action, GetParentInputContext()); #endif // _SPAT_NAV_SUPPORT_ } return FALSE; } void OpColorBox::OnFocus(BOOL focus,FOCUS_REASON reason) { } void OpColorBox::OnKeyboardInputLost(OpInputContext* new_input_context, OpInputContext* old_input_context, FOCUS_REASON reason) { if (!new_input_context || !new_input_context->IsChildInputContextOf(this)) CloseWindow(); InvalidateAll(); }
// stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다. // GnDirectx9Renderer.pch는 미리 컴파일된 헤더가 됩니다. // stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다. #include "GnDirectx9RendererPCH.h" GNDIRECTX9RENDERER_ENTRY void LinkError_GnDirectx9RendererFunc() { return; }
//https://www.spoj.com/problems/DEFKIN/ //Defkin SPOJ #include<iostream> #include<bits/stdc++.h> #include<algorithm> using namespace std; #define ll long long ll x[1000000]; ll y[1000000]; int main() { ll t; cin>>t; while(t--) { ll w,h; cin>>w>>h; ll n; cin>>n; for(ll i=0;i<n;i++) { cin>>x[i]>>y[i]; } sort(x,x+n); sort(y,y+n); ll dx =x[0],dy =y[0]; for(int i = 1;i<n;i++) { dx = max(dx,x[i] - x[i-1]); dy = max(dy,y[i] - y[i-1]); } dx = max(dx, w + 1 - x[n-1]); dy = max(dy, h + 1 - y[n-1]); cout<<(dx-1)*(dy-1); } return 0; }
#include<iostream> #include<vector> using std::vector; using std::cin; using std::cout; using std::endl; int main() { vector<int> v; int i; while(cin >> i) v.push_back(i); auto size = v.size(); size = size % 2 == 0 ? size/2 : (size / 2 + 1); for(decltype(v.size()) index = 0; index < size; index++) { decltype(v.size()) next = v.size() - index - 1; if(next != index) cout << v[index] + v[next] << endl; else cout << v[index] << endl; } return 0; }
#include <fstream> #include <iostream> #include "sodium.h" #include "cryptobox/core/HSM.hpp" #include "cryptobox/core/Storage.hpp" namespace cryptobox { HSM::HSM(std::string const& storagePath) : storagePath_{storagePath} { // bring up the key store entries_ = std::move(io::retrieve(storagePath_)); } HSM::~HSM() { // dump the key store io::dump(storagePath_, entries_); } std::optional<HandleT> HSM::Create() { // generate a handle auto handle = randombytes_random(); // fill in the public/private key std::vector<unsigned char> pubKey(crypto_sign_PUBLICKEYBYTES); std::vector<unsigned char> privKey(crypto_sign_SECRETKEYBYTES); crypto_sign_keypair(pubKey.data(), privKey.data()); // add an etry entries_[handle] = {pubKey, privKey}; return handle; } std::optional<Buffer> HSM::Sign(HandleT handle, Buffer const& msg) { // signed msg buffer std::vector<unsigned char> signedMsg(crypto_sign_BYTES + msg.size()); // get the private key if (auto iter = entries_.find(handle); iter != entries_.end()) { auto const& privKey = std::get<1>(iter->second); // sign unsigned long long signedMsgLen; crypto_sign(signedMsg.data(), &signedMsgLen, msg.data(), msg.size(), privKey.data()); assert(signedMsgLen>0 && "Assert Signed Msg Length is greater than 0"); signedMsg.resize(signedMsgLen); return signedMsg; } return {}; } std::optional<std::pair<HSM::Status, Buffer>> HSM::Verify( HandleT handle, Buffer const& signedMsg) { // reserve at least the size of the signed msg std::vector<unsigned char> msg(signedMsg.size()); if (auto iter = entries_.find(handle); iter != entries_.end()) { unsigned long long msgLen; Status status = Accepted; auto const& pubKey = std::get<0>(iter->second); if (crypto_sign_open(msg.data(), &msgLen, signedMsg.data(), signedMsg.size(), pubKey.data()) != 0) { status = Rejected; return std::pair{status, msg}; } assert(msgLen > 0 && "Assert Msg Length After Verification is greated than 0"); msg.resize(msgLen); return std::pair{status, msg}; } return {}; } }
#include <omtalk/Om/ObjectModel.h>
#include "Enemy.h" #include <string> #include <random> #include <ctime> using namespace std; void Enemy::_regenerateDefence(int defence) { // The defence of the Enemy decreases by 20% after each reset. Otherwise there is no way to kill the Don. _defence = (int)(defence - ((20 / 100)*defence)); } Enemy::Enemy(string name, char tile, int attack, int defence, int hp, int expVal, int level) { _name = name; _tile = tile; _attack = attack; _defence = defence; _hp = hp; _expVal = expVal; _level = level; } void Enemy::getPositionOfEnemy(int & x, int & y) { x = _x; y = _y; } void Enemy::setPositionOfEnemy(int x, int y) { _x = x; _y = y; } int Enemy::getEnemyAttack() { static mt19937 randomEngine(time(NULL)); uniform_int_distribution<int> attack(0, _attack); return attack(randomEngine); } int Enemy::takeDamage(int attack) {/* int originalDef = _defence; int temp = attack; attack -= _defence; if (attack <= 0) { _defence -= temp; return 0; } if (_defence <= 0) { _regenerateDefence(originalDef); } _hp -= attack; if (_hp > 0) { return 0; }*/ _hp -= attack; if (_hp > 0) return 0; return _expVal; } Enemy::~Enemy() { }
#include "SuperMutant.hpp" SuperMutant::SuperMutant(void) : Enemy(170, "Super Mutant"){ std::cout << "Gaaah. Me want smash heads !"<< std::endl; return; } SuperMutant::~SuperMutant(){ std::cout << "Aaargh ..."<< std::endl; return; } SuperMutant::SuperMutant(SuperMutant const & src) : Enemy(src){ // std::cout << "Copy constructor called" << std::endl; *this = src; return; } void SuperMutant::takeDamage(int dmg){ dmg -= 3; if(dmg > 0){ setHitPoints(getHP() - dmg); if(getHP() < 0){ setHitPoints(0); } } } SuperMutant & SuperMutant::operator=(SuperMutant const & rhs){ // std::cout << "Assignation operator called" << std::endl; setType(rhs.getType()); setHitPoints(rhs.getHP()); return *this; }
#include <iostream> #include <sstream> #include <cstdlib> #include <cstdio> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <iomanip> #include <set> #include <climits> #include <ctime> #include <complex> #include <cmath> #include <string> #include <cctype> #include <cstring> #include <algorithm> using namespace std; #define endl '\n' typedef pair<int,int> pii; typedef long double ld; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; const int maxn=1005; const int INF=0x3f3f3f3f; const double PI=acos(-1.0); const double EPS=1e-9; inline int sgn(double a){return a<-EPS? -1:a>EPS;} int dx[]={0,0,-1,1}; int dy[]={1,-1,0,0}; int n,m; char mp[maxn][maxn]; bool vis[maxn][maxn]; int ind[maxn][maxn]; map<int,int> num; int tind=0; int ans[maxn][maxn]; map<int,int> test; void dfs(int x,int y){ vis[x][y]=true; ind[x][y]=tind; num[tind]++; for(int k=0;k<4;k++){ int tx=x+dx[k]; int ty=y+dy[k]; if(tx>=0&&tx<n&&ty>=0&&ty<m&&mp[tx][ty]=='.'&&!vis[tx][ty]){ dfs(tx,ty); } } } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); // freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); cin>>n>>m; for(int i=0;i<n;i++) cin>>mp[i]; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(mp[i][j]=='.'&&!vis[i][j]){ dfs(i,j); tind++; } } } for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(mp[i][j]=='.'){ ans[i][j]=-1; }else{ ans[i][j]=1; test.clear(); for(int k=0;k<4;k++){ int tx=i+dx[k]; int ty=j+dy[k]; if(tx>=0&&tx<n&&ty>=0&&ty<m&&mp[tx][ty]=='.'){ if(test[ind[tx][ty]]==0){ test[ind[tx][ty]]=1; ans[i][j]+=num[ind[tx][ty]]; } } } } } } for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(ans[i][j]!=-1) cout<<ans[i][j]%10; else cout<<"."; } cout<<endl; } return 0; }
#ifndef INCLUDED_MATH_MATH_H #define INCLUDED_MATH_MATH_H namespace Math { class Vector3; } namespace Math{ //円周率 static const float pi = 3.14159265358979323846f; //角度の単位変換に使う static const float to_deg = 180.f / pi; static const float to_rad = pi / 180.f; //ラジアンから度に直す float To_Deg(float rad); //度からラジアンに直す float To_Rad(float deg); //度をもらうsin関数 float Sin(float deg); //度をもらうcos関数 float Cos(float deg); //度をもらうtan関数 float Tan(float deg); //floatをもらうasin関数 float Asin(float a); //floatをもらうacos関数 float Acos(float a); //floatをもらい度を返すatan2関数 float Atan2(float y, float x); //floatをもらうsqrt関数 float Sqrt(float a); //floatをもらうfabs関数 float Fabs(float a); //floatをもらうpow関数 nのp乗 float Pow(float n, float p); //intをもらうpow関数 nのp乗 int Pow(int n, int p); //floatをもらうexp関数 float Exp(float x); }//namespace Math #endif
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "10340" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif string substr,str; while( cin >> substr >> str ){ int i = 0; bool ans = false; for(int j = 0 ; j < str.size() ; j++ ){ if( str[j] == substr[i] ) i++; if( i == substr.size() ) ans = true; } if(ans) printf("Yes\n"); else printf("No\n"); } return 0; }
/**************************************************************************** ** Copyright (c) 2006 - 2011, the LibQxt project. ** See the Qxt AUTHORS file for a list of authors and copyright holders. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** * Neither the name of the LibQxt project 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ** <http://libqxt.org> <foundation@libqxt.org> *****************************************************************************/ #ifndef QXTABSTRACTHTTPCONNECTOR_H #define QXTABSTRACTHTTPCONNECTOR_H #include "qxtglobal.h" #include <QObject> #include <QHostAddress> #include "qhttpheader.h" QT_FORWARD_DECLARE_CLASS(QIODevice) QT_FORWARD_DECLARE_CLASS(QTcpServer) class QxtHttpSessionManager; class QxtSslServer; class QxtAbstractHttpConnectorPrivate; class QXT_WEB_EXPORT QxtAbstractHttpConnector : public QObject { friend class QxtHttpSessionManager; Q_OBJECT public: QxtAbstractHttpConnector(QObject* parent = 0); virtual bool listen(const QHostAddress& iface, quint16 port) = 0; virtual bool shutdown() = 0; virtual quint16 serverPort() const; protected: QxtHttpSessionManager* sessionManager() const; void addConnection(QIODevice* device); QIODevice* getRequestConnection(quint32 requestID); virtual bool canParseRequest(const QByteArray& buffer) = 0; virtual QHttpRequestHeader parseRequest(QByteArray& buffer) = 0; virtual void writeHeaders(QIODevice* device, const QHttpResponseHeader& header) = 0; private Q_SLOTS: void incomingData(QIODevice* device = 0); void disconnected(); private: void setSessionManager(QxtHttpSessionManager* manager); QXT_DECLARE_PRIVATE(QxtAbstractHttpConnector) }; class QxtHttpServerConnectorPrivate; class QXT_WEB_EXPORT QxtHttpServerConnector : public QxtAbstractHttpConnector { Q_OBJECT public: QxtHttpServerConnector(QObject* parent = 0, QTcpServer* server = 0); virtual bool listen(const QHostAddress& iface, quint16 port = 80); virtual bool shutdown(); virtual quint16 serverPort() const; QTcpServer* tcpServer() const; protected: virtual bool canParseRequest(const QByteArray& buffer); virtual QHttpRequestHeader parseRequest(QByteArray& buffer); virtual void writeHeaders(QIODevice* device, const QHttpResponseHeader& header); private Q_SLOTS: void acceptConnection(); private: QXT_DECLARE_PRIVATE(QxtHttpServerConnector) }; #if defined(QT_SECURETRANSPORT) || !defined(QT_NO_OPENSSL) class QXT_WEB_EXPORT QxtHttpsServerConnector : public QxtHttpServerConnector { Q_OBJECT public: QxtHttpsServerConnector(QObject* parent = 0); virtual bool listen(const QHostAddress& iface, quint16 port = 443); QxtSslServer* tcpServer() const; protected Q_SLOTS: virtual void peerVerifyError(const QSslError &error); virtual void sslErrors(const QList<QSslError> &errors); }; #endif class QxtScgiServerConnectorPrivate; class QXT_WEB_EXPORT QxtScgiServerConnector : public QxtAbstractHttpConnector { Q_OBJECT public: QxtScgiServerConnector(QObject* parent = 0); virtual bool listen(const QHostAddress& iface, quint16 port); virtual bool shutdown(); virtual quint16 serverPort() const; protected: virtual bool canParseRequest(const QByteArray& buffer); virtual QHttpRequestHeader parseRequest(QByteArray& buffer); virtual void writeHeaders(QIODevice* device, const QHttpResponseHeader& header); private Q_SLOTS: void acceptConnection(); private: QXT_DECLARE_PRIVATE(QxtScgiServerConnector) }; /* Commented out pending implementation class QxtFcgiConnectorPrivate; class QXT_WEB_EXPORT QxtFcgiConnector : public QxtAbstractHttpConnector { Q_OBJECT public: QxtFcgiConnector(QObject* parent = 0); virtual bool listen(const QHostAddress& iface, quint16 port); virtual bool shutdown(); private: QXT_DECLARE_PRIVATE(QxtFcgiConnector) }; */ #endif // QXTABSTRACTHTTPCONNECTOR_H
#include <sys/stat.h> #include <signal.h> #include "Version.h" #include "IniFile.h" #include "Configure.h" #include "Logger.h" #ifndef WIN32 #include <sys/time.h> #include <sys/resource.h> #include <unistd.h> #include <getopt.h> #endif void daemonize() { #ifndef WIN32 pid_t pid, sid; /* already a daemon */ if ( getppid() == 1 ) return; /* Fork off the parent process */ pid = fork(); if (pid < 0) { exit(EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { exit(EXIT_SUCCESS); } /* At this point we are executing as the child process */ /* Change the file mode mask */ umask(0); /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { exit(EXIT_FAILURE); } /* Redirect standard files to /dev/null */ freopen( "/dev/null", "r", stdin); freopen( "/dev/null", "w", stdout); freopen( "/dev/null", "w", stderr); #endif } Configure::Configure() { level = 0; server_id = 0; server_priority = 0 ; max_table = 0; max_user = 0; report_ip[0]='\0'; starttime = time(NULL); lasttime = starttime; isLogReport = 0; } const char* const short_options = "p:s:t:l:u:c:r:vdh"; struct option long_options[] = { { "port", 1, NULL, 'p' }, { "sid", 1, NULL, 's' }, { "level", 1, NULL, 'l' }, { "priority", 1, NULL, 'r' }, { "maxuser", 1, NULL, 'u' }, { "maxtab", 1, NULL, 'c' }, { "daemon", 0, NULL, 'd' }, { "version", 0, NULL, 'v' }, { "help", 0, NULL, 'h' }, { "config", 0, NULL, 'f' }, { 0, 0, 0, 0}, }; void printHelp() { #ifdef ____DEBUG_VERSION____ printf("showhand server: %s.%s.%s\n",VERSION,SUBVER,"DEBUG_VERSION"); #else printf("showhand server: %s.%s.%s\n",VERSION,SUBVER,"RELEASE_VERSION"); #endif printf("-%s %-10s %-15s %s\n", "p","--port","<port>","tcp port number to listen on"); printf("-%s %-10s %-15s %s\n", "l","--level","<level>","server level for player 1- 50 coin, 2- 500 coin, 3- 5000 coin , 4- 50000 coin"); printf("-%s %-10s %-15s %s\n", "s","--svid","<server id>","server id of this progress"); printf("-%s %-10s %-15s %s\n", "r","--priority","<server priority>","priority for this game progress"); printf("-%s %-10s %-15s %s\n", "u","--maxuser","<max user>","max online user count"); printf("-%s %-10s %-15s %s\n", "c","--maxtab","<max table>","max table count"); printf("-%s %-10s %-15s %s\n", "r","--reportip","<report ip>",""); printf("-%s %-10s %-15s %s\n", "d","--daemonize","","run as a daemon"); printf("-%s %-10s %-15s %s\n", "v","--version","","print version info"); printf("-%s %-10s %-15s %s\n", "h","--help","","print this help and exit"); printf("-%s %-10s %-15s %s\n", "f","--config","","print config info"); printf("\n"); } int Configure::parse_args(int argc, char *argv[]) { if(argc==1) { printHelp(); return -1; } int opt; while ((opt = getopt_long (argc, argv, short_options, long_options, NULL)) != -1) { switch (opt) { case 'p': port = atoi(optarg); break; case 'l': level = atoi(optarg); break; case 's': //server Id server_id = atoi(optarg); break; case 'r': server_priority = atoi(optarg); break; case 'u': max_user = atoi(optarg); break; case 'c': max_table = atoi(optarg); break; case 'd': { signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN); daemonize(); } break; case 'v': #ifdef ____DEBUG_VERSION____ printf("showhand server: %s.%s.%s\n",VERSION,SUBVER,"DEBUG_VERSION"); #else printf("showhand server: %s.%s.%s\n",VERSION,SUBVER,"RELEASE_VERSION"); #endif return -1; case 'h': printHelp(); return -1; case 'f': read_conf("../conf/showhand.ini"); printConf(); return -1; case ':': printHelp(); printf("-%c requires an argument\n",opt); return -1; default: printHelp(); printf("Parse error.\n"); return -1; } } if(port==0) { printf("Please Input server_port: -p port\n"); printHelp(); return -1; } if(server_id==0) { printf("Please Input server_id: -s svid\n"); printHelp(); return -1; } if(level==0) { printf("Please Input level: -l level\n"); printHelp(); return -1; } return 0; } int Configure::read_conf(const char file[256]) { IniFile iniFile(file); if(!iniFile.IsOpen()) { printf("Open IniFile Error:[%s]\n",file); return -1; } //日志 m_loglevel = iniFile.ReadInt("Log", "LEVEL", 0); m_logRemoteIp = iniFile.ReadString("Log", "RemoteIp", ""); m_logRemotePort = iniFile.ReadInt("Log", "RemotePort", 0); //最大棋桌 最大人数 if(max_table==0) max_table = iniFile.ReadInt("Room" ,"MaxTable", 100); if(max_user==0) max_user = iniFile.ReadInt("Room" ,"MaxUser", 500); monitor_time = iniFile.ReadInt("Room" ,"MonitorTime", 30); keeplive_time = iniFile.ReadInt("Room" ,"KeepliveTime", 100); wincoin1 = iniFile.ReadInt("Room", "TrumptCoin1", 50000); wincoin2 = iniFile.ReadInt("Room", "TrumptCoin2", 10000); wincoin3 = iniFile.ReadInt("Room", "TrumptCoin3", 5000); wincoin4 = iniFile.ReadInt("Room", "TrumptCoin4", 2000); loserate = iniFile.ReadInt("Room" ,"LoseRate", 80); contrllevel = iniFile.ReadInt("Room" ,"ContrlLevel", 2); std::string report = iniFile.ReadString("Report", "IP", ""); strcpy( report_ip, report.c_str() ); char key[15]; sprintf(key,"Alloc_%d",this->level); //匹配服务器 std::string alloc_host = iniFile.ReadString(key,"Host","NULL"); strcpy( alloc_ip, alloc_host.c_str() ); alloc_port = iniFile.ReadInt(key,"Port",0); numplayer = iniFile.ReadInt(key,"NumPlayer",4); rewardcoin = iniFile.ReadInt(key,"RewardCoin",1000000); rewardroll = iniFile.ReadInt(key,"RewardRoll",1000000); rewardRate = iniFile.ReadInt(key,"RewardRate",80); //数据库操作服务器 std::string back_mysql_host = iniFile.ReadString("MySqlServer","Host","NULL"); strcpy( mysql_ip, back_mysql_host.c_str() ); mysql_port = iniFile.ReadInt("MySqlServer","Port",0); //经验服务器 std::string back_round_host = iniFile.ReadString("RoundServer","Host","NULL"); strcpy( round_ip, back_round_host.c_str() ); round_port = iniFile.ReadInt("RoundServer","Port",0); //日志服务器 std::string log_server_host = iniFile.ReadString("LogServer","Host","NULL"); strcpy( log_server_ip, log_server_host.c_str() ); log_server_port = iniFile.ReadInt("LogServer","Port",0); isLogReport = iniFile.ReadInt("LogServer" ,"IsLogReport", 0); //redis ip port std::string redis_host = iniFile.ReadString("REDIS","Host","NULL"); redis_port = iniFile.ReadInt("REDIS","Port",0); strcpy( redis_ip, redis_host.c_str() ); //redis ip port std::string redis_thost = iniFile.ReadString("REDIS","THost","NULL"); redis_tport = iniFile.ReadInt("REDIS","TPort",0); strcpy( redis_tip, redis_thost.c_str() ); //redis ip port std::string redis_nhost = iniFile.ReadString("REDIS","NHost","NULL"); redis_nport = iniFile.ReadInt("REDIS","NPort",0); strcpy( redis_nip, redis_nhost.c_str() ); std::string redist_host = iniFile.ReadString("REDIS","TaskHost","NULL"); taskredis_port = iniFile.ReadInt("REDIS","TaskPort",0); strcpy( taskredis_ip, redist_host.c_str() ); //服务器 std::string server_host = iniFile.ReadString("GameServer","Host","0.0.0.0"); strcpy( listen_address, server_host.c_str() ); if(alloc_port == 0 || mysql_port == 0 ||log_server_port == 0 || redis_port == 0) { printf("allocinfo alloc_port is null is error or mysql_port or log_server is null or redis_port is null level:%d\n", this->level); return -1; } //屏蔽词服务器 std::string word_server_host = iniFile.ReadString("WordServer","Host","NULL"); strcpy( word_server_ip, word_server_host.c_str() ); word_server_port = iniFile.ReadInt("WordServer","Port",0); //UDP服务器 std::string udp_server_host = iniFile.ReadString("UDPServer","Host","NULL"); strcpy( udp_ip, udp_server_host.c_str() ); udp_port = iniFile.ReadInt("UDPServer","Port",0); maxmulone = iniFile.ReadInt("MaxMul","MulOneRound",4); maxmultwo = iniFile.ReadInt("MaxMul","TwoOneRound",5); betcointime = iniFile.ReadInt("Timer","BetCoinTime",20); tablestarttime = iniFile.ReadInt("Timer","TableStartTime",20); kicktime = iniFile.ReadInt("Timer","KickTime",10); timeoutCount = iniFile.ReadInt("TimeOutCount","num",2); fraction = iniFile.ReadInt("Fraction","num",100); esayTaskCount = iniFile.ReadInt("EsayTask","PlayCount",30); esayRandNum = iniFile.ReadInt("EsayTask","RandNum",60); esayTaskRand = iniFile.ReadInt("EsayTask","TaskRand",50); curBeforeCount = iniFile.ReadInt("EsayTask","curBeforeCount",10); esayTaskProbability = iniFile.ReadInt("EsayTask","esayTaskProbability",80); getIngotNoti1 = iniFile.ReadInt("Notify","Num1",10); getIngotNoti2 = iniFile.ReadInt("Notify","Num2",10); getIngotNoti3 = iniFile.ReadInt("Notify","Num3",10); robotTabNum1 = iniFile.ReadInt("RobotTab","Num1",10); robotTabNum2 = iniFile.ReadInt("RobotTab","Num2",10); robotTabNum3 = iniFile.ReadInt("RobotTab","Num3",2); for(int i = 0; i < 10; ++i) { char szhost[16]; char szport[16]; sprintf(szhost,"Host_%d",i); sprintf(szport,"Port_%d",i); std::string temp_server_host = iniFile.ReadString("CheckRedis",szhost,"NULL"); strcpy( CheckInGame[i].host, temp_server_host.c_str() ); CheckInGame[i].port = iniFile.ReadInt("CheckRedis",szport,0); } std::string offline_redis_host = iniFile.ReadString("REDIS", "OfflineHost", "NULL"); offline_redis_port = iniFile.ReadInt("REDIS", "OfflineRedisPort", 6380); strcpy(offline_redis_ip, offline_redis_host.c_str()); //运维用服务器 std::string operation_redis_host = iniFile.ReadString("REDIS", "OperationHost", "NULL"); operation_redis_port = iniFile.ReadInt("REDIS", "OperationPort", 0); strcpy(operation_redis_ip, operation_redis_host.c_str()); return 0; } void Configure::printConf() { printf("==============SysConfig=================\n"); printf("LogRemoteIp=[%s]\n", m_logRemoteIp.c_str()); printf("LogRemotePort=[%d]\n", m_logRemotePort); printf("LogLevel=[%d]\n", m_loglevel); printf("server_id=[%d]\n",server_id); printf("server_level=[%d]\n",level); printf("listen_address=[%s]\n",listen_address); printf("server_port=[%u]\n",port); printf("server_priority=[%d]\n",server_priority); printf("report_ip=[%s]\n",report_ip); printf("redis_host=[%s]\n",redis_ip); printf("redis_port=[%u]\n",redis_port); printf("redis_thost=[%s]\n",redis_tip); printf("redis_tport=[%u]\n",redis_tport); printf("redis_nhost=[%s]\n",redis_nip); printf("redis_nport=[%u]\n",redis_nport); printf("MaxTable=[%d]\n",max_table); printf("MaxUser=[%d]\n",max_user); printf("monitor_time=[%u]\n",monitor_time); printf("keeplive_time=[%u]\n",keeplive_time); printf("alloc_ip=[%s]\n",alloc_ip); printf("alloc_port=[%u]\n",alloc_port); printf("numplayer=[%u]\n",numplayer); printf("udp_ip=[%s]\n",udp_ip); printf("udp_port=[%u]\n",udp_port); printf("maxmulone=[%d]\n",maxmulone); printf("maxmultwo=[%d]\n",maxmultwo); printf("betcointime=[%d]\n",betcointime); printf("tablestarttime=[%d]\n",tablestarttime); printf("timeoutCount=[%d]\n",timeoutCount); printf("kicktime=[%d]\n",kicktime); printf("fraction=[%d]\n",fraction); printf("esayTaskCount=[%d]\n",esayTaskCount); printf("getIngotNoti1=[%d]\n",getIngotNoti1); printf("getIngotNoti2=[%d]\n",getIngotNoti2); printf("getIngotNoti3=[%d]\n",getIngotNoti3); printf("=====================================\n"); }
#include <iostream> template<typename T> bool Copy_equality(T x) { T{x} == x; } template<typename T> bool Copy_assing_equality(T x, T &y) { return (y = x, y == x); } template<typename T> bool Move_assign_effect(T x, T &y, T &z) { return (y == z ? (x == std::move(y), x == z): true) and can_destroy(y); } int main() { return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) Opera Software ASA 1995 - 2011 * * EcmaScript_Manager -- API for access to the ECMAScript engine * Lars T Hansen */ #include "core/pch.h" #include "modules/ecmascript/ecmascript.h" #include "modules/ecmascript/carakan/ecmascript_parameters.h" #include "modules/ecmascript/carakan/src/ecmascript_manager_impl.h" #include "modules/ecmascript/carakan/src/es_program_cache.h" #include "modules/ecmascript/carakan/src/ecma_pi.h" #include "modules/ecmascript/carakan/src/es_pch.h" #include "modules/util/adt/bytebuffer.h" #include "modules/util/tempbuf.h" #include "modules/pi/OpSystemInfo.h" #ifndef _STANDALONE #include "modules/util/opfile/opfile.h" #include "modules/url/url_man.h" #include "modules/dom/domenvironment.h" #endif // _STANDALONE #include "modules/hardcore/cpuusagetracker/cpuusagetrackeractivator.h" #ifndef ARRAY_SIZE # define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) #endif EcmaScript_Manager::RuntimeOrContext::RuntimeOrContext(ES_Runtime *runtime) : runtime(runtime), context(NULL) { OP_ASSERT(runtime); } EcmaScript_Manager::RuntimeOrContext::RuntimeOrContext(ES_Context *context) : runtime(NULL), context(context) { OP_ASSERT(context); } /* static */ EcmaScript_Manager* EcmaScript_Manager::MakeL() { EcmaScript_Manager* em = OP_NEW_L(EcmaScript_Manager_Impl, ()); #ifndef _STANDALONE LEAVE_IF_ERROR(g_main_message_handler->SetCallBack(em, MSG_ES_COLLECT, 0)); #endif // _STANDALONE return em; } EcmaScript_Manager::EcmaScript_Manager() : pending_collections(FALSE) , maintenance_gc_running(FALSE) , first_host_object_clone_handler(NULL) #ifdef ECMASCRIPT_DEBUGGER , reformat_runtime(NULL) , want_reformat(FALSE) #endif // ECMASCRIPT_DEBUGGER , property_name_translator(NULL) #ifdef ES_HEAP_DEBUGGER , heap_id_counter(0) #endif // ES_HEAP_DEBUGGER { // If we use a DLL it is initialized on demand, not here. } /* virtual */ EcmaScript_Manager::~EcmaScript_Manager() { #ifndef _STANDALONE g_main_message_handler->RemoveCallBacks(this, 0); #endif // _STANDALONE OP_DELETE(property_name_translator); property_name_translator = NULL; ES_HostObjectCloneHandler *handler = first_host_object_clone_handler; while (handler) { first_host_object_clone_handler = handler->next; OP_DELETE(handler); handler = first_host_object_clone_handler; } } EcmaScript_Manager_Impl::EcmaScript_Manager_Impl() : EcmaScript_Manager() { } /* virtual */ EcmaScript_Manager_Impl::~EcmaScript_Manager_Impl() { GarbageCollect(); ESRT::Shutdown(g_esrt); } #ifndef _STANDALONE /* virtual */ void EcmaScript_Manager_Impl::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { TRACK_CPU_PER_TAB(g_ecma_gc_cputracker); OP_ASSERT(msg == MSG_ES_COLLECT); if (par2) MaintenanceGarbageCollect(); else GarbageCollect(TRUE, par1 ? ~0 : 0); } #endif // _STANDALONE void EcmaScript_Manager::PurgeDestroyedHeaps() { for (Link *heap = destroy_heaps.First(); heap != NULL;) { ES_Heap *to_remove = static_cast<ES_Heap *>(heap); heap = heap->Suc(); ES_Heap::Destroy(to_remove); } } void EcmaScript_Manager::GarbageCollect(BOOL unconditional/*=TRUE*/, unsigned int timeout/*=0*/) { #ifdef _STANDALONE if (timeout == 0) { for (Link *heap = destroy_heaps.First(); heap != NULL;) { ES_Heap *to_remove = static_cast<ES_Heap *>(heap); heap = heap->Suc(); ES_Heap::Destroy(to_remove); } for (Link *heap = active_heaps.First(); heap != NULL; heap = heap->Suc()) static_cast<ES_Heap *>(heap)->ForceCollect(NULL, GC_REASON_EXTERN); for (Link *heap = inactive_heaps.First(); heap != NULL; heap = heap->Suc()) static_cast<ES_Heap *>(heap)->ForceCollect(NULL, GC_REASON_EXTERN); } #else // _STANDALONE if (unconditional) { if (timeout == 0 || timeout == ~0U && pending_collections == TRUE) { PurgeDestroyedHeaps(); for (Link *heap = active_heaps.First(); heap != NULL; heap = heap->Suc()) static_cast<ES_Heap *>(heap)->ForceCollect(NULL, GC_REASON_EXTERN); for (Link *heap = inactive_heaps.First(); heap != NULL; heap = heap->Suc()) static_cast<ES_Heap *>(heap)->ForceCollect(NULL, GC_REASON_EXTERN); pending_collections = FALSE; } else if (timeout != ~0U) { pending_collections = TRUE; ES_ImportedAPI::PostGCMessage(timeout); } } else if (!pending_collections) { for (Link *heap = active_heaps.First(); heap != NULL; heap = heap->Suc()) static_cast<ES_Heap *>(heap)->MaybeCollect(NULL); for (Link *heap = inactive_heaps.First(); heap != NULL; heap = heap->Suc()) static_cast<ES_Heap *>(heap)->MaybeCollect(NULL); } #endif // _STANDALONE } void EcmaScript_Manager::ScheduleGarbageCollect() { #ifndef _STANDALONE ES_ImportedAPI::PostGCMessage(); #endif // _STANDALONE } void EcmaScript_Manager::StartMaintenanceGC() { #ifndef _STANDALONE if (!maintenance_gc_running) { maintenance_gc_running = TRUE; ES_ImportedAPI::PostMaintenanceGCMessage(ES_PARM_MAINTENANCE_GC_INTERVAL); } #endif // _STANDALONE } void EcmaScript_Manager::StopMaintenanceGC() { #ifndef _STANDALONE OP_ASSERT(maintenance_gc_running); maintenance_gc_running = FALSE; #endif // _STANDALONE } void EcmaScript_Manager::MaintenanceGarbageCollect() { #ifndef _STANDALONE unsigned current_time = g_op_time_info->GetRuntimeTickMS(); Head selected_heaps; unsigned selected_heap_count = 0; BOOL continue_running = FALSE; OP_ASSERT(maintenance_gc_running); PurgeDestroyedHeaps(); for (ES_Heap *heap = static_cast<ES_Heap *>(inactive_heaps.First()), *suc; heap != NULL; heap = suc) { suc = static_cast<ES_Heap *>(heap->Suc()); if (heap->NeedsMaintenanceGC(current_time)) { selected_heap_count++; ES_Heap *sheap = NULL; for (sheap = static_cast<ES_Heap *>(selected_heaps.First()); sheap != NULL; sheap = static_cast<ES_Heap *>(sheap->Suc())) if (heap->LastGC() <= sheap->LastGC()) { heap->Out(); heap->Precede(sheap); selected_heap_count++; break; } if (!sheap) { heap->Out(); heap->Into(&selected_heaps); } } if (heap->ActiveSinceLastGC()) continue_running = TRUE; } // Limit number of heaps to run gc on unsigned max_heaps_to_gc = selected_heap_count / ES_PARM_MAINTENANCE_GC_RATION + 1; if (selected_heap_count && max_heaps_to_gc != selected_heap_count) continue_running = TRUE; for (ES_Heap *heap = static_cast<ES_Heap *>(selected_heaps.First()); heap != NULL && max_heaps_to_gc-- > 0; heap = static_cast<ES_Heap *>(heap->Suc())) heap->ForceCollect(NULL, GC_REASON_MAINTENANCE); inactive_heaps.Append(&selected_heaps); #ifdef ES_NATIVE_SUPPORT // Remove all machine code on inactive heaps for (ES_Heap *heap = static_cast<ES_Heap *>(inactive_heaps.First()); heap != NULL; heap = static_cast<ES_Heap *>(heap->Suc())) if (!heap->ActiveRecently(current_time)) heap->FlushNativeDispatchers(); else continue_running = TRUE; #endif // ES_NATIVE_SUPPORT if (!continue_running) StopMaintenanceGC(); if (maintenance_gc_running) ES_ImportedAPI::PostMaintenanceGCMessage(ES_PARM_MAINTENANCE_GC_INTERVAL); #endif // _STANDALONE } BOOL EcmaScript_Manager::Protect(ES_Object *obj) { OP_ASSERT(!"Deprecated! Use ES_Runtime::Protect()."); /* Workaround: this works for host objects, at least. */ if (obj->IsHostObject()) return static_cast<ES_Host_Object *>(obj)->GetHostObject()->GetRuntime()->Protect(obj); return TRUE; } void EcmaScript_Manager::Unprotect(ES_Object *obj) { OP_ASSERT(!"Deprecated! Use ES_Runtime::Unrotect()."); /* Workaround: this works for host objects, at least. */ if (obj->IsHostObject()) return static_cast<ES_Host_Object *>(obj)->GetHostObject()->GetRuntime()->Unprotect(obj); } long EcmaScript_Manager::GetCurrHeapSize() { unsigned total_size = 0; for (ES_Heap *heap = static_cast<ES_Heap *>(active_heaps.First()); heap; heap = static_cast<ES_Heap *>(heap->Suc())) total_size += heap->GetBytesInHeap(); for (ES_Heap *heap = static_cast<ES_Heap *>(inactive_heaps.First()); heap; heap = static_cast<ES_Heap *>(heap->Suc())) total_size += heap->GetBytesInHeap(); return total_size; } BOOL EcmaScript_Manager::IsDebugging(ES_Runtime *runtime) { if (!runtime) return FALSE; #ifdef ECMASCRIPT_DEBUGGER return GetDebugListener() && GetDebugListener()->EnableDebugging(runtime); #else // ECMASCRIPT_DEBUGGER return FALSE; #endif // ECMASCRIPT_DEBUGGER } #ifdef ECMASCRIPT_DEBUGGER /* virtual */ ES_DebugListener::~ES_DebugListener() { /* Nothing, just here to kill GCC warnings */ } void EcmaScript_Manager::SetDebugListener(ES_DebugListener *listener) { if (!listener) { reformat_function.Unprotect(); if (reformat_runtime) { reformat_runtime->Detach(); reformat_runtime = NULL; } } g_esrt->debugger_listener = listener; } ES_DebugListener * EcmaScript_Manager::GetDebugListener() { return g_esrt->debugger_listener; } void EcmaScript_Manager::IgnoreError(ES_Context *context, ES_Value value) { // TODO: Implement /* ES_DebugControl ctl; ctl.op = ES_DebugControl::IGNORE_ERROR; ctl.u.ignore_error.context = context; ctl.u.ignore_error.value = &value; ES_DebuggerOp(&ctl); */ } static ES_Object ** CopyScopeChain(ES_Object **dst, ES_Object **src, unsigned length) { for (unsigned i = 0; i < length; i++) { *dst = src[i]; dst++; } return dst; } static ES_Object ** CopyScopeChainReversed(ES_Object **dst, ES_Object **src, unsigned length) { for (int i = length - 1; i >= 0; i--) { *dst = src[i]; dst++; } return dst; } void EcmaScript_Manager::GetScope(ES_Context *context, unsigned int frame_index, unsigned *length, ES_Object ***scope) { unsigned frame_length = *length; *length = 0; frame_index = frame_length - frame_index - 1; *scope = NULL; ES_FrameStackIterator frames(context->GetExecutionContext()); /* Look for "frame_index"th major frame; stopping at the one equal or closest to that count. */ while (frames.NextMajorFrame() && frame_index > 0) frame_index--; ES_Code *code = frames.GetCode(); ES_Object *variable_object = frames.GetVariableObject(); unsigned scope_chain_length = 0; unsigned function_scope_chain_length = 0; ES_Object **function_scope_chain = NULL; ES_Object *global_object = code->global_object; if (code && code->type == ES_Code::TYPE_FUNCTION) { ES_Function *current_function = frames.GetFunctionObject(); if (!variable_object) { variable_object = context->GetExecutionContext()->CreateVariableObject(current_function->GetFunctionCode(), frames.GetRegisterFrame() + 2); frames.SetVariableObject(variable_object); } function_scope_chain = current_function->GetScopeChain(); function_scope_chain_length = current_function->GetScopeChainLength(); } scope_chain_length = (variable_object ? 1 : 0) + function_scope_chain_length + code->scope_chain_length + context->GetExecutionContext()->GetExternalScopeChainLength(); // + 1 for global object (never NULL). ++scope_chain_length; if (context->rt_data->debugger_scope_chain == NULL || context->rt_data->debugger_scope_chain_length < scope_chain_length) { OP_DELETEA(context->rt_data->debugger_scope_chain); context->rt_data->debugger_scope_chain_length = 0; context->rt_data->debugger_scope_chain = OP_NEWA(ES_Object *, scope_chain_length); if (context->rt_data->debugger_scope_chain == NULL) return; context->rt_data->debugger_scope_chain_length = scope_chain_length; } ES_Object **dst = context->rt_data->debugger_scope_chain; dst = CopyScopeChain(dst, &variable_object, variable_object ? 1 : 0); dst = CopyScopeChain(dst, function_scope_chain, function_scope_chain_length); // The following two copies might be wrong. Might want to flip Reversed. dst = CopyScopeChainReversed(dst, code->scope_chain, code->scope_chain_length); dst = CopyScopeChain(dst, context->GetExecutionContext()->GetExternalScopeChain(), context->GetExecutionContext()->GetExternalScopeChainLength()); dst = CopyScopeChain(dst, &global_object, 1); OP_ASSERT(dst == context->rt_data->debugger_scope_chain + scope_chain_length); *scope = context->rt_data->debugger_scope_chain; *length = scope_chain_length; } void EcmaScript_Manager::GetStack(ES_Context *context, unsigned int maximum, unsigned int *length, ES_DebugStackElement **stack) { *length = context->GetExecutionContext()->BacktraceForDebugger(maximum); *stack = context->rt_data->debugger_call_stack; } void EcmaScript_Manager::GetExceptionValue(ES_Context *context, ES_Value *exception_value) { context->GetExecutionContext()->GetCurrentException().Export(context, *exception_value); } void EcmaScript_Manager::GetReturnValue(ES_Context *context, ES_Value *return_value) { context->GetExecutionContext()->ReturnValue().Export(context, *return_value); } ES_Object* EcmaScript_Manager::GetCallee(ES_Context *context) { return context->GetExecutionContext()->GetCallee(); } void EcmaScript_Manager::GetCallDetails(ES_Context *context, ES_Object **this_object, ES_Object **callee, int *argc, ES_Value **argv) { ES_Value this_value; context->GetExecutionContext()->GetCallDetails(this_value, *callee, *argc, *argv); if (this_value.type == VALUE_OBJECT) *this_object = this_value.value.object; else *this_object = NULL; } void EcmaScript_Manager::GetCallDetails(ES_Context *context, ES_Value *this_value, ES_Object **callee, int *argc, ES_Value **argv) { context->GetExecutionContext()->GetCallDetails(*this_value, *callee, *argc, *argv); } /* static */ OP_STATUS EcmaScript_Manager::GetFunctionPosition(ES_Object *function_object, unsigned &script_guid, unsigned &line_no) { if (!function_object || !function_object->IsNativeFunctionObject()) return OpStatus::ERR; ES_Function *function = static_cast<ES_Function *>(function_object); ES_FunctionCode *code = function->GetFunctionCode(); ES_FunctionCodeStatic *data = code->GetData(); script_guid = data->source.GetScriptGuid(); line_no = data->start_location.Line(); return OpStatus::OK; } static void GetObjectPropertiesImpl(ES_Context *context, ES_Object *object, ES_PropertyFilter *filter, BOOL skip_non_enum, uni_char ***names, ES_Value **values, GetNativeStatus **getstatus) { ES_Object *obj = ES_Value_Internal(object).GetObject(context); ES_Indexed_Properties *property_names = NULL; ES_Class *klass = NULL; unsigned size = 0; if (!obj->IsScopeObject()) { property_names = obj->GetOwnPropertyNamesSafeL(context, NULL, !skip_non_enum); size = ES_Indexed_Properties::GetUsed(property_names); } else { klass = obj->Class(); size = klass->Count(); } uni_char **lnames = *names = OP_NEWA(uni_char *, size + 1); ES_Value *lvalues = *values = OP_NEWA(ES_Value, size); GetNativeStatus *lgetstatuses = *getstatus = OP_NEWA(GetNativeStatus, size); ANCHOR_ARRAY(uni_char *, lnames); ANCHOR_ARRAY(ES_Value, lvalues); ANCHOR_ARRAY(GetNativeStatus, lgetstatuses); if (!lnames || !lvalues || !lgetstatuses) return; //TODO : Check return value from caller lnames[size] = NULL; ES_CollectorLock gclock(context); if (klass) { // The object is a proper scope object, which is guaranteed to only have class properties for (unsigned i = 0; i < size; ++i) { ES_Identifier_List *klass_table = klass->GetPropertyTable()->properties; JString *string; ES_Value_Internal result; klass_table->Lookup(i, string); if (!GET_OK(obj->GetL(context->GetExecutionContext(), string, result))) result.SetUndefined(); if (OpStatus::IsError(result.Export(context, *lvalues))) return; uni_char *name = StorageZ(context, string); if (filter && filter->Exclude(name, *lvalues)) continue; if (!(*lnames = uni_strdup(name))) return; *lgetstatuses = GETNATIVE_SUCCESS; lnames++, lvalues++, lgetstatuses++; *lnames = NULL; } } else if (property_names) { /* The object is set through the 'with' statement, and the ordinary kind of property enumeration is used; */ ES_Indexed_Property_Iterator iterator(context, NULL, property_names); unsigned index; while (iterator.Next(index)) { *lgetstatuses = GETNATIVE_SUCCESS; ES_Value_Internal value, result; BOOL res; iterator.GetValue(value); uni_char srcstr[16] = {0}; // ARRAY OK 2011-01-06 andre if (value.IsUInt32()) { UINT32 i = value.GetNumAsUInt32(); uni_itoa(i, srcstr, 10); res = obj->GetNativeL(context, i, result); if (!res) *lgetstatuses = GETNATIVE_NOT_OWN_NATIVE_PROPERTY; } else res = obj->GetNativeL(context, value.GetString(), result, NULL, lgetstatuses); if (!res) result.SetUndefined(); if (OpStatus::IsError(result.Export(context, *lvalues))) return; uni_char *name = *srcstr ? srcstr : StorageZ(context, value.GetString()); if (res && filter && filter->Exclude(name, *lvalues)) // we don't necessarily have the value here, so we need to do the exclution when we have continue; if (!(*lnames = uni_strdup(name))) return; lnames++, lvalues++, lgetstatuses++; *lnames = NULL; } } ANCHOR_ARRAY_RELEASE(lnames); ANCHOR_ARRAY_RELEASE(lvalues); ANCHOR_ARRAY_RELEASE(lgetstatuses); } void EcmaScript_Manager::GetObjectProperties(const RuntimeOrContext &runtime_or_context, ES_Object *object, ES_PropertyFilter *filter, BOOL skip_non_enum, uni_char ***names, ES_Value **values, GetNativeStatus **getstatus) { if (runtime_or_context.context) GetObjectPropertiesImpl(runtime_or_context.context, object, filter, skip_non_enum, names, values, getstatus); else { ES_Allocation_Context allocation_context(runtime_or_context.runtime); GetObjectPropertiesImpl(&allocation_context, object, filter, skip_non_enum, names, values, getstatus); } } /** * Look for a certain object in the prototype chain of another object. * * @param object Look in this object's prototype chain. * @param prototype The prototype object to look for. * @return TRUE if the prototype is present, 'FALSE' otherwise. */ static BOOL HasPrototype(ES_Object *object, ES_Object *prototype) { OP_ASSERT(prototype); while (object) if (object == prototype) return TRUE; else object = object->Class()->Prototype(); return FALSE; } void EcmaScript_Manager::GetObjectAttributes(ES_Runtime *runtime, ES_Object *object, ES_DebugObjectElement *attr) { ES_Allocation_Context context(runtime); ES_Object *obj = ES_Value_Internal(object).GetObject(&context); attr->prototype = obj->Class()->Prototype(); attr->classname = obj->Class()->ObjectName(); if (obj->IsFunctionObject()) { attr->u.function.alias = NULL; if (obj->IsHostObject()) { ES_Host_Function *host_function = static_cast<ES_Host_Function *>(obj); if (HasPrototype(obj, runtime->GetFunctionPrototype())) { attr->type = OBJTYPE_HOST_FUNCTION; attr->u.function.nformals = host_function->GetParameterTypesLength(); attr->u.function.name = StorageZ(&context, host_function->GetHostFunctionName()); } else attr->type = OBJTYPE_HOST_CALLABLE_OBJECT; } else { attr->type = OBJTYPE_NATIVE_FUNCTION; ES_Function *function = static_cast<ES_Function *>(obj); attr->u.function.nformals = function->GetLength(); if (function->GetFunctionCode()) { JString *debug_name = function->GetFunctionCode()->GetDebugName(); if (debug_name) attr->u.function.alias = StorageZ(&context, debug_name); } attr->u.function.name = StorageZ(&context, function->GetName(&context)); } } else if (obj->IsHostObject()) attr->type = OBJTYPE_HOST_OBJECT; else attr->type = OBJTYPE_NATIVE_OBJECT; } void EcmaScript_Manager::ObjectTrackedByDebugger(ES_Object *object, BOOL tracked) { object->TrackedByDebugger(tracked); } OP_STATUS EcmaScript_Manager::SetReformatConditionFunction(const uni_char *source) { reformat_function.Unprotect(); /* NULL or empty string disables the function. */ if (!source || !*source) return OpStatus::OK; /* Create runtime in which function will be compiled and code evaluated. */ if (!reformat_runtime) { OpAutoPtr<ES_Runtime> runtime(OP_NEW(ES_Runtime, ())); if (!runtime.get()) return OpStatus::ERR_NO_MEMORY; RETURN_IF_ERROR(runtime->Construct(NULL, NULL, TRUE)); reformat_runtime = runtime.release(); } /* Compile the function with a 'scriptData' argument declared. */ ES_Runtime::CreateFunctionOptions options; options.prevent_debugging = TRUE; options.generate_result = TRUE; options.context = UNI_L("Script reformat function compilation"); const uni_char *arg = UNI_L("scriptData"); ES_Object *function; RETURN_IF_ERROR(reformat_runtime->CreateFunction(NULL, 0, source, uni_strlen(source), &function, 1, &arg, options)); return reformat_function.Protect(reformat_runtime, function); } static BOOL ES_TimesliceExpiredCallback(void *) { /* Abort the script if did not finish within one timeslice. */ return TRUE; } BOOL EcmaScript_Manager::GetWantReformatScript(ES_Runtime *runtime, const uni_char *program_text, unsigned program_text_length) { BOOL reformat = want_reformat && IsDebugging(runtime); /* If program text is set and we have a reformat function compiled, run the function that will determine whether this particular script should be reformatted. */ if (reformat && program_text && reformat_function.GetObject()) { ES_Context *context = reformat_runtime->CreateContext(reformat_runtime->GetGlobalObject(), TRUE); if (!context) return FALSE; ES_ValueString program_string; program_string.string = program_text; program_string.length = program_text_length; ES_Value program_string_value; program_string_value.type = VALUE_STRING_WITH_LENGTH; program_string_value.value.string_with_length = &program_string; /* Push function and original script source as an argument. */ reformat_runtime->PushCall(context, reformat_function.GetObject(), 1, &program_string_value); int iter = 0; ES_Eval_Status eval_result; eval_result = reformat_runtime->ExecuteContext(context, iter, FALSE, FALSE, &ES_TimesliceExpiredCallback); ES_Value value; reformat_runtime->GetReturnValue(context, &value); /* Reformat the script only when program evaluates to 'true'. */ if (eval_result == ES_NORMAL_AFTER_VALUE && value.type == VALUE_BOOLEAN) reformat = value.value.boolean; else reformat = FALSE; reformat_runtime->DeleteContext(context); } return reformat; } #endif // ECMASCRIPT_DEBUGGER void EcmaScript_Manager::RegisterHostObjectCloneHandler(ES_HostObjectCloneHandler *handler) { handler->next = first_host_object_clone_handler; first_host_object_clone_handler = handler; } void EcmaScript_Manager::UnregisterHostObjectCloneHandler(ES_HostObjectCloneHandler *handler) { ES_HostObjectCloneHandler **ptr = &first_host_object_clone_handler; while (*ptr) if (*ptr == handler) { *ptr = handler->next; break; } else ptr = &(*ptr)->next; } BOOL EcmaScript_Manager::IsScriptSupported(const uni_char *type, const uni_char *language) { BOOL handle_script = FALSE; int n = 0; if (type && *type) { // Recognized MIME types for "JavaScript": // // application/ecmascript // application/javascript // application/x-ecmascript // application/x-javascript // text/ecmascript // text/javascript // text/javascript1.[0-5] // text/jscript // text/livescript // text/x-ecmascript // text/x-javascript // // All other MIME types are rejected. For recognized MIME types, // all parameters are considered unknown and the MIME type // is as a consequence rejected. Including 'version'. // // http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html#scriptingLanguages while (*type == ' ') ++type; if (uni_strni_eq(type, "TEXT/", 5)) { type += 5; check_script_media_type: BOOL with_x = FALSE; if (uni_strni_eq(type, "X-", 2)) { type += 2; with_x = TRUE; } if (uni_strni_eq(type, "JSCRIPT", 7)) { n = 7; handle_script = !with_x; } else if (uni_strni_eq(type, "JAVASCRIPT", 10)) { handle_script = TRUE; type += 10; if (!with_x && type[0] == '1' && type[1] == '.' && type[2] >= '0' && type[2] <= '5' && (!type[3] || type[3] == ' ')) n = 3; } else if (uni_strni_eq(type, "ECMASCRIPT", 10)) { n = 10; handle_script = TRUE; } else if (uni_strni_eq(type, "LIVESCRIPT", 10)) { n = 10; handle_script = !with_x; } } else if (uni_strni_eq(type, "APPLICATION/", 12)) { type += 12; if (uni_strni_eq(type, "X-", 2)) type += 2; if (uni_strni_eq(type, "JAVASCRIPT", 10)) { n = 10; handle_script = TRUE; } else if (uni_strni_eq(type, "ECMASCRIPT", 10)) { n = 10; handle_script = TRUE; } } type += n; while (*type == ' ') ++type; if (*type) handle_script = FALSE; } else if (language && *language) { // Language types supported are any of the text/.. types above // (but without the text/ bit.) type = language; goto check_script_media_type; } else handle_script = TRUE; return handle_script; } static OP_STATUS sanitize(OP_STATUS r) { if (OpStatus::IsMemoryError(r) || OpStatus::IsSuccess(r)) return r; else return OpStatus::ERR; } /* static */ OP_STATUS EcmaScript_Manager_Impl::Initialise() { OP_STATUS r = 0; g_esrt = NULL; TRAP(r, g_esrt = ESRT::Initialize()); if (OpStatus::IsError(r)) { if (g_esrt) ESRT::Shutdown(g_esrt); return sanitize(r); } #ifndef CONSTANT_DATA_IS_EXECUTABLE OpPseudoThread::InitCodeVectors(); #endif // CONSTANT_DATA_IS_EXECUTABLE #ifdef ES_NATIVE_SUPPORT extern void ES_SetupFunctionHandlers(); ES_SetupFunctionHandlers(); #endif // ES_NATIVE_SUPPORT return OpStatus::OK; } void EcmaScript_Manager::HandleOutOfMemory() { if (g_esrt && g_esrt->program_cache) g_esrt->program_cache->Clear(); } void EcmaScript_Manager::AddHeap(ES_Heap *heap) { heap->Into(&inactive_heaps); } void EcmaScript_Manager::RemoveHeap(ES_Heap *heap) { heap->Out(); } void EcmaScript_Manager::MoveHeapToDestroyList(ES_Heap *heap) { heap->Out(); heap->Into(&destroy_heaps); } void EcmaScript_Manager::MoveHeapToInactiveList(ES_Heap *heap) { heap->Out(); heap->Into(&inactive_heaps); } void EcmaScript_Manager::MoveHeapToActiveList(ES_Heap *heap) { heap->Out(); heap->Into(&active_heaps); } #ifdef ES_HEAP_DEBUGGER ES_Heap * EcmaScript_Manager::GetHeapById(unsigned id) { ES_Heap *heap; for (heap = static_cast<ES_Heap *>(active_heaps.First()); heap; heap = static_cast<ES_Heap *>(heap->Suc())) if (heap->Id() == id) return heap; for (heap = static_cast<ES_Heap *>(inactive_heaps.First()); heap; heap = static_cast<ES_Heap *>(heap->Suc())) if (heap->Id() == id) return heap; for (heap = static_cast<ES_Heap *>(destroy_heaps.First()); heap; heap = static_cast<ES_Heap *>(heap->Suc())) if (heap->Id() == id) return heap; return NULL; } void EcmaScript_Manager::ForceGCOnHeap(ES_Heap *heap) { heap->ForceCollect(NULL, GC_REASON_SHUTDOWN); } ES_Runtime * EcmaScript_Manager::GetNextRuntimePerHeap(ES_Runtime *runtime) { return runtime->next_runtime_per_heap; } #endif // ES_HEAP_DEBUGGER
/* 46450368 - 48579580 */ // Nicolás Saliba - Gonzalo Nicolari. // Instituto de Computación - Facultad de Ingeniería, Laboratorio de Programación 2. #include "../include/binario.h" #include "../include/cadena.h" #include "../include/uso_cadena.h" #include "../include/info.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> /* ceil */ #include <algorithm> /* max */ struct rep_binario { info_t dato; rep_binario *izq; rep_binario *der; }; binario_t crear_binario() { return NULL; } binario_t insertar_en_binario(info_t i, binario_t b) { if (es_vacio_binario(b)) { b = new rep_binario; b->dato = i; b->der = NULL; b->izq = NULL; } else { if (strcmp(frase_info(raiz(b)), frase_info(i)) < 0) b->der = insertar_en_binario(i, derecho(b)); else b->izq = insertar_en_binario(i, izquierdo(b)); } return b; } info_t mayor(binario_t b) { if (!es_vacio_binario(b)) if (!es_vacio_binario(derecho(b))) return mayor(derecho(b)); return (raiz(b)); } binario_t remover_mayor(binario_t b) { assert(!es_vacio_binario(b)); if (derecho(b) == NULL) { binario_t izq = izquierdo(b); delete(b); b = izq; } else b->der = remover_mayor(derecho(b)); return b; } static binario_t masDerecho(binario_t braiz, binario_t &padre, binario_t actual, binario_t result) { // Avanzo hasta el más derecho. if (!es_vacio_binario(derecho(actual))) result = masDerecho(braiz, actual, derecho(actual), result); else result = actual; // Arreglo el resto del árbol. if ((actual == result) && (padre != braiz)) padre->der = izquierdo(actual); return result; } static binario_t masIzquierdo(binario_t &padre, binario_t actual) { if (!es_vacio_binario(izquierdo(actual))) actual = masIzquierdo(actual, izquierdo(actual)); else if (!es_vacio_binario(derecho(actual))) padre->izq = derecho(actual); return actual; } binario_t remover_de_binario(const char *t, binario_t b) { if (strcmp(t, frase_info(raiz(b))) == 0) { if (es_vacio_binario(derecho(b)) && es_vacio_binario(izquierdo(b))) b = liberar_binario(b); else if (!es_vacio_binario(izquierdo(b))) { binario_t aux = crear_binario(); aux = masDerecho(b, b, izquierdo(b), aux); if (aux != izquierdo(b)) aux->izq = izquierdo(b); else { if (!es_vacio_binario(izquierdo(aux))) { binario_t aux2 = crear_binario(); aux2 = masDerecho(b, b, aux, aux2); aux2->izq = izquierdo(aux); aux2->der = derecho(aux); aux->izq = aux2; } else b->izq = NULL; } aux->der = derecho(b); info_t a_borrar = raiz(b); liberar_info(a_borrar); delete b; return aux; } else { binario_t aux = masIzquierdo(b, derecho(b)); if (aux != derecho(b)) { aux->izq = izquierdo(b); aux->der = derecho(b); } else { if (!es_vacio_binario(derecho(aux))) { binario_t aux2 = crear_binario(); aux2 = masDerecho(b, b, aux, aux2); aux2->izq = izquierdo(aux); aux2->der = derecho(aux); aux->izq = aux2; } else b->der = NULL; } info_t a_borrar = raiz(b); liberar_info(a_borrar); delete b; return aux; } } else if (strcmp(t, frase_info(raiz(b))) < 0) { if (!es_vacio_binario(izquierdo(b))) b->izq = remover_de_binario(t, izquierdo(b)); } else if (!es_vacio_binario(derecho(b))) b->der = remover_de_binario(t, derecho(b)); return b; } binario_t liberar_binario(binario_t b) { if (b != NULL) { b->izq = liberar_binario(izquierdo(b)); b->der = liberar_binario(derecho(b)); info_t a_borrar = raiz(b); liberar_info(a_borrar); delete b; b = NULL; } return b; } bool es_vacio_binario(binario_t b) { return b == NULL; } static int absoluto(int n) { return (n >= 0) ? (n) : (-n); } static bool auxEsAVL(binario_t actual, nat &altura) { bool esIzqAVL = false; bool esDerAVL = false; nat alturaIzq = 0; nat alturaDer = 0; if (!es_vacio_binario(actual)) { // Compruebo si los hijos son AVL. esIzqAVL = auxEsAVL(actual->izq, alturaIzq); esDerAVL = auxEsAVL(actual->der, alturaDer); altura = 1 + std::max(alturaDer, alturaIzq); return (absoluto(alturaIzq - alturaDer) <= 1) ? (esIzqAVL && esDerAVL) : false; } else { altura = 0; return true; } } bool es_AVL(binario_t b) { if (!es_vacio_binario(b)) { nat aux = 0; return auxEsAVL(b, aux); } else return true; } info_t raiz(binario_t b) { return (b->dato); } binario_t izquierdo(binario_t b) { return (b->izq); } binario_t derecho(binario_t b) { return (b->der); } binario_t buscar_subarbol(const char *t, binario_t b) { binario_t res; if (es_vacio_binario(b)) res = crear_binario(); else { if (strcmp(t, frase_info(raiz(b))) < 0) res = buscar_subarbol(t, izquierdo(b)); else if (strcmp(t, frase_info(raiz(b))) > 0) res = buscar_subarbol(t, derecho(b)); else res = b; } return res; } static int maximo(nat n1, nat n2) { return (n1 >= n2) ? (n1) : (n2); } nat altura_binario(binario_t b) { if (es_vacio_binario(b)) return 0; else return 1 + maximo(altura_binario(izquierdo(b)), altura_binario(derecho(b))); } static int auxCantBin(binario_t b, int cont) { if (!es_vacio_binario(izquierdo(b))) { cont++; cont = auxCantBin(izquierdo(b), cont); } if (!es_vacio_binario(derecho(b))) { cont++; cont = auxCantBin(derecho(b), cont); } return cont; } nat cantidad_binario(binario_t b) { if (es_vacio_binario(b)) return 0; else return auxCantBin(b, 1); } static nat auxSumaUltimosPares(binario_t actual, nat i, nat pos ,nat &cont, nat sumaPares) { if (!es_vacio_binario(actual)) { pos++; sumaPares = auxSumaUltimosPares(derecho(actual), i, pos, cont, sumaPares); if ((cont < i) && (numero_info(raiz(actual)) % 2) == 0) { cont++; sumaPares += numero_info(raiz(actual)); } sumaPares = auxSumaUltimosPares(izquierdo(actual), i, pos, cont, sumaPares); } return sumaPares; } int suma_ultimos_pares(nat i, binario_t b) { nat cont = 0; return auxSumaUltimosPares(b, i, 0, cont, 0); } static void lin(binario_t b, cadena_t c) { if (!es_vacio_binario(b)) { lin(izquierdo(b), c); insertar_al_final(copia_info(raiz(b)), c); lin(derecho(b), c); } } cadena_t linealizacion(binario_t b) { cadena_t result = crear_cadena(); lin(b, result); return result; } /* Devuelve la mitad de la cadena. */ static nat medioCadena(nat ini, nat fin) { return ceil(((double)ini + (double)fin) / 2); } static binario_t auxCadenaABinario(nat inicio, cadena_t cad, nat largo) { if (inicio > largo) return NULL; else { // Obtengo el elemento posicionado en la mitad de la cadena. binario_t result = new rep_binario; result->dato = copia_info(info_cadena(kesimo(medioCadena(inicio, largo), cad), cad)); // Divido la cadena y sigo con los hijos. result->izq = auxCadenaABinario(inicio, cad, medioCadena(inicio, largo) - 1); result->der = auxCadenaABinario(medioCadena(inicio, largo) + 1, cad, largo); return result; } } binario_t cadena_a_binario(cadena_t cad) { return !es_vacia_cadena(cad) ? auxCadenaABinario(1, cad, longitud(cad)) : crear_binario(); } /* Compara el elemento numérico de b con la clave y devuelve un booleano con el resultado de la comparación. */ static bool esMenor(binario_t b, int clave) { return numero_info(raiz(b)) < clave; } /* Busca la nueva raíz para el árbol de elementos que cumplen la condición (resultado). Si lo encuentra devuelve el elemento, si no devuelve NULL. */ static binario_t buscarNuevaRaiz(binario_t actual, int clave) { if (!es_vacio_binario(derecho(actual))) actual = buscarNuevaRaiz(derecho(actual), clave); if (esMenor(actual, clave)) return actual; // Si no encontré una nueva raíz busco en el hijo izquierdo. if (!es_vacio_binario(izquierdo(actual))) actual = buscarNuevaRaiz(izquierdo(actual), clave); return NULL; } static binario_t auxMenoresRecorrer(binario_t result, binario_t actual, int clave) { if (!es_vacio_binario(actual)) { if (esMenor(actual, clave)) // Verifico que no esté agregado porque podría llegar a ser una raíz obtenida en buscarNuevaRaiz. if (es_vacio_binario(buscar_subarbol(frase_info(raiz(actual)), result))) result = insertar_en_binario(copia_info(raiz(actual)), result); result = auxMenoresRecorrer(result, izquierdo(actual), clave); result = auxMenoresRecorrer(result, derecho(actual), clave); } return result; } static binario_t auxMenores(binario_t result, binario_t actual, int clave) { if (!es_vacio_binario(actual)) { if (esMenor(actual, clave)) { // Verifico que no esté agregado porque podría llegar a ser una raíz obtenida en buscarNuevaRaiz. if (es_vacio_binario(buscar_subarbol(frase_info(raiz(actual)), result))) result = insertar_en_binario(copia_info(raiz(actual)), result); } else if (!es_vacio_binario(izquierdo(actual))) { binario_t nuevaRaiz = buscarNuevaRaiz(izquierdo(actual), clave); if (!es_vacio_binario(nuevaRaiz)) { // Verifico que no esté agregado porque podría llegar a ser una raíz obtenida en buscarNuevaRaiz. if (es_vacio_binario(buscar_subarbol(frase_info(raiz(nuevaRaiz)), result))) result = insertar_en_binario(copia_info(raiz(nuevaRaiz)), result); } } result = auxMenoresRecorrer(result, derecho(actual), clave); result = auxMenoresRecorrer(result, izquierdo(actual), clave); } return result; } binario_t menores(int clave, binario_t b) { binario_t result = crear_binario(); if (!es_vacio_binario(b)) { if (esMenor(b, clave)) result = insertar_en_binario(copia_info(raiz(b)), result); else if (!es_vacio_binario(izquierdo(b))) { // Obtengo la nueva raiz del árbol a retornar. binario_t nuevaRaiz = buscarNuevaRaiz(izquierdo(b), clave); if (!es_vacio_binario(nuevaRaiz)) result = insertar_en_binario(copia_info(raiz(nuevaRaiz)), result); } // Ahora sigo con el resto del árbol. result = auxMenoresRecorrer(result, derecho(b), clave); result = auxMenores(result, izquierdo(b), clave); } return result; } static bool auxCamino(binario_t b, cadena_t c, localizador_t loc) { // Si empiezan igual. if (strcmp(frase_info(info_cadena(loc, c)), frase_info(raiz(b))) == 0) { // Compruebo si hay mas letras en la cadena. if (es_localizador(siguiente(loc, c))) { // Si debe avanzar a la izquierda o derecha en el árbol. if (strcmp(frase_info(info_cadena(siguiente(loc, c), c)), frase_info(raiz(b))) > 0) { if (!es_vacio_binario(derecho(b))) return auxCamino(derecho(b), c, siguiente(loc, c)); else return false; } else { if (!es_vacio_binario(izquierdo(b))) return auxCamino(izquierdo(b), c, siguiente(loc, c)); else return false; } // Compruebo si terminé en una hoja. } else if (es_vacio_binario(derecho(b)) && es_vacio_binario(izquierdo(b))) return true; } return false; } bool es_camino(cadena_t c, binario_t b) { return (!es_vacio_binario(b)) ? auxCamino(b, c, inicio_cadena(c)) : false; } static cadena_t auxNivel(binario_t b, cadena_t cad, localizador_t loc, nat actual, nat l) { if (!es_vacio_binario(b)) { actual++; if (actual == l) cad = insertar_al_final(copia_info(raiz(b)), cad); else { // Sigo buscando. cad = auxNivel(izquierdo(b), cad, loc, actual, l); cad = auxNivel(derecho(b), cad, loc, actual, l); } } return cad; } cadena_t nivel_en_binario(nat l, binario_t b) { cadena_t cad = crear_cadena(); cad = auxNivel(b, cad, inicio_cadena(cad), 0, l); return cad; } static void auxImprimirBinario(binario_t b, int cont) { if (!es_vacio_binario(derecho(b))) auxImprimirBinario(derecho(b), cont + 1); char *infoText = info_a_texto(raiz(b)); for (int i = 0; i < cont; i++) printf("-"); printf("%s", infoText); printf("\n"); delete[] infoText; if (!es_vacio_binario(izquierdo(b))) auxImprimirBinario(izquierdo(b), cont + 1); } void imprimir_binario(binario_t b) { printf("\n"); if (!es_vacio_binario(b)) auxImprimirBinario(b, 0); }
// // Created by 邦邦 on 2022/4/22. // #ifndef BB_POOL_H #define BB_POOL_H #include <vector> #include <list> #include <mutex> #include <future> #include <thread> #include <functional> #include "pool_wait.h" namespace bb{ class pool{ struct task_list{ task_list():lock(mutex,std::defer_lock){} std::thread thread{}; std::mutex mutex{}; std::unique_lock<std::mutex> lock; std::condition_variable condition{}; std::list<std::function<void()>> task{}; }; unsigned short index{}; //当前下标 unsigned short work_max; //最大线程数 std::vector<task_list> f_list{}; //任务 bool state_ = true; //为假停止阻塞 explicit pool(const unsigned short &max=3); ~pool(); void run(unsigned short &i); public: static pool &obj(const unsigned short &max=3); //当全部线程阻塞时,空出线程后将没有运行的项目运行 static pool_wait &objWait(const unsigned short &max=3); void push(const std::function<void()> &f); void close(); }; } #endif //BB_POOL_H
// config.h #pragma once #include <filesystem> #include <map> #include <string> namespace leap { namespace system { struct Config { void parse(const std::filesystem::path&); const std::string& get_str(const std::string& key, const std::string& default_value) const; float get_float(const std::string& key, float default_value) const; int get_int(const std::string& key, int default_value) const; bool get_bool(const std::string& key, bool default_value) const; protected: std::map<std::string, std::string> properties_; }; } // namespace system } // namespace leap
/* * **************************************************************************** * * * * * Copyright 2008, xWorkshop Inc. * * * All rights reserved. * * * Redistribution and use in source and binary forms, with or without * * * modification, are permitted provided that the following conditions are * * * met: * * * * Redistributions of source code must retain the above copyright * * * notice, this list of conditions and the following disclaimer. * * * * Redistributions in binary form must reproduce the above * * * copyright notice, this list of conditions and the following disclaimer * * * in the documentation and/or other materials provided with the * * * distribution. * * * * Neither the name of xWorkshop 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. * * * * * * Author: stoneyrh@163.com * * * * * **************************************************************************** */ #ifndef _XDATA_BUFFER_H_ #define _XDATA_BUFFER_H_ #include "xio.hxx" #include "xbyte_array.hxx" namespace xws { class xdata_buffer { public: xdata_buffer(); xdata_buffer(xbyte_array* byte_array); ~xdata_buffer(); void set_data(const xbyte_array& byte_array); void set_data(xbyte_ptr data, xsize_t size); xbyte_array byte_array() const { return *byte_array_; } xsize_t write(void* data, xsize_t size); xsize_t write(xint8_t value) { return write(&value, sizeof(value)); } xsize_t write(xint16_t value) { return write(&value, sizeof(value)); } xsize_t write(xint32_t value) { return write(&value, sizeof(value)); } xsize_t write(xint64_t value) { return write(&value, sizeof(value)); } xsize_t write(xuint8_t value) { return write(&value, sizeof(value)); } xsize_t write(xuint16_t value) { return write(&value, sizeof(value)); } xsize_t write(xuint32_t value) { return write(&value, sizeof(value)); } xsize_t write(xuint64_t value) { return write(&value, sizeof(value)); } // Write the end characters to indicate the end of string xsize_t write(const std::string& str) { // For empty string, we write an end character to indicate it is an empty string // So that when read out, we could tell now it is empty string return str.empty() ? write((void*)"\0", sizeof(char)) : write((void*)str.c_str(), (str.length() + 1) * sizeof(char)); } xsize_t write(const std::wstring& str) { // For empty string, we write an end character to indicate it is an empty string // So that when read out, we could tell now it is empty string return str.empty() ? write((void*)L"\0", sizeof(wchar_t)) : write((void*)str.c_str(), (str.length() + 1) * sizeof(wchar_t)); } xsize_t read(void* data, xsize_t size); xsize_t read(xint8_t& value) { return read(&value, sizeof(value)); } xsize_t read(xint16_t& value) { return read(&value, sizeof(value)); } xsize_t read(xint32_t& value) { return read(&value, sizeof(value)); } xsize_t read(xint64_t& value) { return read(&value, sizeof(value)); } xsize_t read(xuint8_t& value) { return read(&value, sizeof(value)); } xsize_t read(xuint16_t& value) { return read(&value, sizeof(value)); } xsize_t read(xuint32_t& value) { return read(&value, sizeof(value)); } xsize_t read(xuint64_t& value) { return read(&value, sizeof(value)); } xsize_t read(std::string& str); xsize_t read(std::wstring& str); xsize_t current_offset() const { return current_offset_; } void seek(xint32_t offset, seek_where where = seek_beg); bool at_end() const { return current_offset_ >= byte_array_->size(); } private: xbyte_array* byte_array_; xsize_t current_offset_; xbyte_array default_array_; }; } // namespace xws #endif
// // Created by heyhey on 20/03/2018. // #ifndef PLDCOMP_EXPRESSIONUNAIRE_H #define PLDCOMP_EXPRESSIONUNAIRE_H #include <ostream> #include "Expression.h" class ExpressionUnaire : public Expression { public: enum Operateur {VAGUE, PARENTHESE, EXCLAMATION}; ExpressionUnaire(); virtual ~ExpressionUnaire(); private: Operateur operateur; Expression* expression; public: Operateur getOperateur() const; void setOperateur(Operateur operateur); Expression* getExpression() const; void setExpression(Expression* expression); private: friend ostream &operator<<(ostream &os, const ExpressionUnaire &unaire); }; #endif //PLDCOMP_EXPRESSIONUNAIRE_H
#include <stdio.h> #include <memory.h> #include <pigpio.h> #include "rfHandlerV2.h" #include "coding/OokDecoder.h" #include "coding/KakuDecoder.h" #include "coding/NewKakuDecoder.h" #include "coding/OregonDecoder.h" #include "coding/AlectoDecoder.h" #include "Logger.h" #define MAX_STACK_ELEM 10 typedef struct { int first, last; OokDecoder *list[MAX_STACK_ELEM]; } stackMatches_t; static stackMatches_t matches = { 0, 0 }; static int b_Receive; #define MAX_DECODERS 20 OokDecoder *decoders[MAX_DECODERS]; int ndecoders = 0; void addDecoder(OokDecoder *pdecoder) { decoders[ndecoders++] = pdecoder; } void deleteDecoders() { for(int i=0; i!=ndecoders;i++) delete(decoders[i]); } void resetDecoders() { for(int i=0; i!=ndecoders;i++) decoders[i]->resetDecoder(); } OokDecoder *newDecoder(OokDecoder *pdecoder) { char *decoderName = pdecoder->getDecoderName(); if (!strcmp(decoderName,"KAKU")) return new KakuDecoder(pdecoder); if (!strcmp(decoderName,"NEWKAKU")) return new NewKakuDecoder(pdecoder); if (!strcmp(decoderName,"OREGON_V1")) return new OregonDecoderV1(pdecoder); if (!strcmp(decoderName,"OREGON_V2")) return new OregonDecoderV2(pdecoder); if (!strcmp(decoderName,"OREGON_V3")) return new OregonDecoderV3(pdecoder); if (!strcmp(decoderName,"ALECTO_V4")) return new AlectoDecoderV4(pdecoder); return NULL; } rfHandlerV2::rfHandlerV2(int dataPin, int trSelPin, int rsstPin, int pwdnPin) { this->dataPin = dataPin; this->trSelPin = trSelPin; this->rsstPin = rsstPin; this->pwdnPin = pwdnPin; /* Data & rsst pin as input */ gpioSetMode(this->dataPin, PI_INPUT); gpioSetMode(this->rsstPin, PI_INPUT); /* Trsel as output */ gpioSetMode(this->trSelPin, PI_OUTPUT); if (this->pwdnPin != -1) { gpioSetMode(this->pwdnPin, PI_OUTPUT); /* power on */ gpioWrite(this->pwdnPin,0); } /* 5ms max gap RSST_PIN last pulse */ //gpioSetWatchdog(this->rsstPin, TIME_OUT); /* monitor RSST_PIN level changes */ //gpioSetAlertFunc(this->rsstPin, alertRsst); // Arm data monitoring gpioSetAlertFunc(this->dataPin, alertData); addDecoder(new KakuDecoder()); addDecoder(new NewKakuDecoder()); addDecoder(new OregonDecoderV1()); addDecoder(new OregonDecoderV2()); addDecoder(new OregonDecoderV3()); addDecoder(new AlectoDecoderV4()); // Receive by default (send "on demand") setReceiveMode(); } rfHandlerV2::~rfHandlerV2() { deleteDecoders(); } void rfHandlerV2::setReceiveMode() { /* link device in receive mode TRSEL -> low */ gpioWrite(this->trSelPin,0); /* data gpio in input mode */ gpioSetMode(this->dataPin, PI_INPUT); gpioDelay(1000); /* 1ms delay ? */ b_Receive = true; resetDecoders(); } void rfHandlerV2::setSendMode() { b_Receive = false; /* link device in receive mode TRSEL -> high */ gpioWrite(this->trSelPin,1); gpioDelay(1000); /* 1ms delay ? */ /* data gpio in output mode */ gpioSetMode(this->dataPin, PI_OUTPUT); } OokDecoder *rfHandlerV2::popMatches() { OokDecoder *pmatch = NULL; if (matches.first != matches.last) { // Copy pulses in last position pmatch = matches.list[matches.first]; if (++matches.first == MAX_STACK_ELEM) matches.first = 0; } return pmatch; } void rfHandlerV2::pushMatches(OokDecoder *match) { int futureLast = matches.last; if (++futureLast == MAX_STACK_ELEM) futureLast = 0; // Not full stack ? if (futureLast != matches.first) { matches.list[matches.last] = match; matches.last = futureLast; } } static uint32_t lastTick; static OokDecoder *pdecoderFound = NULL; void rfHandlerV2::alertData(int gpio, int level, uint32_t tick) { uint32_t pulse = tick - lastTick; if (b_Receive) { // Debug //pulses.level[pulses.npulses] = level; //pulses.tick[pulses.npulses++] = tick; //if (pulses.npulses >= MAX_PULSES) // pulses.npulses = 0; //if (pulse < 32000 ) { int idecoder; for(idecoder = 0; idecoder!=ndecoders; idecoder++) { OokDecoder *pdecoder = decoders[idecoder]; //printf("nextPulse %ld\n",pulse); if (pdecoder->nextPulse(pulse)) { // Ok found pdecoderFound = pdecoder; break; } } if (pdecoderFound!=NULL) { //printf("!!! Found %s\n",pdecoderFound->getDecoderName()); pushMatches(newDecoder(pdecoderFound)); resetDecoders(); pdecoderFound = NULL; } //} else { // resetDecoders(); //} } lastTick = tick; } void displayPulses(pulses_t *p_pulses) { int i; printf("Pulses count = %d : ",p_pulses->npulses); for (i=0; i!= p_pulses->npulses; i++) { //printf("%d,%d,%d;",p_pulses->tick[i],p_pulses->level[i],(i>0)?p_pulses->tick[i]-p_pulses->tick[i-1]:-1); printf("%d,",p_pulses->tick[i]); } printf("\n"); } extern int g_RepeatDefault; extern long g_DelayDefault; /** * Send RF pulses * */ void rfHandlerV2::sendRF(int nrepeats, uint32_t delay, pulses_t *p_pulses) { setSendMode(); int bigRepeat = g_RepeatDefault; int bigDelay = g_DelayDefault; while(bigRepeat--) { for (int irepeat = 0; irepeat != nrepeats; irepeat++) { //displayPulses(p_pulses); for (int i=0; i!= p_pulses->npulses; i++) { gpioWrite(this->dataPin,p_pulses->level[i]); if (p_pulses->tick[i] > 0) gpioDelay(p_pulses->tick[i]); } gpioWrite(this->dataPin,0); gpioDelay(delay); //printf("delay = %ld\n",delay); } if (bigRepeat>0) { gpioDelay(bigDelay); //printf("Big delay = %ld\n",bigDelay); } } setReceiveMode(); } // Compatibility ... to be modified ... static char inputBuffer[60]; static struct RawSignalStruct RawSignal = {0,0,0,0,0,0L}; void rfHandlerV2::sendRFMessage(char *message) { // Repeat default & delay //RawSignal.Repeats = 3; //RawSignal.Delay = SEND_REPEAT_DELAY; RawSignal.Repeats = g_RepeatDefault; RawSignal.Delay = g_DelayDefault; strcpy(inputBuffer,message); for(int i=0; i!=ndecoders;i++) { if (decoders[i]->TX(inputBuffer,&RawSignal)) { pulses_t pulses; pulses.npulses = 0; int ilevel = 1; for (int i=1;i<RawSignal.Number;i++) { pulses.tick[pulses.npulses] = RawSignal.Pulses[i]; pulses.level[pulses.npulses] = ilevel; pulses.npulses++; ilevel = !ilevel; } // Send with repetition sendRF(RawSignal.Repeats, (uint32_t) RawSignal.Delay, &pulses); break; } } }
class desert_large_net_kit { weight = 50; }; class forest_large_net_kit { weight = 50; }; class desert_net_kit { weight = 25; }; class forest_net_kit { weight = 25; }; class winter_net_kit { weight = 25; }; class winter_large_net_kit { weight = 50; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "platforms/windows/pi/util/WindowsBackgroundClearer.h" #include "platforms/windows/pi/WindowsOpWindow.h" #include "platforms/windows/pi/WindowsOpMessageLoop.h" #include "platforms/windows/pi/util/WindowFrame.h" #include "adjunct/desktop_pi/DesktopOpUiInfo.h" #include "adjunct/desktop_util/prefs/PrefsCollectionDesktopUI.h" #include "adjunct/desktop_util/widget_utils/LogoThumbnailClipper.h" #include "adjunct/quick/widgets/OpPagebar.h" #include "modules/locale/oplanguagemanager.h" #include "modules/widgets/OpWidget.h" #include "modules/widgets/WidgetContainer.h" #include "modules/widgets/OpButton.h" #include "modules/skin/OpSkinManager.h" #include "modules/display/vis_dev.h" #include <VSStyle.h> #include <WinUser.h> extern HINSTANCE hInst; void AlphaBlt(HDC dst, INT32 dstx, INT32 dsty, INT32 dstwidth, INT32 dstheight, HDC src, INT32 srcx, INT32 srcy, INT32 srcwidth, INT32 srcheight); #ifdef _DEBUG extern void OutputDebugLogging(const uni_char *tmp, ...); extern void OutputDebugLogging(const uni_char *tmp, char *); #define CLEARER_TRACE(x, y) // OutputDebugLogging(x, y) #else #define CLEARER_TRACE(x, y) #endif // _DEBUG static inline bool isLanguageRTL() { return g_languageManager && g_languageManager->GetWritingDirection() == OpLanguageManager::RTL; } /* static */ OP_STATUS OpBorderButtons::Construct(OpBorderButtons** obj, WindowsOpWindow *window, HTHEME theme, BOOL pagebar_on_top) { // Only create the quick caption buttons when the title bar is not visible - this covers the conditions where this // is the case if(g_skin_manager->HasPersonaSkin() && !window->m_menubar_visibility && theme && (pagebar_on_top || window->m_fullscreen)) { *obj = OP_NEW(QuickBorderButtons, (window, theme)); CLEARER_TRACE(UNI_L("QuickBorderButtons created\n"), ""); } else { *obj = OP_NEW(NativeBorderButtons, (window, theme)); CLEARER_TRACE(UNI_L("NativeBorderButtons created\n"), ""); } if (*obj == NULL) return OpStatus::ERR_NO_MEMORY; OP_STATUS s = (*obj)->Init(); if (OpStatus::IsError(s)) { OP_DELETE(*obj); return s; } return OpStatus::OK; } /** * Those classes handles the regular themed max/min/close buttons in the windows border */ WindowsRectOffsets NativeBorderButtons::NativeBorderButton::ButtonIdToRectId() { OP_ASSERT(id != WINPART_NONE); switch(id) { case WINPART_CLOSE: return WIN_RECT_CLOSE_BUTTON; case WINPART_MAXIMIZE: return WIN_RECT_MAXIMIZE_BUTTON; case WINPART_MINIMIZE: return WIN_RECT_MINIMIZE_BUTTON; default: return WIN_RECT_CLOSE_BUTTON; //for the compiler to stop b... nagging about codepaths } } int NativeBorderButtons::NativeBorderButton::ButtonIdToWindowPart(bool is_maximized) { OP_ASSERT(id != WINPART_NONE); switch(id) { case WINPART_CLOSE: return WP_CLOSEBUTTON; case WINPART_MAXIMIZE: return is_maximized ? WP_RESTOREBUTTON : WP_MAXBUTTON; case WINPART_MINIMIZE: return WP_MINBUTTON; default: return WP_CLOSEBUTTON; //for the compiler } } int NativeBorderButtons::NativeBorderButton::GetCurrentButtonState(WindowsButtonId pushed, WindowsButtonId hovered, bool /*is_maximized*/, bool is_hwnd_active) { // 1. the hovered is respected no matter if windows is active or not // 2. if a button is pressed, however, hovered is not respected anymore; // with pressed, hovered is only used to apply PUSHED [3] state // 3. clicking a not active window activates it on mouse down; hovered and pressed are not used // 4. clicking an active window sends a sys command on mouse up if (is_hwnd_active && pushed != WINPART_NONE) return pushed == id && hovered == id ? CBS_PUSHED : CBS_NORMAL; else return hovered == id ? CBS_HOT : is_hwnd_active ? CBS_NORMAL : CBS_DISABLED; } void NativeBorderButtons::NativeBorderButton::Paint(HTHEME theme, HDC hdc, WindowsButtonId pushed, WindowsButtonId hovered, bool is_maximized, bool is_hwnd_active) { DrawThemeBackground(theme, hdc, ButtonIdToWindowPart(is_maximized), GetCurrentButtonState(pushed, hovered, is_maximized, is_hwnd_active), &btn_rect, NULL); } OP_STATUS NativeBorderButtons::Init() { METHOD_CALL; SetListener(this); SetUpdateNeededWhen(UPDATE_NEEDED_WHEN_VISIBLE); // add us first so we get painted last m_window->GetDesktopWindow()->GetWidgetContainer()->GetRoot()->AddChild(this, FALSE, TRUE); return OpStatus::OK; } NativeBorderButtons::~NativeBorderButtons() { SetListener(NULL); Remove(); } WindowsButtonId NativeBorderButtons::ButtonFromPoint(const OpPoint &point) { OpRect rect = GetRect(); POINT pt = { point.x + rect.x, point.y + rect.y }; #if 0 const char* part = "WINPART_NONE"; if (PtInRect(&m_btn_close.GetRect(), pt)) part = "WINPART_CLOSE"; else if (PtInRect(&m_btn_maximize.GetRect(), pt)) part = "WINPART_MAXIMIZE"; else if (PtInRect(&m_btn_minimize.GetRect(), pt)) part = "WINPART_MINIMIZE"; char buffer[1024]; sprintf(buffer, "(%d, %d) -> (%d, %d) -> %s\n", point.x, point.y, pt.x, pt.y, part); OutputDebugStringA(buffer); #endif if (PtInRect(&m_btn_close.GetRect(), pt)) return WINPART_CLOSE; else if (PtInRect(&m_btn_maximize.GetRect(), pt)) return WINPART_MAXIMIZE; else if (PtInRect(&m_btn_minimize.GetRect(), pt)) return WINPART_MINIMIZE; return WINPART_NONE; } void NativeBorderButtons::Paint(HDC dc) { METHOD_CALL; if(!dc) return; if (ShouldNotLayOut()) return; bool active = m_window->m_hwnd_active != FALSE; bool maximized = m_window->m_state == OpWindow::MAXIMIZED; m_btn_close.Paint(m_theme, dc, m_pushed, m_hovered, maximized, active); m_btn_maximize.Paint(m_theme, dc, m_pushed, m_hovered, maximized, active); m_btn_minimize.Paint(m_theme, dc, m_pushed, m_hovered, maximized, active); } void NativeBorderButtons::GetSize(INT32* w, INT32* h) { *w = GetSystemMetrics(SM_CXSIZE) * WIN_RECT_MAX; *h = GetSystemMetrics(SM_CYSIZE); } struct vals { template <typename T> static T minval(T a, T b) { return a < b ? a : b; } template <typename T> static T minval(T a, T b, T c) { return minval(c, minval(a, b)); } template <typename T> static T maxval(T a, T b) { return a > b ? a : b; } template <typename T> static T maxval(T a, T b, T c) { return maxval(c, maxval(a, b)); } }; bool NativeBorderButtons::ShouldNotLayOut() { //mimicking WindowFrame::UseCustomNativeFrame (only part of the expression is used): OpPagebar* pb = m_window->GetPagebar(); bool pagebar_on_top = pb && (pb->GetAlignment() == OpBar::ALIGNMENT_TOP && m_window->m_requested_titlebar_height > 0); // unless the skin is transparent, we're not going to want any kind of special close buttons hit handling bool transparent = !!(g_skin_manager->GetOptionValue("Transparency", FALSE) || g_skin_manager->GetOptionValue("Full Transparency", FALSE)); //Should layout on UX theme-enabled skins without menu bar and with pagebar on top return m_window->m_menubar_visibility || !m_theme || !pagebar_on_top || !transparent; } void NativeBorderButtons::OnLayout(OpWidget *widget) { if (widget != this) return; // Normally, client area is placed within // non-client area and is separate from the frame. // // If, however, we have an UX theme and we have OMenu, // then the coordinates are counted as if (0,0) was in // top-left corner of the window, including frame. // // If we do not have any theme, or we have a standard // menu bar, then we do not draw inside the frame and // the (0,0) will be within client area and the native // buttons will end up covering the trash button (tab // restore button). // // We don't want this... if (ShouldNotLayOut()) { SetRect(OpRect()); return; } RECT btnrect[WIN_RECT_MAX]; CalculateCaptionButtonRects(m_window, btnrect); //finding outline of all three buttons, //including spaces in between RECT out; out.left = vals::minval( btnrect[WIN_RECT_CLOSE_BUTTON].left, btnrect[WIN_RECT_MAXIMIZE_BUTTON].left, btnrect[WIN_RECT_MINIMIZE_BUTTON].left); out.top = vals::minval( btnrect[WIN_RECT_CLOSE_BUTTON].top, btnrect[WIN_RECT_MAXIMIZE_BUTTON].top, btnrect[WIN_RECT_MINIMIZE_BUTTON].top); out.right = vals::maxval( btnrect[WIN_RECT_CLOSE_BUTTON].right, btnrect[WIN_RECT_MAXIMIZE_BUTTON].right, btnrect[WIN_RECT_MINIMIZE_BUTTON].right); out.bottom = vals::maxval( btnrect[WIN_RECT_CLOSE_BUTTON].bottom, btnrect[WIN_RECT_MAXIMIZE_BUTTON].bottom, btnrect[WIN_RECT_MINIMIZE_BUTTON].bottom); SetRect(OpRect(&out)); m_btn_close.SetRect(btnrect); m_btn_maximize.SetRect(btnrect); m_btn_minimize.SetRect(btnrect); } void NativeBorderButtons::OnMouseMove(OpWidget *widget, const OpPoint &point) { WindowsButtonId hover = ButtonFromPoint(point); if (hover == m_hovered) return; m_hovered = hover; RECT inv = GetRect(); InvalidateRect(m_window->m_hwnd, &inv, TRUE); } void NativeBorderButtons::OnMouseLeave(OpWidget *widget) { WindowsButtonId hover = WINPART_NONE; if (hover == m_hovered) return; m_hovered = hover; RECT inv = GetRect(); InvalidateRect(m_window->m_hwnd, &inv, TRUE); } void NativeBorderButtons::OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks) { if (button == MOUSE_BUTTON_1) { m_pushed = ButtonFromPoint(point); RECT inv = GetRect(); InvalidateRect(m_window->m_hwnd, &inv, TRUE); } } void NativeBorderButtons::OnMouseUp(const OpPoint &point, MouseButton button, UINT8 nclicks) { if (button == MOUSE_BUTTON_1) { WindowsButtonId hover = ButtonFromPoint(point); WindowsButtonId current = m_pushed; m_pushed = WINPART_NONE; m_hovered = WINPART_NONE; //so that it does not immediately turn HOVERED if (hover != current || current == WINPART_NONE) return; RECT inv = GetRect(); InvalidateRect(m_window->m_hwnd, &inv, TRUE); int command = 0; switch(hover) { case WINPART_CLOSE: m_window->GetDesktopWindow()->Close(FALSE, TRUE); //mimicking QuickBorderButtons::OnClick return; case WINPART_MAXIMIZE: command = m_window->m_state == OpWindow::MAXIMIZED ? SC_RESTORE : SC_MAXIMIZE; break; case WINPART_MINIMIZE: command = SC_MINIMIZE; break; } PostMessage(m_window->m_hwnd, WM_SYSCOMMAND, command, 0); return; } } /** * This class handles the persona max/min/close buttons in the windows border */ QuickBorderButtons::~QuickBorderButtons() { // make sure the regular buttons are enabled for(int x = 0; x < WINICON_COUNT; x++) { if(!m_window_icons[x].IsEmpty()) { // decrease ref count on images m_window_icons[x].DecVisible(null_image_listener); } OP_DELETE(m_content_providers[x]); } SetListener(NULL); } OP_STATUS QuickBorderButtons::Init() { METHOD_CALL; if(!m_window->GetDesktopWindow()) return OpStatus::ERR_NULL_POINTER; static const struct { WindowBorderIcons id; const uni_char* name; } indices[] = { { WINICON_CLOSE, UNI_L("ZWINCLOSE") }, { WINICON_MAXIMIZE, UNI_L("ZWINMAXIMIZE") }, { WINICON_MINIMIZE, UNI_L("ZWINMINIMIZE") }, { WINICON_RESTORE, UNI_L("ZWINRESTORE") } }; static const struct { const uni_char* appendix; int off; } states[] = { { UNI_L(""), 0 }, { UNI_L("_HOVER"), WINICON_CLOSE_HOVER - WINICON_CLOSE }, { UNI_L("_PRESSED"), WINICON_CLOSE_PRESSED - WINICON_CLOSE }, { UNI_L("_RTL"), WINICON_RTL_OFFSET }, { UNI_L("_HOVER_RTL"), WINICON_RTL_OFFSET + WINICON_CLOSE_HOVER - WINICON_CLOSE }, { UNI_L("_PRESSED_RTL"), WINICON_RTL_OFFSET + WINICON_CLOSE_PRESSED - WINICON_CLOSE }, }; // the longest <name, appendix> pair is 24 chars long uni_char resid[30]; // ARRAY OK 2012-03-23 mzdun for (int i = 0; i < ARRAY_SIZE(indices); ++i) { uni_strcpy(resid, indices[i].name); uni_char* resid_apdx = resid + uni_strlen(resid); for (int j = 0; j < ARRAY_SIZE(states); ++j) { uni_strcpy(resid_apdx, states[j].appendix); WindowBorderIcons id = static_cast<WindowBorderIcons>(indices[i].id + states[j].off); m_window_icons[id] = CreateReplacementWindowButton(this, id, resid); } } OpStatus::Ignore(OpButton::Construct(&m_btn_minimize, OpButton::TYPE_CUSTOM, OpButton::STYLE_IMAGE)); OpStatus::Ignore(OpButton::Construct(&m_btn_restore, OpButton::TYPE_CUSTOM, OpButton::STYLE_IMAGE)); OpStatus::Ignore(OpButton::Construct(&m_btn_close, OpButton::TYPE_CUSTOM, OpButton::STYLE_IMAGE)); OpAutoPtr<OpButton> btn_minimize_p(m_btn_minimize); OpAutoPtr<OpButton> btn_close_p(m_btn_close); OpAutoPtr<OpButton> btn_restore_p(m_btn_restore); // not the end of the world if we OOM above if(!(m_btn_close && m_btn_minimize && m_btn_restore)) return OpStatus::ERR_NO_MEMORY; AddChild(btn_minimize_p.release()); AddChild(btn_restore_p.release()); AddChild(btn_close_p.release()); m_language_is_RTL = isLanguageRTL(); int rtl_diff = m_language_is_RTL ? WINICON_RTL_OFFSET : 0; m_btn_minimize->GetBorderSkin()->SetBitmapImage(m_window_icons[WINICON_MINIMIZE+rtl_diff]); m_btn_minimize->GetBorderSkin()->SetForeground(TRUE); m_btn_minimize->SetName("Window Minimize Button"); m_btn_restore->GetBorderSkin()->SetBitmapImage(m_window->m_state == OpWindow::MAXIMIZED ? m_window_icons[WINICON_RESTORE+rtl_diff] : m_window_icons[WINICON_MAXIMIZE+rtl_diff]); m_btn_restore->GetBorderSkin()->SetForeground(TRUE); m_btn_restore->SetName("Window Close Button"); m_btn_close->GetBorderSkin()->SetBitmapImage(m_window_icons[WINICON_CLOSE+rtl_diff]); m_btn_close->GetBorderSkin()->SetForeground(TRUE); m_btn_close->SetName("Window Restore Button"); SetListener(this); // avoid that the parent element (this) clears the background when painting the children SetSkinIsBackground(TRUE); // add us first so we get painted last m_window->GetDesktopWindow()->GetWidgetContainer()->GetRoot()->AddChild(this, FALSE, TRUE); return OpStatus::OK; } void QuickBorderButtons::Layout() { METHOD_CALL; INT32 w, h; RECT btnrect[WIN_RECT_MAX]; RECT native_frame = m_window->GetFrame()->GetNativeFrameSizes(); NativeBorderButtons::CalculateCaptionButtonRects(m_window, btnrect); GetSize(&w, &h); int right_offset = WINDOW_DEFAULT_BORDER_SIZE + (m_window->m_state == MAXIMIZED ? 0 : WINDOW_DEFAULT_BORDER_SIZE); // we know the size of our native frame so use that instead when maximized btnrect[0].top = native_frame.top; OpRect rect(m_window->m_width - w - right_offset, m_window->m_state == MAXIMIZED ? btnrect[0].top : 0, w, h); if (isLanguageRTL()) rect.x = right_offset; SetRect(rect); } void QuickBorderButtons::LayoutCustomWindowButtons() { METHOD_CALL; bool rtl = isLanguageRTL(); bool reset_images = rtl != m_language_is_RTL; m_language_is_RTL = rtl; OpRect bounds = GetBounds(); struct { WindowBorderIcons icon; OpButton* button; } buttons[] = { WINICON_CLOSE, m_btn_close, WINICON_RESTORE, m_btn_restore, WINICON_MINIMIZE, m_btn_minimize }; int height = m_window_icons[WINICON_CLOSE].Height(); // use the height from the close button int y = m_window->m_state == MAXIMIZED ? -1 : 0; int x = bounds.Right(); if (rtl) { op_swap(buttons[0], buttons[2]); x = bounds.Left() + m_window_icons[WINICON_CLOSE].Width() + m_window_icons[WINICON_RESTORE].Width() + m_window_icons[WINICON_MINIMIZE].Width(); } OpRect rect(x, y, 0, height); for (int i = 0; i < ARRAY_SIZE(buttons); ++i) { rect.width = m_window_icons[buttons[i].icon].Width(); rect.x -= rect.width; buttons[i].button->SetRect(rect); } if (reset_images) { for (int i = 0; i < ARRAY_SIZE(buttons); ++i) SetButtonImage(buttons[i].button, FALSE); } } void QuickBorderButtons::GetSize(INT32* w, INT32* h) { *h = m_window_icons[WINICON_CLOSE].Height(); // use the height from the close button *w = m_window_icons[WINICON_CLOSE].Width() + m_window_icons[WINICON_RESTORE].Width() + m_window_icons[WINICON_MINIMIZE].Width(); } void QuickBorderButtons::OnClick(OpWidget *widget, UINT32 id) { if(widget == m_btn_close) { m_window->GetDesktopWindow()->Close(FALSE, TRUE); } else if(widget == m_btn_minimize) { PostMessage(m_window->m_hwnd, WM_SYSCOMMAND, SC_MINIMIZE, 0); } else if(widget == m_btn_restore) { if(m_window->m_state == OpWindow::MAXIMIZED) { PostMessage(m_window->m_hwnd, WM_SYSCOMMAND, SC_RESTORE, 0); } else { SendMessage(m_window->m_hwnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0); } } } void QuickBorderButtons::SetButtonImage(OpWidget *widget, BOOL hover, BOOL pressed) { WindowBorderIcons icon = WINICON_COUNT; if (widget == m_btn_close) icon = WINICON_CLOSE; else if (widget == m_btn_minimize) icon = WINICON_MINIMIZE; else if (widget == m_btn_restore && m_window->m_state == OpWindow::MAXIMIZED) icon = WINICON_RESTORE; else if (widget == m_btn_restore) icon = WINICON_MAXIMIZE; if (icon == WINICON_COUNT) return; if (isLanguageRTL()) icon = static_cast<WindowBorderIcons>(icon + WINICON_RTL_OFFSET); if (pressed) icon = static_cast<WindowBorderIcons>(icon + WINICON_CLOSE_PRESSED - WINICON_CLOSE); else if (hover) icon = static_cast<WindowBorderIcons>(icon + WINICON_CLOSE_HOVER - WINICON_CLOSE); widget->GetBorderSkin()->SetBitmapImage(m_window_icons[icon]); } // assumes the resource is in the resource section as RCDATA in PNG format /* static */ Image QuickBorderButtons::CreateReplacementWindowButton(QuickBorderButtons* btn_class, WindowBorderIcons icon_offset, const uni_char *resource_name) { Image image; HRSRC res = FindResource(hInst, resource_name, RT_RCDATA); RETURN_VALUE_IF_NULL(res, image); HGLOBAL data = LoadResource(hInst, res); OP_ASSERT(data); RETURN_VALUE_IF_NULL(data, image); DWORD size = SizeofResource(hInst, res); OP_ASSERT(size); if(!size) return image; LPVOID res_data = LockResource(data); // documented to not need any unlock call (and none exists) OP_ASSERT(res_data); RETURN_VALUE_IF_NULL(res_data, image); // we load it with an new content provider. Each content provider must be unique for the lifetime of // the data btn_class->m_content_providers[icon_offset] = OP_NEW(SkinImageContentProvider, ((char *)res_data, size)); RETURN_VALUE_IF_NULL(btn_class->m_content_providers[icon_offset], image); image = imgManager->GetImage(btn_class->m_content_providers[icon_offset]); image.IncVisible(null_image_listener); image.OnLoadAll(btn_class->m_content_providers[icon_offset]); if(!image.ImageDecoded()) image.DecVisible(null_image_listener); return image; } /* static */ void OpBorderButtons::CalculateCaptionButtonRects(WindowsOpWindow* window, RECT* btnrect) { if (IsSystemWinVista()) { TITLEBARINFOEX tinf; tinf.cbSize = sizeof(TITLEBARINFOEX); SendMessage(window->m_hwnd, WM_GETTITLEBARINFOEX, NULL, (LPARAM)&tinf); POINT p; p.x = 0; p.y = 0; ClientToScreen(window->m_hwnd, &p); btnrect[WIN_RECT_CLOSE_BUTTON] = tinf.rgrect[5]; OffsetRect(&btnrect[WIN_RECT_CLOSE_BUTTON], -p.x, -p.y); btnrect[WIN_RECT_MAXIMIZE_BUTTON] = tinf.rgrect[3]; OffsetRect(&btnrect[WIN_RECT_MAXIMIZE_BUTTON], -p.x, -p.y); btnrect[WIN_RECT_MINIMIZE_BUTTON] = tinf.rgrect[2]; OffsetRect(&btnrect[WIN_RECT_MINIMIZE_BUTTON], -p.x, -p.y); } else { UINT32 winw, winh; window->GetInnerSize(&winw, &winh); // FIXME: get the correct rects for xp SIZE s; s.cx = GetSystemMetrics(SM_CXSIZE)-4; s.cy = GetSystemMetrics(SM_CYSIZE)-4; btnrect[WIN_RECT_CLOSE_BUTTON].top = GetSystemMetrics(SM_CYSIZEFRAME)+(GetSystemMetrics(SM_CYCAPTION)-s.cy)/2; btnrect[WIN_RECT_CLOSE_BUTTON].bottom = btnrect[WIN_RECT_CLOSE_BUTTON].top+s.cy; btnrect[WIN_RECT_CLOSE_BUTTON].right = winw-2; btnrect[WIN_RECT_CLOSE_BUTTON].left = btnrect[WIN_RECT_CLOSE_BUTTON].right - s.cx; btnrect[WIN_RECT_MAXIMIZE_BUTTON] = btnrect[WIN_RECT_CLOSE_BUTTON]; OffsetRect(&btnrect[WIN_RECT_MAXIMIZE_BUTTON], -s.cx-2, 0); btnrect[WIN_RECT_MINIMIZE_BUTTON] = btnrect[WIN_RECT_MAXIMIZE_BUTTON]; OffsetRect(&btnrect[WIN_RECT_MINIMIZE_BUTTON], -s.cx-2, 0); } if (isLanguageRTL()) { RECT cli; GetClientRect(window->m_hwnd, &cli); LONG leftandright = cli.left + cli.right; for (int i = 0; i < WIN_RECT_MAX; i++) { LONG width = btnrect[i].right - btnrect[i].left; btnrect[i].left = leftandright - btnrect[i].right; btnrect[i].right = btnrect[i].left + width; } } } /************************************************************************* * * The background clearing hooks trigger by the skin module during paint * for elements that clearbackground=1 * **************************************************************************/ WindowsBackgroundClearer::WindowsBackgroundClearer() : m_window(NULL), m_theme(NULL), m_composition(FALSE), m_clear_background(FALSE), m_use_transparent_state(FALSE), m_menubar_visibility(FALSE), m_pagebar_on_top(TRUE), m_border_buttons(NULL), m_hwBmpDC(NULL), m_hwBmp(NULL), m_hwOldBmp(NULL), m_hwBmpData(NULL), m_hwOpBitmap(NULL), m_has_painted_personas(FALSE) {} WindowsBackgroundClearer::WindowsBackgroundClearer(OpWindow* win, BOOL use_composition, BOOL use_transparent_state, BOOL menubar_visibility, BOOL pagebar_on_top) : m_window(static_cast<WindowsOpWindow *>(win)), m_theme(NULL), m_composition(use_composition), m_use_transparent_state(use_transparent_state), m_menubar_visibility(menubar_visibility), m_pagebar_on_top(pagebar_on_top), m_border_buttons(NULL), m_hwBmpDC(NULL), m_hwBmp(NULL), m_hwOldBmp(NULL), m_hwBmpData(NULL), m_hwOpBitmap(NULL), m_has_painted_personas(FALSE) { METHOD_CALL; m_clear_background = !m_composition; m_theme = OpenThemeData(m_window->m_hwnd, UNI_L("window")); if (HASDwmSetWindowAttribute()) { // we don't need to draw into the frame if the pagebar is not the top most element if(pagebar_on_top && !m_menubar_visibility) { DWMNCRENDERINGPOLICY policy = DWMNCRP_DISABLED; HRESULT hr = OPDwmSetWindowAttribute(m_window->m_hwnd, DWMWA_NCRENDERING_POLICY, (void*)&policy, sizeof(DWMNCRENDERINGPOLICY)); OP_ASSERT(SUCCEEDED(hr) && "Something failed while changing non-client rendering"); hr = hr; // silence warning } } if(m_window->GetDesktopWindow()) { if(OpStatus::IsSuccess(OpBorderButtons::Construct(&m_border_buttons, m_window, m_theme, pagebar_on_top))) { m_border_buttons->Layout(); } } } WindowsBackgroundClearer::~WindowsBackgroundClearer() { METHOD_CALL; if (m_hwBmp) { if (m_hwBmpDC) { SelectObject(m_hwBmpDC, m_hwOldBmp); DeleteDC(m_hwBmpDC); } DeleteObject(m_hwBmp); } OP_DELETE(m_hwOpBitmap); if(m_border_buttons) { m_border_buttons->DeleteButtons(); } if(m_theme) { CloseThemeData(m_theme); } if (HASDwmSetWindowAttribute() && m_window) { DWMNCRENDERINGPOLICY policy = DWMNCRP_USEWINDOWSTYLE; HRESULT hr = OPDwmSetWindowAttribute(m_window->m_hwnd, DWMWA_NCRENDERING_POLICY, (void*)&policy, sizeof(DWMNCRENDERINGPOLICY)); OP_ASSERT(SUCCEEDED(hr) && "Something failed while changing non-client rendering"); hr = hr; // get rid of warning } CLEARER_TRACE(UNI_L("WindowsBackgroundClearer deleted: 0x%08x\n"), this); } void WindowsBackgroundClearer::OnPersonaChanged(OpPersona *persona) { } VEGAPixelStore* WindowsBackgroundClearer::SetupBackBuffers(HDC& dc, UINT32 winw, UINT32 winh) { VEGAPixelStore *ps = NULL; if (!dc) { // Hardware rendering path if (!m_hwOpBitmap || m_hwOpBitmap->Width() != winw || m_hwOpBitmap->Height() != winh) { if (m_hwBmp) { if (m_hwBmpDC) { SelectObject(m_hwBmpDC, m_hwOldBmp); DeleteDC(m_hwBmpDC); } DeleteObject(m_hwBmp); m_hwBmp = NULL; m_hwBmpDC = NULL; } OP_DELETE(m_hwOpBitmap); m_hwOpBitmap = NULL; BITMAPINFO bi; bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bi.bmiHeader.biWidth = winw; bi.bmiHeader.biHeight = -(int)winh; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biBitCount = 32; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biSizeImage = 0; bi.bmiHeader.biXPelsPerMeter = 0; bi.bmiHeader.biYPelsPerMeter = 0; bi.bmiHeader.biClrUsed = 0; bi.bmiHeader.biClrImportant = 0; m_hwBmp = CreateDIBSection(NULL, &bi, DIB_RGB_COLORS, (void**)&m_hwBmpData, NULL, 0); if (!m_hwBmp) return NULL; HDC hdc = GetDC(reinterpret_cast<HWND>(m_window->m_vega_window->getNativeHandle())); m_hwBmpDC = CreateCompatibleDC(hdc); m_hwOldBmp = (HBITMAP)SelectObject(m_hwBmpDC, m_hwBmp); ReleaseDC(reinterpret_cast<HWND>(m_window->m_vega_window->getNativeHandle()), hdc); if (!m_hwBmpDC || OpStatus::IsError(OpBitmap::Create(&m_hwOpBitmap, winw, winh))) return NULL; } ps = &m_hwPs; m_hwPs.format = VPSF_BGRA8888; m_hwPs.height = winh; m_hwPs.width = winw; m_hwPs.stride = m_hwPs.width*4; m_hwPs.buffer = m_hwBmpData; dc = m_hwBmpDC; } else { // software rendering path if (m_hwBmp) { if (m_hwBmpDC) { SelectObject(m_hwBmpDC, m_hwOldBmp); DeleteDC(m_hwBmpDC); } DeleteObject(m_hwBmp); m_hwBmp = NULL; m_hwBmpDC = NULL; } OP_DELETE(m_hwOpBitmap); m_hwOpBitmap = NULL; ps = ((WindowsOpWindow*)m_window)->m_vega_window->getPixelStore(); } return ps; } void WindowsBackgroundClearer::OnBackgroundCleared(OpPainter *op_painter, const OpRect& clear_rect) { METHOD_CALL; OP_ASSERT(op_painter && "If this happens, your paint call of a skin element is oh so wrong"); if(!op_painter) return; // op_painter can be either a top level window painter or an off screen painter to draw menubar bool is_window_painter = m_window->m_mde_screen->GetVegaPainter() == static_cast<VEGAOpPainter*>(op_painter); RECT frame_sizes = m_window->GetFrame()->GetNativeFrameSizes(); #ifdef PERSONA_SKIN_SUPPORT BOOL has_persona_skin = g_skin_manager->HasPersonaSkin(); #else BOOL has_persona_skin = FALSE; #endif // PERSONA_SKIN_SUPPORT HDC dc = m_window->GetRenderTargetDC(); OpRect r(clear_rect); // clear_rect is client coordinates, which means the y coordinate doesn't start // from 0 for window painter if there is a menu bar, but window painter expects // coordinates starting from 0. This is only relevant for hardware backend though, // for software we don't use painter. if (is_window_painter && !dc) r.y -= m_window->m_top_margin; else if (!is_window_painter && dc) return; // some extra work has to be done to clear menu bar with software backend, for now just leave it grey OP_ASSERT(r.y >= 0); RECT rect; UINT32 winw, winh; winw = m_window->m_vega_window->getWidth(); winh = m_window->m_vega_window->getHeight(); int vertical_border = frame_sizes.left; rect.left = -vertical_border; rect.right = winw+vertical_border; rect.top = 0; rect.bottom = winh; VEGAOpPainter* painter = static_cast<VEGAOpPainter*>(op_painter); VEGARenderer* rend = painter->GetRenderer(); VEGARenderTarget* rt = painter->GetRenderTarget(); VEGAPixelStore* ps = SetupBackBuffers(dc, winw, winh); if(!ps) return; VegaBufferClipRect clip(dc, m_window, r, ps); BOOL active = m_window->m_hwnd_active; // always clear menu bar, but only clear window when personas is off if ((!is_window_painter || !has_persona_skin) && m_clear_background) { BOOL drawTitlebar = FALSE; UINT32 color = 0; int ry = r.y; int rh = r.height; if (m_window->m_titlebar_height) { rect.top = frame_sizes.top + GetSystemMetrics(SM_CYCAPTION); if (r.y < rect.top) { if (!IsSystemWinVista()) { RECT cr; cr.left = 1+r.x-vertical_border; cr.right = r.x+1; cr.top = r.y; cr.bottom = r.y+1; DrawThemeBackground(m_theme, dc, WP_FRAMELEFT, active?FS_ACTIVE:FS_INACTIVE, &cr, NULL); color = ((UINT32*)ps->buffer)[r.x+r.y*ps->stride/4] | (255<<24); } rh -= rect.top-r.y; ry = rect.top; RECT caprect; caprect.top = 0; caprect.left = -vertical_border; caprect.bottom = rect.top; caprect.right = winw+vertical_border; DrawThemeBackground(m_theme, dc, WP_CAPTION, active?CS_ACTIVE:CS_INACTIVE, &caprect, NULL); if (!IsSystemWinVista() && !m_hwOpBitmap) { rend->setRenderTarget(rt); rend->setClipRect(r.x, r.y, r.width, r.height); drawGradient(rend, color, winw, rect.top); } // buttons m_border_buttons->Paint(dc); drawTitlebar = TRUE; } } rect.left = 1+r.x-vertical_border; rect.right = r.x+1; DrawThemeBackground(m_theme, dc, WP_FRAMELEFT, active?FS_ACTIVE:FS_INACTIVE, &rect, NULL); for (int yp = 0; yp < rh; ++yp) { UINT32* src = ((UINT32*)ps->buffer)+(ry+yp)*ps->stride/4+r.x; *src |= 255<<24; UINT32* dst = src+1; for (int xp = 1; xp < r.width; ++xp) *(dst++) = *src; } if (m_hwOpBitmap) { // Update the OpBitmap used for hardware rendering UINT32* obd = (UINT32*)m_hwOpBitmap->GetPointer(OpBitmap::ACCESS_WRITEONLY); if (drawTitlebar) { for (int yp = 0; yp < rect.top; ++yp) { UINT32* src = ((UINT32*)ps->buffer)+yp*ps->stride/4; UINT32* dst = obd+yp*m_hwOpBitmap->GetBytesPerLine()/4; for (UINT32 xp = 0; xp < winw; ++xp) *(dst++) = *(src++) | (255<<24); } } for (int yp = 0; yp < rh; ++yp) op_memcpy(obd+(ry+yp)*m_hwOpBitmap->GetBytesPerLine()/4+r.x, ((UINT8*)ps->buffer)+ps->stride*(ry+yp)+r.x*4, r.width*4); m_hwOpBitmap->ReleasePointer(); if (drawTitlebar) { painter->DrawBitmapClipped(m_hwOpBitmap, OpRect(0, 0, winw, rect.top), OpPoint(0,0)); if (!IsSystemWinVista()) { rend->setRenderTarget(rt); rend->setClipRect(r.x, r.y, r.width, r.height); drawGradient(rend, color, winw, rect.top); } } if (rh > 0 && r.width > 0) { painter->DrawBitmapClipped(m_hwOpBitmap, OpRect(r.x, ry, r.width, rh), OpPoint(r.x, ry)); } } } #ifdef PERSONA_SKIN_SUPPORT if(has_persona_skin && is_window_painter) { VisualDevice vd; vd.BeginPaint(painter, clear_rect, clear_rect); WindowsBackgroundClearer::PaintBackground(m_window->m_vega_window->getWidth(), m_window->m_vega_window->getHeight(), m_window, painter, &vd, clear_rect, ::GetFocus() != m_window->m_hwnd); m_has_painted_personas = TRUE; vd.EndPaint(); #endif // PERSONA_SKIN_SUPPORT } if((m_clear_background || has_persona_skin) && m_border_buttons) { m_border_buttons->Layout(); m_border_buttons->Paint(dc); } } /* static */ void WindowsBackgroundClearer::PaintBackground(unsigned int width, unsigned int height, WindowsOpWindow *window, VEGAOpPainter *painter, VisualDevice *vd, const OpRect& paint_rect, BOOL inactive) { METHOD_CALL; #ifdef PERSONA_SKIN_SUPPORT OpSkinElement *elm = g_skin_manager->GetPersona()->GetBackgroundImageSkinElement(); #else OpSkinElement *elm = NULL; #endif // PERSONA_SKIN_SUPPORT if(!elm) return; OpRect rect(0, 0, width, height); vd->Translate(-painter->GetTranslationX(), -painter->GetTranslationY()); OpSkinElement::DrawArguments args; // set a clip rect, needed when painting the background view using this method if(!paint_rect.IsEmpty()) { vd->BeginClipping(paint_rect); args.clip_rect = &paint_rect; } elm->Draw(vd, rect, 0, args); // top border line // white with 30% opacity if(window->GetFrame() && window->GetFrame()->UseCustomUIFrame()) { int color; TRAPD(status, color = g_skin_manager->GetCurrentSkin()->ReadColorL("Options", "Window Border Color", OP_RGBA(255, 255, 255, 76), FALSE)); if (OpStatus::IsSuccess(status)) vd->SetColor32(color); vd->DrawLine(OpPoint(5, 0), OpPoint(width - 5, 0)); } // paint the overlay, if needed if(inactive) { UINT32 color = g_desktop_op_ui_info->GetPersonaDimColor(); vd->SetColor32(color); vd->FillRect(rect); } if(!paint_rect.IsEmpty()) { vd->EndClipping(); } vd->Translate(-vd->GetTranslationX(), -vd->GetTranslationY()); } void WindowsBackgroundClearer::GetBorderButtonsSize(INT32 *w, INT32 *h) { *w = *h = 0; if(m_border_buttons) { m_border_buttons->GetSize(w, h); } else { // just fallback to the system calculations RECT btnrect[WIN_RECT_MAX]; OpBorderButtons::CalculateCaptionButtonRects(m_window, btnrect); for(int i = 0; i < WIN_RECT_MAX; i++) { *w += btnrect[i].right - btnrect[i].left; } *h = btnrect[WIN_RECT_CLOSE_BUTTON].bottom - btnrect[WIN_RECT_CLOSE_BUTTON].top; } } void WindowsBackgroundClearer::drawGradient(VEGARenderer* rend, UINT32 color, unsigned int width, unsigned int height) { int num_stops = 2; VEGA_FIX stops[2] = {0.2f, 0.8f}; UINT32 cols[2] = {color&0xffffff, color}; VEGAFill* grad; int caption_height = GetSystemMetrics(SM_CYCAPTION); int frame_width = GetSystemMetrics(SM_CYSIZEFRAME); RECT btnrect[WIN_RECT_MAX]; NativeBorderButtons::CalculateCaptionButtonRects(m_window, btnrect); // width of rect to apply radial gradient int radial_width = caption_height; // x coordinate of radial gradient int radial_x = btnrect[WIN_RECT_MINIMIZE_BUTTON].left - radial_width + caption_height/3; // center if (OpStatus::IsSuccess(rend->createLinearGradient(&grad, 0, frame_width, 0, frame_width + caption_height, num_stops, stops, cols))) { rend->setFill(grad); rend->fillRect(0, 0, radial_x, height); rend->setFill(NULL); OP_DELETE(grad); } // Right UINT32 rad_cols[2] = {color, color&0xffffff}; if (OpStatus::IsSuccess(rend->createRadialGradient(&grad, VEGA_INTTOFIX(radial_x), VEGA_INTTOFIX(caption_height + frame_width), 0, VEGA_INTTOFIX(radial_x), VEGA_INTTOFIX(caption_height + frame_width), VEGA_INTTOFIX(radial_width), num_stops, stops, rad_cols))) { rend->setFill(grad); rend->fillRect(radial_x, 0, radial_width, height); rend->setFill(NULL); OP_DELETE(grad); } } /****************************************************************************************** * * Implementation of WindowsBackgroundClearer that works for classic ui (non-themed) looks * *******************************************************************************************/ WindowsClassicBackgroundClearer::WindowsClassicBackgroundClearer(OpWindow* win, BOOL use_composition, BOOL use_transparent_state, BOOL menubar_visibility, BOOL pagebar_on_top) : WindowsBackgroundClearer(win, use_composition, use_transparent_state, menubar_visibility, pagebar_on_top) { } void WindowsClassicBackgroundClearer::OnBackgroundCleared(OpPainter *op_painter, const OpRect& clear_rect) { OP_ASSERT(op_painter && "If this happens, your paint call of a skin element is oh so wrong"); if(!op_painter) return; #ifdef PERSONA_SKIN_SUPPORT BOOL has_persona_skin = g_skin_manager->HasPersonaSkin(); #else BOOL has_persona_skin = FALSE; #endif // PERSONA_SKIN_SUPPORT OpRect r(clear_rect); if(has_persona_skin) { #ifdef PERSONA_SKIN_SUPPORT // ensure we're called with the top level painter if (m_window->m_mde_screen->GetVegaPainter() == op_painter) { VisualDevice vd; vd.BeginPaint(op_painter, r, r); WindowsBackgroundClearer::PaintBackground(m_window->m_vega_window->getWidth(), m_window->m_vega_window->getHeight(), m_window, static_cast<VEGAOpPainter*>(op_painter), &vd, clear_rect, ::GetFocus() != m_window->m_hwnd); m_has_painted_personas = TRUE; vd.EndPaint(); } #endif // PERSONA_SKIN_SUPPORT } else { if (m_window->m_mde_screen->GetVegaPainter() == op_painter) { // The window // clear_rect is client coordinates, which means the y coordinate doesn't start // from 0 if there is a menu bar, but when painting to the painter we need view // coordinates, transform here. // Maybe we should fix the caller instead r.y -= m_window->m_top_margin; OP_ASSERT(r.y >= 0); } else { // Some off screen bitmap(menubar for example) } UINT32 color = g_skin_manager->GetCurrentSkin()->GetDefaultColorScheme(); op_painter->SetColor(OP_GET_R_VALUE(color), OP_GET_G_VALUE(color), OP_GET_B_VALUE(color), OP_GET_A_VALUE(color)); op_painter->FillRect(r); } } /* static */ WindowsBackgroundClearer* WindowsBackgroundClearer::Create(WindowsOpWindow* win, BOOL use_transparent_state, BOOL use_composition, BOOL pagebar_on_top) { WinClearerType create_hook_type = WIN_CLEARER_TYPE_NONE; WindowsBackgroundClearer* clearer = win->m_background_clearer; use_transparent_state |= g_skin_manager->HasPersonaSkin(); // The only case background clearer is not needed is when aero is enabled and no personas if (g_skin_manager->HasPersonaSkin() || !use_composition) { // When there is no custom title bar WIN_CLEARER_TYPE_CLASSIC clears background // very quickly with a simple FillRect operation using the color // g_skin_manager->GetCurrentSkin()->GetDefaultColorScheme, it works fine for // classic Windows theme and XP, however for Vista/7 we want to use same color // as the native title bar and border. if (!win->IsThemed() || GetWinType() == WINXP && (win->m_menubar_visibility || !pagebar_on_top)) create_hook_type = WIN_CLEARER_TYPE_CLASSIC; else create_hook_type = WIN_CLEARER_TYPE_NORMAL; } // let's check if we need to recreate it if(!clearer || (clearer && (clearer->GetClearerType() != create_hook_type || clearer->HasComposition() != use_composition || clearer->GetMenubarVisibility() != win->m_menubar_visibility || clearer->IsPagebarOnTop() != pagebar_on_top || clearer->HasTheme() != win->IsThemed() || clearer->HasPersonas() != g_skin_manager->HasPersonaSkin()))) { if(clearer) { CLEARER_TRACE(UNI_L("WindowsBackgroundClearer deleted: 0x%08x\n"), win->m_background_clearer); g_skin_manager->RemoveTransparentBackgroundListener(win->m_background_clearer); OP_DELETE(win->m_background_clearer); win->m_background_clearer = NULL; clearer = NULL; } switch(create_hook_type) { case WIN_CLEARER_TYPE_NORMAL: { clearer = OP_NEW(WindowsBackgroundClearer, (win, use_composition, use_transparent_state, win->m_menubar_visibility, pagebar_on_top)); CLEARER_TRACE(UNI_L("WindowsBackgroundClearer created: 0x%08x\n"), clearer); break; } case WIN_CLEARER_TYPE_CLASSIC: { clearer = OP_NEW(WindowsClassicBackgroundClearer, (win, use_composition, use_transparent_state, win->m_menubar_visibility, pagebar_on_top)); CLEARER_TRACE(UNI_L("WindowsClassicBackgroundClearer created: 0x%08x\n"), clearer); break; } case WIN_CLEARER_TYPE_DUMMY: { clearer = OP_NEW(DummyBackgroundClearer, (win, use_composition, use_transparent_state, win->m_menubar_visibility, pagebar_on_top)); break; } } } // enable transparent skins if we're using a persona if (win->GetDesktopWindow()) { win->GetDesktopWindow()->EnableTransparentSkins(use_transparent_state, FALSE); } if(clearer && clearer != win->m_background_clearer) { g_skin_manager->AddTransparentBackgroundListener(clearer); } return clearer; }
#ifndef PPJ_AST_H #define PPJ_AST_H #include <cstdlib> #include <iostream> #include <vector> #include <set> #include <map> using namespace std; #include "symtable.h" #include "function.h" struct ASTree { int line; string token; string source; ASTree *dad; vector<ASTree*> adj; int type; Function *fun; bool l_value; bool is_ptr; int type_inherited; bool is_loop; bool is_global_decl; int stack_pos; int array_size; vector<int> *arg_types; string arg_name; ASTree() { dad = NULL; type = 0; fun = NULL; l_value = false; is_ptr = false; type_inherited = 0; is_loop = false; is_global_decl = false; arg_types = NULL; } virtual void dfs(SymTable *sym) = 0; void check(bool test, string msg); }; ASTree *makeProduction(string token, string children); #endif
#include "medicalajout.h" #include "ui_medicalajout.h" #include "stock.h" medicalajout::medicalajout(QWidget *parent) : QDialog(parent), ui(new Ui::medicalajout) { ui->setupUi(this); ui->IDML->setVisible(false);ui->IDM->setVisible(false); ui->delaiduDE->setVisible(false);ui->delaiduL->setVisible(false); ui->delaiauDE->setVisible(false);ui->delaiauL->setVisible(false); } medicalajout::~medicalajout() { delete ui; } void medicalajout::on_ajoutermMPB_clicked() { int Qstock = ui->quantiteM->text().toInt(); int Qreserve = ui->reserveM->text().toInt(); QString Marque= ui->marqueM->text(); QString Typee= ui->typeeM->text(); QString Description= ui->descriptionM->text(); QString Reference= ui->referenceM->text(); int ID=ui->IDM->text().toInt(); QString delai_du=ui->delaiduDE->text(); QString delai_au=ui->delaiauDE->text(); int IDtechnique=ui->IDF->text().toInt(); QString taille=ui->TailleLE->text(); QString couleur=ui->couleurLE->text(); stock *S = new stock(Qstock,Qreserve,Marque,Typee,Description,Reference,ID); stockmedical *SM =new stockmedical(Qstock,Qreserve,Marque,Typee,Description,Reference,ID,delai_du,delai_au,ID); if (ui->IDM->text()!=""){ if ((S->ajouterstock(S))&&(SM->ajouterstockmedical(SM))) QMessageBox::information(0, qApp->tr("Ajout"), qApp->tr("Un nouveau stock medical a été ajouté"), QMessageBox::Cancel); else QMessageBox::critical(0, qApp->tr("Ajout"), qApp->tr("Probléme d'ajout"), QMessageBox::Cancel); } else if((ui->IDF->text()!="")){ stock *S = new stock(Qstock,Qreserve,Marque,Typee,Description,Reference,IDtechnique); stocktechnique *ST = new stocktechnique(Qstock,Qreserve,Marque,Typee,Description,Reference,IDtechnique,taille,couleur,IDtechnique); if ((ST->ajoutstocktechnique(ST))&&(S->ajouterstock(S))) QMessageBox::information(0, qApp->tr("Ajout"), qApp->tr("Un nouveau stock technique a été ajouté"), QMessageBox::Cancel); else QMessageBox::critical(0, qApp->tr("Ajout"), qApp->tr("Probléme d'ajout"), QMessageBox::Cancel); } else QMessageBox::critical(0, qApp->tr("Ajout"), qApp->tr("Probléme d'ajout"), QMessageBox::Cancel); } void medicalajout::on_stockmedicalPB_clicked() { ui->TailleL->setVisible(false); ui->TailleLE->setVisible(false); ui->couleurL->setVisible(false); ui->couleurLE->setVisible(false); ui->IDML->setVisible(true);ui->IDM->setVisible(true); ui->IDF->setVisible(false);ui->IDFL->setVisible(false); ui->delaiduDE->setVisible(true);ui->delaiduL->setVisible(true); ui->delaiauDE->setVisible(true);ui->delaiauL->setVisible(true); } void medicalajout::on_stocktechniquePB_clicked() { ui->TailleL->setVisible(true); ui->TailleLE->setVisible(true); ui->couleurL->setVisible(true); ui->couleurLE->setVisible(true); ui->IDML->setVisible(false);ui->IDM->setVisible(false); ui->IDF->setVisible(true);ui->IDFL->setVisible(true); ui->delaiduDE->setVisible(false);ui->delaiduL->setVisible(false); ui->delaiauDE->setVisible(false);ui->delaiauL->setVisible(false); ui->delaiduDE->setVisible(false);ui->delaiduL->setVisible(false); ui->delaiauDE->setVisible(false);ui->delaiauL->setVisible(false); }
#pragma once #include <glad/glad.h> #include <glm/vec3.hpp> #include <vector> namespace LaiEngine { struct sVertex { glm::vec3 Position; glm::vec3 Color; }; class Mesh { public: virtual ~Mesh() {}; std::vector<sVertex> vertices; std::vector<GLuint> indices; }; class Cube : public Mesh { public: Cube(); }; }
#include "directionwidget.h" #include "ui_directionwidget.h" DirectionWidget::DirectionWidget(QWidget *parent) : QWidget(parent), ui(new Ui::DirectionWidget) { ui->setupUi(this); iofile->readFromFile(); nameList = iofile->getNameList(); setSourceList(); setDestinationList(); QPalette *palette = new QPalette(); palette->setColor(QPalette::Base,Qt::gray); palette->setColor(QPalette::Text,Qt::white); ui->mapCheckBox->setCheckState(Qt::Unchecked); ui->listCheckBox->setCheckState(Qt::Unchecked); ui->directionSourceComboBox->setEnabled(false); ui->directionDestinationComboBox->setEnabled(false); ui->sourceRadioButton->setEnabled(false); ui->destinationRadioButton->setEnabled(false); ui->directionButton->setEnabled(false); ui->directionByMapButton->setEnabled(false); ui->lineEdit->setPlaceholderText("Source Value"); ui->lineEdit_2->setPlaceholderText("Destination Value"); ui->lineEdit->setReadOnly(true); ui->lineEdit->setPalette(*palette); ui->lineEdit_2->setReadOnly(true); ui->lineEdit_2->setPalette(*palette); } DirectionWidget::~DirectionWidget() { delete ui; } void DirectionWidget::setSourceList() { QStringListModel *stringListModel = new QStringListModel; stringListModel->setStringList(nameList); QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel; proxyModel->setSourceModel(stringListModel); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); auto completer = new QCompleter(this); completer->setCaseSensitivity(Qt::CaseInsensitive); completer->setModel(proxyModel); completer->setCompletionMode(QCompleter::PopupCompletion); completer->setFilterMode(Qt::MatchContains); completer->setMaxVisibleItems(4); ui->directionSourceComboBox->setModel(proxyModel); ui->directionSourceComboBox->setEditable(true); ui->directionSourceComboBox->setCompleter(completer); } void DirectionWidget::setDestinationList() { QStringListModel *stringListModel = new QStringListModel; stringListModel->setStringList(nameList); QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel; proxyModel->setSourceModel(stringListModel); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); auto completer = new QCompleter(this); completer->setCaseSensitivity(Qt::CaseInsensitive); completer->setModel(proxyModel); completer->setCompletionMode(QCompleter::PopupCompletion); completer->setFilterMode(Qt::MatchContains); completer->setMaxVisibleItems(4); ui->directionDestinationComboBox->setModel(proxyModel); ui->directionDestinationComboBox->setEditable(true); ui->directionDestinationComboBox->setCompleter(completer); } void DirectionWidget::on_listCheckBox_stateChanged(int arg1) { if(arg1 == 0) { ui->directionSourceComboBox->setEnabled(false); ui->directionDestinationComboBox->setEnabled(false); ui->directionButton->setEnabled(false); } else if(arg1 == 2) { ui->directionSourceComboBox->setEnabled(true); ui->directionDestinationComboBox->setEnabled(true); ui->directionButton->setEnabled(true); ui->mapCheckBox->setCheckState(Qt::Unchecked); } } void DirectionWidget::on_mapCheckBox_stateChanged(int arg1) { if(arg1 == 0) { ui->sourceRadioButton->setEnabled(false); ui->destinationRadioButton->setEnabled(false); ui->directionByMapButton->setEnabled(false); } else if(arg1 == 2) { ui->sourceRadioButton->setEnabled(true); ui->destinationRadioButton->setEnabled(true); ui->directionByMapButton->setEnabled(true); ui->listCheckBox->setCheckState(Qt::Unchecked); } } void DirectionWidget::on_directionButton_clicked() { QString source = ui->directionSourceComboBox->currentText(); QString destination = ui->directionDestinationComboBox->currentText(); if(!nameList.contains(source)) { QMessageBox::warning(this,"Warning","Source name does not exist!"); return; } if(!nameList.contains(destination)) { QMessageBox::warning(this,"Warning","Destination name does not exist!"); return; } if(source == destination) { QMessageBox::warning(this,"Warning","Source and destination must be different!"); return; } sourceCoordinate.clear(); destCoordinate.clear(); sourceCoordinate = iofile->getCoordinateByName(source); destCoordinate = iofile->getCoordinateByName(destination); emitPathData(sourceCoordinate,destCoordinate); } void DirectionWidget::on_directionByMapButton_clicked() { if(!sourceTextChanged) { QMessageBox::information(this,"Information","Please choose source point!"); return; } if(!destTextChanged) { QMessageBox::information(this,"Information","Please choose destination point!"); return; } // qDebug()<<source_val; // qDebug()<<destination_val; // qDebug()<<sourceCoordinate; // qDebug()<<destCoordinate; emitPathData(sourceCoordinate,destCoordinate); } void DirectionWidget::on_lineEdit_textChanged(const QString &arg1) { sourceTextChanged = true; source_val = arg1; } void DirectionWidget::on_lineEdit_2_textChanged(const QString &arg1) { destTextChanged = true; destination_val = arg1; } void DirectionWidget::updateCoordinates(int x_val, int y_val) { QString a; a.append(QString::number(x_val)); a.append(","); a.append(QString::number(y_val)); if(ui->sourceRadioButton->isChecked()) { sourceCoordinate.clear(); sourceCoordinate.append(x_val); sourceCoordinate.append(y_val); ui->lineEdit->setText(a); } else if(ui->destinationRadioButton->isChecked()) { destCoordinate.clear(); destCoordinate.append(x_val); destCoordinate.append(y_val); ui->lineEdit_2->setText(a); } else { return; } }
#include <bits/stdc++.h> using namespace std; #define REP(i,n) for(int i=0;i<(n);i++) #define for1(i,n) for(int i=1;i<=n;i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) const int INF = 1<<29; const int MOD=1073741824; #define pp pair<ll,ll> typedef long long int ll; bool isPowerOfTwo (ll x) { return x && (!(x&(x-1))); } void fastio() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); } long long binpow(long long a, long long b) { long long res = 1; while (b > 0) { if (b & 1) res = res * a; a = a * a; b >>= 1; } return res; } // //const int dx[] = {1,0,-1,0,1,1,-1,-1}; // const int dy[] = {0,-1,0,1,1,-1,-1,1}; //////////////////////////////////////////////////////////////////// char a[51][51]; bool vis[51][51]; int dx[]={1,-1,0,0}; int dy[]={0,0,1,-1}; int n,m; bool flag; bool isvalid(int x,int y) { return (x<n && x>=0 && y<m && y>=0); } //string ans="ujwal"; void dfs(int i,int j,int x,int y) { vis[i][j]=true; REP(l,4) { int x1=i+dx[l],y1=j+dy[l]; if(isvalid(x1,y1) && a[i][j]==a[x1][y1] && (x1!=x || y1!=y)) { if(vis[x1][y1]) { flag=1; return; } dfs(x1,y1,i,j); } if(flag) return; } if(flag)return; } int main() { fastio(); int t=1; //cin>>t; while(t--) { cin>>n>>m; REP(i,n) { REP(j,m) cin>>a[i][j]; } memset(vis,0,sizeof(vis)); REP(i,n) { REP(j,m) { if(!vis[i][j]) dfs(i,j,i,j); } } if(flag)cout<<"Yes"; else cout<<"No"; } return 0; }
#include <iostream> #include "conio.h" using namespace std; /*Se ingresa un entero por teclado. Se desea determinar si el número ingresado es primo o no. Utilice bucles "while". */ int main() { int entero, x=2; bool N= true; cout<<"Introduzca el entero: ";cin>>entero; while (N && x < entero){ if(entero % x == 0) N = false; else x = x + 1; } if(N) cout<<"El entero es primo"; else cout<<"El entero No es primo"; return 0; }
/**************************************************************** File Name: phase2.C Author: Tian Zhang, CS Dept., Univ. of Wisconsin-Madison, 1995 Copyright(c) 1995 by Tian Zhang All Rights Reserved Permission to use, copy and modify this software must be granted by the author and provided that the above copyright notice appear in all relevant copies and that both that copyright notice and this permission notice appear in all relevant supporting documentations. Comments and additions may be sent the author at zhang@cs.wisc.edu. ******************************************************************/ #include "global.h" #include "util.h" #include "vector.h" #include "rectangle.h" #include "cfentry.h" #include "cutil.h" #include "parameter.h" #include "status.h" #include "cftree.h" #include "recyqueue.h" #include "phase2.h" extern Para *Paras; void BirchPhase2(Stat **Stats) { int i; short res; Entry *entries=new Entry[Paras->ntrees]; for (i=0; i<Paras->ntrees; i++) entries[i].Init(Stats[i]->Dimension); for (i=0; i<Paras->ntrees; i++) { if (Stats[i]->CurrEntryCnt>Stats[i]->Range) { Stats[i]->Phase = 2; Stats[i]->Passi = 0; Stats[i]->RestLeafPtr=Stats[i]->NewLeafHead; Stats[i]->AvgDensity=(1.0*Stats[i]->NewRoot->N())/(1.0*Stats[i]->CurrEntryCnt); Stats[i]->SelectInitFt2(); Stats[i]->StartNewTree(); Stats[i]->CurrDataCnt=0; // while scanning leaf entries res=TRUE; while (res!=FALSE) { res=Stats[i]->NextEntryFreeRestLeafPtr(Stats[i]->RestLeafK,entries[i]); if (res==TRUE) { if (entries[i].n<Stats[i]->NoiseRate*Stats[i]->AvgDensity && Stats[i]->OutlierQueue!=NULL) Stats[i]->OutlierQueue->AddEnt(entries[i],Stats[i]); else Stats[i]->Accept2(entries[i]); } } // after scanning leaf entries if (Stats[i]->OutlierQueue!=NULL) Stats[i]->ScanOutlierQueue(); std::cout<<"#"<<Stats[i]->name<<" " <<Stats[i]->Phase<<" "<<Stats[i]->Passi<<" " <<Stats[i]->MemUsed<<" "<<Stats[i]->CurrDataCnt<<" " <<Stats[i]->CurrEntryCnt<<" "<<sqrt(Stats[i]->CurFt)<<std::endl; Stats[i]->RebuiltTree2(0); std::cout<<"#"<<Stats[i]->name<<" " <<Stats[i]->Phase<<" "<<Stats[i]->Passi<<" " <<Stats[i]->MemUsed<<" "<<Stats[i]->CurrDataCnt<<" " <<Stats[i]->CurrEntryCnt<<" "<<sqrt(Stats[i]->CurFt)<<std::endl; if (Stats[i]->OutlierQueue!=NULL) Stats[i]->ScanOutlierQueue(); } } delete [] entries; }
#include "datacollectionthread.h" #include "some_fun.h" #include <QDateTime> #include <QDebug> #include <QDir> DataCollectionThread::DataCollectionThread(QObject *parent) : m_pSerialPort(nullptr), m_pFileLog(nullptr) { this->moveToThread(this); } DataCollectionThread::~DataCollectionThread() { requestInterruption(); quit(); wait(); SAFE_DELETE(m_pSerialPort); if (m_pFileLog->isOpen()) { m_pFileLog->close(); } SAFE_DELETE(m_pFileLog); } void DataCollectionThread::run() { m_runFlag = false; if (m_pSerialPort == nullptr) { m_pSerialPort = new QSerialPort(); } if (m_pFileLog == nullptr) { m_pFileLog = new QFile(); } init_logDir(); init_baudMap(); connect(m_pSerialPort, &QSerialPort::readyRead, this, &DataCollectionThread::readSerial); while (!isInterruptionRequested()) { // qDebug() << "while"; this->exec(); } } void DataCollectionThread::init_logDir() { QDir logDir("./log"); if (!logDir.exists()) { QDir t; t.mkdir("./log"); } } void DataCollectionThread::init_baudMap() { m_baudMap.insert(1200, QSerialPort::Baud1200); m_baudMap.insert(2400, QSerialPort::Baud2400); m_baudMap.insert(4800, QSerialPort::Baud4800); m_baudMap.insert(9600, QSerialPort::Baud9600); m_baudMap.insert(19200, QSerialPort::Baud19200); m_baudMap.insert(38400, QSerialPort::Baud38400); m_baudMap.insert(57600, QSerialPort::Baud57600); m_baudMap.insert(115200, QSerialPort::Baud115200); } bool DataCollectionThread::get_dataFromMsg(double *outData) { bool okflag; if (m_receiveData.isEmpty()) { okflag = false; } else { int len = m_receiveData.size(); QString dataStr; for (int i = 0; i < len; ++i) { if (m_receiveData[i] == '\n') { dataStr = m_receiveData.mid(0, i + 1); *outData = dataStr.split(" ")[0].toDouble(); m_receiveData.chop(i + 1); okflag = true; } } } return okflag; } /**************** private slots *****************************/ void DataCollectionThread::readSerial() { //qDebug() << QThread::currentThreadId(); QByteArray tmpmsg = m_pSerialPort->readLine(); if (!m_runFlag) return; m_receiveData += tmpmsg; QTextStream out(m_pFileLog); // out << m_receiveData << endl; out << tmpmsg; out.flush(); double tmpdata; bool okflag; okflag = get_dataFromMsg(&tmpdata); if (okflag) { emit this->dataFromMsg(tmpdata); } //this->exit(); } /**************** public slots *****************************/ void DataCollectionThread::set_parameters_slot(const QString &port, int baud) { m_pSerialPort->setPortName(port); m_pSerialPort->setBaudRate(m_baudMap.value(baud)); m_pSerialPort->setDataBits(QSerialPort::Data8); m_pSerialPort->setParity(QSerialPort::NoParity); m_pSerialPort->setStopBits(QSerialPort::OneStop); m_pSerialPort->setFlowControl(QSerialPort::NoFlowControl); //this->exit(); } void DataCollectionThread::set_startOrStop_slot(bool status) { m_runFlag = status; if (m_runFlag) { QString cuDTstr = QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss"); m_pFileLog->setFileName(QString("./log/%1.log").arg(cuDTstr)); if (m_pFileLog->open(QIODevice::WriteOnly | QIODevice::Text)) { if (m_pSerialPort->open(QIODevice::ReadWrite)) { qDebug() << "成功"; // 成功 return; } } // 失败了 emit this->fileOpenError(); m_runFlag = false; } else { if (m_pFileLog->isOpen()) { m_pFileLog->close(); } if (m_pSerialPort->isOpen()) { m_pSerialPort->close(); } } //this->exit(); }
// Copyright (c) 2012-2017 The Cryptonote developers // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "TransactionValidation.h" #include "TestGenerator.h" #include "CryptoNoteCore/CryptoNoteTools.h" using namespace cn; namespace { struct tx_builder { void step1_init(size_t version = TRANSACTION_VERSION_1, uint64_t unlock_time = 0) { m_tx.inputs.clear(); m_tx.outputs.clear(); m_tx.signatures.clear(); m_tx.version = static_cast<uint8_t>(version); m_tx.unlockTime = unlock_time; m_tx_key = generateKeyPair(); addTransactionPublicKeyToExtra(m_tx.extra, m_tx_key.publicKey); } void step2_fill_inputs(const AccountKeys& sender_account_keys, const std::vector<TransactionSourceEntry>& sources) { BOOST_FOREACH(const TransactionSourceEntry& src_entr, sources) { m_in_contexts.push_back(KeyPair()); KeyPair& in_ephemeral = m_in_contexts.back(); crypto::KeyImage img; generate_key_image_helper(sender_account_keys, src_entr.realTransactionPublicKey, src_entr.realOutputIndexInTransaction, in_ephemeral, img); // put key image into tx input KeyInput input_to_key; input_to_key.amount = src_entr.amount; input_to_key.keyImage = img; // fill outputs array and use relative offsets BOOST_FOREACH(const TransactionSourceEntry::OutputEntry& out_entry, src_entr.outputs) input_to_key.outputIndexes.push_back(out_entry.first); input_to_key.outputIndexes = absolute_output_offsets_to_relative(input_to_key.outputIndexes); m_tx.inputs.push_back(input_to_key); } } void step3_fill_outputs(const std::vector<TransactionDestinationEntry>& destinations) { size_t output_index = 0; BOOST_FOREACH(const TransactionDestinationEntry& dst_entr, destinations) { crypto::KeyDerivation derivation; crypto::PublicKey out_eph_public_key; crypto::generate_key_derivation(dst_entr.addr.viewPublicKey, m_tx_key.secretKey, derivation); crypto::derive_public_key(derivation, output_index, dst_entr.addr.spendPublicKey, out_eph_public_key); TransactionOutput out; out.amount = dst_entr.amount; KeyOutput tk; tk.key = out_eph_public_key; out.target = tk; m_tx.outputs.push_back(out); output_index++; } } void step4_calc_hash() { getObjectHash(*static_cast<TransactionPrefix*>(&m_tx), m_tx_prefix_hash); } void step5_sign(const std::vector<TransactionSourceEntry>& sources) { m_tx.signatures.clear(); size_t i = 0; BOOST_FOREACH(const TransactionSourceEntry& src_entr, sources) { std::vector<const crypto::PublicKey*> keys_ptrs; BOOST_FOREACH(const TransactionSourceEntry::OutputEntry& o, src_entr.outputs) { keys_ptrs.push_back(&o.second); } m_tx.signatures.push_back(std::vector<crypto::Signature>()); std::vector<crypto::Signature>& sigs = m_tx.signatures.back(); sigs.resize(src_entr.outputs.size()); generate_ring_signature(m_tx_prefix_hash, boost::get<KeyInput>(m_tx.inputs[i]).keyImage, keys_ptrs, m_in_contexts[i].secretKey, src_entr.realOutput, sigs.data()); i++; } } Transaction m_tx; KeyPair m_tx_key; std::vector<KeyPair> m_in_contexts; crypto::Hash m_tx_prefix_hash; }; Transaction make_simple_tx_with_unlock_time(const std::vector<test_event_entry>& events, const cn::Block& blk_head, const cn::AccountBase& from, const cn::AccountBase& to, uint64_t amount, uint64_t fee, uint64_t unlock_time) { std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_head, from, to, amount, fee, 0, sources, destinations); tx_builder builder; builder.step1_init(TRANSACTION_VERSION_1, unlock_time); builder.step2_fill_inputs(from.getAccountKeys(), sources); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); builder.step5_sign(sources); return builder.m_tx; }; crypto::PublicKey generate_invalid_pub_key() { for (int i = 0; i <= 0xFF; ++i) { crypto::PublicKey key; memset(&key, i, sizeof(crypto::PublicKey)); if (!crypto::check_key(key)) { return key; } } throw std::runtime_error("invalid public key wasn't found"); return crypto::PublicKey(); } } //---------------------------------------------------------------------------------------------------------------------- // Tests bool gen_tx_big_version::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), m_currency.minimumFee(), 0, sources, destinations); tx_builder builder; builder.step1_init(TRANSACTION_VERSION_2 + 1, 0); builder.step2_fill_inputs(miner_account.getAccountKeys(), sources); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_unlock_time::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS_N(events, blk_1, blk_0, miner_account, 10); REWIND_BLOCKS(events, blk_1r, blk_1, miner_account); auto make_tx_with_unlock_time = [&](uint64_t unlock_time) -> Transaction { return make_simple_tx_with_unlock_time(events, blk_1, miner_account, miner_account, MK_COINS(1), m_currency.minimumFee(), unlock_time); }; std::list<Transaction> txs_0; txs_0.push_back(make_tx_with_unlock_time(0)); events.push_back(txs_0.back()); txs_0.push_back(make_tx_with_unlock_time(get_block_height(blk_1r) - 1)); events.push_back(txs_0.back()); txs_0.push_back(make_tx_with_unlock_time(get_block_height(blk_1r))); events.push_back(txs_0.back()); txs_0.push_back(make_tx_with_unlock_time(get_block_height(blk_1r) + 1)); events.push_back(txs_0.back()); txs_0.push_back(make_tx_with_unlock_time(get_block_height(blk_1r) + 2)); events.push_back(txs_0.back()); txs_0.push_back(make_tx_with_unlock_time(ts_start - 1)); events.push_back(txs_0.back()); txs_0.push_back(make_tx_with_unlock_time(time(0) + 60 * 60)); events.push_back(txs_0.back()); MAKE_NEXT_BLOCK_TX_LIST(events, blk_2, blk_1r, miner_account, txs_0); return true; } bool gen_tx_no_inputs_no_outputs::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); tx_builder builder; builder.step1_init(); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_no_inputs_has_outputs::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), m_currency.minimumFee(), 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step3_fill_outputs(destinations); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_has_inputs_no_outputs::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), m_currency.minimumFee(), 0, sources, destinations); destinations.clear(); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.getAccountKeys(), sources); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); builder.step5_sign(sources); events.push_back(builder.m_tx); MAKE_NEXT_BLOCK_TX1(events, blk_1, blk_0r, miner_account, builder.m_tx); return true; } bool gen_tx_invalid_input_amount::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), m_currency.minimumFee(), 0, sources, destinations); sources.front().amount++; tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.getAccountKeys(), sources); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_in_to_key_wo_key_offsets::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), m_currency.minimumFee(), 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.getAccountKeys(), sources); builder.step3_fill_outputs(destinations); KeyInput& in_to_key = boost::get<KeyInput>(builder.m_tx.inputs.front()); uint32_t key_offset = in_to_key.outputIndexes.front(); in_to_key.outputIndexes.pop_back(); CHECK_AND_ASSERT_MES(in_to_key.outputIndexes.empty(), false, "txin contained more than one key_offset"); builder.step4_calc_hash(); in_to_key.outputIndexes.push_back(key_offset); builder.step5_sign(sources); in_to_key.outputIndexes.pop_back(); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_key_offest_points_to_foreign_key::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); MAKE_NEXT_BLOCK(events, blk_1, blk_0, miner_account); REWIND_BLOCKS(events, blk_1r, blk_1, miner_account); MAKE_ACCOUNT(events, alice_account); MAKE_ACCOUNT(events, bob_account); MAKE_TX_LIST_START(events, txs_0, miner_account, bob_account, MK_COINS(60) + 1, blk_1); MAKE_TX_LIST(events, txs_0, miner_account, alice_account, MK_COINS(60) + 1, blk_1); MAKE_NEXT_BLOCK_TX_LIST(events, blk_2, blk_1r, miner_account, txs_0); std::vector<TransactionSourceEntry> sources_bob; std::vector<TransactionDestinationEntry> destinations_bob; fill_tx_sources_and_destinations(events, blk_2, bob_account, miner_account, MK_COINS(60) + 1 - m_currency.minimumFee(), m_currency.minimumFee(), 0, sources_bob, destinations_bob); std::vector<TransactionSourceEntry> sources_alice; std::vector<TransactionDestinationEntry> destinations_alice; fill_tx_sources_and_destinations(events, blk_2, alice_account, miner_account, MK_COINS(60) + 1 - m_currency.minimumFee(), m_currency.minimumFee(), 0, sources_alice, destinations_alice); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(bob_account.getAccountKeys(), sources_bob); KeyInput& in_to_key = boost::get<KeyInput>(builder.m_tx.inputs.front()); in_to_key.outputIndexes.front() = sources_alice.front().outputs.front().first; builder.step3_fill_outputs(destinations_bob); builder.step4_calc_hash(); builder.step5_sign(sources_bob); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_sender_key_offest_not_exist::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), m_currency.minimumFee(), 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.getAccountKeys(), sources); KeyInput& in_to_key = boost::get<KeyInput>(builder.m_tx.inputs.front()); in_to_key.outputIndexes.front() = std::numeric_limits<uint32_t>::max(); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_mixed_key_offest_not_exist::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); MAKE_NEXT_BLOCK(events, blk_1, blk_0, miner_account); REWIND_BLOCKS(events, blk_1r, blk_1, miner_account); MAKE_ACCOUNT(events, alice_account); MAKE_ACCOUNT(events, bob_account); MAKE_TX_LIST_START(events, txs_0, miner_account, bob_account, MK_COINS(1) + m_currency.minimumFee(), blk_1); MAKE_TX_LIST(events, txs_0, miner_account, alice_account, MK_COINS(1) + m_currency.minimumFee(), blk_1); MAKE_NEXT_BLOCK_TX_LIST(events, blk_2, blk_1r, miner_account, txs_0); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_2, bob_account, miner_account, MK_COINS(1), m_currency.minimumFee(), 1, sources, destinations); sources.front().outputs[(sources.front().realOutput + 1) % 2].first = std::numeric_limits<uint32_t>::max(); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(bob_account.getAccountKeys(), sources); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_key_image_not_derive_from_tx_key::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), m_currency.minimumFee(), 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.getAccountKeys(), sources); KeyInput& in_to_key = boost::get<KeyInput>(builder.m_tx.inputs.front()); KeyPair kp = generateKeyPair(); crypto::KeyImage another_ki; crypto::generate_key_image(kp.publicKey, kp.secretKey, another_ki); in_to_key.keyImage = another_ki; builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); // Tx with invalid key image can't be subscribed, so create empty signature builder.m_tx.signatures.resize(1); builder.m_tx.signatures[0].resize(1); builder.m_tx.signatures[0][0] = boost::value_initialized<crypto::Signature>(); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_key_image_is_invalid::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), m_currency.minimumFee(), 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.getAccountKeys(), sources); KeyInput& in_to_key = boost::get<KeyInput>(builder.m_tx.inputs.front()); crypto::PublicKey pub = generate_invalid_pub_key(); memcpy(&in_to_key.keyImage, &pub, sizeof(crypto::EllipticCurvePoint)); builder.step3_fill_outputs(destinations); builder.step4_calc_hash(); // Tx with invalid key image can't be subscribed, so create empty signature builder.m_tx.signatures.resize(1); builder.m_tx.signatures[0].resize(1); builder.m_tx.signatures[0][0] = boost::value_initialized<crypto::Signature>(); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_check_input_unlock_time::generate(std::vector<test_event_entry>& events) const { static const size_t tests_count = 6; uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS_N(events, blk_1, blk_0, miner_account, tests_count - 1); REWIND_BLOCKS(events, blk_1r, blk_1, miner_account); std::array<AccountBase, tests_count> accounts; for (size_t i = 0; i < tests_count; ++i) { MAKE_ACCOUNT(events, acc); accounts[i] = acc; } std::list<Transaction> txs_0; auto make_tx_to_acc = [&](size_t acc_idx, uint64_t unlock_time) { txs_0.push_back(make_simple_tx_with_unlock_time(events, blk_1, miner_account, accounts[acc_idx], MK_COINS(1) + m_currency.minimumFee(), m_currency.minimumFee(), unlock_time)); events.push_back(txs_0.back()); }; uint64_t blk_3_height = get_block_height(blk_1r) + 2; make_tx_to_acc(0, 0); make_tx_to_acc(1, blk_3_height - 1); make_tx_to_acc(2, blk_3_height); make_tx_to_acc(3, blk_3_height + 1); make_tx_to_acc(4, time(0) - 1); make_tx_to_acc(5, time(0) + 60 * 60); MAKE_NEXT_BLOCK_TX_LIST(events, blk_2, blk_1r, miner_account, txs_0); std::list<Transaction> txs_1; auto make_tx_from_acc = [&](size_t acc_idx, bool invalid) { Transaction tx = make_simple_tx_with_unlock_time(events, blk_2, accounts[acc_idx], miner_account, MK_COINS(1), m_currency.minimumFee(), 0); if (invalid) { DO_CALLBACK(events, "mark_invalid_tx"); } else { txs_1.push_back(tx); } events.push_back(tx); }; make_tx_from_acc(0, false); make_tx_from_acc(1, false); make_tx_from_acc(2, false); make_tx_from_acc(3, true); make_tx_from_acc(4, false); make_tx_from_acc(5, true); MAKE_NEXT_BLOCK_TX_LIST(events, blk_3, blk_2, miner_account, txs_1); return true; } bool gen_tx_txout_to_key_has_invalid_key::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), m_currency.minimumFee(), 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.getAccountKeys(), sources); builder.step3_fill_outputs(destinations); KeyOutput& out_to_key = boost::get<KeyOutput>(builder.m_tx.outputs.front().target); out_to_key.key = generate_invalid_pub_key(); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_output_with_zero_amount::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), m_currency.minimumFee(), 0, sources, destinations); tx_builder builder; builder.step1_init(); builder.step2_fill_inputs(miner_account.getAccountKeys(), sources); builder.step3_fill_outputs(destinations); builder.m_tx.outputs.front().amount = 0; builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } bool gen_tx_signatures_are_invalid::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); MAKE_NEXT_BLOCK(events, blk_1, blk_0, miner_account); REWIND_BLOCKS(events, blk_1r, blk_1, miner_account); MAKE_ACCOUNT(events, alice_account); MAKE_ACCOUNT(events, bob_account); MAKE_TX_LIST_START(events, txs_0, miner_account, bob_account, MK_COINS(1) + m_currency.minimumFee(), blk_1); MAKE_TX_LIST(events, txs_0, miner_account, alice_account, MK_COINS(1) + m_currency.minimumFee(), blk_1); MAKE_NEXT_BLOCK_TX_LIST(events, blk_2, blk_1r, miner_account, txs_0); MAKE_TX(events, tx_0, miner_account, miner_account, MK_COINS(60), blk_2); events.pop_back(); MAKE_TX_MIX(events, tx_1, bob_account, miner_account, MK_COINS(1), 1, blk_2); events.pop_back(); // Tx with nmix = 0 without signatures DO_CALLBACK(events, "mark_invalid_tx"); BinaryArray sr_tx = toBinaryArray(static_cast<TransactionPrefix>(tx_0)); events.push_back(serialized_transaction(sr_tx)); // Tx with nmix = 0 have a few inputs, and not enough signatures DO_CALLBACK(events, "mark_invalid_tx"); sr_tx = toBinaryArray(tx_0); sr_tx.resize(sr_tx.size() - sizeof(crypto::Signature)); events.push_back(serialized_transaction(sr_tx)); // Tx with nmix = 0 have a few inputs, and too many signatures DO_CALLBACK(events, "mark_invalid_tx"); sr_tx = toBinaryArray(tx_0); sr_tx.insert(sr_tx.end(), sr_tx.end() - sizeof(crypto::Signature), sr_tx.end()); events.push_back(serialized_transaction(sr_tx)); // Tx with nmix = 1 without signatures DO_CALLBACK(events, "mark_invalid_tx"); sr_tx = toBinaryArray(static_cast<TransactionPrefix>(tx_1)); events.push_back(serialized_transaction(sr_tx)); // Tx with nmix = 1 have not enough signatures DO_CALLBACK(events, "mark_invalid_tx"); sr_tx = toBinaryArray(tx_1); sr_tx.resize(sr_tx.size() - sizeof(crypto::Signature)); events.push_back(serialized_transaction(sr_tx)); // Tx with nmix = 1 have too many signatures DO_CALLBACK(events, "mark_invalid_tx"); sr_tx = toBinaryArray(tx_1); sr_tx.insert(sr_tx.end(), sr_tx.end() - sizeof(crypto::Signature), sr_tx.end()); events.push_back(serialized_transaction(sr_tx)); return true; } GenerateTransactionWithZeroFee::GenerateTransactionWithZeroFee(bool keptByBlock) : m_keptByBlock(keptByBlock) { } bool GenerateTransactionWithZeroFee::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(alice_account); GENERATE_ACCOUNT(bob_account); MAKE_GENESIS_BLOCK(events, blk_0, alice_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, alice_account); cn::Transaction tx; construct_tx_to_key(m_logger, events, tx, blk_0, alice_account, bob_account, MK_COINS(1), 0, 0); if (!m_keptByBlock) { DO_CALLBACK(events, "mark_invalid_tx"); } else { event_visitor_settings settings; settings.txs_keeped_by_block = true; settings.valid_mask = 1; events.push_back(settings); } events.push_back(tx); return true; } MultiSigTx_OutputSignatures::MultiSigTx_OutputSignatures(size_t givenKeys, uint32_t requiredSignatures, bool shouldSucceed) : m_givenKeys(givenKeys), m_requiredSignatures(requiredSignatures), m_shouldSucceed(shouldSucceed) { m_currency = CurrencyBuilder(m_logger).upgradeHeightV2(0).currency(); for (size_t i = 0; i < m_givenKeys; ++i) { AccountBase acc; acc.generate(); m_outputAccounts.push_back(acc); } } bool MultiSigTx_OutputSignatures::generate(std::vector<test_event_entry>& events) const { TestGenerator generator(m_currency, events); generator.generator.defaultMajorVersion = BLOCK_MAJOR_VERSION_2; return generate(generator); } bool MultiSigTx_OutputSignatures::generate(TestGenerator& generator) const { generator.generateBlocks(m_currency.minedMoneyUnlockWindow(), BLOCK_MAJOR_VERSION_2); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(generator.events, generator.lastBlock, generator.minerAccount, generator.minerAccount, MK_COINS(1), m_currency.minimumFee(), 0, sources, destinations); tx_builder builder; builder.step1_init(TRANSACTION_VERSION_2); builder.step2_fill_inputs(generator.minerAccount.getAccountKeys(), sources); MultisignatureOutput target; for (const auto& acc : m_outputAccounts) { target.keys.push_back(acc.getAccountKeys().address.spendPublicKey); } target.requiredSignatureCount = m_requiredSignatures; target.term = 0; TransactionOutput txOut = { MK_COINS(1), target }; builder.m_tx.outputs.push_back(txOut); builder.step4_calc_hash(); builder.step5_sign(sources); if (!m_shouldSucceed) { generator.addCallback("mark_invalid_tx"); } generator.addEvent(builder.m_tx); if (!m_shouldSucceed) { generator.addCallback("mark_invalid_block"); } generator.makeNextBlock(builder.m_tx); return true; } bool MultiSigTx_InvalidOutputSignature::generate(std::vector<test_event_entry>& events) const { uint64_t ts_start = 1338224400; GENERATE_ACCOUNT(miner_account); MAKE_GENESIS_BLOCK(events, blk_0, miner_account, ts_start); REWIND_BLOCKS(events, blk_0r, blk_0, miner_account); std::vector<TransactionSourceEntry> sources; std::vector<TransactionDestinationEntry> destinations; fill_tx_sources_and_destinations(events, blk_0, miner_account, miner_account, MK_COINS(1), m_currency.minimumFee(), 0, sources, destinations); tx_builder builder; builder.step1_init(TRANSACTION_VERSION_2); builder.step2_fill_inputs(miner_account.getAccountKeys(), sources); MultisignatureOutput target; crypto::PublicKey pk; crypto::SecretKey sk; crypto::generate_keys(pk, sk); // fill with 1 valid key target.keys.push_back(pk); // and 1 invalid target.keys.push_back(generate_invalid_pub_key()); target.requiredSignatureCount = 2; target.term = 0; TransactionOutput txOut = { MK_COINS(1), target }; builder.m_tx.outputs.push_back(txOut); builder.step4_calc_hash(); builder.step5_sign(sources); DO_CALLBACK(events, "mark_invalid_tx"); events.push_back(builder.m_tx); return true; } namespace { void fillMultisignatureInput(TestGenerator& generator, tx_builder& builder, uint64_t inputAmount, uint32_t givenSignatures) { builder.step1_init(TRANSACTION_VERSION_2); // create input MultisignatureInput input; input.amount = inputAmount; input.signatureCount = givenSignatures; input.outputIndex = 0; input.term = 0; builder.m_tx.inputs.push_back(input); // create output std::vector<TransactionDestinationEntry> destinations; destinations.emplace_back(inputAmount - generator.currency().minimumFee(), generator.minerAccount.getAccountKeys().address); builder.step3_fill_outputs(destinations); // calc hash builder.step4_calc_hash(); } } MultiSigTx_Input::MultiSigTx_Input( size_t givenKeys, uint32_t requiredSignatures, uint32_t givenSignatures, bool inputShouldSucceed) : MultiSigTx_OutputSignatures(givenKeys, requiredSignatures, true), m_givenSignatures(givenSignatures), m_inputShouldSucceed(inputShouldSucceed) { m_currency = CurrencyBuilder(m_logger).upgradeHeightV2(0).currency(); } bool MultiSigTx_Input::generate(std::vector<test_event_entry>& events) const { TestGenerator generator(m_currency, events); generator.generator.defaultMajorVersion = BLOCK_MAJOR_VERSION_2; // create outputs MultiSigTx_OutputSignatures::generate(generator); tx_builder builder; fillMultisignatureInput(generator, builder, MK_COINS(1), m_givenSignatures); // calc signatures builder.m_tx.signatures.resize(builder.m_tx.signatures.size() + 1); auto& outsigs = builder.m_tx.signatures.back(); for (size_t i = 0; i < m_givenSignatures; ++i) { const auto& pk = m_outputAccounts[i].getAccountKeys().address.spendPublicKey; const auto& sk = m_outputAccounts[i].getAccountKeys().spendSecretKey; crypto::Signature sig; crypto::generate_signature(builder.m_tx_prefix_hash, pk, sk, sig); outsigs.push_back(sig); } if (!m_inputShouldSucceed) { generator.addCallback("mark_invalid_tx"); } generator.addEvent(builder.m_tx); return true; } MultiSigTx_BadInputSignature::MultiSigTx_BadInputSignature() : MultiSigTx_OutputSignatures(1, 1, true) { } bool MultiSigTx_BadInputSignature::generate(std::vector<test_event_entry>& events) const { TestGenerator generator(m_currency, events); generator.generator.defaultMajorVersion = BLOCK_MAJOR_VERSION_2; // create outputs MultiSigTx_OutputSignatures::generate(generator); tx_builder builder; fillMultisignatureInput(generator, builder, MK_COINS(1), 1); // calc signatures builder.m_tx.signatures.resize(builder.m_tx.signatures.size() + 1); auto& outsigs = builder.m_tx.signatures.back(); const auto& pk = m_outputAccounts[0].getAccountKeys().address.spendPublicKey; const auto& sk = m_outputAccounts[0].getAccountKeys().spendSecretKey; // modify the transaction prefix hash crypto::Hash badHash = builder.m_tx_prefix_hash; *reinterpret_cast<uint16_t*>(&badHash) = 0xdead; // sign the hash crypto::Signature sig; crypto::generate_signature(badHash, pk, sk, sig); outsigs.push_back(sig); // transaction with bad signature should be rejected generator.addCallback("mark_invalid_tx"); generator.addEvent(builder.m_tx); // blocks with transaction with bad signature should be rejected generator.addCallback("mark_invalid_block"); generator.makeNextBlock(builder.m_tx); return true; }
//Ordinary function #include <algorithm> #include <ctime> #include <cstdlib> #include <vector> #include <iostream> using namespace std; /*int randGen_1() { return rand() % 10 + 1; }*/ class myFunctor { // function: public: myFunctor() : num(1) {} void operator() (int i) { cout << "#" << num++ << ": " << i << endl; } private: int num; }; struct myStruct { // function object type: void operator() (int i) { cout << ' ' << i; } } myobject; //Function object class RandGen_2 { public: RandGen_2() : numbers() { } int operator()(); private: vector<int> numbers; }; void main(void) { srand(time(NULL)); vector<int> numbers1(7); vector<int> numbers2(7); //this is how to use "ordinary"function /* srand(time(NULL)); // it is necessary to remember to call this generate(numbers.begin(), numbers.end(), randGen_1); */ //this is how to use function object RandGen_2 randGen_1; generate(numbers1.begin(), numbers1.end(), randGen_1); sort(numbers1.begin(), numbers1.begin() + 7); cout << "1st lotto row: "; for_each(numbers1.begin(), numbers1.end(), myobject); RandGen_2 randGen_2; generate(numbers2.begin(), numbers2.end(), randGen_2); sort(numbers2.begin(), numbers2.end()); cout << endl << "2nd lotto row: "; for_each(numbers2.begin(), numbers2.end(), myobject); cout << endl << "Same number: " << endl; vector<int> same(7); auto it = set_intersection(numbers1.begin(), numbers1.end(), numbers2.begin(), numbers2.end(), same.begin()); same.resize(it - same.begin()); for_each(same.begin(), same.end(), myFunctor()); } int RandGen_2::operator()() { int number; do { number = rand() % 37 + 1; } while (find(numbers.begin(), numbers.end(), number) != numbers.end()); numbers.push_back(number); return number; }
int motor_one1=9; int motor_one2=10; int motor_two1=5; int motor_two2=3; void setup() { // put your setup code here, to run once: pinMode(6,INPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); pinMode(11,INPUT); pinMode(5,OUTPUT); pinMode(3,OUTPUT); } void loop() { // put your main code here, to run repeatedly: int sensorstate1= digitalRead(6); int sensorstate2= digitalRead(11); if(sensorstate1==HIGH && sensorstate2==HIGH) {analogWrite(9,0); analogWrite(10,200); analogWrite(5,0); analogWrite(3,200); delay(1000); analogWrite(9,0); analogWrite(10,0); analogWrite(5,0); analogWrite(3,0); delay(500); {analogWrite(9,0); analogWrite(10,50); analogWrite(5,125); analogWrite(3,0); } if(sensorstate1==LOW && sensorstate2==HIGH) {analogWrite(9,0); analogWrite(10,200); analogWrite(5,0); analogWrite(3,200); delay(1000); analogWrite(9,0); analogWrite(10,0); analogWrite(5,0); analogWrite(3,0); delay(500); analogWrite(9,0); analogWrite(10,50); analogWrite(5,125); analogWrite(3,0); if(sensorstate1==HIGH && sensorstate2==LOW) {analogWrite(9,0); analogWrite(10,200); analogWrite(5,0); analogWrite(3,200); delay(1000); analogWrite(9,0); analogWrite(10,0); analogWrite(5,0); analogWrite(3,0); delay(500); analogWrite(9,0); analogWrite(10,50); analogWrite(5,125); analogWrite(3,0); } } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef SIMPLEWEBSERVERMANAGERIMPL_H #define SIMPLEWEBSERVERMANAGERIMPL_H #ifdef WIDGET_RUNTIME_SUPPORT # ifdef WIDGET_RUNTIME_UNITE_SUPPORT #include "../WebServerStateListener.h" #include "SimpleWebServerController.h" #include "WebServerDeviceHandler.h" #include "WebServerStarter.h" #include "WebServerStateView.h" #include "adjunct/quick/webserver/controller/WebServerSettingsContext.h" /** * The entry point when it comes to SimpleWebServerManager internal * implementation. * * Initializes and manages the lifetimes of the different classes realizing the * web server management functions. * * @author Wojciech Dzierzanowski (wdzierzanowski) * @see SimpleWebServerManager */ class SimpleWebServerManagerImpl : public WebServerStateListener // TODO: public OpPrefsListener, // TODO: public MessageObject, { public: SimpleWebServerManagerImpl(); virtual ~SimpleWebServerManagerImpl(); OP_STATUS Init(); OP_STATUS AddWebServerStateListener(WebServerStateListener& listener); OP_STATUS StartWebServer(); OP_STATUS ShowWebServerStatus(); // // WebServerStateListener // virtual OP_STATUS OnLoggedIn(); private: BOOL ConfigureWithDialog(); BOOL LogInWithDialog(); const WebServerSettingsContext& GetWebServerSettings(); static WebServerSettingsContext s_web_server_settings; WebServerStarter m_web_server_starter; WebServerDeviceHandler m_device_handler; SimpleWebServerController m_controller; WebServerStateView m_web_server_state_view; BOOL m_configuration_pending; }; # endif // WIDGET_RUNTIME_UNITE_SUPPORT #endif // WIDGET_RUNTIME_SUPPORT #endif // SIMPLEWEBSERVERMANAGERIMPL_H
#ifndef BSMAI_CLIENT #define BSMAI_CLIENT #include <iostream> #include <sstream> #include <fstream> #include <curl/curl.h> #include "json.hpp" class PhenoAIClient{ private: std::string _server_ip; int _server_port; CURL* _curl; public: // Constructor PhenoAIClient(std::string ip, int port){ // Store server settings set_server_ip(ip); set_server_port(port); // Create curl handle curl_global_init(CURL_GLOBAL_ALL); _curl = curl_easy_init(); } // Destructor ~PhenoAIClient(){ curl_global_cleanup(); } // Getters and setters std::string get_server_ip(){ return _server_ip; } int get_server_port(){ return _server_port; } void set_server_ip(std::string ip){ _server_ip = ip; } void set_server_port(int port){ _server_port = port; } // Predict functions nlohmann::json predict_values(float data[], int nParameters, bool mapping){ // Translate data array to python format list std::string datalist = "["; for(int i=0; i<nParameters; ++i){ if(datalist != "["){ datalist += ","; } std::ostringstream buff; buff << data[i]; datalist += buff.str(); } datalist += "]"; // Query server std::string result = query("values", datalist, mapping); // Convert result into json object return resultConstructor(result); } nlohmann::json predict_file(const char* filepath, bool mapping){ // Translate data array to python format list std::ifstream ifs(filepath); std::string content( (std::istreambuf_iterator<char>(ifs) ), (std::istreambuf_iterator<char>() ) ); // Query server std::string result = query("file", content, mapping); // Convert result into json object return resultConstructor(result); } // Send request std::string query(std::string mode, std::string data, bool mapping){ // Create post request std::string mapping_str = (mapping)?"1":"0"; std::string poststring = "get_results_as_string=1&mode="+mode+"&data="+data+"&mapping="+mapping_str+""; std::string readBuffer; // Check if curl handle exists if (_curl){ // Allocate space for result code CURLcode res; // First set the URL that is about the receive our POST. This URL can // just as well be a https:// URL if that is what should receive the data curl_easy_setopt(_curl, CURLOPT_URL, _server_ip.c_str()); curl_easy_setopt(_curl, CURLOPT_PORT, _server_port); curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(_curl, CURLOPT_WRITEDATA, &readBuffer); // New specify the POST data curl_easy_setopt(_curl, CURLOPT_POSTFIELDS, poststring.c_str()); // Perform the request, res will get the return code res = curl_easy_perform(_curl); // Check for errors if(res != CURLE_OK){ std::cout << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl; } // Always cleanup curl_easy_cleanup(_curl); } return readBuffer; } // Result constructor nlohmann::json resultConstructor(std::string result){ auto jsonresult = nlohmann::json::parse(result); if(jsonresult["status"] == "error"){ std::string errortype = jsonresult["type"]; std::string errormessage = jsonresult["message"]; std::string error = errormessage+" ("+errortype+")"; throw std::runtime_error(error); } return jsonresult; } static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void* userp){ ((std::string*)userp)->append((char*)contents, size * nmemb); return size*nmemb; } }; #endif
#include<iostream> #include<algorithm> #include<vector> using namespace std; class NestedInteger { public: // Return true if this NestedInteger holds a single integer, rather than a nested list. bool isInteger() const{ return isInt; } // Return the single integer that this NestedInteger holds, if it holds a single integer // The result is undefined if this NestedInteger holds a nested list int getInteger() const{ return val; } // Return the nested list that this NestedInteger holds, if it holds a nested list // The result is undefined if this NestedInteger holds a single integer const vector<NestedInteger> &getList() const{ return nestedList; } int val; bool isInt; vector<NestedInteger> nestedList; }; class NestedIterator { public: NestedIterator(vector<NestedInteger> &nestedList) { //基本思想:递归dfs深度优先搜索 pos=0; dfs(nestedList); } void dfs(vector<NestedInteger> nestedList) { for(int i=0;i<nestedList.size();i++) { if(nestedList[i].isInteger()) val.push_back(nestedList[i].getInteger()); else dfs(nestedList[i].getList()); } } int next() { return val[pos++]; } bool hasNext() { return pos<val.size()?true:false; } private: vector<int> val; int pos; }; int main() { NestedInteger i1,i2,i3; i1.isInt=true; i1.val=1; i2.isInt=true; i2.val=2; i3.isInt=false; i3.nestedList={i1,i2}; vector<NestedInteger> nestedList{i1,i2,i3}; NestedIterator i(nestedList); while (i.hasNext()) cout << i.next()<<endl; return 0; }
#ifndef WINDOWS_PANEL_H #define WINDOWS_PANEL_H #include "adjunct/quick_toolkit/windows/DesktopWindow.h" #include "modules/inputmanager/inputaction.h" #include "adjunct/quick/panels/HotlistPanel.h" #include "modules/util/adt/opvector.h" #include "modules/widgets/OpWidget.h" class OpToolbar; class OpWindowList; /*********************************************************************************** ** ** WindowsPanel ** ***********************************************************************************/ class WindowsPanel : public HotlistPanel { public: WindowsPanel(); virtual ~WindowsPanel() {}; virtual OP_STATUS Init(); virtual void GetPanelText(OpString& text, Hotlist::PanelTextType text_type); virtual const char* GetPanelImage() {return "Panel Windows";} virtual void OnLayoutPanel(OpRect& rect); virtual void OnFullModeChanged(BOOL full_mode); virtual void OnFocus(BOOL focus,FOCUS_REASON reason); virtual Type GetType() {return PANEL_TYPE_WINDOWS;} // == OpInputContext ====================== virtual const char* GetInputContextName() {return "Windows Panel";} virtual BOOL OnInputAction(OpInputAction* action); private: OpWindowList* m_windows_view; }; #endif // WINDOWS_PANEL_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Adam Minchinton, Michal Zajaczkowski */ #ifndef _AUTOUPDATER_H_INCLUDED_ #define _AUTOUPDATER_H_INCLUDED_ #ifdef AUTO_UPDATE_SUPPORT #define g_autoupdater (&AutoUpdater::GetInstance()) #include "adjunct/autoupdate/autoupdatexml.h" #include "adjunct/autoupdate/platformupdater.h" #include "adjunct/autoupdate/file_downloader.h" #include "adjunct/autoupdate/updatableresource.h" #include "adjunct/autoupdate/statusxmldownloader.h" #include "adjunct/desktop_util/version/operaversion.h" #include "adjunct/autoupdate/scheduler/optaskscheduler.h" #include "modules/util/adt/oplisteners.h" #include "modules/prefs/prefsmanager/collections/pc_ui.h" #include "modules/prefs/prefsmanager/opprefslistener.h" #ifdef OPERA_CONSOLE # include "modules/console/opconsoleengine.h" #endif class AutoUpdateXML; class UpdatableResource; class StatusXMLDownloader; class StatusXMLDownloaderListener; #ifndef _MACINTOSH_ namespace opera_update_checker { namespace ipc { class Channel; }} #endif // _MACINTOSH_ enum AutoUpdateError { AUNoError, //< No error AUInternalError, //< wrong initializations of objects etc. AUInProgressError, //< check for updates while an update is in progress AUConnectionError, //< no network connection, server not reachable, failed ssl handshake etc. AUSaveError, //< no permission, not enough disk space AUValidationError, //< extraction failed, wrong checksum, corrupt/invalid package, wrong format/file, wrong Opera version, XML parsing error AUUpdateError //< error when updating resources }; /** * Enum for the automation level */ enum LevelOfAutomation { NoChecking = 0, ///< Opera shall never automatically connect to opera.com to retrieve updates or information about them. CheckForUpdates, ///< Opera shall periodically connect to opera.com to get updates to resources, as well as notify the user about available updates to the application. AutoInstallUpdates ///< Opera shall periodically connect to opera.com to get updates to resources, as well as automatically download and install available security (minor) updates to the application, and notify the user that an update has taken place. }; /** * This class is the base class for the auto update functionallity. * * It should contain all code to do any platform/product independent * functionallity such as version comparisons, xml parsing, * downloading of files etc. * * @see platformupdater.h For the interface used to manage updates on the platform. * */ class AutoUpdater: public FileDownloadListener, public MessageObject, public OpTimerListener, public StatusXMLDownloaderListener, public OpPrefsListener { public: enum ScheduleCheckType { // Used when scheduling next update check on browser startup ScheduleStartup, // Used when scheduling next update check after previous check completed ScheduleRunning }; enum AutoUpdateState { AUSUpToDate, AUSChecking, AUSUpdateAvailable, AUSDownloading, AUSReadyToUpdate, AUSUpdating, AUSUnpacking, AUSReadyToInstall, AUSErrorDownloading, AUSError }; enum CheckerState { CheckerOk, CheckerCouldntLaunch }; class AutoUpdateListener { public: virtual ~AutoUpdateListener() {} virtual void OnUpToDate(BOOL silent) = 0; virtual void OnChecking(BOOL silent) = 0; virtual void OnUpdateAvailable(UpdatableResource::UpdatableResourceType type, OpFileLength update_size, const uni_char* update_info_url, BOOL silent) = 0; virtual void OnDownloading(UpdatableResource::UpdatableResourceType type, OpFileLength total_size, OpFileLength downloaded_size, double kbps, unsigned long time_estimate, BOOL silent) = 0; virtual void OnDownloadingDone(UpdatableResource::UpdatableResourceType type, const OpString& filename, OpFileLength total_size, BOOL silent) = 0; virtual void OnDownloadingFailed(BOOL silent) = 0; virtual void OnRestartingDownload(INT32 seconds_until_restart, AutoUpdateError last_error, BOOL silent) = 0; virtual void OnReadyToUpdate() = 0; virtual void OnUpdating() = 0; virtual void OnFinishedUpdating() = 0; virtual void OnUnpacking() = 0; virtual void OnReadyToInstallNewVersion(const OpString& version, BOOL silent) = 0; virtual void OnError(AutoUpdateError error, BOOL silent) = 0; }; /** * Initialize the updater. Also call Activate to run it, as this * does not start the auto updater! Call Activate() when this function * returns OK. * * @return OK if the updater is correctly initialized and ready to go, * err if there was some problem. */ virtual OP_STATUS Init(BOOL check_increased_update_check_interval = TRUE); /** * Add an autoupdate listener */ OP_STATUS AddListener(AutoUpdateListener* listener) { return m_listeners.Add(listener); } /** * Remove an autoupdate listener */ OP_STATUS RemoveListener(AutoUpdateListener* listener) { return m_listeners.Remove(listener); } virtual void StatusXMLDownloaded(StatusXMLDownloader* downloader); virtual void StatusXMLDownloadFailed(StatusXMLDownloader* downloader, StatusXMLDownloader::DownloadStatus); /** Signals a change in an integer preference. * Function from OpPrefsListener interface. * * @param id Identity of the collection that has changed the value. * @param pref Identity of the preference. * @param newvalue The new value of the preference. */ virtual void PrefChanged(OpPrefsCollection::Collections id, int pref, int newvalue); /** * Activate the updater. AutoUpdater won't check for new updates * until this function is called. If a new update is due, * this function will initate it. If it's not due, this * function will schedule it. */ OP_STATUS Activate(); /** * Check for updates right now */ OP_STATUS CheckForUpdate(); /** * Called from FileDownloader when file download done */ virtual void OnFileDownloadDone(FileDownloader* file_downloader, OpFileLength total_size); /** * Called from FileDownloader when file download failed */ virtual void OnFileDownloadFailed(FileDownloader* file_downloader); /** * Called from FileDownloader when file download was aborted */ virtual void OnFileDownloadAborted(FileDownloader* file_downloader); /** * Called from FileDownloader when file download progresses */ virtual void OnFileDownloadProgress(FileDownloader* file_downloader, OpFileLength total_size, OpFileLength downloaded_size, double kbps, unsigned long time_estimate); /** * Callback used to signal that the * user has requested to be reminded later of some upgrade * * @param wait Interval to wait before notifying again. */ void DeferUpdate(); /** * Callback used to signal that the * user has requested that an update download should begin. */ OP_STATUS DownloadUpdate(); /** * Get download page url (www.opera.com/download) */ OP_STATUS GetDownloadPageURL(OpString& url); /** * Get the Opera version */ static OperaVersion& GetOperaVersion() { return m_opera_version; } /** * Stores the given int preference value and commits the preference store. Does leave trapping and converts it to OP_STATUS. * * @param which - The int preference ID to store, i.e. PrefsCollectionUI::TimeOfLastUpdateCheck * @param val - The new preference value to be stored * * @returns - OpStatus::OK saving and commiting the change went well, error code otherwise. */ OP_STATUS WritePref(PrefsCollectionUI::integerpref which, int val); AutoUpdater(); /** * Destructor. */ virtual ~AutoUpdater(); /** Sets the user initiated flag. @see m_user_initiated. */ void SetIsUserInitited(BOOL val) { m_user_initiated = val; } protected: StatusXMLDownloader* m_xml_downloader; ///< Holds the downloader that manages downloading the status xml. AutoUpdateXML* m_autoupdate_xml; AutoUpdateServerURL* m_autoupdate_server_url; /** * OpTimerListener implementation */ virtual void OnTimeOut( OpTimer *timer ); /** * Get download status */ void GetDownloadStatus(INT32* total_file_count, INT32* downloaded_file_count, INT32* failed_download_count); /** * Check all resources */ BOOL CheckAllResources(); /** * Get the type of the (possibly) available update */ UpdatableResource::UpdatableResourceType GetAvailableUpdateType() const; /** * Get the version of the (possibly) available update */ BOOL GetAvailablePackageInfo(OpString* version, OpString* info_url, OpFileLength* size) const; /** * Get the total size of the update */ OpFileLength GetTotalUpdateSize() const; /** * Check current update state, and decide on next action */ virtual OP_STATUS CheckAndUpdateState(); /** * MessageObject override */ virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); private: /* * The autoupdate automatic check scheduling works by the following rules. All time values are given in seconds. * * Preferences: * * PrefsCollectionUI::TimeOfLastUpdateCheck - The timestamp of the last update check, saved after each automatic autoupdate check request is made with success; * PrefsCollectionUI::UpdateCheckInterval - Number of seconds between automatic update checks. If changed by the autoupdate server in response to an autoupdate * request, will cause to drop the package update, should any be received with the autoupdate response; * PrefsCollectionUI::DelayedUpdateCheckInterval - Number of seconds added to PrefsCollectionUI::UpdateCheckInterval while scheduling an autoupdate check, will be * increased by the autoupdate mechanism when an error occurs during automatic update check, will be returned back to * 0 after a succesful download of the autoupdate XML response; * * Constants: * These values are mainly used to guard the settings read from preferences. * * MAX_UPDATE_CHECK_INTERVAL_SEC - Maximum interval between two automatic checks; * MIN_UPDATE_CHECK_INTERVAL_SEC - Minimum interval between two automatic checks, used when scheduling a check after the browser has started; * MIN_UPDATE_CHECK_INTERVAL_RUNNING_SEC - Minimum interval between two automatic checks, used when scheduling a check after a previous check during one browser session; * UPDATE_CHECK_INTERVAL_DELTA - The number of seconds that will be added to the DelayedUpdateCheckInterval after an unsuccesful autoupdate check; * AUTOUPDATE_RECHECK_TIMEOUT - The number of seconds that need to pass in order to redownload the autoupdate XML after the browser exited duting downloading of an * update, most likely as a result of a crash. If the browser is run again before this time elapses, the already downloaded XML response * is used if possible. * * Scheduling an update check: * * 1. Update check is scheduled: * a) at browser startup - AutoUpdater::Activate(); * b) after a succeful check - AutoUpdater::CheckAndUpdateState() for state AUSUpToDate; * c) after a check error - AutoUpdater::CheckAndUpdateState() for state AUSError. * 2. The number of seconds to next update check is calculated ad follows: * The time of last check and time between checks is read from the preferences, see above. The time between checks is the sum of the UpdateCheckInterval and DelayedUpdateCheckInterval values. * The sum is then normalized so that is falls into the range of [MIN_UPDATE_CHECK_INTERVAL_RUNNING_SEC, MAX_UPDATE_CHECK_INTERVAL_SEC] during normal operation (see 1b and 1c) and * [MIN_UPDATE_CHECK_INTERVAL_SEC, MAX_UPDATE_CHECK_INTERVAL_SEC] at browser startup (1a). The time of next scheduled check is then calculated by adding the time between checks to the time * of last check read from preferences (TimeOfLastUpdateCheck). If the time of next scheduled check is in the past, the check is scheduled immediately, otherwise the calculated time of next check * is used. The minimum scheduled time is 1 second for debug builds and 5 seconds for release builds. * */ /** * Maximal time between two automatic updates */ static const int MAX_UPDATE_CHECK_INTERVAL_SEC; /** * Minimal time between two automatic checks, used when scheduling an update check on browser startup */ static const int MIN_UPDATE_CHECK_INTERVAL_SEC; /** * Minimal time between two automatic checks happening during one browser session */ static const int MIN_UPDATE_CHECK_INTERVAL_RUNNING_SEC; /** * The update check interval will be increased with this value on each update check failure */ static const int UPDATE_CHECK_INTERVAL_DELTA_SEC; /** * Timeout to determine if we should use an already downloaded xml on disk, or check with the server again, * when e.g. downloading was aborted last time we ran Opera. * If the current time minus the time of last check is greater than this timeout, we recheck with the server. */ static const int AUTOUPDATE_RECHECK_TIMEOUT_SEC; /** * Retry period in case the core SSL updaters are busy at the moment of autoupdate check. The AutoUpdater class will * retry the update check attempt within the given time in such a case. * Value given in seconds. */ static const int AUTOUPDATE_SSL_UPDATERS_BUSY_RECHECK_TIMEOUT_SEC; /** * The base timeout for resource checking, see DSK-336588. During activation of the autoupdate module, we check the * resource timestamps, see AutpUpdateXML::NeedsResourceCheck(). In case we want to update the resources only (i.e. * in case any of the resources checked have a zero timestamp), we trigger a resource update check "right after" * activation of the module. * The "right after" time is determined by this base time with the DelayedUpdateCheckInterval added to it. */ static const int AUTOUPDATE_RESOURCE_CHECK_BASE_TIMEOUT_SEC; /** * Function that starts the download of the status XML document supplying * the necessary parameters. When the document is done downloading, the * StatusXMLDownloaded will be called. The caller of this function can * just return control and do nothing until this callback arrives. * * @return OK if the download is correctly initiated, err otherwise. */ OP_STATUS DownloadStatusXML(); /** * Schedules an immediate resource update check. Sets the m_resource_check_only flag to TRUE. If an update * check is already scheduled, the schedule timer will be deleted and the resource check will be scheduled. * The update check schedule will be restored after the resource check finishes. * * @return OK if the check was scheduled correctly, ERR_NO_ACCESS if a check is currently in progress, * ERR_NO_MEMORY on OOM. */ OP_STATUS ScheduleResourceCheck(); /** * Method encapsulating starting of the timer that triggers an update check. * Sets the m_resource_check_only flag to FALSE. * * @param timeout Timeout in sections until update check * * @return OK if the check was scheduled correctly, ERR otherwise. */ OP_STATUS ScheduleUpdateCheck(ScheduleCheckType schedule_type); /** * This method returns the number of seconds to the next update check at the moment * of the call. * * This method is overriden by selftests in order to schedule an immediate check. * * @param timeout Timeout in sections until update check * * @return The number of seconds that need to pass until the next update check occurs. */ virtual int CalculateTimeOfNextUpdateCheck(ScheduleCheckType schedule_type); /** * This method returns the number of seconds for the initial resource check, if any is * needed. More information can be found in DSK-336588. * * @return The number of seconds that need to pass before we do the resource check. */ int CalculateTimeOfResourceCheck(); /** * Function starting downloading of specified types * * @param include_resources_requiring_restart TRUE if add types that would require restart to complete update * * @return OK if the download was started, ERR otherwise. */ OP_STATUS DownloadUpdate(BOOL include_resources_requiring_restart); /** * Function starting next download * * @param previous_download Previous finished download * * @return OK if the download started, ERR on failure, ERR_NO_SUCH_RESOURCE if no more files to download. */ OP_STATUS StartNextDownload(FileDownloader* previous_download); /** * Function stopping downloading * * @return OK if the downloads were stopped, ERR otherwise. */ OP_STATUS StopDownloads(); /** * Function encapsulating starting of the timer that triggers a new download. * The function will work out how long the timer needs to be set for itself. * * @return OK if the check was scheduled correctly, ERR otherwise. */ OP_STATUS ScheduleDownload(); /** * Function to start updating the implied types. * * @param include_resources_requiring_restart TRUE if add types that would require restart to complete update * * @return OK if updating succeeded, ERR otherwise. */ OP_STATUS StartUpdate(BOOL include_resources_requiring_restart); /** * Function to clean up all resources. */ OP_STATUS CleanupAllResources(); #ifndef _MACINTOSH_ /** * Tries to run the checker. */ OP_STATUS TryRunningChecker(); #endif // _MACINTOSH_ /** * Broadcasts autoupdate events to all the listeners * */ void BroadcastOnUpToDate(BOOL silent); void BroadcastOnChecking(BOOL silent); void BroadcastOnUpdateAvailable(UpdatableResource::UpdatableResourceType type, OpFileLength update_size, const uni_char* update_info_url, BOOL silent); void BroadcastOnDownloading(UpdatableResource::UpdatableResourceType type, OpFileLength total_size, OpFileLength downloaded_size, double kbps, unsigned long time_estimate, BOOL silent); void BroadcastOnDownloadingDone(UpdatableResource::UpdatableResourceType type, const OpString& filename, OpFileLength total_size, BOOL silent); void BroadcastOnDownloadingFailed(BOOL silent); void BroadcastOnRestartingDownload(INT32 seconds_until_restart, AutoUpdateError last_error, BOOL silent); void BroadcastOnReadyToUpdate(); void BroadcastOnUpdating(); void BroadcastOnFinishedUpdating(); void BroadcastOnUnpacking(); void BroadcastOnReadyToInstallNewVersion(const OpString& version, BOOL silent); void BroadcastOnError(AutoUpdateError error, BOOL silent); /** * Set autoupdate set */ OP_STATUS SetUpdateState(AutoUpdateState update_state); /** * Set last error */ void SetLastError(AutoUpdateError error) { m_last_error = error; } /** * Indicates if it is a silently running update. * * If the update is triggered by the user (ie using CheckForUpdates() or DownloadUpdate()), * the update is not silent. Otherwise, it is silent. Exception: if update level is CheckForUpdates, * automatic updates are silent only until an update is available. */ BOOL IsSilent() const { return m_silent_update; } /** * Reset internal members. */ void Reset(); #ifdef AUTOUPDATE_PACKAGE_INSTALLATION /** * Check if a newer version has been downloaded * * Check if we have the autoupdate.txt file * This means the user have downloaded a newer version, but not installed it yet. * Dont ask for upgrades in this case. */ virtual BOOL HasDownloadedNewerVersion(); /** * Delete the upgrade folder if there is no autoupdate.txt there. * */ void DeleteUpgradeFolderIfNeeded(); #endif /** * Increases the value stored in the PrefsCollectionUI::DelayedUpdateCheckInterval preference. The value is used * to increase the interval to the next update check in case of error. * See more information about calculating the time of next update check above. * */ void IncreaseDelayedUpdateCheckInterval(); LevelOfAutomation m_level_of_automation; ///< Holds the level of automation AutoUpdateState m_update_state; ///< Holds the state of updating (whether an update has been discovered) OpListeners<AutoUpdateListener> m_listeners; ///< Listener for autoupdate events for external classes BOOL m_silent_update; ///< Indicates if it is a silently running update AutoUpdateError m_last_error; ///< Last occurred error OpTimer* m_update_check_timer; ///< Timer for rescheduling update check OpTimer* m_download_timer; ///< Timer for rescheduling download INT32 m_download_countdown; ///< Holds the remaining seconds till restarting download INT32 m_download_retries; ///< Holds the number retried downloads BOOL m_activated; ///< Set if the autoupdater has been activated BOOL m_check_increased_update_check_interval; ///< Set if autoupdater should check if the server is increasing the update check interval. In case it does, any packages should not be downloaded to avoid overloading the server. BOOL m_include_resources_requiring_restart; ///< When updating include resources that would need restart for update completion BOOL m_resources_check_only; ///< Determines what update level will be used for the update check, resources only or an full update check. static OperaVersion m_opera_version; ///< Holds the current Opera version AutoUpdateState m_state_after_unpacking; ///<Which state to move to once unpacking is done // AutoUpdater keeps time of last update check, interval, and delay in member variables, // because prefs, where these values are also stored, may be read only (DSK-353750) time_t m_time_of_last_update_check; ///< Time of last update check in seconds INT32 m_update_check_interval; ///< Interval between update checks in seconds INT32 m_update_check_random_delta; ///< A random time delta (in seconds) added to the check interval in order to have slightly different check time. It's needed by the server to detect UUID/LUT collisions. INT32 m_update_check_delay; ///< Additional delay for update check in seconds, used when server is not responding BOOL m_user_initiated; ///< TRUE if the current check is initiated by a user. It should be cleared after the check is done. #ifndef _MACINTOSH_ opera_update_checker::ipc::Channel* m_channel_to_checker; ///< IPC channel to the checker process. INT64 m_channel_id; ///< Id of the communication channel to the checker. OpString m_checker_path; ///< The path to the checker executable. OpTimer* m_checker_launch_retry_timer; ///< The checker launch retry timer. unsigned m_checker_launch_retry_count; ///< The counter of the checker launch reties. CheckerState m_checker_state; ///< The current checker state. static const unsigned MAX_CHECKER_LAUNCH_RETRIES = 5; static const unsigned CHECKER_LAUNCH_RETRY_TIME_MS = 10000; #endif // _MACINTOSH_ }; namespace Console { /* Write message to console */ void WriteMessage(const uni_char* message); /* Write error to console */ void WriteError(const uni_char* error); }; #endif // AUTO_UPDATE_SUPPORT #endif // _AUTOUPDATER_H_INCLUDED_
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2006 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "modules/display/vis_dev.h" #include "modules/logdoc/htm_elm.h" #ifdef DEBUG_GFX static int max_region_rect_count = 0; int display_flushrects = 0; int avoid_overdraw = 1; #endif class BgClipRect : public OpRect, public Link { public: BgClipRect(const OpRect& rect) : OpRect(rect) {} }; BOOL IsWorthDelaying(const OpRect &rect) { return rect.width > 20 && rect.height > 20; } /*BOOL IsWorthExcluding(const OpRect &rect) { // FIX: If the rect is small enough to flush a big enough background from stack or exclude it and keep hole. return TRUE; }*/ BOOL IsRegionSmall(const BgRegion &region) { // Downshifts with 3 to get 8px resolution and decrease risk of overflow unsigned int area = 0; for(int j = 0; j < region.num_rects; j++) area += (region.rects[j].width >> 3) * (region.rects[j].height >> 3); if (area < 3 * 3) return TRUE; return FALSE; } OpRect OpRectClip(const OpRect &this_rect, const OpRect &clip_rect) { OP_ASSERT(clip_rect.width >= 0 && clip_rect.height >= 0); OpRect tmp; if(!this_rect.Intersecting(clip_rect)) return tmp; int x1 = this_rect.x; int x2 = this_rect.x + this_rect.width; int y1 = this_rect.y; int y2 = this_rect.y + this_rect.height; tmp.x = MAX(x1, clip_rect.x); tmp.y = MAX(y1, clip_rect.y); tmp.width = MIN(x2, clip_rect.x + clip_rect.width) - tmp.x; tmp.height = MIN(y2, clip_rect.y + clip_rect.height) - tmp.y; return tmp; } // == BgRegion ================================================= BgRegion::BgRegion() : rects(NULL) , num_rects(0) , max_rects(0) { } BgRegion::~BgRegion() { Reset(); } void BgRegion::Reset(BOOL free_mem) { if (free_mem) { OP_DELETEA(rects); rects = NULL; max_rects = 0; } num_rects = 0; bounding_rect.Empty(); } OP_STATUS BgRegion::Set(OpRect rect) { Reset(); bounding_rect = rect; return AddRect(rect); } OP_STATUS BgRegion::Set(const BgRegion& rgn) { Reset(TRUE); int new_max_rects = rgn.num_rects; OpRect *new_rects = OP_NEWA(OpRect, new_max_rects); if (!new_rects) return OpStatus::ERR_NO_MEMORY; op_memcpy(new_rects, rgn.rects, sizeof(OpRect) * new_max_rects); rects = new_rects; num_rects = rgn.num_rects; bounding_rect = rgn.bounding_rect; max_rects = new_max_rects; return OpStatus::OK; } OP_STATUS BgRegion::GrowIfNeeded() { if(num_rects == max_rects) { // FIX: realloc would be better, and *2 or something like that. int new_max_rects = (max_rects == 0 ? 1 : max_rects + 8); OpRect *new_rects = OP_NEWA(OpRect, new_max_rects); if (!new_rects) return OpStatus::ERR_NO_MEMORY; if(rects) op_memcpy(new_rects, rects, sizeof(OpRect) * max_rects); OP_DELETEA(rects); rects = new_rects; max_rects = new_max_rects; } return OpStatus::OK; } OP_STATUS BgRegion::AddRect(const OpRect& rect) { OP_ASSERT(!rect.IsEmpty()); RETURN_IF_ERROR(GrowIfNeeded()); rects[num_rects++] = rect; #ifdef DEBUG_GFX if (num_rects > max_region_rect_count) max_region_rect_count = num_rects; #endif if (num_rects == 1) bounding_rect = rects[0]; else bounding_rect.UnionWith(rect); #ifdef DEBUG_GFX #ifdef _DEBUG uni_char tmp[300]; // ARRAY OK 2009-08-11 marcusc uni_sprintf(tmp, L"BgRegion::AddRect num_rects: %d \n", num_rects); OutputDebugString(tmp); #endif #endif return OpStatus::OK; } OP_STATUS BgRegion::AddRectIfNotContained(const OpRect& rect) { for (int i = 0; i < num_rects; i++) if (rects[i].Contains(rect)) return OpStatus::OK; return AddRect(rect); } OP_STATUS BgRegion::Constrain(unsigned int tile_side) { OP_ASSERT(tile_side); OP_ASSERT(num_rects); // first pass, count number of rects needed int count = 0; for (int i = 0; i < num_rects; ++ i) { const OpRect& r = rects[i]; const unsigned tiles_x = (r.width + tile_side-1) / tile_side; const unsigned tiles_y = (r.height + tile_side-1) / tile_side; count += tiles_x * tiles_y; } OP_ASSERT(count >= num_rects); if (count == num_rects) return OpStatus::OK; // allocate new rect array OpRect* split_rects = OP_NEWA(OpRect, count); RETURN_OOM_IF_NULL(split_rects); // second pass, split rects int j = 0; for (int i = 0; i < num_rects; ++i) { const OpRect& r = rects[i]; const unsigned tiles_x = (r.width + tile_side-1) / tile_side; const unsigned tiles_y = (r.height + tile_side-1) / tile_side; // easier to start from 0 and add r.y to each rect int y_pos = 0; for (unsigned y = 0; y < tiles_y; ++y) { const unsigned remaining_h = r.height - y_pos; const unsigned tile_h = MIN(tile_side, remaining_h); // easier to start from 0 and add r.x to each rect int x_pos = 0; for (unsigned x = 0; x < tiles_x; ++x) { const unsigned remaining_w = r.width - x_pos; const unsigned tile_w = MIN(tile_side, remaining_w); split_rects[j].Set(r.x + x_pos, r.y + y_pos, tile_w, tile_h); ++ j; x_pos += tile_w; } OP_ASSERT(x_pos == r.width); y_pos += tile_h; } OP_ASSERT(y_pos == r.height); } OP_ASSERT(j == count); OP_DELETEA(rects); rects = split_rects; num_rects = max_rects = count; return OpStatus::OK; } void BgRegion::RemoveRect(int index) { OP_ASSERT(index >= 0 && index < num_rects); if(index < num_rects - 1) for(int i = index; i < num_rects - 1; i++) rects[i] = rects[i + 1]; num_rects--; if (num_rects == 0) bounding_rect.Empty(); else if (num_rects == 1) bounding_rect = rects[0]; } void BgRegion::ExtendBoundingRect(const OpRect& rect) { bounding_rect.UnionWith(rect); } OP_STATUS BgRegion::IncludeRect(OpRect rect) { OP_ASSERT(!rect.IsEmpty()); for(int i = 0; i < num_rects; i++) { if (rect.Contains(rects[i])) { RemoveRect(i); i--; // Redo this index } else if (rect.Intersecting(rects[i])) { BgRegion r_split; RETURN_IF_ERROR(r_split.ExcludeRectInternal(rect, rects[i])); for(int j = 0; j < r_split.num_rects; j++) { RETURN_IF_ERROR(IncludeRect(r_split.rects[j])); } return OpStatus::OK; } } return AddRect(rect); } OP_STATUS BgRegion::ExcludeRect(OpRect rect, BOOL keep_hole) { if (num_rects > 1 && !bounding_rect.Intersecting(rect)) return OpStatus::OK; // Optimization if (!rect.IsEmpty()) { // Split all intersecting rectangles int num_to_split = num_rects; for(int i = 0; i < num_to_split; i++) { if (rects[i].Intersecting(rect)) { RETURN_IF_ERROR(ExcludeRectInternal(rects[i], rect)); if (keep_hole) { rects[i] = OpRectClip(rects[i], rect); } else { RemoveRect(i); num_to_split--; i--; } } } } #ifdef _DEBUG int k, m, area = 0; for(k = 0; k < num_rects; k++) for(m = 0; m < num_rects; m++) if (k != m && rects[k].Intersecting(rects[m])) { OP_ASSERT(0); } for(k = 0; k < num_rects; k++) { int rect_area = rects[k].width * rects[k].height; if (rect_area != 0 && rect_area / rects[k].width == rects[k].height) area += rect_area; } int bounding_area = bounding_rect.width * bounding_rect.height; if (bounding_area != 0 && bounding_area / bounding_rect.width == bounding_rect.height) OP_ASSERT(area <= bounding_area); #endif return OpStatus::OK; } OP_STATUS BgRegion::ExcludeRectInternal(OpRect rect, OpRect remove) { OP_ASSERT(rect.Intersecting(remove)); remove = OpRectClip(remove, rect); // Top if (remove.y > rect.y) RETURN_IF_ERROR(AddRect(OpRect(rect.x, rect.y, rect.width, remove.y - rect.y))); // Left if (remove.x > rect.x) RETURN_IF_ERROR(AddRect(OpRect(rect.x, remove.y, remove.x - rect.x, remove.height))); // Right if (remove.x + remove.width < rect.x + rect.width) RETURN_IF_ERROR(AddRect(OpRect(remove.x + remove.width, remove.y, rect.x + rect.width - (remove.x + remove.width), remove.height))); // Bottom if (remove.y + remove.height < rect.y + rect.height) RETURN_IF_ERROR(AddRect(OpRect(rect.x, remove.y + remove.height, rect.width, rect.y + rect.height - (remove.y + remove.height)))); return OpStatus::OK; } void BgRegion::CoalesceRects() { for(int i = 0; i < num_rects; i++) { for(int j = 0; j < num_rects; j++) { if (i == j) continue; if (i > num_rects - 1) break; if (// Vertical (rects[i].x == rects[j].x && rects[i].width == rects[j].width && ((rects[i].y + rects[i].height == rects[j].y) || (rects[j].y + rects[j].height == rects[i].y))) || // Horizontal (rects[i].y == rects[j].y && rects[i].height == rects[j].height && ((rects[i].x + rects[i].width == rects[j].x) || (rects[j].x + rects[j].width == rects[i].x))) ) { rects[i].UnionWith(rects[j]); RemoveRect(j); j--; } } } } BOOL BgRegion::Equals(BgRegion& other) { if (num_rects != other.num_rects) return FALSE; for(int i = 0; i < num_rects; i++) { if (!rects[i].Equals(other.rects[i])) return FALSE; } return TRUE; } // == BgClipStack ================================================= BgClipStack::BgClipStack() : num(0) { op_memset(info, 0, sizeof(BgInfo *) * MAX_BG_INFO); #ifdef DEBUG_GFX flushed_color_pixels = 0; total_color_pixels = 0; flushed_img_pixels = 0; total_img_pixels = 0; #endif } BgClipStack::~BgClipStack() { while (BgClipRect *cr = (BgClipRect *) cliplist.Last()) { cr->Out(); OP_DELETE(cr); } for(int i = 0; i < MAX_BG_INFO; i++) { if (info[i]) { OP_DELETE(info[i]); info[i] = NULL; } } } OP_STATUS BgClipStack::Begin(VisualDevice *vd) { for(int i = 0; i < MAX_BG_INFO; i++) { if (!info[i]) info[i] = OP_NEW(BgInfo, ()); if (!info[i]) return OpStatus::ERR_NO_MEMORY; } #ifdef DEBUG_GFX flushed_color_pixels = 0; total_color_pixels = 0; flushed_img_pixels = 0; total_img_pixels = 0; #endif return OpStatus::OK; } void BgClipStack::End(VisualDevice *vd) { FlushAll(vd); #ifdef DEBUG_GFX #ifdef _DEBUG double color_ratio = total_color_pixels == 0 ? 1 : (double)flushed_color_pixels / (double)total_color_pixels; double img_ratio = total_img_pixels == 0 ? 1 : (double)flushed_img_pixels / (double)total_img_pixels; uni_char buf[200]; // ARRAY OK 2009-01-27 emil uni_sprintf(buf, L"Avoid overdraw ratio: color %d%% img %d%%\n", (int)(color_ratio * 100.0), (int)(img_ratio * 100.0)); OutputDebugString(buf); OP_ASSERT(color_ratio <= 1 && img_ratio <= 1); #endif #endif } OP_STATUS BgClipStack::PushClipping(OpRect rect) { if (cliplist.Last()) { BgClipRect *cr = (BgClipRect *) cliplist.Last(); rect = OpRectClip(rect, *cr); } BgClipRect *cr = OP_NEW(BgClipRect, (rect)); if (!cr) return OpStatus::ERR_NO_MEMORY; cr->Into(&cliplist); return OpStatus::OK; } void BgClipStack::PopClipping() { BgClipRect *cr = (BgClipRect *) cliplist.Last(); if (cr) { cr->Out(); OP_DELETE(cr); } } BOOL BgClipStack::GetClipping(OpRect &clip_rect) { BgClipRect *cr = (BgClipRect *) cliplist.Last(); if (cr) { clip_rect = *cr; return TRUE; } return FALSE; } void BgClipStack::RemoveBg(int index) { // Unreference the Image object. if (info[index]->type == BgInfo::IMAGE) info[index]->img = Image(); for(int j = index; j < num - 1; j++) { BgInfo *tmp = info[j + 1]; info[j + 1] = info[j]; info[j] = tmp; } num--; } void BgClipStack::CoverBg(VisualDevice *vd, const OpRect& crect, BOOL keep_hole) { OpRect rect = crect; // Clip to curent cliprect BgClipRect *cr = (BgClipRect *) cliplist.Last(); if (cr) rect = OpRectClip(rect, *cr); if (rect.IsEmpty()) return; for(int i = 0; i < num; i++) { OP_STATUS status = info[i]->region.ExcludeRect(rect, keep_hole); if (OpStatus::IsError(status)) { FlushAll(vd); return; } // If Bg has become small or has too many rectangles, we'll flush it. // Too many rectangles results in expensive region calculations. if (IsRegionSmall(info[i]->region) || info[i]->region.num_rects > 10) { // We should not flush anything outside the current clip rectangle. Then those areas are lost. if (!cr || cr->Contains(info[i]->rect)) { FlushBg(vd, i); i--; } } } } void BgClipStack::FlushBg(VisualDevice *vd, OpRect rect) { // Clip to curent cliprect BgClipRect *cr = (BgClipRect *) cliplist.Last(); if (cr) rect = OpRectClip(rect, *cr); int i; int count = 0; for(i = 0; i < num; i++) { if (info[i]->region.bounding_rect.Intersecting(rect)) // Might intersect { for(int j = 0; j < info[i]->region.num_rects; j++) { if (rect.Intersecting(info[i]->region.rects[j])) { BgInfo *bg = info[i]; // FIX: if (bg->region.rects[j].width * bg->region.rects[j].height > (bg->region.bounding_rect.width * bg->region.bounding_rect.height) * 0.7) // int stop = 0; vd->PaintBg(bg->region.rects[j], bg, 0); bg->region.RemoveRect(j); j--; count++; } } } } // Remove empty regions for(i = 0; i < num; i++) { if (info[i]->region.num_rects == 0) { RemoveBg(i); i--; } } } void BgClipStack::FlushAll(VisualDevice *vd) { while (num) FlushLast(vd); } void BgClipStack::FlushLast(VisualDevice *vd) { FlushBg(vd, num - 1); } void BgClipStack::FlushBg(VisualDevice *vd, int index) { OP_ASSERT(index >= 0 && index < num); BgInfo *bg = info[index]; for(int i = 0; i < bg->region.num_rects; i++) { const OpRect &r = bg->region.rects[i]; // If this trig, we flush background that will not be visible // due to the current clipping! We must avoid that! #ifdef CSS_TRANSFORMS // ...unless we have a transform, and cliprects are // in different coordinate spaces OP_ASSERT(!cliplist.Last() || ((BgClipRect *) cliplist.Last())->Contains(r) || vd->HasTransform()); #else OP_ASSERT(!cliplist.Last() || ((BgClipRect *) cliplist.Last())->Contains(r)); #endif // CSS_TRANSFORMS vd->PaintBg(r, bg, 1); } RemoveBg(index); } void BgClipStack::FlushBg(HTML_Element* element, VisualDevice *vd) { int i; for (i = 0; i < num; i++) { if (info[i]->element == element) break; if (info[i]->element->Type() == HE_BODY && element->Type() == HE_DOC_ROOT) // Sometimes the HE_DOC_ROOT is added as a bodybackground (special case) break; if (element->IsAncestorOf(info[i]->element)) break; } while (i < num) { FlushLast(vd); } } BgInfo *BgClipStack::Add(VisualDevice *vd) { if (num >= MAX_BG_INFO - 1) // FIX: Is the last one the best to flush? Maby the first one is better!?! // Maby even check which one to flush? Based on area or intersecting with the current coverarea. FlushLast(vd); num++; return info[num - 1]; } void BgClipStack::AddBg(HTML_Element* element, VisualDevice *vd, const COLORREF &bg_color, OpRect rect) { // Clip to current cliprect #ifdef CSS_TRANSFORMS // ... but not if a transform is set, because then the clipping // won't be correct if (!vd->HasTransform()) #endif // CSS_TRANSFORMS { BgClipRect *cr = (BgClipRect *) cliplist.Last(); if (cr) rect = OpRectClip(rect, *cr); } if (rect.IsEmpty()) return; BgInfo *last = Add(vd); last->element = element; last->type = BgInfo::COLOR; last->bg_color = bg_color; last->rect = rect; OP_STATUS status = last->region.Set(rect); #ifdef DEBUG_GFX total_color_pixels += rect.width * rect.height; if (!avoid_overdraw) { FlushAll(vd); return; } #endif if (!IsWorthDelaying(rect) || OpStatus::IsError(status)) FlushLast(vd); } void BgClipStack::AddBg(HTML_Element* element, VisualDevice *vd, Image& img, OpRect rect, OpPoint offset, ImageListener* image_listener, int imgscale_x, int imgscale_y, CSSValue image_rendering) { // Clip to current cliprect #ifdef CSS_TRANSFORMS // ... but not if a transform is set, because then the clipping // won't be correct if (!vd->HasTransform()) #endif // CSS_TRANSFORMS { BgClipRect *cr = (BgClipRect *) cliplist.Last(); if (cr) { OpRect oldrect = rect; rect = OpRectClip(rect, *cr); offset.x += rect.x - oldrect.x; offset.y += rect.y - oldrect.y; } } if (rect.IsEmpty()) return; BgInfo *last = Add(vd); last->element = element; last->type = BgInfo::IMAGE; last->img = img; last->rect = rect; OP_STATUS status = last->region.Set(rect); last->offset = offset; last->image_listener = image_listener; last->imgscale_x = imgscale_x; last->imgscale_y = imgscale_y; last->image_rendering = image_rendering; #ifdef DEBUG_GFX total_img_pixels += rect.width * rect.height; if (!avoid_overdraw) { FlushAll(vd); return; } #endif if (!IsWorthDelaying(rect) || OpStatus::IsError(status)) FlushLast(vd); } #ifdef CSS_GRADIENT_SUPPORT void BgClipStack::AddBg(HTML_Element* element, VisualDevice *vd, COLORREF current_color, const CSS_Gradient &gradient, OpRect rect, const OpRect &gradient_rect, const OpRect &repeat_space, CSSValue repeat_x, CSSValue repeat_y) { // Clip to current cliprect #ifdef CSS_TRANSFORMS // ... but not if a transform is set, because then the clipping // won't be correct if (!vd->HasTransform()) #endif // CSS_TRANSFORMS { BgClipRect *cr = (BgClipRect *) cliplist.Last(); if (cr) rect = OpRectClip(rect, *cr); } if (rect.IsEmpty()) return; BgInfo *last = Add(vd); last->element = element; last->type = BgInfo::GRADIENT; // This pointer is guaranteed to live past painting, provided that all functions in the call stack // from VerticalBox::PaintBgAndBorder and up pass BgImages or CSS_Gradient arguments by reference. last->gradient = &gradient; last->current_color = current_color; last->rect = rect; last->img_rect = gradient_rect; last->repeat_x = repeat_x; last->repeat_y = repeat_y; last->repeat_space = repeat_space; OP_STATUS region_status = last->region.Set(rect); #ifdef DEBUG_GFX total_color_pixels += rect.width * rect.height; if (!avoid_overdraw) { FlushAll(vd); return; } #endif if (!IsWorthDelaying(rect) || OpStatus::IsError(region_status)) FlushLast(vd); } #endif // CSS_GRADIENT_SUPPORT
#include "Player.hpp" Player::Player() { m_pos.x = 96; m_pos.y = 96; m_vel.x = 0; m_vel.y = 0; m_dim.width = 32; m_dim.height = 32; m_speed = 4; m_upPressed = false; m_downPressed = false; m_leftPressed = false; m_rightPressed = false; } Player::~Player() { } void Player::events(const float &delta, const Dimension<int> &screen, const SDL_Event& evnt) { if (evnt.type == SDL_KEYDOWN && evnt.key.repeat == 0) { switch (evnt.key.keysym.sym) { case SDLK_a: m_vel.x -= m_speed; m_leftPressed = true; break; case SDLK_d: m_vel.x += m_speed; m_rightPressed = true; break; case SDLK_s: m_vel.y += m_speed; m_downPressed = true; break; case SDLK_w: m_vel.y -= m_speed; m_upPressed = true; break; } } else if (evnt.type == SDL_KEYUP && evnt.key.repeat == 0) { switch (evnt.key.keysym.sym) { case SDLK_a: if (m_leftPressed) m_vel.x += m_speed; break; case SDLK_d: if (m_rightPressed) m_vel.x -= m_speed; break; case SDLK_s: if (m_downPressed) m_vel.y -= m_speed; break; case SDLK_w: if (m_upPressed) m_vel.y += m_speed; break; } } } void Player::update(Point<int> &camera, const Level* level, const float &delta, const Dimension<int> &screen) { int tileRes = level->getTileRes(); int yMax = (screen.height / tileRes); if (yMax > level->getHeight()) { yMax = level->getHeight(); } int xMax = (screen.width / tileRes); if (xMax > level->getWidth()) { xMax = level->getWidth(); } bool collision = false; int dx = 0, dy = 0; m_pos.x += m_vel.x; for (int y = camera.y / tileRes && !collision; y < yMax; y++) { for (int x = camera.x / tileRes && !collision; x < xMax; x++) { if (level->getTile(x, y) == TILE_SOLID) { dx = (x * tileRes) - camera.x; dy = (y * tileRes) - camera.y; if (isColliding(dx, dy, tileRes)) { if (m_vel.x > 0) { m_pos.x = dx - m_dim.width; } else if (m_vel.x < 0) { m_pos.x = dx + tileRes; } collision = true; } } } } collision = false; m_pos.y += m_vel.y; for (int y = camera.y / tileRes && !collision; y < yMax; y++) { for (int x = camera.x / tileRes && !collision; x < xMax; x++) { if (level->getTile(x, y) == TILE_SOLID) { dx = (x * tileRes) - camera.x; dy = (y * tileRes) - camera.y; if (isColliding(dx, dy, tileRes)) { if (m_vel.y > 0) m_pos.y = dy - m_dim.height; else if (m_vel.y < 0) m_pos.y = dy + tileRes; collision = true; } } } } updateCamera(camera, level); } void Player::render(Point<int> &camera, const Level* level, const float &delta, const Dimension<int> &screen) { Graphics2D::SetColor(1, 0, 0); Graphics2D::DrawFilledQuad(m_pos.x, m_pos.y, m_dim.width, m_dim.height); } void Player::updateCamera(Point<int>& camera, const Level* level) { camera.x = m_pos.x - level->getTotalWidth() / 2; camera.y = m_pos.y - level->getTotalHeight() / 2; //Keep the camera in bounds if (camera.x < 0) { camera.x = 0; } if (camera.y < 0) { camera.y = 0; } if (camera.x > level->getTotalWidth()) { camera.x = level->getTotalWidth(); } if (camera.y > level->getTotalHeight()) { camera.y = level->getTotalHeight(); } } bool Player::isColliding(const int & x, const int & y, const int& res){ //The sides of the rectangles int leftA, leftB; int rightA, rightB; int topA, topB; int bottomA, bottomB; //Calculate the sides of rect A PLAYER leftA = m_pos.x; rightA = m_pos.x + m_dim.width; topA = m_pos.y; bottomA = m_pos.y + m_dim.height; //Calculate the sides of rect B int tileRes = res; leftB = x; rightB = x + tileRes; topB = y; bottomB = y + tileRes; //If any of the sides from A are outside of B if (bottomA <= topB){ return false; } if (topA >= bottomB){ return false; } if (rightA <= leftB){ return false; } if (leftA >= rightB){ return false; } //If none of the sides from A are outside B return true; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2006 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include <ctype.h> #include <signal.h> #include <sys/time.h> #include "modules/debug/debug.h" #if defined(_DEBUG) && defined(DBG_CAP_IMPL_IN_PLATFORM) void #ifdef DEBUG_ENABLE_OPASSERT // no suitable capability ... Debug_OpAssert #else // before anticimex_2_beta_4: Debug::OpAssert #endif (const char* expression, const char* file, int line) { fprintf(stderr, "### Assertion failed for expression: %s\n" "### \tin %s:%d\n", expression, file, line); fflush(stderr); Debugger(); } void Debug::GetTime(DebugTime& time) { //#warning "port me" // FIXME: port me (Debug::GetTime) time.sec = time.msec = 0; } void #ifdef DEBUG_ENABLE_SYSTEM_OUTPUT // would be better to have a capability ... dbg_systemoutput #else Debug::SystemDebugOutput #endif (const uni_char* str) { // This fuction is deliberately rather self-contained, to allow OP_ASSERT without a full core. if (!str) return; const uni_char* s=str; int length = 0; while (*s++) ++length; s = str; char *str8 = (char*)malloc(length+1),*t=str8; if (!t) return; for (int i=0; i<length; i++) *t++ = (char) *s++; *t = '\0'; fprintf(stderr, "%s", str8); free(str8); } #ifdef DEBUG_ENABLE_SYSTEM_OUTPUT void dbg_logfileoutput(const char* txt, int len) { #warning "implement me" } #endif // DEBUG_ENABLE_SYSTEM_OUTPUT #endif // DBG_CAP_IMPL_IN_PLATFORM
#include "../GraphicsProperties.h" #include <nexus_config.h> #include <nexus_platform.h> #include <nxclient.h> namespace WPEFramework { namespace Device { namespace Implementation { class NexusPlatform : public Plugin::IGraphicsProperties { public: NexusPlatform() : _totalGpuRam(0) { NEXUS_Error rc = NxClient_Join(NULL); ASSERT(!rc); NEXUS_Platform_GetConfiguration(&_platformConfig); UpdateTotalGpuRam(_totalGpuRam); } NexusPlatform(const NexusPlatform&) = delete; NexusPlatform& operator= (const NexusPlatform&) = delete; virtual ~NexusPlatform() { NxClient_Uninit(); } public: uint64_t TotalGpuRam() const override { return _totalGpuRam; } uint64_t FreeGpuRam() const override { uint64_t freeRam = 0; NEXUS_MemoryStatus status; NEXUS_Error rc = NEXUS_UNKNOWN; #if NEXUS_MEMC0_GRAPHICS_HEAP if (_platformConfig.heap[NEXUS_MEMC0_GRAPHICS_HEAP]) { rc = NEXUS_Heap_GetStatus(_platformConfig.heap[NEXUS_MEMC0_GRAPHICS_HEAP], &status); if (rc == NEXUS_SUCCESS) { freeRam = static_cast<uint64_t>(status.free); } } #endif #if NEXUS_MEMC1_GRAPHICS_HEAP if (_platformConfig.heap[NEXUS_MEMC1_GRAPHICS_HEAP]) { rc = NEXUS_Heap_GetStatus(_platformConfig.heap[NEXUS_MEMC1_GRAPHICS_HEAP], &status); if (rc == NEXUS_SUCCESS) { freeRam += static_cast<uint64_t>(status.free); } } #endif #if NEXUS_MEMC2_GRAPHICS_HEAP if (_platformConfig.heap[NEXUS_MEMC2_GRAPHICS_HEAP]) { rc = NEXUS_Heap_GetStatus(_platformConfig.heap[NEXUS_MEMC2_GRAPHICS_HEAP], &status); if (rc == NEXUS_SUCCESS) { freeRam += static_cast<uint64_t>(status.free); } } #endif return (freeRam); } private: void UpdateTotalGpuRam(uint64_t& totalRam) const { NEXUS_MemoryStatus status; NEXUS_Error rc = NEXUS_UNKNOWN; #if NEXUS_MEMC0_GRAPHICS_HEAP if (_platformConfig.heap[NEXUS_MEMC0_GRAPHICS_HEAP]) { rc = NEXUS_Heap_GetStatus(_platformConfig.heap[NEXUS_MEMC0_GRAPHICS_HEAP], &status); if (rc == NEXUS_SUCCESS) { totalRam = static_cast<uint64_t>(status.size); } } #endif #if NEXUS_MEMC1_GRAPHICS_HEAP if (_platformConfig.heap[NEXUS_MEMC1_GRAPHICS_HEAP]) { rc = NEXUS_Heap_GetStatus(_platformConfig.heap[NEXUS_MEMC1_GRAPHICS_HEAP], &status); if (rc == NEXUS_SUCCESS) { totalRam += static_cast<uint64_t>(status.size); } } #endif #if NEXUS_MEMC2_GRAPHICS_HEAP if (_platformConfig.heap[NEXUS_MEMC2_GRAPHICS_HEAP]) { rc = NEXUS_Heap_GetStatus(_platformConfig.heap[NEXUS_MEMC2_GRAPHICS_HEAP], &status); if (rc == NEXUS_SUCCESS) { totalRam += static_cast<uint64_t>(status.size); } } #endif } private: uint64_t _totalGpuRam; NEXUS_PlatformConfiguration _platformConfig; }; } } /* static */ Core::ProxyType<Plugin::IGraphicsProperties> Plugin::IGraphicsProperties::Instance() { static Core::ProxyType<Device::Implementation::NexusPlatform> nexusPlatform(Core::ProxyType<Device::Implementation::NexusPlatform>::Create()); return static_cast<Core::ProxyType<Plugin::IGraphicsProperties>>(nexusPlatform); } }
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*- * * Copyright (C) 1995-2002 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef XSLT_HANDLER_H #define XSLT_HANDLER_H #ifdef XSLT_SUPPORT # include "modules/xslt/src/xslt_parser.h" # include "modules/xmlutils/xmltokenbackend.h" # include "modules/util/opstring.h" # include "modules/util/adt/opvector.h" class XSLT_HandlerTokenHandler : public XMLTokenHandler, public XMLTokenBackend, public XSLT_StylesheetParser::Callback, public MessageObject { public: enum State { ANALYZING, PARSING_SOURCETREE, DISABLED }; private: class TransformationCallback; friend class TransformationCallback; class TransformationCallback : public XSLT_Stylesheet::Transformation::Callback { private: XSLT_HandlerTokenHandler *parent; public: TransformationCallback(XSLT_HandlerTokenHandler *parent) : parent(parent) { } virtual void ContinueTransformation (XSLT_Stylesheet::Transformation *transformation) { parent->ContinueTransformation (transformation); } virtual OP_STATUS LoadDocument (URL document_url, XMLTokenHandler *token_handler) { return parent->LoadDocument (document_url, token_handler); } virtual void CancelLoadDocument (XMLTokenHandler *token_handler) { parent->CancelLoadDocument (token_handler); } #ifdef XSLT_ERRORS virtual OP_BOOLEAN HandleMessage (XSLT_Stylesheet::Transformation::Callback::MessageType type, const uni_char *message) { return parent->HandleMessage (type, message); } #endif // XSLT_ERRORS } transformation_callback; /** * Sometimes we delay the decision if xslt should be invoked * or not while we're browsing through the document prologue. * and then we save the tokens we see in a list of these objects. */ class QueuedToken { public: XMLToken::Type type; OpString name; OpString data; class Attribute { public: XMLCompleteName name; OpString value; }; OpAutoVector<Attribute> attributes; }; State state; XSLT_Handler *handler; XSLT_Handler::TreeCollector *tree_collector; BOOL tree_collector_finished; XMLParser *parser; OpAutoVector<QueuedToken> queued_tokens; unsigned queue_offset; XMLTokenHandler *token_handler; XSLT_Stylesheet::Transformation::StringDataCollector *string_data_collector; BOOL destroy_when_finished; XMLTokenHandler::SourceCallback *source_callback; XSLT_StylesheetParser *stylesheet_parser; BOOL stylesheet_parser_finished; XMLTokenHandler *stylesheet_parser_token_handler; XSLT_Stylesheet *stylesheet; XSLT_Stylesheet::Transformation *stylesheet_transformation; MessageHandler *mh; BOOL message_posted; #ifdef SELFTEST public: class PostMessageCallback { public: virtual ~PostMessageCallback () {} virtual BOOL PostMessage (BOOL start_transformation) = 0; }; private: PostMessageCallback *post_message_cb; #endif // SELFTEST /* From XMLTokenHandler: */ virtual Result HandleToken (XMLToken &token); virtual void SetSourceCallback (XMLTokenHandler::SourceCallback *source_callback); /* From XMLTokenBackend: */ virtual BOOL GetLiteralIsWhitespace (); virtual const uni_char *GetLiteralSimpleValue (); virtual uni_char *GetLiteralAllocatedValue (); virtual unsigned GetLiteralLength (); virtual OP_STATUS GetLiteral (XMLToken::Literal &literal); virtual void ReleaseLiteralPart (unsigned index); #ifdef XML_ERRORS virtual BOOL GetTokenRange (XMLRange &range); virtual BOOL GetAttributeRange (XMLRange &range, unsigned index); #endif // XML_ERRORS /* From XSLT_StylesheetParser::Callback: */ virtual OP_STATUS LoadOtherStylesheet (URL stylesheet_url, XMLTokenHandler *token_handler, BOOL is_import); virtual void CancelLoadOtherStylesheet (XMLTokenHandler *token_handler); #ifdef XSLT_ERRORS virtual OP_BOOLEAN HandleMessage (XSLT_StylesheetParser::Callback::MessageType type, const uni_char *message); #endif // XSLT_ERRORS virtual OP_STATUS ParsingFinished (XSLT_StylesheetParser *parser); /* From XSLT_Stylesheet::Transformation::Callback via TransformationCallback: */ void ContinueTransformation (XSLT_Stylesheet::Transformation *transformation); OP_STATUS LoadDocument (URL document_url, XMLTokenHandler *token_handler); void CancelLoadDocument (XMLTokenHandler *token_handler); #ifdef XSLT_ERRORS OP_BOOLEAN HandleMessage (XSLT_Stylesheet::Transformation::Callback::MessageType type, const uni_char *message); #endif // XSLT_ERRORS class XMLTokenHandlerElm : public Link { public: XMLTokenHandlerElm () : token_handler (0) { } virtual ~XMLTokenHandlerElm () { OP_DELETE (token_handler); } XMLTokenHandler *token_handler; }; Head token_handlers; void ContinueTransformation (); void AbortTransformation (BOOL oom); BOOL PostMessage (BOOL start_transformation); public: XSLT_HandlerTokenHandler (XSLT_Handler *handler) : transformation_callback (this), state (ANALYZING), handler (handler), tree_collector (0), tree_collector_finished (FALSE), parser (0), queue_offset (0), token_handler (0), string_data_collector (0), destroy_when_finished (FALSE), source_callback (0), stylesheet_parser (0), stylesheet_parser_finished (FALSE), stylesheet_parser_token_handler (0), stylesheet (0), stylesheet_transformation (0), mh (0), message_posted (FALSE) { #ifdef SELFTEST post_message_cb = 0; #endif // SELFTEST } virtual ~XSLT_HandlerTokenHandler (); /* From MessageObject: */ virtual void HandleCallback (OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); State GetState () { return state; } XMLTokenHandler *GetTokenHandler () { return token_handler; } BOOL HasQueuedTokens () { return queue_offset != queued_tokens.GetCount (); } BOOL HasStylesheet () { return stylesheet != 0; } XMLTokenHandler::Result EnqueueToken (const XMLToken &token); XMLTokenHandler::Result FlushQueue (); XMLTokenHandler::Result StartParsingSourceTree (XMLToken &token, URL documen_url, const uni_char *stylesheet_url); XMLTokenHandler::Result Disable (XMLToken &token); void StartTransformation (BOOL from_handletoken); #ifdef SELFTEST void SetPostMessageCallback (PostMessageCallback *cb) { post_message_cb = cb; } #endif // SELFTEST }; #endif // XSLT_SUPPORT #endif // XSLT_HANDLER_H
#include"stdio.h" #include"conio.h" void main(void) { int a,b,c,y1,y2,y3,y4; clrscr(); printf("\n\nPut the value of a = "); scanf("%d",&a); printf("\nPut the value of b = "); scanf("%d",&b); printf("\nPut the value of c = "); scanf("%d",&c); y1=(a==b)!=c; y2=(a!=b); y3=(a>=b); y4=(c==b==a)==10; printf("\n\n\nThe result of Y1=(a==b)!=c is %d",y1); printf("\n\nThe result of Y2=(a!=b) is %d",y2); printf("\n\nThe result of Y3=(a>=b) is %d",y3); printf("\n\nThe result of Y4=(a==b==c)==10 is %d",y4); getch(); }
/* versionL With AK8LS * Date: 20200220 */ #include "FWCore/ParameterSet/interface/ParameterSet.h" // edm::ParameterSet #include "FWCore/Utilities/interface/Exception.h" // cms::Exception #include "PhysicsTools/FWLite/interface/TFileService.h" // fwlite::TFileService #include "DataFormats/FWLite/interface/InputSource.h" // fwlite::InputSource #include "DataFormats/FWLite/interface/OutputFiles.h" // fwlite::OutputFiles #include "DataFormats/Math/interface/LorentzVector.h" // math::PtEtaPhiMLorentzVector #include "DataFormats/Math/interface/deltaR.h" // deltaR #if __has_include (<FWCore/ParameterSetReader/interface/ParameterSetReader.h>) # include <FWCore/ParameterSetReader/interface/ParameterSetReader.h> // edm::readPSetsFrom() #else # include <FWCore/PythonParameterSet/interface/MakeParameterSets.h> // edm::readPSetsFrom() #endif #include <TBenchmark.h> // TBenchmark #include <TString.h> // TString, Form #include <TError.h> // gErrorAbortLevel, kError #include <TLorentzVector.h> #include <TMath.h> #include <TROOT.h> // TROOT #include "tthAnalysis/HiggsToTauTau/interface/RecoLepton.h" // RecoLepton #include "tthAnalysis/HiggsToTauTau/interface/RecoJet.h" // RecoJet #include "tthAnalysis/HiggsToTauTau/interface/RecoHadTau.h" // RecoHadTau #include "tthAnalysis/HiggsToTauTau/interface/GenLepton.h" // GenLepton #include "tthAnalysis/HiggsToTauTau/interface/GenJet.h" // GenJet #include "tthAnalysis/HiggsToTauTau/interface/GenHadTau.h" // GenHadTau #include "tthAnalysis/HiggsToTauTau/interface/ObjectMultiplicity.h" // ObjectMultiplicity #include "tthAnalysis/HiggsToTauTau/interface/RecoMEt.h" // RecoMEt #include "tthAnalysis/HiggsToTauTau/interface/TMVAInterface.h" // TMVAInterface #include "tthAnalysis/HiggsToTauTau/interface/XGBInterface.h" // XGBInterface #include "tthAnalysis/HiggsToTauTau/interface/mvaAuxFunctions.h" // check_mvaInputs, get_mvaInputVariables #include "tthAnalysis/HiggsToTauTau/interface/mvaInputVariables.h" // auxiliary functions for computing input variables of the MVA used for signal extraction in the 3l category #include "tthAnalysis/HiggsToTauTau/interface/LeptonFakeRateInterface.h" // LeptonFakeRateInterface #include "tthAnalysis/HiggsToTauTau/interface/JetToTauFakeRateInterface.h" // JetToTauFakeRateInterface #include "tthAnalysis/HiggsToTauTau/interface/RecoElectronReader.h" // RecoElectronReader #include "tthAnalysis/HiggsToTauTau/interface/RecoMuonReader.h" // RecoMuonReader #include "tthAnalysis/HiggsToTauTau/interface/RecoHadTauReader.h" // RecoHadTauReader #include "tthAnalysis/HiggsToTauTau/interface/RecoJetReader.h" // RecoJetReader #include "tthAnalysis/HiggsToTauTau/interface/RecoJetReaderAK8.h" // RecoJetReaderAK8 #include "tthAnalysis/HiggsToTauTau/interface/RecoMEtReader.h" // RecoMEtReader #include "tthAnalysis/HiggsToTauTau/interface/MEtFilterReader.h" // MEtFilterReader #include "tthAnalysis/HiggsToTauTau/interface/GenLeptonReader.h" // GenLeptonReader #include "tthAnalysis/HiggsToTauTau/interface/GenParticleReader.h" // GenParticleReader #include "tthAnalysis/HiggsToTauTau/interface/GenHadTauReader.h" // GenHadTauReader #include "tthAnalysis/HiggsToTauTau/interface/GenPhotonReader.h" // GenPhotonReader #include "tthAnalysis/HiggsToTauTau/interface/GenJetReader.h" // GenJetReader #include "tthAnalysis/HiggsToTauTau/interface/LHEInfoReader.h" // LHEInfoReader #include "tthAnalysis/HiggsToTauTau/interface/PSWeightReader.h" // PSWeightReader #include "tthAnalysis/HiggsToTauTau/interface/ObjectMultiplicityReader.h" // ObjectMultiplicityReader #include "tthAnalysis/HiggsToTauTau/interface/convert_to_ptrs.h" // convert_to_ptrs #include "tthAnalysis/HiggsToTauTau/interface/ParticleCollectionCleaner.h" // RecoElectronCollectionCleaner, RecoMuonCollectionCleaner, RecoHadTauCollectionCleaner, RecoJetCollectionCleaner #include "tthAnalysis/HiggsToTauTau/interface/ParticleCollectionGenMatcher.h" // RecoElectronCollectionGenMatcher, RecoMuonCollectionGenMatcher, RecoHadTauCollectionGenMatcher, RecoJetCollectionGenMatcher #include "tthAnalysis/HiggsToTauTau/interface/RecoElectronCollectionSelectorLoose.h" // RecoElectronCollectionSelectorLoose #include "tthAnalysis/HiggsToTauTau/interface/RecoElectronCollectionSelectorFakeable.h" // RecoElectronCollectionSelectorFakeable #include "tthAnalysis/HiggsToTauTau/interface/RecoElectronCollectionSelectorTight.h" // RecoElectronCollectionSelectorTight #include "tthAnalysis/HiggsToTauTau/interface/RecoMuonCollectionSelectorLoose.h" // RecoMuonCollectionSelectorLoose #include "tthAnalysis/HiggsToTauTau/interface/RecoMuonCollectionSelectorFakeable.h" // RecoMuonCollectionSelectorFakeable #include "tthAnalysis/HiggsToTauTau/interface/RecoMuonCollectionSelectorTight.h" // RecoMuonCollectionSelectorTight #include "tthAnalysis/HiggsToTauTau/interface/RecoHadTauCollectionSelectorFakeable.h" // RecoHadTauCollectionSelectorFakeable #include "tthAnalysis/HiggsToTauTau/interface/RecoHadTauCollectionSelectorTight.h" // RecoHadTauCollectionSelectorTight #include "tthAnalysis/HiggsToTauTau/interface/RecoJetCollectionSelector.h" // RecoJetCollectionSelector #include "tthAnalysis/HiggsToTauTau/interface/RecoJetCollectionSelectorBtag.h" // RecoJetCollectionSelectorBtagLoose, RecoJetCollectionSelectorBtagMedium #include "tthAnalysis/HiggsToTauTau/interface/RunLumiEventSelector.h" // RunLumiEventSelector #include "tthAnalysis/HiggsToTauTau/interface/MEtFilterSelector.h" // MEtFilterSelector #include "tthAnalysis/HiggsToTauTau/interface/ElectronHistManager.h" // ElectronHistManager #include "tthAnalysis/HiggsToTauTau/interface/MuonHistManager.h" // MuonHistManager #include "tthAnalysis/HiggsToTauTau/interface/HadTauHistManager.h" // HadTauHistManager #include "tthAnalysis/HiggsToTauTau/interface/JetHistManager.h" // JetHistManager #include "tthAnalysis/HiggsToTauTau/interface/JetHistManagerAK8.h" // JetHistManagerAK8 #include "tthAnalysis/HiggsToTauTau/interface/MEtHistManager.h" // MEtHistManager #include "tthAnalysis/HiggsToTauTau/interface/MEtFilterHistManager.h" // MEtFilterHistManager #include "tthAnalysis/HiggsToTauTau/interface/MVAInputVarHistManager.h" // MVAInputVarHistManager #include "tthAnalysis/HiggsToTauTau/interface/EvtYieldHistManager.h" // EvtYieldHistManager #include "tthAnalysis/HiggsToTauTau/interface/CutFlowTableHistManager.h" // CutFlowTableHistManager #include "tthAnalysis/HiggsToTauTau/interface/WeightHistManager.h" // WeightHistManager #include "tthAnalysis/HiggsToTauTau/interface/GenEvtHistManager.h" // GenEvtHistManager #include "tthAnalysis/HiggsToTauTau/interface/LHEInfoHistManager.h" // LHEInfoHistManager #include "tthAnalysis/HiggsToTauTau/interface/leptonTypes.h" // getLeptonType, kElectron, kMuon #include "tthAnalysis/HiggsToTauTau/interface/analysisAuxFunctions.h" // getBTagWeight_option, getHadTau_genPdgId, isHigherPt, isMatched #include "tthAnalysis/HiggsToTauTau/interface/leptonGenMatchingAuxFunctions.h" // getLeptonGenMatch_definitions_3lepton, getLeptonGenMatch_string, getLeptonGenMatch_int #include "tthAnalysis/HiggsToTauTau/interface/GenMatchInterface.h" // GenMatchInterface #include "tthAnalysis/HiggsToTauTau/interface/fakeBackgroundAuxFunctions.h" // getWeight_3L #include "tthAnalysis/HiggsToTauTau/interface/hltPath.h" // hltPath, create_hltPaths, hltPaths_isTriggered, hltPaths_delete #include "tthAnalysis/HiggsToTauTau/interface/hltPathReader.h" // hltPathReader #include "tthAnalysis/HiggsToTauTau/interface/Data_to_MC_CorrectionInterface_2016.h" #include "tthAnalysis/HiggsToTauTau/interface/Data_to_MC_CorrectionInterface_2017.h" #include "tthAnalysis/HiggsToTauTau/interface/Data_to_MC_CorrectionInterface_2018.h" #include "tthAnalysis/HiggsToTauTau/interface/lutAuxFunctions.h" // loadTH2, get_sf_from_TH2 #include "tthAnalysis/HiggsToTauTau/interface/cutFlowTable.h" // cutFlowTableType #include "tthAnalysis/HiggsToTauTau/interface/L1PreFiringWeightReader.h" // L1PreFiringWeightReader #include "tthAnalysis/HiggsToTauTau/interface/NtupleFillerBDT.h" // NtupleFillerBDT #include "tthAnalysis/HiggsToTauTau/interface/TTreeWrapper.h" // TTreeWrapper #include "tthAnalysis/HiggsToTauTau/interface/hltFilter.h" // hltFilter() #include "tthAnalysis/HiggsToTauTau/interface/EvtWeightManager.h" // EvtWeightManager #include "tthAnalysis/HiggsToTauTau/interface/analysisAuxFunctions.h" // findGenLepton_and_NeutrinoFromWBoson #include "tthAnalysis/HiggsToTauTau/interface/HHWeightInterface.h" // HHWeightInterface #include "tthAnalysis/HiggsToTauTau/interface/BtagSFRatioFacility.h" // BtagSFRatioFacility #include "tthAnalysis/HiggsToTauTau/interface/RecoJetCollectionSelectorAK8.h" // RecoJetSelectorAK8 #include "hhAnalysis/multilepton/interface/RecoJetCollectionSelectorAK8_hh_Wjj.h" // RecoJetSelectorAK8_hh_Wjj #include "hhAnalysis/multilepton/interface/EvtHistManager_hh_3l.h" // EvtHistManager_hh_3l #include "tthAnalysis/HiggsToTauTau/interface/EventInfo.h" // EventInfo #include "tthAnalysis/HiggsToTauTau/interface/EventInfoReader.h" // EventInfoReader #include "hhAnalysis/multilepton/interface/EvtWeightRecorderHH.h" // EvtWeightRecorderHH #include <boost/math/special_functions/sign.hpp> // boost::math::sign() #include <boost/algorithm/string/predicate.hpp> // boost::starts_with() #include <boost/algorithm/string/replace.hpp> // boost::replace_all_copy() #include <iostream> // std::cerr, std::fixed #include <iomanip> // std::setprecision(), std::setw() #include <string> // std::string #include <vector> // std::vector<> #include <cstdlib> // EXIT_SUCCESS, EXIT_FAILURE #include <fstream> // std::ofstream #include <assert.h> // assert #include <array> // std::array<> #include <tuple> // std::tuple<>, std::get<>(), std::make_tuple() #include <TH2.h> // TH2 #define DoNotUsehh_3lConditions // uncomment this if 2lss_1tau rec-level selection conditions are not required typedef math::PtEtaPhiMLorentzVector LV; typedef std::vector<std::string> vstring; enum { kFR_disabled, kFR_3lepton }; //const int hadTauSelection_antiElectron = 1; // vLoose //const int hadTauSelection_antiMuon = 1; // Loose const int hadTauSelection_antiElectron = -1; // not applied const int hadTauSelection_antiMuon = -1; // not applied const int printLevel = 3; //bool wayToSortDecreasing(double i, double j) { return i > j; } Era era_current; double smoothBtagCut(double assocJet_pt) // RecoMuonSelectorFakeable:: { const double smoothBtagCut_minPt_ = 20.; const double smoothBtagCut_maxPt_ = 45.; const double smoothBtagCut_ptDiff_ = (smoothBtagCut_maxPt_ - smoothBtagCut_minPt_); const double min_jetBtagCSV_ = get_BtagWP(era_current, Btag::kDeepJet, BtagWP::kLoose); const double max_jetBtagCSV_ = get_BtagWP(era_current, Btag::kDeepJet, BtagWP::kMedium); const double ptInterp = std::min(1., std::max(0., assocJet_pt - smoothBtagCut_minPt_) / smoothBtagCut_ptDiff_); return ptInterp * min_jetBtagCSV_ + (1. - ptInterp) * max_jetBtagCSV_; } void dumpGenParticles(const std::string& label, const std::vector<GenParticle>& particles) { for ( size_t idxParticle = 0; idxParticle < particles.size(); ++idxParticle ) { std::cout << label << " #" << idxParticle << ":" << " "; std::cout << particles[idxParticle]; std::cout << std::endl; } } void dumpGenParticles(const std::string& label, const std::vector<GenParticle*>& particles) { for ( size_t idxParticle = 0; idxParticle < particles.size(); ++idxParticle ) { std::cout << label << " #" << idxParticle << ":" << " "; std::cout << *particles[idxParticle]; std::cout << std::endl; } } void dumpGenParticle(const std::string& label, GenParticle *particle, int index=0) { std::cout << label << " #" << index << ":" << " "; std::cout << *particle; std::cout << std::endl; } void dumpGenParticle(const std::string& label, const GenParticle *particle, int index=0) { std::cout << label << " #" << index << ":" << " "; std::cout << *particle; std::cout << std::endl; } std::pair<const GenLepton*, const GenParticle*> findGenLepton_and_NeutrinoFromWBoson_1(const GenParticle* genWBoson, const std::vector<GenLepton>& genLeptons, const std::vector<GenParticle>& genNeutrinos) { const GenLepton* genLeptonFromWBoson = nullptr; const GenParticle* genNeutrinoFromWBoson = nullptr; double minDeltaMass = 1.e+3; for ( std::vector<GenLepton>::const_iterator genLepton = genLeptons.begin(); genLepton != genLeptons.end(); ++genLepton ) { for ( std::vector<GenParticle>::const_iterator genNeutrino = genNeutrinos.begin(); genNeutrino != genNeutrinos.end(); ++genNeutrino ) { Particle::LorentzVector genLepton_and_NeutrinoP4 = genLepton->p4() + genNeutrino->p4(); double deltaMass = TMath::Abs(genLepton_and_NeutrinoP4.mass() - genWBoson->mass()); double dR = deltaR(genLepton_and_NeutrinoP4, genWBoson->p4()); //if ( deltaMass < 5 && deltaMass < minDeltaMass && dR < 1. ) { if ( deltaMass < 1. && deltaMass < minDeltaMass && dR < 0.01 ) { genLeptonFromWBoson = &(*genLepton); genNeutrinoFromWBoson = &(*genNeutrino); minDeltaMass = deltaMass; } } } if (genLeptonFromWBoson && genNeutrinoFromWBoson && 0==1) { std::cout<<"W->l nu matching: m(W):"<<genWBoson->mass()<<", m(l nu): "<<(genLeptonFromWBoson->p4()+genNeutrinoFromWBoson->p4()).mass()<<", dR(W, l nu): "<<deltaR((genLeptonFromWBoson->p4()+genNeutrinoFromWBoson->p4()), genWBoson->p4())<<std::endl; } return std::pair<const GenLepton*, const GenParticle*>(genLeptonFromWBoson, genNeutrinoFromWBoson); } bool isGenMarchFound(Particle::LorentzVector LVRecoParticle, std::vector<GenParticle*> genParticles) { bool isGenMatchFound = false; for (size_t igenP=0; igenP < genParticles.size(); igenP++) { if ( ! genParticles[igenP]) continue; Particle::LorentzVector LVGenP = genParticles[igenP]->p4(); if ( deltaR(LVRecoParticle, LVGenP) < 0.3 && (std::abs(LVRecoParticle.pt() - LVGenP.pt()) < 0.5*LVGenP.pt())) isGenMatchFound = true; } return isGenMatchFound; } bool isGenMarchFound(Particle::LorentzVector LVRecoParticle, std::vector<GenParticle*> genParticles, int &idxGenParticle) { bool isGenMatchFound = false; for (size_t igenP=0; igenP < genParticles.size(); igenP++) { if ( ! genParticles[igenP]) continue; Particle::LorentzVector LVGenP = genParticles[igenP]->p4(); if ( deltaR(LVRecoParticle, LVGenP) < 0.3 && (std::abs(LVRecoParticle.pt() - LVGenP.pt()) < 0.5*LVGenP.pt())) { isGenMatchFound = true; idxGenParticle = igenP; } } return isGenMatchFound; } bool isGenMarchFound(Particle::LorentzVector LVRecoParticle, std::vector<GenParticle*> genParticles, GenParticle *& matchedGenParticle) { bool isGenMatchFound = false; //if ( ! genParticles) return isGenMatchFound; for (size_t igenP=0; igenP < genParticles.size(); igenP++) { if ( ! genParticles[igenP]) continue; Particle::LorentzVector LVGenP = genParticles[igenP]->p4(); if ( deltaR(LVRecoParticle, LVGenP) < 0.3 && (std::abs(LVRecoParticle.pt() - LVGenP.pt()) < 0.5*LVGenP.pt())) { isGenMatchFound = true; matchedGenParticle = genParticles[igenP]; } } return isGenMatchFound; } void fillHistogram_ptResolution(TH1*& h, Particle::LorentzVector recP, Particle::LorentzVector genP) { h->Fill((recP.pt() - genP.pt()) / genP.pt()); return; } /* void printWjj(const std::vector<const RecoJetAK8*>& jets_ak8, const RecoJetCollectionSelectorAK8_hh_Wjj& jetSelectorAK8_Wjj, const std::vector<GenParticle>& genWBosons, const std::vector<GenParticle>& genWJets) { std::cout << "<printWjj>:" << std::endl; std::cout << "#genWBosons = " << genWBosons.size() << std::endl; for ( size_t idxWBoson = 0; idxWBoson < genWBosons.size(); ++idxWBoson ) { const GenParticle& genWBoson = genWBosons[idxWBoson]; std::cout << " genWBoson #" << idxWBoson << ": pT = " << genWBoson.pt() << ", eta = " << genWBoson.eta() << ", phi = " << genWBoson.phi() << std::endl; } std::cout << "#genWJets = " << genWJets.size() << std::endl; for ( size_t idxWJet = 0; idxWJet < genWJets.size(); ++idxWJet ) { const GenParticle& genWJet = genWJets[idxWJet]; std::cout << " genWJet #" << idxWJet << ": pT = " << genWJet.pt() << ", eta = " << genWJet.eta() << ", phi = " << genWJet.phi() << std::endl; } for ( size_t idxWBoson = 0; idxWBoson < genWBosons.size(); ++idxWBoson ) { bool isMatched = false; Particle::LorentzVector genWjjP4 = genWBosons[idxWBoson].p4(); std::cout << "genWBoson id: " << idxWBoson << std::endl; std::cout << "genWjj: pT = " << genWjjP4.pt() << ", eta = " << genWjjP4.eta() << ", phi = " << genWjjP4.phi() << std::endl; for ( std::vector<const RecoJetAK8*>::const_iterator jet_ak8 = jets_ak8.begin(); jet_ak8 != jets_ak8.end(); ++jet_ak8 ) { double dR = deltaR(genWjjP4, (*jet_ak8)->p4()); if ( dR < 0.8 ) { std::cout << "matches reconstructed AK8 jet: pT = " << (*jet_ak8)->pt() << ", eta = " << (*jet_ak8)->eta() << ", phi = " << (*jet_ak8)->phi() << "," << " msoftdrop = " << (*jet_ak8)->msoftdrop() << ", tau21 = " << (*jet_ak8)->tau2()/(*jet_ak8)->tau1() << ", which "; if ( jetSelectorAK8_Wjj.getSelector()(**jet_ak8) ) { std::cout << "PASSES"; isMatched = true; } else { std::cout << "FAILS"; } std::cout << " the W->jj jet selection." << std::endl; std::cout << "generator-level subjets:" << std::endl; for ( std::vector<GenParticle>::const_iterator genWJet1 = genWJets.begin(); genWJet1 != genWJets.end(); ++genWJet1 ) { for ( std::vector<GenParticle>::const_iterator genWJet2 = genWJet1 + 1; genWJet2 != genWJets.end(); ++genWJet2 ) { if ( deltaR(genWJet1->p4() + genWJet2->p4(), genWjjP4) < 1.e-1 && std::fabs((genWJet1->p4() + genWJet2->p4()).mass() - genWjjP4.mass()) < 1.e+1 ) { std::cout << " genWJet #1: pT = " << genWJet1->pt() << ", eta = " << genWJet1->eta() << ", phi = " << genWJet1->phi() << std::endl; std::cout << " genWJet #2: pT = " << genWJet2->pt() << ", eta = " << genWJet2->eta() << ", phi = " << genWJet2->phi() << std::endl; } } } std::cout << "reconstructed subjets:" << std::endl; const RecoSubjetAK8* subjet1 = (*jet_ak8)->subJet1(); if ( subjet1 ) std::cout << " subjet #1: pT = " << subjet1->pt() << ", eta = " << subjet1->eta() << ", phi = " << subjet1->phi() << std::endl; const RecoSubjetAK8* subjet2 = (*jet_ak8)->subJet2(); if ( subjet2 ) std::cout << " subjet #2: pT = " << subjet2->pt() << ", eta = " << subjet2->eta() << ", phi = " << subjet2->phi() << std::endl; } } if ( genWjjP4.pt() > 100. && !isMatched ) std::cout << "--> DEBUG (Wjj) !!" << std::endl; } } */ /* std::pair<const GenLepton*, const GenParticle*> findGenLepton_and_NeutrinoFromWBoson_1(const GenParticle* genWBoson, const std::vector<GenLepton>& genLeptons, const std::vector<GenParticle>& genNeutrinos) { const GenLepton* genLeptonFromWBoson = nullptr; const GenParticle* genNeutrinoFromWBoson = nullptr; double minDeltaMass = 1.e+3; for ( std::vector<GenLepton>::const_iterator genLepton = genLeptons.begin(); genLepton != genLeptons.end(); ++genLepton ) { for ( std::vector<GenParticle>::const_iterator genNeutrino = genNeutrinos.begin(); genNeutrino != genNeutrinos.end(); ++genNeutrino ) { Particle::LorentzVector genLepton_and_NeutrinoP4 = genLepton->p4() + genNeutrino->p4(); double deltaMass = TMath::Abs(genLepton_and_NeutrinoP4.mass() - genWBoson->mass()); double dR = deltaR(genLepton_and_NeutrinoP4, genWBoson->p4()); //if ( deltaMass < 5 && deltaMass < minDeltaMass && dR < 1. ) { if ( deltaMass < 1. && deltaMass < minDeltaMass && dR < 0.01 ) { genLeptonFromWBoson = &(*genLepton); genNeutrinoFromWBoson = &(*genNeutrino); minDeltaMass = deltaMass; } } } if (genLeptonFromWBoson && genNeutrinoFromWBoson && 0==1) { std::cout<<"W->l nu matching: m(W):"<<genWBoson->mass()<<", m(l nu): "<<(genLeptonFromWBoson->p4()+genNeutrinoFromWBoson->p4()).mass()<<", dR(W, l nu): "<<deltaR((genLeptonFromWBoson->p4()+genNeutrinoFromWBoson->p4()), genWBoson->p4())<<std::endl; } return std::pair<const GenLepton*, const GenParticle*>(genLeptonFromWBoson, genNeutrinoFromWBoson); } */ /** * @brief Produce datacard and control plots for 3l categories. */ int main(int argc, char* argv[]) { //--- throw an exception in case ROOT encounters an error gErrorAbortLevel = kError; //--- stop ROOT from keeping track of all histograms TH1::AddDirectory(false); //--- parse command-line arguments if ( argc < 2 ) { std::cout << "Usage: " << argv[0] << " [parameters.py]" << std::endl; return EXIT_FAILURE; } std::cout << "<analyze_hh_3l_gen>:" << std::endl; //--- keep track of time it takes the macro to execute TBenchmark clock; clock.Start("analyze_hh_3l_gen"); //--- read python configuration parameters if ( !edm::readPSetsFrom(argv[1])->existsAs<edm::ParameterSet>("process") ) throw cms::Exception("analyze_hh_3l_gen") << "No ParameterSet 'process' found in configuration file = " << argv[1] << " !!\n"; edm::ParameterSet cfg = edm::readPSetsFrom(argv[1])->getParameter<edm::ParameterSet>("process"); edm::ParameterSet cfg_analyze = cfg.getParameter<edm::ParameterSet>("analyze_hh_3l_gen"); std::string treeName = cfg_analyze.getParameter<std::string>("treeName"); std::string process_string = cfg_analyze.getParameter<std::string>("process"); bool isMC_ttH = process_string == "TTH"; bool isMC_tH = process_string == "TH"; bool isMC_EWK = process_string == "WZ" || process_string == "ZZ"; bool isSignal = boost::starts_with(process_string, "signal_") && process_string.find("_hh_") != std::string::npos; bool isHH_rwgt_allowed = boost::starts_with(process_string, "signal_ggf_nonresonant_") && process_string.find("cHHH") == std::string::npos; std::string histogramDir = cfg_analyze.getParameter<std::string>("histogramDir"); bool isMCClosure_e = histogramDir.find("mcClosure_e") != std::string::npos; bool isMCClosure_m = histogramDir.find("mcClosure_m") != std::string::npos; std::string era_string = cfg_analyze.getParameter<std::string>("era"); const Era era = get_era(era_string); era_current = era; // single lepton triggers vstring triggerNames_1e = cfg_analyze.getParameter<vstring>("triggers_1e"); std::vector<hltPath*> triggers_1e = create_hltPaths(triggerNames_1e, "triggers_1e"); bool use_triggers_1e = cfg_analyze.getParameter<bool>("use_triggers_1e"); vstring triggerNames_1mu = cfg_analyze.getParameter<vstring>("triggers_1mu"); std::vector<hltPath*> triggers_1mu = create_hltPaths(triggerNames_1mu, "triggers_1mu"); bool use_triggers_1mu = cfg_analyze.getParameter<bool>("use_triggers_1mu"); // double lepton triggers vstring triggerNames_2e = cfg_analyze.getParameter<vstring>("triggers_2e"); std::vector<hltPath*> triggers_2e = create_hltPaths(triggerNames_2e, "triggers_2e"); bool use_triggers_2e = cfg_analyze.getParameter<bool>("use_triggers_2e"); vstring triggerNames_1e1mu = cfg_analyze.getParameter<vstring>("triggers_1e1mu"); std::vector<hltPath*> triggers_1e1mu = create_hltPaths(triggerNames_1e1mu, "triggers_1e1mu"); bool use_triggers_1e1mu = cfg_analyze.getParameter<bool>("use_triggers_1e1mu"); vstring triggerNames_2mu = cfg_analyze.getParameter<vstring>("triggers_2mu"); std::vector<hltPath*> triggers_2mu = create_hltPaths(triggerNames_2mu, "triggers_2mu"); bool use_triggers_2mu = cfg_analyze.getParameter<bool>("use_triggers_2mu"); // triple lepton triggers vstring triggerNames_3e = cfg_analyze.getParameter<vstring>("triggers_3e"); std::vector<hltPath*> triggers_3e = create_hltPaths(triggerNames_3e, "triggers_3e"); bool use_triggers_3e = cfg_analyze.getParameter<bool>("use_triggers_3e"); vstring triggerNames_2e1mu = cfg_analyze.getParameter<vstring>("triggers_2e1mu"); std::vector<hltPath*> triggers_2e1mu = create_hltPaths(triggerNames_2e1mu, "triggers_2e1mu"); bool use_triggers_2e1mu = cfg_analyze.getParameter<bool>("use_triggers_2e1mu"); vstring triggerNames_1e2mu = cfg_analyze.getParameter<vstring>("triggers_1e2mu"); std::vector<hltPath*> triggers_1e2mu = create_hltPaths(triggerNames_1e2mu, "triggers_1e2mu"); bool use_triggers_1e2mu = cfg_analyze.getParameter<bool>("use_triggers_1e2mu"); vstring triggerNames_3mu = cfg_analyze.getParameter<vstring>("triggers_3mu"); std::vector<hltPath*> triggers_3mu = create_hltPaths(triggerNames_3mu, "triggers_3mu"); bool use_triggers_3mu = cfg_analyze.getParameter<bool>("use_triggers_3mu"); bool apply_offline_e_trigger_cuts_1e = cfg_analyze.getParameter<bool>("apply_offline_e_trigger_cuts_1e"); bool apply_offline_e_trigger_cuts_1mu = cfg_analyze.getParameter<bool>("apply_offline_e_trigger_cuts_1mu"); bool apply_offline_e_trigger_cuts_2e = cfg_analyze.getParameter<bool>("apply_offline_e_trigger_cuts_2e"); bool apply_offline_e_trigger_cuts_1e1mu = cfg_analyze.getParameter<bool>("apply_offline_e_trigger_cuts_1e1mu"); bool apply_offline_e_trigger_cuts_2mu = cfg_analyze.getParameter<bool>("apply_offline_e_trigger_cuts_2mu"); bool apply_offline_e_trigger_cuts_3e = cfg_analyze.getParameter<bool>("apply_offline_e_trigger_cuts_3e"); bool apply_offline_e_trigger_cuts_2e1mu = cfg_analyze.getParameter<bool>("apply_offline_e_trigger_cuts_2e1mu"); bool apply_offline_e_trigger_cuts_1e2mu = cfg_analyze.getParameter<bool>("apply_offline_e_trigger_cuts_1e2mu"); bool apply_offline_e_trigger_cuts_3mu = cfg_analyze.getParameter<bool>("apply_offline_e_trigger_cuts_3mu"); const std::string electronSelection_string = cfg_analyze.getParameter<std::string>("electronSelection"); const std::string muonSelection_string = cfg_analyze.getParameter<std::string>("muonSelection"); const int electronSelection = get_selection(electronSelection_string); const int muonSelection = get_selection(muonSelection_string); bool apply_leptonGenMatching = cfg_analyze.getParameter<bool>("apply_leptonGenMatching"); std::vector<leptonGenMatchEntry> leptonGenMatch_definitions = getLeptonGenMatch_definitions_3lepton(true); std::cout << leptonGenMatch_definitions; GenMatchInterface genMatchInterface(3, apply_leptonGenMatching, false); TString hadTauSelection_string = cfg_analyze.getParameter<std::string>("hadTauSelection").data(); TObjArray* hadTauSelection_parts = hadTauSelection_string.Tokenize("|"); assert(hadTauSelection_parts->GetEntries() >= 1); std::string hadTauSelection_part2 = ( hadTauSelection_parts->GetEntries() == 2 ) ? (dynamic_cast<TObjString*>(hadTauSelection_parts->At(1)))->GetString().Data() : ""; delete hadTauSelection_parts; const double lep_mva_cut_mu = cfg_analyze.getParameter<double>("lep_mva_cut_mu"); const double lep_mva_cut_e = cfg_analyze.getParameter<double>("lep_mva_cut_e"); enum { kOS, kSS }; std::string leptonChargeSelection_string = cfg_analyze.getParameter<std::string>("leptonChargeSelection"); int leptonChargeSelection = -1; if ( leptonChargeSelection_string == "OS" ) leptonChargeSelection = kOS; else if ( leptonChargeSelection_string == "SS" ) leptonChargeSelection = kSS; else throw cms::Exception("analyze_hh_3l_gen") << "Invalid Configuration parameter 'leptonChargeSelection' = " << leptonChargeSelection_string << " !!\n"; const int minNumJets = 1; bool isMC = cfg_analyze.getParameter<bool>("isMC"); if (!isMC) { std::cout << "analyze_hh_3l_gen: running not on MC. Generator-level studies can only run on MC *** ERROR ***" << std::endl; throw cmsException("analyze_hh_3l_gen", __LINE__) << " Generator-level studies can only run on MC " <<static_cast<int>(era); } bool hasLHE = cfg_analyze.getParameter<bool>("hasLHE"); bool hasPS = cfg_analyze.getParameter<bool>("hasPS"); bool apply_LHE_nom = cfg_analyze.getParameter<bool>("apply_LHE_nom"); bool useObjectMultiplicity = cfg_analyze.getParameter<bool>("useObjectMultiplicity"); std::string central_or_shift_main = cfg_analyze.getParameter<std::string>("central_or_shift"); std::vector<std::string> central_or_shifts_local = cfg_analyze.getParameter<std::vector<std::string>>("central_or_shifts_local"); edm::VParameterSet lumiScale = cfg_analyze.getParameter<edm::VParameterSet>("lumiScale"); bool apply_genWeight = cfg_analyze.getParameter<bool>("apply_genWeight"); std::string apply_topPtReweighting_str = cfg_analyze.getParameter<std::string>("apply_topPtReweighting"); bool apply_topPtReweighting = ! apply_topPtReweighting_str.empty(); bool apply_l1PreFireWeight = cfg_analyze.getParameter<bool>("apply_l1PreFireWeight"); bool apply_btagSFRatio = cfg_analyze.getParameter<bool>("applyBtagSFRatio"); bool apply_hlt_filter = cfg_analyze.getParameter<bool>("apply_hlt_filter"); bool apply_met_filters = cfg_analyze.getParameter<bool>("apply_met_filters"); edm::ParameterSet cfgMEtFilter = cfg_analyze.getParameter<edm::ParameterSet>("cfgMEtFilter"); MEtFilterSelector metFilterSelector(cfgMEtFilter, isMC); const bool useNonNominal = cfg_analyze.getParameter<bool>("useNonNominal"); const bool useNonNominal_jetmet = useNonNominal || ! isMC; if(! central_or_shifts_local.empty()) { assert(central_or_shift_main == "central"); assert(std::find(central_or_shifts_local.cbegin(), central_or_shifts_local.cend(), "central") != central_or_shifts_local.cend()); } else { central_or_shifts_local = { central_or_shift_main }; } edm::ParameterSet triggerWhiteList; if(! isMC) { triggerWhiteList = cfg_analyze.getParameter<edm::ParameterSet>("triggerWhiteList"); } const edm::ParameterSet additionalEvtWeight = cfg_analyze.getParameter<edm::ParameterSet>("evtWeight"); const bool applyAdditionalEvtWeight = additionalEvtWeight.getParameter<bool>("apply"); EvtWeightManager * eventWeightManager = nullptr; if(applyAdditionalEvtWeight) { eventWeightManager = new EvtWeightManager(additionalEvtWeight); eventWeightManager->set_central_or_shift(central_or_shift_main); } bool isDEBUG = cfg_analyze.getParameter<bool>("isDEBUG"); if ( isDEBUG ) std::cout << "Warning: DEBUG mode enabled -> trigger selection will not be applied for data !!" << std::endl; checkOptionValidity(central_or_shift_main, isMC); const int met_option = useNonNominal_jetmet ? kJetMET_central_nonNominal : getMET_option(central_or_shift_main, isMC); const int jetPt_option = useNonNominal_jetmet ? kJetMET_central_nonNominal : getJet_option(central_or_shift_main, isMC); const int hadTauPt_option = useNonNominal_jetmet ? kHadTauPt_uncorrected : getHadTauPt_option(central_or_shift_main); std::cout << "central_or_shift = " << central_or_shift_main << "\n" " -> hadTauPt_option = " << hadTauPt_option << "\n" " -> met_option = " << met_option << "\n" " -> jetPt_option = " << jetPt_option << '\n' ; edm::ParameterSet cfg_dataToMCcorrectionInterface; cfg_dataToMCcorrectionInterface.addParameter<std::string>("era", era_string); cfg_dataToMCcorrectionInterface.addParameter<std::string>("hadTauSelection", hadTauSelection_part2); cfg_dataToMCcorrectionInterface.addParameter<int>("hadTauSelection_antiElectron", hadTauSelection_antiElectron); cfg_dataToMCcorrectionInterface.addParameter<int>("hadTauSelection_antiMuon", hadTauSelection_antiMuon); Data_to_MC_CorrectionInterface_Base * dataToMCcorrectionInterface = nullptr; switch(era) { case Era::k2016: dataToMCcorrectionInterface = new Data_to_MC_CorrectionInterface_2016(cfg_dataToMCcorrectionInterface); break; case Era::k2017: dataToMCcorrectionInterface = new Data_to_MC_CorrectionInterface_2017(cfg_dataToMCcorrectionInterface); break; case Era::k2018: dataToMCcorrectionInterface = new Data_to_MC_CorrectionInterface_2018(cfg_dataToMCcorrectionInterface); break; default: throw cmsException("analyze_hh_3l", __LINE__) << "Invalid era = " << static_cast<int>(era); } std::string applyFakeRateWeights_string = cfg_analyze.getParameter<std::string>("applyFakeRateWeights"); int applyFakeRateWeights = -1; if ( applyFakeRateWeights_string == "disabled" ) applyFakeRateWeights = kFR_disabled; else if ( applyFakeRateWeights_string == "3lepton" ) applyFakeRateWeights = kFR_3lepton; else throw cms::Exception("analyze_hh_3l_gen") << "Invalid Configuration parameter 'applyFakeRateWeights' = " << applyFakeRateWeights_string << " !!\n"; LeptonFakeRateInterface* leptonFakeRateInterface = 0; if ( applyFakeRateWeights == kFR_3lepton) { edm::ParameterSet cfg_leptonFakeRateWeight = cfg_analyze.getParameter<edm::ParameterSet>("leptonFakeRateWeight"); cfg_leptonFakeRateWeight.addParameter<std::string>("era", era_string); cfg_leptonFakeRateWeight.addParameter<std::vector<std::string>>("central_or_shifts", central_or_shifts_local); leptonFakeRateInterface = new LeptonFakeRateInterface(cfg_leptonFakeRateWeight); } bool fillGenEvtHistograms = cfg_analyze.getParameter<bool>("fillGenEvtHistograms"); edm::ParameterSet cfg_EvtYieldHistManager = cfg_analyze.getParameter<edm::ParameterSet>("cfgEvtYieldHistManager"); std::string branchName_electrons = cfg_analyze.getParameter<std::string>("branchName_electrons"); std::string branchName_muons = cfg_analyze.getParameter<std::string>("branchName_muons"); std::string branchName_hadTaus = cfg_analyze.getParameter<std::string>("branchName_hadTaus"); //std::string branchName_jets = cfg_analyze.getParameter<std::string>("branchName_jets"); std::string branchName_jets_ak4 = cfg_analyze.getParameter<std::string>("branchName_jets_ak4"); std::string branchName_jets_ak8_Wjj = cfg_analyze.getParameter<std::string>("branchName_jets_ak8_Wjj"); std::string branchName_subjets_ak8_Wjj = cfg_analyze.getParameter<std::string>("branchName_subjets_ak8_Wjj"); std::string branchName_met = cfg_analyze.getParameter<std::string>("branchName_met"); std::string branchName_genLeptons = cfg_analyze.getParameter<std::string>("branchName_genLeptons"); std::string branchName_genHadTaus = cfg_analyze.getParameter<std::string>("branchName_genHadTaus"); std::string branchName_genPhotons = cfg_analyze.getParameter<std::string>("branchName_genPhotons"); std::string branchName_genJets = cfg_analyze.getParameter<std::string>("branchName_genJets"); std::string branchName_muonGenMatch = cfg_analyze.getParameter<std::string>("branchName_muonGenMatch"); std::string branchName_electronGenMatch = cfg_analyze.getParameter<std::string>("branchName_electronGenMatch"); std::string branchName_hadTauGenMatch = cfg_analyze.getParameter<std::string>("branchName_hadTauGenMatch"); std::string branchName_jetGenMatch = cfg_analyze.getParameter<std::string>("branchName_jetGenMatch"); const bool redoGenMatching = cfg_analyze.getParameter<bool>("redoGenMatching"); const bool jetCleaningByIndex = cfg_analyze.getParameter<bool>("jetCleaningByIndex"); const bool genMatchingByIndex = cfg_analyze.getParameter<bool>("genMatchingByIndex"); std::string branchName_genHiggses = cfg_analyze.getParameter<std::string>("branchName_genHiggses"); std::string branchName_genNeutrinos = cfg_analyze.getParameter<std::string>("branchName_genNeutrinos"); std::string branchName_genWBosons = cfg_analyze.getParameter<std::string>("branchName_genWBosons"); std::string branchName_genWJets = cfg_analyze.getParameter<std::string>("branchName_genWJets"); std::string selEventsFileName_input = cfg_analyze.getParameter<std::string>("selEventsFileName_input"); std::cout << "selEventsFileName_input = " << selEventsFileName_input << std::endl; RunLumiEventSelector* run_lumi_eventSelector = nullptr; if ( selEventsFileName_input != "" ) { edm::ParameterSet cfgRunLumiEventSelector; cfgRunLumiEventSelector.addParameter<std::string>("inputFileName", selEventsFileName_input); cfgRunLumiEventSelector.addParameter<std::string>("separator", ":"); run_lumi_eventSelector = new RunLumiEventSelector(cfgRunLumiEventSelector); } std::string selEventsFileName_output = cfg_analyze.getParameter<std::string>("selEventsFileName_output"); std::cout << "selEventsFileName_output = " << selEventsFileName_output << std::endl; fwlite::InputSource inputFiles(cfg); int maxEvents = inputFiles.maxEvents(); std::cout << " maxEvents = " << maxEvents << std::endl; unsigned reportEvery = inputFiles.reportAfter(); fwlite::OutputFiles outputFile(cfg); fwlite::TFileService fs = fwlite::TFileService(outputFile.file().data()); TTreeWrapper * inputTree = new TTreeWrapper(treeName.data(), inputFiles.files(), maxEvents); std::cout << "Loaded " << inputTree -> getFileCount() << " file(s).\n"; //--- declare event-level variables EventInfo eventInfo(isMC, isSignal, isHH_rwgt_allowed, apply_topPtReweighting); const std::string default_cat_str = "default"; std::vector<std::string> evt_cat_strs = { default_cat_str }; //--- HH scan const edm::ParameterSet hhWeight_cfg = cfg_analyze.getParameterSet("hhWeight_cfg"); const bool apply_HH_rwgt = eventInfo.is_hh_nonresonant() && hhWeight_cfg.getParameter<bool>("apply_rwgt"); const HHWeightInterface * HHWeight_calc = nullptr; if(apply_HH_rwgt) { HHWeight_calc = new HHWeightInterface(hhWeight_cfg); evt_cat_strs = HHWeight_calc->get_scan_strs(); } const size_t Nscan = evt_cat_strs.size(); std::cout << "Number of points being scanned = " << Nscan << '\n'; const std::vector<edm::ParameterSet> tHweights = cfg_analyze.getParameterSetVector("tHweights"); if((isMC_tH || isMC_ttH) && ! tHweights.empty()) { eventInfo.loadWeight_tH(tHweights); } EventInfoReader eventInfoReader(&eventInfo); if(apply_topPtReweighting) { eventInfoReader.setTopPtRwgtBranchName(apply_topPtReweighting_str); } inputTree -> registerReader(&eventInfoReader); ObjectMultiplicity objectMultiplicity; ObjectMultiplicityReader objectMultiplicityReader(&objectMultiplicity); if(useObjectMultiplicity) { inputTree -> registerReader(&objectMultiplicityReader); } const int minLeptonSelection = std::min(electronSelection, muonSelection); hltPathReader hltPathReader_instance({ triggers_1e, triggers_1mu, triggers_2e, triggers_1e1mu, triggers_2mu, triggers_3e, triggers_2e1mu, triggers_1e2mu, triggers_3mu }); inputTree -> registerReader(&hltPathReader_instance); if(eventWeightManager) { inputTree->registerReader(eventWeightManager); } L1PreFiringWeightReader * l1PreFiringWeightReader = nullptr; if(apply_l1PreFireWeight) { l1PreFiringWeightReader = new L1PreFiringWeightReader(era); inputTree->registerReader(l1PreFiringWeightReader); } BtagSFRatioFacility * btagSFRatioFacility = nullptr; if(apply_btagSFRatio) { const edm::ParameterSet btagSFRatio = cfg_analyze.getParameterSet("btagSFRatio"); btagSFRatioFacility = new BtagSFRatioFacility(btagSFRatio); } //--- declare particle collections const bool readGenObjects = isMC && !redoGenMatching; RecoMuonReader* muonReader = new RecoMuonReader(era, branchName_muons, isMC, readGenObjects); inputTree -> registerReader(muonReader); RecoMuonCollectionGenMatcher muonGenMatcher; RecoMuonCollectionSelectorLoose preselMuonSelector(era, -1, isDEBUG); RecoMuonCollectionSelectorFakeable fakeableMuonSelector(era, -1, isDEBUG); RecoMuonCollectionSelectorTight tightMuonSelector(era, -1, isDEBUG); muonReader->set_mvaTTH_wp(lep_mva_cut_mu); RecoElectronReader* electronReader = new RecoElectronReader(era, branchName_electrons, isMC, readGenObjects); inputTree -> registerReader(electronReader); RecoElectronCollectionGenMatcher electronGenMatcher; RecoElectronCollectionCleaner electronCleaner(0.05, isDEBUG); RecoElectronCollectionSelectorLoose preselElectronSelector(era, -1, isDEBUG); RecoElectronCollectionSelectorFakeable fakeableElectronSelector(era, -1, isDEBUG); RecoElectronCollectionSelectorTight tightElectronSelector(era, -1, isDEBUG); electronReader->set_mvaTTH_wp(lep_mva_cut_e); RecoHadTauReader* hadTauReader = new RecoHadTauReader(era, branchName_hadTaus, isMC, readGenObjects); hadTauReader->setHadTauPt_central_or_shift(hadTauPt_option); inputTree -> registerReader(hadTauReader); RecoHadTauCollectionGenMatcher hadTauGenMatcher; RecoHadTauCollectionCleaner hadTauCleaner(0.3, isDEBUG); RecoHadTauCollectionSelectorFakeable fakeableHadTauSelector(era, -1, isDEBUG); fakeableHadTauSelector.set_if_looser(hadTauSelection_part2); fakeableHadTauSelector.set_min_antiElectron(hadTauSelection_antiElectron); fakeableHadTauSelector.set_min_antiMuon(hadTauSelection_antiMuon); RecoHadTauCollectionSelectorTight tightHadTauSelector(era, -1, isDEBUG); tightHadTauSelector.set(hadTauSelection_part2); tightHadTauSelector.set_min_antiElectron(hadTauSelection_antiElectron); tightHadTauSelector.set_min_antiMuon(hadTauSelection_antiMuon); RecoJetReader* jetReaderAK4 = new RecoJetReader(era, isMC, branchName_jets_ak4, readGenObjects); jetReaderAK4->setPtMass_central_or_shift(jetPt_option); jetReaderAK4->read_btag_systematics((central_or_shifts_local.size() > 1 || central_or_shift_main != "central") && isMC); inputTree->registerReader(jetReaderAK4); RecoJetCollectionGenMatcher jetGenMatcherAK4; RecoJetCollectionCleaner jetCleanerAK4_dR04(0.4, isDEBUG); RecoJetCollectionCleanerByIndex jetCleanerAK4_byIndex(isDEBUG); RecoJetCollectionCleaner jetCleanerAK4_dR08(0.8, isDEBUG); RecoJetCollectionCleaner jetCleanerAK4_dR12(1.2, isDEBUG); RecoJetCollectionSelector jetSelectorAK4(era, -1, isDEBUG); RecoJetCollectionSelector jetSelectorAK4_vbf(era, -1, isDEBUG); jetSelectorAK4_vbf.getSelector().set_max_absEta(4.7); RecoJetCollectionSelectorBtagLoose jetSelectorAK4_bTagLoose(era, -1, isDEBUG); RecoJetCollectionSelectorBtagMedium jetSelectorAK4_bTagMedium(era, -1, isDEBUG); // refer analyze_hh_bb1l.cc macro RecoJetReaderAK8* jetReaderAK8_Wjj = new RecoJetReaderAK8(era, isMC, branchName_jets_ak8_Wjj, branchName_subjets_ak8_Wjj); // TO-DO: implement jet energy scale uncertainties, b-tag weights, // and jet pT and (softdrop) mass corrections described in Section 3.4.3 of AN-2018/058 (v4) inputTree->registerReader(jetReaderAK8_Wjj); RecoJetCollectionCleanerAK8 jetCleanerAK8_dR08(0.8, isDEBUG); RecoJetCollectionCleanerAK8 jetCleanerAK8_dR12(1.2, isDEBUG); RecoJetCollectionCleanerAK8 jetCleanerAK8_dR16(1.6, isDEBUG); RecoJetCollectionSelectorAK8 jetSelectorAK8(era, -1, isDEBUG); RecoJetCollectionSelectorAK8_hh_Wjj jetSelectorAK8_Wjj(era, -1, isDEBUG); //--- declare missing transverse energy RecoMEtReader* metReader = new RecoMEtReader(era, isMC, branchName_met); metReader->setMEt_central_or_shift(met_option); inputTree -> registerReader(metReader); MEtFilter metFilters; MEtFilterReader* metFilterReader = new MEtFilterReader(&metFilters, era); inputTree -> registerReader(metFilterReader); GenLeptonReader * genLeptonReader = nullptr; GenHadTauReader * genHadTauReader = nullptr; GenPhotonReader * genPhotonReader = nullptr; GenJetReader * genJetReader = nullptr; GenParticleReader * genHiggsReader = nullptr; GenParticleReader * genNeutrinoReader = nullptr; LHEInfoReader * lheInfoReader = nullptr; PSWeightReader * psWeightReader = nullptr; GenParticleReader * genMatchToMuonReader = nullptr; GenParticleReader * genMatchToElectronReader = nullptr; GenParticleReader * genMatchToHadTauReader = nullptr; GenParticleReader * genMatchToJetReader = nullptr; std::cout << "\n isMC: " << isMC << ", readGenObjects: " << readGenObjects << ", genMatchingByIndex: " << genMatchingByIndex << ", fillGenEvtHistograms: " << fillGenEvtHistograms << std::endl; if(isMC) { //if(! readGenObjects) if(1==1) { genLeptonReader = new GenLeptonReader(branchName_genLeptons); inputTree -> registerReader(genLeptonReader); genHadTauReader = new GenHadTauReader(branchName_genHadTaus); inputTree -> registerReader(genHadTauReader); genJetReader = new GenJetReader(branchName_genJets); inputTree -> registerReader(genJetReader); genNeutrinoReader = new GenParticleReader(branchName_genNeutrinos); inputTree->registerReader(genNeutrinoReader); if(genMatchingByIndex) { genMatchToMuonReader = new GenParticleReader(branchName_muonGenMatch); genMatchToMuonReader -> readGenPartFlav(true); inputTree -> registerReader(genMatchToMuonReader); genMatchToElectronReader = new GenParticleReader(branchName_electronGenMatch); genMatchToElectronReader -> readGenPartFlav(true); inputTree -> registerReader(genMatchToElectronReader); genMatchToHadTauReader = new GenParticleReader(branchName_hadTauGenMatch); genMatchToHadTauReader -> readGenPartFlav(true); inputTree -> registerReader(genMatchToHadTauReader); genMatchToJetReader = new GenParticleReader(branchName_jetGenMatch); genMatchToJetReader -> readGenPartFlav(true); inputTree -> registerReader(genMatchToJetReader); } else { //genPhotonReader = new GenPhotonReader(branchName_genPhotons); //inputTree -> registerReader(genPhotonReader); } genPhotonReader = new GenPhotonReader(branchName_genPhotons); inputTree -> registerReader(genPhotonReader); } genHiggsReader = new GenParticleReader(branchName_genHiggses); inputTree->registerReader(genHiggsReader); lheInfoReader = new LHEInfoReader(hasLHE); inputTree -> registerReader(lheInfoReader); psWeightReader = new PSWeightReader(hasPS, apply_LHE_nom); inputTree -> registerReader(psWeightReader); } GenParticleReader* genWBosonReader = nullptr; GenParticleReader* genWJetReader = nullptr; if ( isMC ) { genWBosonReader = new GenParticleReader(branchName_genWBosons); inputTree->registerReader(genWBosonReader); genWJetReader = new GenParticleReader(branchName_genWJets); inputTree->registerReader(genWJetReader); } std::cout << "genLeptonReader: " << genLeptonReader << ", genHadTauReader: " << genHadTauReader << ", genJetReader: " << genJetReader << ", genNeutrinoReader: " << genNeutrinoReader << ", genPhotonReader: " << genPhotonReader << ",\ngenMatchToMuonReader: " << genMatchToMuonReader << ", genMatchToElectronReader: " << genMatchToElectronReader << ", genMatchToHadTauReader: " << genMatchToHadTauReader << ", genMatchToJetReader: " << genMatchToJetReader << ",\ngenHiggsReader: " << genHiggsReader << ",\ngenWBosonReader: " << genWBosonReader << ", genWJetReader: " << genWJetReader << std::endl; std::string mvaFileName_hh_3l_SUMBk_HH = "hhAnalysis/multilepton/data/3l_0tau_HH_XGB_noTopness_evtLevelSUM_HH_res_26Var.pkl"; std::vector<std::string> mvaInputs_hh_3l_SUMBk_HH = { "lep1_conePt", "lep1_eta", "mindr_lep1_jet", "mT_lep1", "lep2_conePt", "lep2_eta", "mindr_lep2_jet", "mT_lep2", "lep3_conePt", "lep3_eta", "mindr_lep3_jet", "mT_lep3", "avg_dr_jet", "dr_leps", "dr_lss", "dr_los1", "dr_los2", "met_LD", "m_jj", "diHiggsMass", "mTMetLepton1", "mTMetLepton2", "nJet", "nElectron", "sumLeptonCharge", "numSameFlavor_OS" }; XGBInterface mva_xgb_hh_3l_SUMBk_HH(mvaFileName_hh_3l_SUMBk_HH, mvaInputs_hh_3l_SUMBk_HH); bool selectBDT = ( cfg_analyze.exists("selectBDT") ) ? cfg_analyze.getParameter<bool>("selectBDT") : false; //--- open output file containing run:lumi:event numbers of events passing final event selection criteria std::ostream* selEventsFile = ( selEventsFileName_output != "" ) ? new std::ofstream(selEventsFileName_output.data(), std::ios::out) : 0; std::cout << "process: " << process_string << std::endl; vstring categories_evt = { "hh_WjjBoosted", "hh_WjjResolved", "hh_WjjHasOnly1j", //"hh_3lneg", "hh_3lpos", //"hh_3l_nonVBF", "hh_3l_VBF" }; bool skipHHDecayModeHistograms = true; //--- declare histograms struct selHistManagerType { ElectronHistManager* electrons_; std::map<std::string, ElectronHistManager*> electrons_in_categories_; MuonHistManager* muons_; std::map<std::string, MuonHistManager*> muons_in_categories_; HadTauHistManager* hadTaus_; JetHistManager* jetsAK4_; JetHistManager* leadJetAK4_; JetHistManager* subleadJetAK4_; JetHistManagerAK8* jetsAK8_Wjj_; JetHistManager* BJetsAK4_loose_; JetHistManager* leadBJetAK4_loose_; JetHistManager* subleadBJetAK4_loose_; JetHistManager* BJetsAK4_medium_; MEtHistManager* met_; MEtFilterHistManager* metFilters_; std::map<std::string, EvtHistManager_hh_3l*> evt_; std::map<std::string, std::map<std::string, EvtHistManager_hh_3l*>> evt_in_categories_; std::map<std::string, std::map<std::string, EvtHistManager_hh_3l*>> evt_in_decayModes_; std::map<std::string, std::map<std::string, std::map<std::string, EvtHistManager_hh_3l*>>> evt_in_categories_and_decayModes_; EvtYieldHistManager* evtYield_; WeightHistManager* weights_; }; std::map<std::string, GenEvtHistManager*> genEvtHistManager_beforeCuts; std::map<std::string, GenEvtHistManager*> genEvtHistManager_afterCuts; std::map<std::string, LHEInfoHistManager*> lheInfoHistManager; std::map<std::string, std::map<int, selHistManagerType*>> selHistManagers; std::map<int, TH1*> hMEt_All_0 ; std::map<int, TH1*> hHt_All_0; std::map<int, TH1*> hMEt_LD_All_0; std::map<int, TH1*> hHT_All_0; std::map<int, TH1*> hSTMET_All_0; // std::map<int, TH1*> hMEt_SFOS_0; std::map<int, TH1*> hHt_SFOS_0; std::map<int, TH1*> hMEt_LD_SFOS_0; std::map<int, TH1*> hHT_SFOS_0; std::map<int, TH1*> hSTMET_SFOS_0; // std::map<int, TH1*> hMEt_All_1; std::map<int, TH1*> hHt_All_1; std::map<int, TH1*> hMEt_LD_All_1; std::map<int, TH1*> hHT_All_1; std::map<int, TH1*> hSTMET_All_1; // std::map<int, TH1*> hMEt_SFOS_1; std::map<int, TH1*> hHt_SFOS_1; std::map<int, TH1*> hMEt_LD_SFOS_1; std::map<int, TH1*> hHT_SFOS_1; std::map<int, TH1*> hSTMET_SFOS_1; // std::map<int, TH1*> hm_2lpreselUnclean_0; std::map<int, TH1*> hm_2lpreselUnclean_1; std::map<int, TH1*> hm_SFOS2lpresel_0; std::map<int, TH1*> hm_SFOS2lpresel_1; std::map<int, TH1*> hm_SFOS4lpresel_0; std::map<int, TH1*> hm_SFOS4lpresel_1; // Gen-level study std::map<int, TH1*> hdrmin_H_WW_gen; std::map<int, TH1*> hdmmin_H_WW_gen; std::map<int, TH1*> hdrmin_W_qq_gen; std::map<int, TH1*> hdmmin_W_qq_gen; std::map<int, TH1*> hdrmin_W_lnu_gen; std::map<int, TH1*> hdmmin_W_lnu_gen; // std::map<int, TH1*> hptGenWjj_HHTo4W_3l_1qq; std::map<int, TH1*> hptGenWjet1_HHTo4W_3l_1qq; std::map<int, TH1*> hptGenWjet2_HHTo4W_3l_1qq; std::map<int, TH1*> hptGenLep3_HHTo4W_3l_1qq; std::map<int, TH1*> hptGenLep1_HHTo4W_3l_1qq; std::map<int, TH1*> hptGenLep2_HHTo4W_3l_1qq; std::map<int, TH1*> hptGenLepLead_HHTo4W_3l_1qq; std::map<int, TH1*> hptGenLepSublead_HHTo4W_3l_1qq; std::map<int, TH1*> hptGenLepSubsublead_HHTo4W_3l_1qq; // std::map<int, TH1*> hetaGenWjj_HHTo4W_3l_1qq; std::map<int, TH1*> hetaGenWjet1_HHTo4W_3l_1qq; std::map<int, TH1*> hetaGenWjet2_HHTo4W_3l_1qq; std::map<int, TH1*> hetaGenLep3_HHTo4W_3l_1qq; std::map<int, TH1*> hetaGenLep1_HHTo4W_3l_1qq; std::map<int, TH1*> hetaGenLep2_HHTo4W_3l_1qq; // std::map<int, TH1*> hdr_GenWj1j2_HHTo4W_3l_1qq; std::map<int, TH1*> hdr_GenLep3_Wjj_HHTo4W_3l_1qq; std::map<int, TH1*> hdr_GenLep3_Wjet1_HHTo4W_3l_1qq; std::map<int, TH1*> hdr_GenLep3_Wjet2_HHTo4W_3l_1qq; std::map<int, TH1*> hdr_GenLep3_WjetNear_HHTo4W_3l_1qq; std::map<int, TH1*> hdr_GenLep3_WjetFar_HHTo4W_3l_1qq; // std::map<int, TH2*> hdr_GenWj1j2_vs_ptGenWjj_HHTo4W_3l_1qq; std::map<int, TH2*> hdr_GenLep3_Wjj_vs_ptWjj_HHTo4W_3l_1qq; std::map<int, TH2*> hdr_GenLep3_Wjet1_vs_ptWjj_HHTo4W_3l_1qq; std::map<int, TH2*> hdr_GenLep3_Wjet2_vs_ptWjj_HHTo4W_3l_1qq; std::map<int, TH2*> hdr_GenLep3_WjetNear_vs_ptWjj_HHTo4W_3l_1qq; std::map<int, TH2*> hdr_GenLep3_WjetFar_vs_ptWjj_HHTo4W_3l_1qq; std::map<int, TH1*> hptResolution_preselLeptonsFull_Ele; std::map<int, TH1*> hptResolution_preselLeptonsFull_Mu; std::map<int, TH1*> hptResolution_preselLeptonsFull_GenMatchHHTo4WLeps_Ele; std::map<int, TH1*> hptResolution_preselLeptonsFull_GenMatchHHTo4WLeps_Mu; // std::map<int, TH1*> hptResolution_fakeableLeptonsFull_Ele; std::map<int, TH1*> hptResolution_fakeableLeptonsFull_Mu; std::map<int, TH1*> hptResolution_fakeableLeptonsFull_GenMatchHHTo4WLeps_Ele; std::map<int, TH1*> hptResolution_fakeableLeptonsFull_GenMatchHHTo4WLeps_Mu; // std::map<int, TH1*> hptResolution_tightLeptonsFull_Ele; std::map<int, TH1*> hptResolution_tightLeptonsFull_Mu; std::map<int, TH1*> hptResolution_tightLeptonsFull_GenMatchHHTo4WLeps_Ele; std::map<int, TH1*> hptResolution_tightLeptonsFull_GenMatchHHTo4WLeps_Mu; // std::map<int, TH1*> hptResolution_AK4; std::map<int, TH1*> hptResolution_AK4_GenMatchHHTo4WJets; std::map<int, TH1*> hptResolution_AK8subjet_GenMatchHHTo4WJets; // std::map<int, TH1*> hptResolutionAK4_AK8Overlap; std::map<int, TH1*> hmassResolutionAK4_AK8Overlap; std::map<int, TH1*> hptResolutionAK8_AK4Overlap; std::map<int, TH1*> hmassResolutionAK8_AK4Overlap; std::map<int, TH2*> hptResolutionAK4_vs_ptGen_AK8Overlap; std::map<int, TH2*> hmassResolutionAK4_vs_ptGen_AK8Overlap; std::map<int, TH2*> hptResolutionAK8_vs_ptGen_AK4Overlap; std::map<int, TH2*> hmassResolutionAK8_vs_ptGen_AK4Overlap; std::map<int, TH1*> hmass_jj_AK4_AK8Overlap; std::map<int, TH1*> hmass_jj_AK8_AK4Overlap; std::map<int, TH1*> hmass_Genjj_AK8_AK4Overlap; std::map<int, TH1*> hmassResolutionAK4_AK8Overlap_0; std::map<int, TH1*> hmassResolutionAK8_AK4Overlap_0; std::map<int, TH2*> hmassResolutionAK4_0_vs_ptWGen_AK8Overlap; std::map<int, TH2*> hmassResolutionAK8_0_vs_ptWGen_AK4Overlap; //std::map<int, TH1*> ; for(const std::string & central_or_shift: central_or_shifts_local) { const bool skipBooking = central_or_shift != central_or_shift_main; std::vector<const GenMatchEntry*> genMatchDefinitions = genMatchInterface.getGenMatchDefinitions(); for (const GenMatchEntry * genMatchDefinition : genMatchDefinitions) { std::string process_and_genMatch = process_string; process_and_genMatch += genMatchDefinition->getName(); int idxLepton = genMatchDefinition->getIdx(); std::cout << "process_and_genMatch: " << process_and_genMatch << ", \t histogramDir: " << histogramDir.data() << ",\t idxLepton: " << idxLepton << std::endl; selHistManagerType* selHistManager = new selHistManagerType(); if(! skipBooking) { selHistManager->electrons_ = new ElectronHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/electrons", histogramDir.data()), era_string, central_or_shift, "allHistograms")); selHistManager->electrons_->bookHistograms(fs); selHistManager->muons_ = new MuonHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/muons", histogramDir.data()), era_string, central_or_shift, "allHistograms")); selHistManager->muons_->bookHistograms(fs); selHistManager->hadTaus_ = new HadTauHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/hadTaus", histogramDir.data()), era_string, central_or_shift, "allHistograms")); selHistManager->hadTaus_->bookHistograms(fs); selHistManager->jetsAK4_ = new JetHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/jetsAK4", histogramDir.data()), era_string, central_or_shift, "allHistograms")); selHistManager->jetsAK4_->bookHistograms(fs); selHistManager->leadJetAK4_ = new JetHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/leadJetAK4", histogramDir.data()), era_string, central_or_shift, "minimalHistograms", 0)); selHistManager->leadJetAK4_->bookHistograms(fs); selHistManager->subleadJetAK4_ = new JetHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/subleadJetAK4", histogramDir.data()), era_string, central_or_shift, "minimalHistograms", 1)); selHistManager->subleadJetAK4_->bookHistograms(fs); selHistManager->jetsAK8_Wjj_ = new JetHistManagerAK8(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/jetsAK8_Wjj", histogramDir.data()), era_string, central_or_shift, "allHistograms")); selHistManager->jetsAK8_Wjj_->bookHistograms(fs); selHistManager->BJetsAK4_loose_ = new JetHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/BJetsAK4_loose", histogramDir.data()), era_string, central_or_shift, "allHistograms")); selHistManager->BJetsAK4_loose_->bookHistograms(fs); selHistManager->leadBJetAK4_loose_ = new JetHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/leadBJetAK4_loose", histogramDir.data()), era_string, central_or_shift, "minimalHistograms", 0)); selHistManager->leadBJetAK4_loose_->bookHistograms(fs); selHistManager->subleadBJetAK4_loose_ = new JetHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/subleadBJetAK4_loose", histogramDir.data()), era_string, central_or_shift, "minimalHistograms", 1)); selHistManager->subleadBJetAK4_loose_->bookHistograms(fs); selHistManager->BJetsAK4_medium_ = new JetHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/BJetsAK4_medium", histogramDir.data()), era_string, central_or_shift, "allHistograms")); selHistManager->BJetsAK4_medium_->bookHistograms(fs); selHistManager->met_ = new MEtHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/met", histogramDir.data()), era_string, central_or_shift)); selHistManager->met_->bookHistograms(fs); selHistManager->metFilters_ = new MEtFilterHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/metFilters", histogramDir.data()), era_string, central_or_shift)); selHistManager->metFilters_->bookHistograms(fs); } for(const std::string & evt_cat_str: evt_cat_strs) { std::cout << "\t evt_cat_str: " << evt_cat_str << std::endl; if(skipBooking && evt_cat_str != default_cat_str) { continue; } const std::string process_string_new = evt_cat_str == default_cat_str ? process_string : process_string + evt_cat_str ; const std::string process_and_genMatchName = boost::replace_all_copy( process_and_genMatch, process_string, process_string_new ); std::cout << "\t evt_cat_str: " << evt_cat_str << "\t process_string_new: " << process_string_new << ", process_and_genMatchName: " << process_and_genMatchName << std::endl; selHistManager->evt_[evt_cat_str] = new EvtHistManager_hh_3l(makeHistManager_cfg(process_and_genMatchName, Form("%s/sel/evt", histogramDir.data()), era_string, central_or_shift)); selHistManager->evt_[evt_cat_str]->bookHistograms(fs); } // additional histograms //book1D(dir, "numElectrons", "numElectrons", 5, -0.5, +4.5); for(const std::string & category: categories_evt) { std::cout << "\t category: " << category << std::endl; TString histogramDir_category = histogramDir.data(); histogramDir_category.ReplaceAll("hh_3l", Form("%s", category.data())); for(const std::string & evt_cat_str: evt_cat_strs) { if(skipBooking && evt_cat_str != default_cat_str) { continue; } const std::string process_string_new = evt_cat_str == default_cat_str ? process_string : process_string + evt_cat_str ; const std::string process_and_genMatchName = boost::replace_all_copy( process_and_genMatch, process_string, process_string_new ); std::cout << "\t\t evt_cat_str: " << evt_cat_str << "\t process_string_new: " << process_string_new << ", process_and_genMatchName: " << process_and_genMatchName << std::endl; selHistManager->evt_in_categories_[evt_cat_str][category] = new EvtHistManager_hh_3l(makeHistManager_cfg(process_and_genMatchName, Form("%s/sel/evt", histogramDir_category.Data()), era_string, central_or_shift)); selHistManager->evt_in_categories_[evt_cat_str][category]->bookHistograms(fs); } } const vstring decayModes_evt = eventInfo.getDiHiggsDecayModes(); if(isSignal && !skipHHDecayModeHistograms) { for(const std::string & decayMode_evt: decayModes_evt) { std::string decayMode_and_genMatch = process_string; decayMode_and_genMatch += ("_DecayMode_" + decayMode_evt); decayMode_and_genMatch += genMatchDefinition->getName(); std::cout << "\t decayMode_evt: " << decayMode_evt << ", decayMode_and_genMatch: " << decayMode_and_genMatch << std::endl; for(const std::string & evt_cat_str: evt_cat_strs) { if(skipBooking && evt_cat_str != default_cat_str) { continue; } const std::string process_string_new = evt_cat_str == default_cat_str ? process_string: process_string + "_" + evt_cat_str ; const std::string decayMode_and_genMatchName = boost::replace_all_copy( decayMode_and_genMatch, process_string, process_string_new ); std::cout << "\t\t evt_cat_str: " << evt_cat_str << "\t process_string_new: " << process_string_new << ", decayMode_and_genMatchName: " << decayMode_and_genMatchName << std::endl; selHistManager -> evt_in_decayModes_[evt_cat_str][decayMode_evt] = new EvtHistManager_hh_3l(makeHistManager_cfg( decayMode_and_genMatchName, Form("%s/sel/evt", histogramDir.data()), era_string, central_or_shift )); selHistManager -> evt_in_decayModes_[evt_cat_str][decayMode_evt] -> bookHistograms(fs); for(const std::string & category: categories_evt) { TString histogramDir_category = histogramDir.data(); histogramDir_category.ReplaceAll("hh_3l", Form("%s", category.data())); selHistManager -> evt_in_categories_and_decayModes_[evt_cat_str][category][decayMode_evt] = new EvtHistManager_hh_3l(makeHistManager_cfg( decayMode_and_genMatchName, Form("%s/sel/evt", histogramDir_category.Data()), era_string, central_or_shift )); selHistManager -> evt_in_categories_and_decayModes_[evt_cat_str][category][decayMode_evt] -> bookHistograms(fs); } } } } if(! skipBooking) { edm::ParameterSet cfg_EvtYieldHistManager_sel = makeHistManager_cfg(process_and_genMatch, Form("%s/sel/evtYield", histogramDir.data()), era_string, central_or_shift); cfg_EvtYieldHistManager_sel.addParameter<edm::ParameterSet>("runPeriods", cfg_EvtYieldHistManager); cfg_EvtYieldHistManager_sel.addParameter<bool>("isMC", isMC); selHistManager->evtYield_ = new EvtYieldHistManager(cfg_EvtYieldHistManager_sel); selHistManager->evtYield_->bookHistograms(fs); selHistManager->weights_ = new WeightHistManager(makeHistManager_cfg(process_and_genMatch, Form("%s/sel/weights", histogramDir.data()), era_string, central_or_shift)); selHistManager->weights_->bookHistograms(fs, { "genWeight", "pileupWeight", "triggerWeight", "data_to_MC_correction", "fakeRate" }); } selHistManagers[central_or_shift][idxLepton] = selHistManager; // additional histograms if (central_or_shift == central_or_shift_main) { //TFileDirectory subD1 = fs.mkdir(Form("%s/sel/evt/%s", histogramDir.data(),process_string.data())); //TFileDirectory subD1 = fs.mkdir(Form("%s/sel/evt/%s", histogramDir.data(),process_and_genMatch.data())); TFileDirectory subD1 = fs.mkdir(Form("%s/sel/study/%s", histogramDir.data(),process_and_genMatch.data())); hMEt_All_0[idxLepton] = subD1.make<TH1D>("hMEt_All_0", "hMEt_All_0", 200, 0.,500.); hHt_All_0[idxLepton] = subD1.make<TH1D>("hHt_All_0", "hHt_All_0", 200, 0.,500.); hMEt_LD_All_0[idxLepton] = subD1.make<TH1D>("hMEt_LD_All_0", "hMEt_LD_All_0", 200, 0.,500.); hHT_All_0[idxLepton] = subD1.make<TH1D>("hHT_All_0", "hHT_All_0", 200, 0.,1000.); hSTMET_All_0[idxLepton] = subD1.make<TH1D>("hSTMET_All_0", "hSTMET_All_0", 200, 0.,1000.); // hMEt_SFOS_0[idxLepton] = subD1.make<TH1D>("hMEt_SFOS_0", "hMEt_SFOS_0", 200, 0.,500.); hHt_SFOS_0[idxLepton] = subD1.make<TH1D>("hHt_SFOS_0", "hHt_SFOS_0", 200, 0.,500.); hMEt_LD_SFOS_0[idxLepton] = subD1.make<TH1D>("hMEt_LD_SFOS_0", "hMEt_LD_SFOS_0", 200, 0.,500.); hHT_SFOS_0[idxLepton] = subD1.make<TH1D>("hHT_SFOS_0", "hHT_SFOS_0", 200, 0.,1000.); hSTMET_SFOS_0[idxLepton] = subD1.make<TH1D>("hSTMET_SFOS_0", "hSTMET_SFOS_0", 200, 0.,1000.); // hMEt_All_1[idxLepton] = subD1.make<TH1D>("hMEt_All_1", "hMEt_All_1", 200, 0.,500.); hHt_All_1[idxLepton] = subD1.make<TH1D>("hHt_All_1", "hHt_All_1", 200, 0.,500.); hMEt_LD_All_1[idxLepton] = subD1.make<TH1D>("hMEt_LD_All_1", "hMEt_LD_All_1", 200, 0.,500.); hHT_All_1[idxLepton] = subD1.make<TH1D>("hHT_All_1", "hHT_All_1", 200, 0.,1000.); hSTMET_All_1[idxLepton] = subD1.make<TH1D>("hSTMET_All_1", "hSTMET_All_1", 200, 0.,1000.); // hMEt_SFOS_1[idxLepton] = subD1.make<TH1D>("hMEt_SFOS_1", "hMEt_SFOS_1", 200, 0.,500.); hHt_SFOS_1[idxLepton] = subD1.make<TH1D>("hHt_SFOS_1", "hHt_SFOS_1", 200, 0.,500.); hMEt_LD_SFOS_1[idxLepton] = subD1.make<TH1D>("hMEt_LD_SFOS_1", "hMEt_LD_SFOS_1", 200, 0.,500.); hHT_SFOS_1[idxLepton] = subD1.make<TH1D>("hHT_SFOS_1", "hHT_SFOS_1", 200, 0.,1000.); hSTMET_SFOS_1[idxLepton] = subD1.make<TH1D>("hSTMET_SFOS_1", "hSTMET_SFOS_1", 200, 0.,1000.); // hm_2lpreselUnclean_0[idxLepton] = subD1.make<TH1D>("hm_2lpreselUnclean_0", "hm_2lpreselUnclean_0", 200, 0.,200.); hm_2lpreselUnclean_1[idxLepton] = subD1.make<TH1D>("hm_2lpreselUnclean_1", "hm_2lpreselUnclean_1", 200, 0.,200.); hm_SFOS2lpresel_0[idxLepton] = subD1.make<TH1D>("hm_SFOS2lpresel_0", "hm_SFOS2lpresel_0", 200, 0.,200.); hm_SFOS2lpresel_1[idxLepton] = subD1.make<TH1D>("hm_SFOS2lpresel_1", "hm_SFOS2lpresel_1", 200, 0.,200.); hm_SFOS4lpresel_0[idxLepton] = subD1.make<TH1D>("hm_SFOS4lpresel_0", "hm_SFOS4lpresel_0", 200, 0.,500.); hm_SFOS4lpresel_1[idxLepton] = subD1.make<TH1D>("hm_SFOS4lpresel_1", "hm_SFOS4lpresel_1", 200, 0.,500.); // gen-level histograms hdrmin_H_WW_gen[idxLepton] = subD1.make<TH1D>("hdrmin_H_WW_gen", "hdrmin_H_WW_gen", 200, 0.,5.); hdmmin_H_WW_gen[idxLepton] = subD1.make<TH1D>("hdmmin_H_WW_gen", "hdmmin_H_WW_gen", 200, 0.,20.); hdrmin_W_qq_gen[idxLepton] = subD1.make<TH1D>("hdrmin_W_qq_gen", "hdrmin_W_qq_gen", 200, 0.,5.); hdmmin_W_qq_gen[idxLepton] = subD1.make<TH1D>("hdmmin_W_qq_gen", "hdmmin_W_qq_gen", 200, 0.,20.); hdrmin_W_lnu_gen[idxLepton] = subD1.make<TH1D>("hdrmin_W_lnu_gen", "hdrmin_W_lnu_gen",200, 0.,5.); hdmmin_W_lnu_gen[idxLepton] = subD1.make<TH1D>("hdmmin_W_lnu_gen", "hdmmin_W_lnu_gen",200, 0.,20.); // hptGenWjj_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hptGenWjj_HHTo4W_3l_1qq", "hptGenWjj_HHTo4W_3l_1qq", 200, 0., 1000); hptGenWjet1_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hptGenWjet1_HHTo4W_3l_1qq", "hptGenWjet1_HHTo4W_3l_1qq", 200, 0., 1000); hptGenWjet2_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hptGenWjet2_HHTo4W_3l_1qq", "hptGenWjet2_HHTo4W_3l_1qq", 200, 0., 1000); hptGenLep3_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hptGenLep3_HHTo4W_3l_1qq", "hptGenLep3_HHTo4W_3l_1qq", 200, 0., 1000); hptGenLep1_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hptGenLep1_HHTo4W_3l_1qq", "hptGenLep1_HHTo4W_3l_1qq", 200, 0., 1000); hptGenLep2_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hptGenLep2_HHTo4W_3l_1qq", "hptGenLep2_HHTo4W_3l_1qq", 200, 0., 1000.); hptGenLepLead_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hptGenLepLead_HHTo4W_3l_1qq", "hptGenLepLead_HHTo4W_3l_1qq", 200, 0., 1000.); hptGenLepSublead_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hptGenLepSublead_HHTo4W_3l_1qq", "hptGenLepSublead_HHTo4W_3l_1qq", 200, 0., 1000.); hptGenLepSubsublead_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hptGenLepSubsublead_HHTo4W_3l_1qq", "hptGenLepSubsublead_HHTo4W_3l_1qq", 200, 0., 1000.); // hetaGenWjj_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hetaGenWjj_HHTo4W_3l_1qq", "hetaGenWjj_HHTo4W_3l_1qq", 200, -5, 5.); hetaGenWjet1_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hetaGenWjet1_HHTo4W_3l_1qq", "hetaGenWjet1_HHTo4W_3l_1qq", 200, -5, 5.); hetaGenWjet2_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hetaGenWjet2_HHTo4W_3l_1qq", "hetaGenWjet2_HHTo4W_3l_1qq", 200, -5, 5.); hetaGenLep3_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hetaGenLep3_HHTo4W_3l_1qq", "hetaGenLep3_HHTo4W_3l_1qq", 200, -5, 5.); hetaGenLep1_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hetaGenLep1_HHTo4W_3l_1qq", "hetaGenLep1_HHTo4W_3l_1qq", 200, -5, 5.); hetaGenLep2_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hetaGenLep2_HHTo4W_3l_1qq", "hetaGenLep2_HHTo4W_3l_1qq", 200, -5, 5.); // hdr_GenWj1j2_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hdr_GenWj1j2_HHTo4W_3l_1qq", "hdr_GenWj1j2_HHTo4W_3l_1qq", 200, 0., 10.); hdr_GenLep3_Wjj_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hdr_GenLep3_Wjj_HHTo4W_3l_1qq", "hdr_GenLep3_Wjet1_HHTo4W_3l_1qq", 200, 0., 10.); hdr_GenLep3_Wjet1_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hdr_GenLep3_Wjet1_HHTo4W_3l_1qq", "hdr_GenLep3_Wjet1_HHTo4W_3l_1qq", 200, 0., 10.); hdr_GenLep3_Wjet2_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hdr_GenLep3_Wjet2_HHTo4W_3l_1qq", "hdr_GenLep3_Wjet2_HHTo4W_3l_1qq", 200, 0., 10.); hdr_GenLep3_WjetNear_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hdr_GenLep3_WjetNear_HHTo4W_3l_1qq", "hdr_GenLep3_WjetNear_HHTo4W_3l_1qq", 200, 0., 10.); hdr_GenLep3_WjetFar_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH1D>("hdr_GenLep3_WjetFar_HHTo4W_3l_1qq", "hdr_GenLep3_WjetFar_HHTo4W_3l_1qq", 200, 0., 10.); // hdr_GenWj1j2_vs_ptGenWjj_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH2D>("hdr_GenWj1j2_vs_ptGenWjj_HHTo4W_3l_1qq", "hdr_GenWj1j2_vs_ptGenWjj_HHTo4W_3l_1qq", 200, 0., 1000., 200, 0., 10.); hdr_GenLep3_Wjj_vs_ptWjj_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH2D>("hdr_GenLep3_Wjj_vs_ptWjj_HHTo4W_3l_1qq", "hdr_GenLep3_Wjj_vs_ptWjj_HHTo4W_3l_1qq", 200, 0., 1000., 200, 0., 10.); hdr_GenLep3_Wjet1_vs_ptWjj_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH2D>("hdr_GenLep3_Wjet1_vs_ptWjj_HHTo4W_3l_1qq", "hdr_GenLep3_Wjet1_vs_ptWjj_HHTo4W_3l_1qq", 200, 0., 1000., 200, 0., 10.); hdr_GenLep3_Wjet2_vs_ptWjj_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH2D>("hdr_GenLep3_Wjet2_vs_ptWjj_HHTo4W_3l_1qq", "hdr_GenLep3_Wjet2_vs_ptWjj_HHTo4W_3l_1qq", 200, 0., 1000., 200, 0., 10.); hdr_GenLep3_WjetNear_vs_ptWjj_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH2D>("hdr_GenLep3_WjetNear_vs_ptWjj_HHTo4W_3l_1qq", "hdr_GenLep3_WjetNear_vs_ptWjj_HHTo4W_3l_1qq", 200, 0., 1000., 200, 0., 10.); hdr_GenLep3_WjetFar_vs_ptWjj_HHTo4W_3l_1qq[idxLepton] = subD1.make<TH2D>("hdr_GenLep3_WjetFar_vs_ptWjj_HHTo4W_3l_1qq", "hdr_GenLep3_WjetFar_vs_ptWjj_HHTo4W_3l_1qq", 200, 0., 1000., 200, 0., 10.); hptResolution_preselLeptonsFull_Ele[idxLepton] = subD1.make<TH1D>("hptResolution_preselLeptonsFull_Ele", "hptResolution_preselLeptonsFull_Ele", 200, -0.5, 0.5); hptResolution_preselLeptonsFull_Mu[idxLepton] = subD1.make<TH1D>("hptResolution_preselLeptonsFull_Mu", "hptResolution_preselLeptonsFull_Mu", 200, -0.5, 0.5); hptResolution_preselLeptonsFull_GenMatchHHTo4WLeps_Ele[idxLepton] = subD1.make<TH1D>("hptResolution_preselLeptonsFull_GenMatchHHTo4WLeps_Ele", "hptResolution_preselLeptonsFull_GenMatchHHTo4WLeps_Ele", 200, -0.5, 0.5); hptResolution_preselLeptonsFull_GenMatchHHTo4WLeps_Mu[idxLepton] = subD1.make<TH1D>("hptResolution_preselLeptonsFull_GenMatchHHTo4WLeps_Mu", "hptResolution_preselLeptonsFull_GenMatchHHTo4WLeps_Mu", 200, -0.5, 0.5); // hptResolution_fakeableLeptonsFull_Ele[idxLepton] = subD1.make<TH1D>("hptResolution_fakeableLeptonsFull_Ele", "hptResolution_fakeableLeptonsFull_Ele", 200, -0.5, 0.5); hptResolution_fakeableLeptonsFull_Mu[idxLepton] = subD1.make<TH1D>("hptResolution_fakeableLeptonsFull_Mu", "hptResolution_fakeableLeptonsFull_Mu", 200, -0.5, 0.5); hptResolution_fakeableLeptonsFull_GenMatchHHTo4WLeps_Ele[idxLepton] = subD1.make<TH1D>("hptResolution_fakeableLeptonsFull_GenMatchHHTo4WLeps_Ele","hptResolution_fakeableLeptonsFull_GenMatchHHTo4WLeps_Ele", 200, -0.5, 0.5); hptResolution_fakeableLeptonsFull_GenMatchHHTo4WLeps_Mu[idxLepton] = subD1.make<TH1D>("hptResolution_fakeableLeptonsFull_GenMatchHHTo4WLeps_Mu", "hptResolution_fakeableLeptonsFull_GenMatchHHTo4WLeps_Mu", 200, -0.5, 0.5); // hptResolution_tightLeptonsFull_Ele[idxLepton] = subD1.make<TH1D>("hptResolution_tightLeptonsFull_Ele", "hptResolution_tightLeptonsFull_Ele", 200, -0.5, 0.5); hptResolution_tightLeptonsFull_Mu[idxLepton] = subD1.make<TH1D>("hptResolution_tightLeptonsFull_Mu", "hptResolution_tightLeptonsFull_Mu", 200, -0.5, 0.5); hptResolution_tightLeptonsFull_GenMatchHHTo4WLeps_Ele[idxLepton] = subD1.make<TH1D>("hptResolution_tightLeptonsFull_GenMatchHHTo4WLeps_Ele", "hptResolution_tightLeptonsFull_GenMatchHHTo4WLeps_Ele", 200, -0.5, 0.5); hptResolution_tightLeptonsFull_GenMatchHHTo4WLeps_Mu[idxLepton] = subD1.make<TH1D>("hptResolution_tightLeptonsFull_GenMatchHHTo4WLeps_Mu", "hptResolution_tightLeptonsFull_GenMatchHHTo4WLeps_Mu", 200, -0.5, 0.5); // hptResolution_AK4[idxLepton] = subD1.make<TH1D>("hptResolution_AK4", "hptResolution_AK4", 200, -1, 1); hptResolution_AK4_GenMatchHHTo4WJets[idxLepton] = subD1.make<TH1D>("hptResolution_AK4_GenMatchHHTo4WJets", "hptResolution_AK4_GenMatchHHTo4WJets", 200, -1, 1); hptResolution_AK8subjet_GenMatchHHTo4WJets[idxLepton] = subD1.make<TH1D>("hptResolution_AK8subjet_GenMatchHHTo4WJets", "hptResolution_AK8subjet_GenMatchHHTo4WJets", 200, -1, 1); // hptResolutionAK4_AK8Overlap[idxLepton] = subD1.make<TH1D>("hptResolutionAK4_AK8Overlap", "hptResolutionAK4_AK8Overlap", 200, -2, 2); hmassResolutionAK4_AK8Overlap[idxLepton] = subD1.make<TH1D>("hmassResolutionAK4_AK8Overlap", "hmassResolutionAK4_AK8Overlap", 200, -30, 30); hptResolutionAK8_AK4Overlap[idxLepton] = subD1.make<TH1D>("hptResolutionAK8_AK4Overlap", "hptResolutionAK8_AK4Overlap", 200, -2, 2); hmassResolutionAK8_AK4Overlap[idxLepton] = subD1.make<TH1D>("hmassResolutionAK8_AK4Overlap", "hmassResolutionAK8_AK4Overlap", 200, -30, 30); hptResolutionAK4_vs_ptGen_AK8Overlap[idxLepton] = subD1.make<TH2D>("hptResolutionAK4_vs_ptGen_AK8Overlap", "hptResolutionAK4_vs_ptGen_AK8Overlap", 200, 0., 1000., 200, -100, 100); hmassResolutionAK4_vs_ptGen_AK8Overlap[idxLepton] = subD1.make<TH2D>("hmassResolutionAK4_vs_ptGen_AK8Overlap", "hmassResolutionAK4_vs_ptGen_AK8Overlap", 200, 0., 1000., 200, -100, 100); hptResolutionAK8_vs_ptGen_AK4Overlap[idxLepton] = subD1.make<TH2D>("hptResolutionAK8_vs_ptGen_AK4Overlap", "hptResolutionAK8_vs_ptGen_AK4Overlap", 200, 0., 1000., 200, -100, 100); hmassResolutionAK8_vs_ptGen_AK4Overlap[idxLepton] = subD1.make<TH2D>("hmassResolutionAK8_vs_ptGen_AK4Overlap", "hmassResolutionAK8_vs_ptGen_AK4Overlap", 200, 0., 1000., 200, -100, 100); hmass_jj_AK4_AK8Overlap[idxLepton] = subD1.make<TH1D>("hmass_jj_AK4_AK8Overlap", "hmass_jj_AK4_AK8Overlap", 200, 0, 200); hmass_jj_AK8_AK4Overlap[idxLepton] = subD1.make<TH1D>("hmass_jj_AK8_AK4Overlap", "hmass_jj_AK8_AK4Overlap", 200, 0, 200); hmass_Genjj_AK8_AK4Overlap[idxLepton] = subD1.make<TH1D>("hmass_Genjj_AK8_AK4Overlap", "hmass_Genjj_AK8_AK4Overlap", 200, 0, 200); hmassResolutionAK4_AK8Overlap_0[idxLepton] = subD1.make<TH1D>("hmassResolutionAK4_AK8Overlap_0", "hmassResolutionAK4_AK8Overlap_0", 200, -2, 2); hmassResolutionAK8_AK4Overlap_0[idxLepton] = subD1.make<TH1D>("hmassResolutionAK8_AK4Overlap_0", "hmassResolutionAK8_AK4Overlap_0", 200, -2, 2); hmassResolutionAK4_0_vs_ptWGen_AK8Overlap[idxLepton] = subD1.make<TH2D>("hmassResolutionAK4_0_vs_ptWGen_AK8Overlap", "hmassResolutionAK4_0_vs_ptWGen_AK8Overlap", 200, 0., 1000., 200, -2, 2); hmassResolutionAK8_0_vs_ptWGen_AK4Overlap[idxLepton] = subD1.make<TH2D>("hmassResolutionAK8_0_vs_ptWGen_AK4Overlap", "hmassResolutionAK8_0_vs_ptWGen_AK4Overlap", 200, 0., 1000., 200, -2, 2); } } if(isMC && ! skipBooking) { genEvtHistManager_beforeCuts[central_or_shift] = new GenEvtHistManager(makeHistManager_cfg(process_string, Form("%s/unbiased/genEvt", histogramDir.data()), era_string, central_or_shift)); genEvtHistManager_beforeCuts[central_or_shift]->bookHistograms(fs); genEvtHistManager_afterCuts[central_or_shift] = new GenEvtHistManager(makeHistManager_cfg(process_string, Form("%s/sel/genEvt", histogramDir.data()), era_string, central_or_shift)); genEvtHistManager_afterCuts[central_or_shift]->bookHistograms(fs); lheInfoHistManager[central_or_shift] = new LHEInfoHistManager(makeHistManager_cfg(process_string, Form("%s/sel/lheInfo", histogramDir.data()), era_string, central_or_shift)); lheInfoHistManager[central_or_shift]->bookHistograms(fs); if(eventWeightManager) { genEvtHistManager_beforeCuts[central_or_shift]->bookHistograms(fs, eventWeightManager); genEvtHistManager_afterCuts[central_or_shift]->bookHistograms(fs, eventWeightManager); } } } NtupleFillerBDT<float, int> * bdt_filler = nullptr; typedef std::remove_pointer<decltype(bdt_filler)>::type::float_type float_type; typedef std::remove_pointer<decltype(bdt_filler)>::type::int_type int_type; if ( selectBDT ) { bdt_filler = new std::remove_pointer<decltype(bdt_filler)>::type( makeHistManager_cfg(process_string, Form("%s/sel/evtntuple", histogramDir.data()), era_string, central_or_shift_main) ); bdt_filler -> register_variable<float_type>( "lep1_pt", "lep1_conePt", "lep1_eta", "lep1_tth_mva", "mindr_lep1_jet", "mT_lep1", "lep2_pt", "lep2_conePt", "lep2_eta", "lep2_tth_mva", "mindr_lep2_jet", "mT_lep2", "lep3_pt", "lep3_conePt", "lep3_eta", "lep3_tth_mva", "mindr_lep3_jet", "mT_lep3", "avg_dr_jet", "ptmiss", "htmiss", "dr_leps", "lumiScale", "genWeight", "evtWeight", "lep1_genLepPt", "lep2_genLepPt", "lep3_genLepPt", "lep1_fake_prob", "lep2_fake_prob", "lep3_fake_prob", "lep1_frWeight", "lep2_frWeight", "lep3_frWeight", //"mvaOutput_3l_ttV", "mvaOutput_3l_ttbar", "mvaDiscr_3l", "mbb_loose", "mbb_medium", "dr_lss", "dr_los1", "dr_los2", "met", "mht", "met_LD", "HT", "STMET", "mSFOS2l", "m_jj", "diHiggsVisMass", "diHiggsMass", "mTMetLepton1", "mTMetLepton2", "vbf_m_jj", "vbf_dEta_jj", "numSelJets_nonVBF", "numAK4jets", "numAK8jets", "jet1_pt", "jet2_pt", "jet1_m", "jet2_m", "dr_WjetsLep3", "dr_Wjet1Lep3", "dr_Wjet2Lep3" ); bdt_filler -> register_variable<int_type>( "nJet", "nBJetLoose", "nBJetMedium", "nElectron", "nMuon", "lep1_isTight", "lep2_isTight", "lep3_isTight", "sumLeptonCharge", "numSameFlavor_OS", "isVBF", "isWjjBoosted","eventCategory" ); bdt_filler -> bookTree(fs); } int analyzedEntries = 0; int selectedEntries = 0; double selectedEntries_weighted = 0.; std::map<std::string, int> selectedEntries_byGenMatchType; // key = process_and_genMatch std::map<std::string, std::map<std::string, double>> selectedEntries_weighted_byGenMatchType; // key = process_and_genMatch std::map<std::string, int> selectedEntries_byDecayModeType; // key = decayMode_and_genMatch std::map<std::string, std::map<std::string, double>> selectedEntries_weighted_byDecayModeType; // key = decayMode_and_genMatch TH1* histogram_analyzedEntries = fs.make<TH1D>("analyzedEntries", "analyzedEntries", 1, -0.5, +0.5); TH1* histogram_selectedEntries = fs.make<TH1D>("selectedEntries", "selectedEntries", 1, -0.5, +0.5); cutFlowTableType cutFlowTable; const edm::ParameterSet cutFlowTableCfg = makeHistManager_cfg( process_string, Form("%s/sel/cutFlow", histogramDir.data()), era_string, central_or_shift_main ); const std::vector<std::string> cuts = { "run:ls:event selection", "object multiplicity", "trigger", ">= 3 presel leptons", "presel lepton trigger match", ">= N jets", "b-jet veto", "3 sel leptons", "fakeable lepton trigger match", "HLT filter matching", "sel tau veto", "m(ll) > 12 GeV", "lead lepton pT > 25 GeV && sublead lepton pT > 15 GeV && third lepton pT > 10 GeV", "sel lepton charge", "Z-boson mass veto", "H->ZZ*->4l veto", "met LD", "MEt filters", "signal region veto", }; CutFlowTableHistManager * cutFlowHistManager = new CutFlowTableHistManager(cutFlowTableCfg, cuts); cutFlowHistManager->bookHistograms(fs); int knMuPassJetBtagMedium = 0; int knMuPassFakeablePromptMva = 0; int knMuFailFakeablePromptMva = 0; while(inputTree -> hasNextEvent() && (! run_lumi_eventSelector || (run_lumi_eventSelector && ! run_lumi_eventSelector -> areWeDone()))) { if(inputTree -> canReport(reportEvery) /*|| printLevel > 2*/) { std::cout << "processing Entry " << inputTree -> getCurrentMaxEventIdx() << " or " << inputTree -> getCurrentEventIdx() << " entry in #" << (inputTree -> getProcessedFileCount() - 1) << " (" << eventInfo << ") file (" << selectedEntries << " Entries selected)\n"; } ++analyzedEntries; histogram_analyzedEntries->Fill(0.); if (run_lumi_eventSelector && !(*run_lumi_eventSelector)(eventInfo)) { continue; } EvtWeightRecorderHH evtWeightRecorder(central_or_shifts_local, central_or_shift_main, isMC); cutFlowTable.update("run:ls:event selection", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("run:ls:event selection", evtWeightRecorder.get(central_or_shift_main)); if(inputTree -> canReport(reportEvery) || printLevel > 2) { std::cout << "\n\nprocessing Entry " << inputTree -> getCurrentMaxEventIdx() << " or " << inputTree -> getCurrentEventIdx() << " entry in #" << (inputTree -> getProcessedFileCount() - 1) << " (" << eventInfo << ") file (" << selectedEntries << " Entries selected)" << std::endl; } if ( isDEBUG ) { std::cout << "event #" << inputTree -> getCurrentMaxEventIdx() << ' ' << eventInfo << '\n'; } if(run_lumi_eventSelector) { std::cout << "processing Entry " << inputTree -> getCurrentMaxEventIdx() << ": " << eventInfo << '\n'; if(inputTree -> isOpen()) { std::cout << "input File = " << inputTree -> getCurrentFileName() << '\n'; } } if(useObjectMultiplicity) { if(objectMultiplicity.getNRecoLepton(minLeptonSelection) < 3 || objectMultiplicity.getNRecoLepton(kTight) > 3 ) { if(isDEBUG || run_lumi_eventSelector) { std::cout << "event " << eventInfo.str() << " FAILS preliminary object multiplicity cuts\n"; } continue; } } cutFlowTable.update("object multiplicity", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("object multiplicity", evtWeightRecorder.get(central_or_shift_main)); int genMatchIdx_0 = 2; // 0: fakes, 1: Convs, 2: non-fakes //--- build collections of generator level particles (before any cuts are applied, to check distributions in unbiased event samples) std::vector<GenLepton> genLeptons; std::vector<GenLepton> genElectrons; std::vector<GenLepton> genMuons; std::vector<GenHadTau> genHadTaus; std::vector<GenPhoton> genPhotons; std::vector<GenJet> genJets; std::vector<GenParticle> genNeutrinos; std::vector<GenParticle> genHiggses; std::vector<GenParticle> muonGenMatch; std::vector<GenParticle> electronGenMatch; std::vector<GenParticle> hadTauGenMatch; std::vector<GenParticle> jetGenMatch; if(isMC && fillGenEvtHistograms) { if(genLeptonReader) { genLeptons = genLeptonReader->read(); for(const GenLepton & genLepton: genLeptons) { const int abs_pdgId = std::abs(genLepton.pdgId()); switch(abs_pdgId) { case 11: genElectrons.push_back(genLepton); break; case 13: genMuons.push_back(genLepton); break; default: assert(0); } } } if(genHadTauReader) genHadTaus = genHadTauReader->read(); if(genPhotonReader) genPhotons = genPhotonReader->read(); if(genJetReader) genJets = genJetReader->read(); if(genHiggsReader) genHiggses = genHiggsReader->read(); if(genNeutrinoReader) genNeutrinos = genNeutrinoReader->read(); if(genMatchToMuonReader) muonGenMatch = genMatchToMuonReader->read(); if(genMatchToElectronReader) electronGenMatch = genMatchToElectronReader->read(); if(genMatchToHadTauReader) hadTauGenMatch = genMatchToHadTauReader->read(); if(genMatchToJetReader) jetGenMatch = genMatchToJetReader->read(); if(isDEBUG) { printCollection("genLeptons", genLeptons); printCollection("genHadTaus", genHadTaus); printCollection("genPhotons", genPhotons); printCollection("genJets", genJets); printCollection("genHiggses", genHiggses); } } std::vector<GenParticle> genWBosons; std::vector<GenParticle> genWJets; if ( isMC ) { genWBosons = genWBosonReader->read(); genWJets = genWJetReader->read(); } if ( isDEBUG ) { dumpGenParticles("genWBoson", genWBosons); dumpGenParticles("genWJet", genWJets); } if (isMC) { if (printLevel > 7) { std::cout << "Print Generator level particle collection: " << std::endl; if (genLeptons.size()>0) printCollection("genLeptons", genLeptons); if (genElectrons.size()>0) printCollection("genElectrons", genElectrons); if (genMuons.size()>0) printCollection("genMuons", genMuons); if (genHadTaus.size()>0) printCollection("genHadTaus", genHadTaus); if (genNeutrinos.size()>0) printCollection("genNeutrinos", genNeutrinos); if (genPhotons.size()>0) printCollection("genPhotons", genPhotons); if (genJets.size()>0) printCollection("genJets", genJets); if (genHiggses.size()>0) printCollection("genHiggses", genHiggses); if (genWBosons.size()>0) dumpGenParticles("genWBoson", genWBosons); if (genWJets.size()>0) dumpGenParticles("genWJet", genWJets); std::cout << "GenMatch collection::\n"; if (electronGenMatch.size()>0) printCollection("electronGenMatch", electronGenMatch); if (muonGenMatch.size()>0) printCollection("muonGenMatch", muonGenMatch); if (hadTauGenMatch.size()>0) printCollection("hadTauGenMatch", hadTauGenMatch); if (jetGenMatch.size()>0) printCollection("jetGenMatch", jetGenMatch); } if (printLevel > 5) printf("\nngenHiggs: %lu, ngenW: %lu, ngenLep: %lu, ngenNu: %lu, ngenJet: %lu, ngenWjets: %lu, \t\t ngenHadTaus: %lu \n\n\n", genHiggses.size(),genWBosons.size(),genLeptons.size(),genNeutrinos.size(),genJets.size(),genWJets.size(), genHadTaus.size()); } std::vector<GenParticle *> genHiggses_Copy1; std::vector<GenParticle *> genWBosons_Copy1; std::vector<GenParticle *> genWJets_Copy1; std::vector<GenParticle *> genLeptons_Copy1; std::vector<GenParticle *> genNeutrinos_Copy1; std::map<std::string, std::vector<GenParticle *>> genWFromHHTo4W; // <'iH0', {W0, W1}>, <'iH1', {W0, W1}> std::map<std::string, std::vector<GenParticle *>> genWDaughtersFromHHTo4W; // <'iH0_iW0', {WD0, WD1}>, <'iH0_iW1', {WD0, WD1}>, <'iH1_iW0', {WD0, WD1}>, <'iH1_iW1', {WD0, WD1}>, std::map<std::string, std::string> genWDecayModeFromHHTo4W; // <'iH0_iW0', 'WDecayMode_leptonic/hadronic'>, simillary for other 'iHx_iWy' std::string sWDecayMode_Leptonic = "WDecayMode_Leptonic"; std::string sWDecayMode_Hadronic = "WDecayMode_Hadronic"; int nGenWBosonInHHDecay = 0; int nGenZBosonInHHDecay = 0; int nGenWDecayLeptonic = 0; int nGenWDecayHadronic = 0; bool isGenEvtHHTo4W_4l_0qq = false; bool isGenEvtHHTo4W_3l_1qq = false; bool isGenEvtHHTo4W_2l_2qq = false; bool isGenEvtHHTo4W_1l_3qq = false; bool isGenEvtHHTo4W_0l_4qq = false; // Event HH->4W->3l3nu 2q GenParticle *genLeptonFromHToWW_lnu_qq = nullptr; GenParticle *genNutrinoFromHToWW_lnu_qq = nullptr; GenParticle *genJet1FromHToWW_lnu_qq = nullptr; GenParticle *genJet2FromHToWW_lnu_qq = nullptr; GenParticle *genLepton1FromHToWW_2l2nu = nullptr; GenParticle *genLepton2FromHToWW_2l2nu = nullptr; GenParticle *genNutrino1FromHToWW_2l2nu = nullptr; GenParticle *genNutrino2FromHToWW_2l2nu = nullptr; bool isGenEvtCatBoosted = false; bool isGenEvtCatResolved = false; int nGenMuFromHHTo4W = 0; int nGenEleFromHHTo4W = 0; bool isHHTo4WDecayParticlesWithInCMSGeoAcpt = false; bool isHHTo4WDecayParticlesWithInCMSRecoAcpt = false; const double CMSEtaMax_Jet = 2.4; const double CMSEtaMax_Lepton = 2.4; const double CMSEtaMax_Electron = 2.5; const double CMSEtaMax_Muon = 2.4; const double CMSEtaMax_Tauh = 2.3; const double ptWFatjetBoosted = 100.; const double ptWJetBoosted = 20.; std::map<std::string, std::vector<double>> ptThrshLeptons; ptThrshLeptons["ptThrsh_4l"] = std::vector<double> {25., 15., 15., 10.}; ptThrshLeptons["ptThrsh_3l"] = std::vector<double> {25., 15., 10.}; ptThrshLeptons["ptThrsh_2l"] = std::vector<double> {25., 15.}; ptThrshLeptons["ptThrsh_1l"] = std::vector<double> {30.}; const double ptThresholdJet = 25.; bool isHHTo4W_3lnu_1qq_GenStudy = false; if (isMC && isHHTo4W_3lnu_1qq_GenStudy) { // store GenParticles for events HH->4W -> 3l3nu 2q ----------- Approach-1 new ---------------- for (size_t iParticle=0; iParticle < genHiggses.size(); iParticle++) { genHiggses_Copy1.push_back(dynamic_cast<GenParticle*>(&genHiggses[iParticle])); } for (size_t iParticle=0; iParticle < genWBosons.size(); iParticle++) { genWBosons_Copy1.push_back(dynamic_cast<GenParticle*>(&genWBosons[iParticle])); } for (size_t iParticle=0; iParticle < genWJets.size(); iParticle++) { genWJets_Copy1.push_back(dynamic_cast<GenParticle*>(&genWJets[iParticle])); } for (size_t iParticle=0; iParticle < genLeptons.size(); iParticle++) { genLeptons_Copy1.push_back(dynamic_cast<GenParticle*>(&genLeptons[iParticle])); } for (size_t iParticle=0; iParticle < genNeutrinos.size(); iParticle++) { genNeutrinos_Copy1.push_back(dynamic_cast<GenParticle*>(&genNeutrinos[iParticle])); } if (printLevel > 5) { std::cout << "Print genParicles of interest: copy1: " << std::endl; dumpGenParticles("genHiggses_Copy1", genHiggses_Copy1); dumpGenParticles("genWBosons_Copy1", genWBosons_Copy1); dumpGenParticles("genWJets_Copy1", genWJets_Copy1); dumpGenParticles("genLeptons_Copy1", genLeptons_Copy1); dumpGenParticles("genNeutrinos_Copy1", genNeutrinos_Copy1); } const double dR_H_WW_max = 0.5; const double dm_H_WW_max = 2.0; const double dR_W_qq_max = 1.5; const double dm_W_qq_max = 4.0; const double dR_W_lnu_max = 1.5; const double dm_W_lnu_max = 4.0; for (size_t iGenH=0; iGenH < genHiggses_Copy1.size(); iGenH++) { GenParticle *genH = genHiggses_Copy1[iGenH]; double dr_min = 9999.; double dm_min = 9999.; size_t idxGenW1FronH = 9999; size_t idxGenW2FronH = 9999; GenParticle *genW1FromH = nullptr; GenParticle *genW2FromH = nullptr; if (printLevel > 5) dumpGenParticle("\ngenH",genH,iGenH); double dr_min_1 = 9999.; double dm_min_1 = 9999.; for (size_t iGenW1=0; iGenW1 < genWBosons_Copy1.size(); iGenW1++) { for (size_t iGenW2=iGenW1+1; iGenW2 < genWBosons_Copy1.size(); iGenW2++) { GenParticle *genW1 = genWBosons_Copy1[iGenW1]; GenParticle *genW2 = genWBosons_Copy1[iGenW2]; Particle::LorentzVector particleWW = genW1->p4() + genW2->p4(); double dr = deltaR(genH->p4(), particleWW); double dm = std::abs(genH->mass() - particleWW.mass()); //dumpGenParticle("genWBosons_Copy1",genW1,iGenW1); //dumpGenParticle("genWBosons_Copy1",genW2,iGenW2); //printf("\t\t\tdm: %f, dr: %f \n",dm,dr); if (dr < dR_H_WW_max && dr < dr_min && dm < dm_H_WW_max && dm < dm_min) { idxGenW1FronH = iGenW1; idxGenW2FronH = iGenW2; genW1FromH = genW1; genW2FromH = genW2; dr_min = dr; dm_min = dm; } if (dr < dr_min_1) { dr_min_1 = dr; } if (dm < dm_min_1) { dm_min_1 = dm; } } } hdrmin_H_WW_gen[genMatchIdx_0]->Fill(dr_min_1); hdmmin_H_WW_gen[genMatchIdx_0]->Fill(dm_min_1); //if (idxGenW1FronH < 9999 && idxGenW2FronH < 9999) { if (genW1FromH && genW2FromH) { std::string sIdxH = Form("iH%lu",iGenH); genWFromHHTo4W[sIdxH] = std::vector<GenParticle *> {genW1FromH, genW2FromH}; if (printLevel > 5) dumpGenParticle("\t Tagged genW1_FromH",genW1FromH,idxGenW1FronH); if (printLevel > 5) dumpGenParticle("\t Tagged genW2_FromH",genW2FromH,idxGenW2FronH); if (printLevel > 5) printf("\t Tagged WW: dMass: %f, dR: %f\n", std::abs(genH->mass() - (genW1FromH->p4() + genW2FromH->p4()).mass()), deltaR(genH->p4(), (genW1FromH->p4() + genW2FromH->p4()))); // erase the tagged W from the genW collection genWBosons_Copy1.erase(genWBosons_Copy1.begin() + idxGenW1FronH); // after erase all the higher index will decrease by 1 if (idxGenW1FronH > idxGenW2FronH) genWBosons_Copy1.erase(genWBosons_Copy1.begin() + idxGenW2FronH); else genWBosons_Copy1.erase(genWBosons_Copy1.begin() + idxGenW2FronH -1); } } if (printLevel > 5) std::cout << "genWFromHHTo4W.size: " << genWFromHHTo4W.size() << std::endl; cutFlowTable.update("gen HHTo4V ", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("gen HHTo4V ", evtWeightRecorder.get(central_or_shift_main)); // check HH-->4W events and not HH-->2W2Z or 4Z events const static int pdgid_Z = 23; const static int pdgid_W = 24; for (size_t iGenH=0; iGenH <genWFromHHTo4W.size(); iGenH++) { std::string sIdxH = Form("iH%lu",iGenH); std::vector<GenParticle *> genWs = genWFromHHTo4W[sIdxH]; for (size_t iW=0; iW < genWs.size(); iW++) { GenParticle *genW = genWs[iW]; if (std::abs(genW->pdgId()) == pdgid_W) nGenWBosonInHHDecay++; if (std::abs(genW->pdgId()) == pdgid_Z) nGenZBosonInHHDecay++; } } if (printLevel > 4) printf("HH-->4V: nV: nW: %i, nZ: %i\n",nGenWBosonInHHDecay,nGenZBosonInHHDecay); cutFlowTable.update(Form("gen HH --> %iW%iZ event",nGenWBosonInHHDecay,nGenZBosonInHHDecay), evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms(Form("gen HH --> %iW%iZ event",nGenWBosonInHHDecay,nGenZBosonInHHDecay), evtWeightRecorder.get(central_or_shift_main)); // select HH --> 4W $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ if ( !(nGenWBosonInHHDecay == 4)) continue; for (size_t iGenH=0; iGenH <genWFromHHTo4W.size(); iGenH++) { // iterate over number of Higgs std::string sIdxH = Form("iH%lu",iGenH); std::vector<GenParticle *> genWsFromH = genWFromHHTo4W[sIdxH]; if (printLevel > 5) dumpGenParticle("\n\ngenHiggses_Copy1",genHiggses_Copy1[iGenH],iGenH); for (size_t iW=0; iW < genWsFromH.size(); iW++) { std::string sIdxH_IdxW = Form("iH%lu_iW%lu",iGenH,iW); GenParticle *genW = genWsFromH[iW]; GenParticle *genWDaughter1 = nullptr; GenParticle *genWDaughter2 = nullptr; size_t idxGenWDaughter1 = 9999; size_t idxGenWDaughter2 = 9999; double dr_min = 9999.; double dm_min = 9999.; if (printLevel > 5) dumpGenParticle(" genWFromH",genW,iW); double dr_min_1_lep = 9999.; double dm_min_1_lep = 9999.; double dr_min_1_qq = 9999.; double dm_min_1_qq = 9999.; // look for hadronic decay for (size_t iParticle1=0; iParticle1 < genWJets_Copy1.size(); iParticle1++) { for (size_t iParticle2=iParticle1+1; iParticle2 < genWJets_Copy1.size(); iParticle2++) { GenParticle *genD1 = genWJets_Copy1[iParticle1]; GenParticle *genD2 = genWJets_Copy1[iParticle2]; double dr = deltaR(genW->p4(), (genD1->p4() + genD2->p4())); double dm = std::abs(genW->mass() - (genD1->p4() + genD2->p4()).mass()); if (dr < dR_W_qq_max && dr < dr_min && dm < dm_W_qq_max && dm < dm_min) { genWDaughter1 = genD1; genWDaughter2 = genD2; idxGenWDaughter1 = iParticle1; idxGenWDaughter2 = iParticle2; dr_min = dr; dm_min = dm; } if (dr < dr_min_1_qq) { dr_min_1_qq = dr; } if (dm < dm_min_1_qq) { dm_min_1_qq = dm; } } } if (genWDaughter1 && genWDaughter2) { genWDaughtersFromHHTo4W[sIdxH_IdxW] = std::vector<GenParticle *> {genWDaughter1, genWDaughter2}; genWDecayModeFromHHTo4W[sIdxH_IdxW] = sWDecayMode_Hadronic; if (printLevel > 5) dumpGenParticle("\t Tagged genD1_FromW WJets",genWDaughter1,idxGenWDaughter1); if (printLevel > 5) dumpGenParticle("\t Tagged genD2_FromW WJets",genWDaughter2,idxGenWDaughter2); if (printLevel > 5) printf("\t Tagged D1D2: dMass: %f, dR: %f\n", std::abs(genW->mass() - (genWDaughter1->p4() + genWDaughter2->p4()).mass()), deltaR(genW->p4(), (genWDaughter1->p4() + genWDaughter2->p4()))); // erase the tagged Wjets from the genWJets collection genWJets_Copy1.erase(genWJets_Copy1.begin() + idxGenWDaughter1); // after erase all the higher index will decrease by 1 if (idxGenWDaughter1 > idxGenWDaughter2) genWJets_Copy1.erase(genWJets_Copy1.begin() + idxGenWDaughter2); else genWJets_Copy1.erase(genWJets_Copy1.begin() + idxGenWDaughter2 -1); //$$$$$$$$$$$$$$$$$$$$ //continue; // after finding W-> D1 D2 no need to look into Lepton and neutrino collection } // look for leptonic decay dr_min = dm_min = 9999.; for (size_t iParticle1=0; iParticle1 < genLeptons_Copy1.size(); iParticle1++) { for (size_t iParticle2=0; iParticle2 < genNeutrinos_Copy1.size(); iParticle2++) { GenParticle *genD1 = genLeptons_Copy1[iParticle1]; GenParticle *genD2 = genNeutrinos_Copy1[iParticle2]; double dr = deltaR(genW->p4(), (genD1->p4() + genD2->p4())); double dm = std::abs(genW->mass() - (genD1->p4() + genD2->p4()).mass()); if (printLevel > 8) dumpGenParticle(" \t genLeptons_Copy1: ",genLeptons_Copy1[iParticle1],iParticle1); if (printLevel > 8) dumpGenParticle(" \t genNeutrinos_Copy1: ",genNeutrinos_Copy1[iParticle2],iParticle2); if (printLevel > 8) printf("\t\t\t\t dm: %f, dr: %f \n", dm, dr); if (dr < dR_W_lnu_max && dr < dr_min && dm < dm_W_lnu_max && dm < dm_min) { genWDaughter1 = genD1; genWDaughter2 = genD2; idxGenWDaughter1 = iParticle1; idxGenWDaughter2 = iParticle2; dr_min = dr; dm_min = dm; } if (dr < dr_min_1_lep) { dr_min_1_lep = dr; } if (dm < dm_min_1_lep) { dm_min_1_lep = dm; } } } //if (genWDaughter1 && genWDaughter2) { if (genWDaughter1 && genWDaughter2 && genWDecayModeFromHHTo4W[sIdxH_IdxW] != sWDecayMode_Hadronic) { genWDaughtersFromHHTo4W[sIdxH_IdxW] = std::vector<GenParticle *> {genWDaughter1, genWDaughter2}; genWDecayModeFromHHTo4W[sIdxH_IdxW] = sWDecayMode_Leptonic; if (printLevel > 5) dumpGenParticle("\t Tagged genD1_FromW Lep",genWDaughter1,idxGenWDaughter1); if (printLevel > 5) dumpGenParticle("\t Tagged genD2_FromW Nut",genWDaughter2,idxGenWDaughter2); if (printLevel > 5) printf("\t Tagged D1D2: dMass: %f, dR: %f\n", std::abs(genW->mass() - (genWDaughter1->p4() + genWDaughter2->p4()).mass()), deltaR(genW->p4(), (genWDaughter1->p4() + genWDaughter2->p4()))); // erase the tagged Wjets from the genWJets collection genLeptons_Copy1.erase(genLeptons_Copy1.begin() + idxGenWDaughter1); genNeutrinos_Copy1.erase(genNeutrinos_Copy1.begin() + idxGenWDaughter2); } if (dr_min_1_qq < dr_min_1_lep) hdrmin_W_qq_gen[genMatchIdx_0]->Fill(dr_min_1_qq); else hdrmin_W_lnu_gen[genMatchIdx_0]->Fill(dr_min_1_lep); if (dm_min_1_qq < dm_min_1_lep) hdmmin_W_qq_gen[genMatchIdx_0]->Fill(dm_min_1_qq); else hdmmin_W_lnu_gen[genMatchIdx_0]->Fill(dm_min_1_lep); } } for (size_t iGenH=0; iGenH <genWFromHHTo4W.size(); iGenH++) { // iterate over number of Higgs std::string sIdxH = Form("iH%lu",iGenH); std::vector<GenParticle *> genWsFromH = genWFromHHTo4W[sIdxH]; for (size_t iW=0; iW < genWsFromH.size(); iW++) { // iterate over number of W from Higgs std::string sIdxH_IdxW = Form("iH%lu_iW%lu",iGenH,iW); if (genWDecayModeFromHHTo4W[sIdxH_IdxW] == sWDecayMode_Leptonic) nGenWDecayLeptonic++; if (genWDecayModeFromHHTo4W[sIdxH_IdxW] == sWDecayMode_Hadronic) nGenWDecayHadronic++; } } if (nGenWBosonInHHDecay == 4 && nGenWDecayLeptonic == 4 && nGenWDecayHadronic == 0) isGenEvtHHTo4W_4l_0qq = true; if (nGenWBosonInHHDecay == 4 && nGenWDecayLeptonic == 3 && nGenWDecayHadronic == 1) isGenEvtHHTo4W_3l_1qq = true; if (nGenWBosonInHHDecay == 4 && nGenWDecayLeptonic == 2 && nGenWDecayHadronic == 2) isGenEvtHHTo4W_2l_2qq = true; if (nGenWBosonInHHDecay == 4 && nGenWDecayLeptonic == 1 && nGenWDecayHadronic == 3) isGenEvtHHTo4W_1l_3qq = true; if (nGenWBosonInHHDecay == 4 && nGenWDecayLeptonic == 0 && nGenWDecayHadronic == 4) isGenEvtHHTo4W_0l_4qq = true; // Select HHTo4W_3l_1qq events only if ( !(isGenEvtHHTo4W_3l_1qq)) continue; if (printLevel > 4) printf("gen HH --> %iW%iZ event: %i l, %i hadronic decay mode \n",nGenWBosonInHHDecay,nGenZBosonInHHDecay, nGenWDecayLeptonic,nGenWDecayHadronic); cutFlowTable.update(Form("gen HH --> %iW%iZ event: %i l, %i hadronic decay mode",nGenWBosonInHHDecay,nGenZBosonInHHDecay, nGenWDecayLeptonic,nGenWDecayHadronic), evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms(Form("gen HH --> %iW%iZ event: %i l, %i hadronic decay mode",nGenWBosonInHHDecay,nGenZBosonInHHDecay, nGenWDecayLeptonic,nGenWDecayHadronic), evtWeightRecorder.get(central_or_shift_main)); // Check CMS geometric acceptance for HH->4W decay particles isHHTo4WDecayParticlesWithInCMSGeoAcpt = true; isHHTo4WDecayParticlesWithInCMSRecoAcpt = true; std::vector<double> genLeptonsPt_tmp; for (size_t iGenH=0; iGenH <genWFromHHTo4W.size(); iGenH++) { std::string sIdxH = Form("iH%lu",iGenH); std::vector<GenParticle *> genWsFromH = genWFromHHTo4W[sIdxH]; for (size_t iW=0; iW < genWsFromH.size(); iW++) { std::string sIdxH_IdxW = Form("iH%lu_iW%lu",iGenH,iW); std::vector<GenParticle*> genWDaughterPair = genWDaughtersFromHHTo4W[sIdxH_IdxW]; if (genWDecayModeFromHHTo4W[sIdxH_IdxW] == sWDecayMode_Hadronic) { for (size_t iD=0; iD < genWDaughterPair.size(); iD++) { GenParticle *genParticle = genWDaughterPair[iD]; if ( !(std::abs(genParticle->eta()) < CMSEtaMax_Jet)) { isHHTo4WDecayParticlesWithInCMSGeoAcpt = false; isHHTo4WDecayParticlesWithInCMSRecoAcpt = false; } else if ( !(genParticle->pt() > ptThresholdJet)) { isHHTo4WDecayParticlesWithInCMSRecoAcpt = false; } } } if (genWDecayModeFromHHTo4W[sIdxH_IdxW] == sWDecayMode_Leptonic) { GenParticle *genParticle = genWDaughterPair[0]; // [0]: lep, [1]: nutrino genLeptonsPt_tmp.push_back(genParticle->pt()); if ( !((std::abs(genParticle->pdgId()) == 11 && std::abs(genParticle->eta()) < CMSEtaMax_Electron) || (std::abs(genParticle->pdgId()) == 13 && std::abs(genParticle->eta()) < CMSEtaMax_Muon)) ) { isHHTo4WDecayParticlesWithInCMSGeoAcpt = false; isHHTo4WDecayParticlesWithInCMSRecoAcpt = false; } } } } if (printLevel > 10) { printf("gen lepton (%lu) pt before sorting: ",genLeptonsPt_tmp.size()); for (size_t iL=0; iL < genLeptonsPt_tmp.size(); iL++) printf(" %f, ",genLeptonsPt_tmp[iL]); printf("\n"); } std::sort(genLeptonsPt_tmp.begin(), genLeptonsPt_tmp.end(), std::greater<double>()); if (printLevel > 10) { printf("gen lepton (%lu) pt after sorting: ",genLeptonsPt_tmp.size()); for (size_t iL=0; iL < genLeptonsPt_tmp.size(); iL++) printf(" %f, ",genLeptonsPt_tmp[iL]); printf("\n"); } std::string sptThrshLep_tmp = Form("ptThrsh_%lul",genLeptonsPt_tmp.size()); for (size_t iL=0; iL < genLeptonsPt_tmp.size(); iL++) { if ( !(genLeptonsPt_tmp[iL] > ptThrshLeptons[sptThrshLep_tmp][iL])) isHHTo4WDecayParticlesWithInCMSRecoAcpt = false; } if (printLevel > 5) std::cout << "isHHTo4WDecayParticlesWithInCMSGeoAcpt: " << isHHTo4WDecayParticlesWithInCMSGeoAcpt << ", isHHTo4WDecayParticlesWithInCMSRecoAcpt: " << isHHTo4WDecayParticlesWithInCMSRecoAcpt << std::endl; if (isHHTo4WDecayParticlesWithInCMSGeoAcpt) { cutFlowTable.update(Form("gen HH --> %iW%iZ event: %i l, %i hadronic decay mode : within CMS geoetry",nGenWBosonInHHDecay,nGenZBosonInHHDecay, nGenWDecayLeptonic,nGenWDecayHadronic), evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms(Form("gen HH --> %iW%iZ event: %i l, %i hadronic decay mode : within CMS geoetry",nGenWBosonInHHDecay,nGenZBosonInHHDecay, nGenWDecayLeptonic,nGenWDecayHadronic), evtWeightRecorder.get(central_or_shift_main)); } if (isHHTo4WDecayParticlesWithInCMSGeoAcpt && isHHTo4WDecayParticlesWithInCMSRecoAcpt) { cutFlowTable.update(Form("gen HH --> %iW%iZ event: %i l, %i hadronic decay mode : within CMS geoetry & reco acpt",nGenWBosonInHHDecay,nGenZBosonInHHDecay, nGenWDecayLeptonic,nGenWDecayHadronic), evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms(Form("gen HH --> %iW%iZ event: %i l, %i hadronic decay mode : within CMS geoetry",nGenWBosonInHHDecay,nGenZBosonInHHDecay, nGenWDecayLeptonic,nGenWDecayHadronic), evtWeightRecorder.get(central_or_shift_main)); } // HH->4W 3l 2q category only //if ( !((nGenWBosonInHHDecay == 4) && nGenWDecayLeptonic == 3 && nGenWDecayHadronic == 1)) continue; if ( !(isHHTo4WDecayParticlesWithInCMSGeoAcpt && isHHTo4WDecayParticlesWithInCMSRecoAcpt)) continue; // print HH->4W particles if (printLevel > 4 && (nGenWDecayLeptonic + nGenWDecayHadronic) >= 4) { for (size_t iGenH=0; iGenH <genWFromHHTo4W.size(); iGenH++) { std::string sIdxH = Form("iH%lu",iGenH); std::vector<GenParticle *> genWsFromH = genWFromHHTo4W[sIdxH]; dumpGenParticle("\n\ngenHiggses_Copy1",genHiggses_Copy1[iGenH],iGenH); for (size_t iW=0; iW < genWsFromH.size(); iW++) { std::string sIdxH_IdxW = Form("iH%lu_iW%lu",iGenH,iW); dumpGenParticle(" genWFromH",genWsFromH[iW],iW); std::cout << "\t\t " << genWDecayModeFromHHTo4W[sIdxH_IdxW] << std::endl; std::vector<GenParticle*> genWDaughterPair = genWDaughtersFromHHTo4W[sIdxH_IdxW]; for (size_t iD=0; iD < genWDaughterPair.size(); iD++) { dumpGenParticle("\t WDaughter ",genWDaughterPair[iD],iD); } } } } if ((nGenWBosonInHHDecay == 4) && nGenWDecayLeptonic == 3 && nGenWDecayHadronic == 1) { isGenEvtHHTo4W_3l_1qq = true; int idxH_TypeHToWW_lnu_qq = -1; int idxH_TypeHToWW_2l2nu = -1; int idxW_TypeW_lnu_InHToWW_lnu_qq = -1; int idxW_TypeW_qq_InHToWW_lnu_qq = -1; for (size_t iGenH=0; iGenH <genWFromHHTo4W.size(); iGenH++) { std::string sIdxH = Form("iH%lu",iGenH); std::vector<GenParticle *> genWsFromH = genWFromHHTo4W[sIdxH]; for (size_t iW=0; iW < genWsFromH.size(); iW++) { std::string sIdxH_IdxW = Form("iH%lu_iW%lu",iGenH,iW); std::vector<GenParticle *> genWDaughters = genWDaughtersFromHHTo4W[sIdxH_IdxW]; if (genWDecayModeFromHHTo4W[sIdxH_IdxW] == sWDecayMode_Hadronic) { idxW_TypeW_qq_InHToWW_lnu_qq = iW; genJet1FromHToWW_lnu_qq = genWDaughters[0]; genJet2FromHToWW_lnu_qq = genWDaughters[1]; idxW_TypeW_lnu_InHToWW_lnu_qq = 0; if (idxW_TypeW_qq_InHToWW_lnu_qq == idxW_TypeW_lnu_InHToWW_lnu_qq) idxW_TypeW_lnu_InHToWW_lnu_qq++; std::string sIdxH_TypeHToWW_lnu_qq_IdxW_TypeW_lnu = Form("iH%lu_iW%i",iGenH,idxW_TypeW_lnu_InHToWW_lnu_qq); genLeptonFromHToWW_lnu_qq = genWDaughtersFromHHTo4W[sIdxH_TypeHToWW_lnu_qq_IdxW_TypeW_lnu][0]; genNutrinoFromHToWW_lnu_qq = genWDaughtersFromHHTo4W[sIdxH_TypeHToWW_lnu_qq_IdxW_TypeW_lnu][1]; idxH_TypeHToWW_lnu_qq = iGenH; idxH_TypeHToWW_2l2nu = 0; if (idxH_TypeHToWW_lnu_qq == idxH_TypeHToWW_2l2nu) idxH_TypeHToWW_2l2nu++; std::string sIdxH_TypeHToWW_2l2nu_IdxW0 = Form("iH%i_iW%i",idxH_TypeHToWW_2l2nu,0); genLepton1FromHToWW_2l2nu = genWDaughtersFromHHTo4W[sIdxH_TypeHToWW_2l2nu_IdxW0][0]; genNutrino1FromHToWW_2l2nu = genWDaughtersFromHHTo4W[sIdxH_TypeHToWW_2l2nu_IdxW0][1]; // std::string sIdxH_TypeHToWW_2l2nu_IdxW1 = Form("iH%i_iW%i",idxH_TypeHToWW_2l2nu,1); genLepton2FromHToWW_2l2nu = genWDaughtersFromHHTo4W[sIdxH_TypeHToWW_2l2nu_IdxW1][0]; genNutrino2FromHToWW_2l2nu = genWDaughtersFromHHTo4W[sIdxH_TypeHToWW_2l2nu_IdxW1][1]; } } } if (printLevel > 5) { std::cout << "Printf HH->4W 3l 2j particles: \n";// << isGenEvtHHTo4W_3l_1qq << std::endl; dumpGenParticle("genJet1FromHToWW_lnu_qq",genJet1FromHToWW_lnu_qq,0); dumpGenParticle("genJet2FromHToWW_lnu_qq",genJet2FromHToWW_lnu_qq,0); dumpGenParticle("genLeptonFromHToWW_lnu_qq",genLeptonFromHToWW_lnu_qq,0); dumpGenParticle("genNutrinoFromHToWW_lnu_qq",genNutrinoFromHToWW_lnu_qq,0); dumpGenParticle("genLepton1FromHToWW_2l2nu",genLepton1FromHToWW_2l2nu,0); dumpGenParticle("genNutrino1FromHToWW_2l2nu",genNutrino1FromHToWW_2l2nu,0); dumpGenParticle("genLepton2FromHToWW_2l2nu",genLepton2FromHToWW_2l2nu,0); dumpGenParticle("genNutrino2FromHToWW_2l2nu",genNutrino2FromHToWW_2l2nu,0); } std::vector<GenParticle *> genLepsFromHHTo4W = {genLepton1FromHToWW_2l2nu, genLepton2FromHToWW_2l2nu, genLeptonFromHToWW_lnu_qq}; nGenMuFromHHTo4W = 0; nGenEleFromHHTo4W = 0; for (size_t i=0; i < genLepsFromHHTo4W.size(); i++) { GenParticle *gen = genLepsFromHHTo4W[i]; if (std::abs(gen->pdgId()) == 11) nGenEleFromHHTo4W++; if (std::abs(gen->pdgId()) == 13) nGenMuFromHHTo4W++; } if (nGenEleFromHHTo4W >= 1) { cutFlowTable.update("gen HH --> 4W --> 3l 1qq, within CMS geoetry & reco acpt, nEle > 0", evtWeightRecorder.get(central_or_shift_main)); } if (nGenMuFromHHTo4W >= 1) { cutFlowTable.update("gen HH --> 4W --> 3l 1qq, within CMS geoetry & reco acpt, nMu > 0", evtWeightRecorder.get(central_or_shift_main)); } if ((genJet1FromHToWW_lnu_qq->p4() + genJet2FromHToWW_lnu_qq->p4()).pt() > ptWFatjetBoosted) { isGenEvtCatBoosted = true; /*cutFlowTable.update("gen HHTo4W 3l qq event - boosted ", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("gen HHTo4W 3l qq event - boosted", evtWeightRecorder.get(central_or_shift_main));*/ } else { isGenEvtCatResolved = true; /*cutFlowTable.update("gen HHTo4W 3l qq event - resolved", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("gen HHTo4W 3l qq event - resolved", evtWeightRecorder.get(central_or_shift_main));*/ } cutFlowTable.update(Form("gen HHTo4W 3l qq event - CMS GeoAccpt %i, RecoAcpt %i, Cat: isBoosted %i",isHHTo4WDecayParticlesWithInCMSGeoAcpt,isHHTo4WDecayParticlesWithInCMSRecoAcpt,isGenEvtCatBoosted), evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms(Form("gen HHTo4W 3l qq event - CMS GeoAccpt %i, RecoAcpt %i, Cat: isBoosted %i",isHHTo4WDecayParticlesWithInCMSGeoAcpt,isHHTo4WDecayParticlesWithInCMSRecoAcpt,isGenEvtCatBoosted), evtWeightRecorder.get(central_or_shift_main)); Particle::LorentzVector LVGenWjj = (genJet1FromHToWW_lnu_qq->p4() + genJet2FromHToWW_lnu_qq->p4()); hptGenWjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(LVGenWjj.pt()); hptGenLep3_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genLeptonFromHToWW_lnu_qq->pt()); // hetaGenWjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(LVGenWjj.eta()); hetaGenLep3_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genLeptonFromHToWW_lnu_qq->eta()); // hdr_GenWj1j2_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(deltaR(genJet1FromHToWW_lnu_qq->p4(), genJet2FromHToWW_lnu_qq->p4())); hdr_GenWj1j2_vs_ptGenWjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(LVGenWjj.pt(), deltaR(genJet1FromHToWW_lnu_qq->p4(), genJet2FromHToWW_lnu_qq->p4())); hdr_GenLep3_Wjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(deltaR(genLeptonFromHToWW_lnu_qq->p4(), LVGenWjj)); hdr_GenLep3_Wjj_vs_ptWjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(LVGenWjj.pt(), deltaR(genLeptonFromHToWW_lnu_qq->p4(), LVGenWjj)); double dr_GenLep3_Wjet1; double dr_GenLep3_Wjet2; double dr_GenLep3_WjetNear; double dr_GenLep3_WjetFar; if (genJet1FromHToWW_lnu_qq->pt() > genJet2FromHToWW_lnu_qq->pt()) { hptGenWjet1_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genJet1FromHToWW_lnu_qq->pt()); hptGenWjet2_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genJet2FromHToWW_lnu_qq->pt()); hetaGenWjet1_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genJet1FromHToWW_lnu_qq->eta()); hetaGenWjet2_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genJet2FromHToWW_lnu_qq->eta()); hdr_GenLep3_Wjet1_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet1FromHToWW_lnu_qq->p4())); hdr_GenLep3_Wjet2_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet2FromHToWW_lnu_qq->p4())); hdr_GenLep3_Wjet1_vs_ptWjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(LVGenWjj.pt(), deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet1FromHToWW_lnu_qq->p4())); hdr_GenLep3_Wjet2_vs_ptWjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(LVGenWjj.pt(), deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet2FromHToWW_lnu_qq->p4())); } else { hptGenWjet1_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genJet2FromHToWW_lnu_qq->pt()); hptGenWjet2_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genJet1FromHToWW_lnu_qq->pt()); hetaGenWjet1_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genJet2FromHToWW_lnu_qq->eta()); hetaGenWjet2_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genJet1FromHToWW_lnu_qq->eta()); hdr_GenLep3_Wjet1_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet2FromHToWW_lnu_qq->p4())); hdr_GenLep3_Wjet2_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet1FromHToWW_lnu_qq->p4())); hdr_GenLep3_Wjet1_vs_ptWjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(LVGenWjj.pt(), deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet2FromHToWW_lnu_qq->p4())); hdr_GenLep3_Wjet2_vs_ptWjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(LVGenWjj.pt(), deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet1FromHToWW_lnu_qq->p4())); } if (deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet1FromHToWW_lnu_qq->p4()) < deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet2FromHToWW_lnu_qq->p4())) { hdr_GenLep3_WjetNear_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet1FromHToWW_lnu_qq->p4())); hdr_GenLep3_WjetFar_HHTo4W_3l_1qq[genMatchIdx_0] ->Fill(deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet2FromHToWW_lnu_qq->p4())); hdr_GenLep3_WjetNear_vs_ptWjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(LVGenWjj.pt(), deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet1FromHToWW_lnu_qq->p4())); hdr_GenLep3_WjetFar_vs_ptWjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(LVGenWjj.pt(), deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet2FromHToWW_lnu_qq->p4())); } else { hdr_GenLep3_WjetNear_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet2FromHToWW_lnu_qq->p4())); hdr_GenLep3_WjetFar_HHTo4W_3l_1qq[genMatchIdx_0] ->Fill(deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet1FromHToWW_lnu_qq->p4())); hdr_GenLep3_WjetNear_vs_ptWjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(LVGenWjj.pt(), deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet2FromHToWW_lnu_qq->p4())); hdr_GenLep3_WjetFar_vs_ptWjj_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(LVGenWjj.pt(), deltaR(genLeptonFromHToWW_lnu_qq->p4(), genJet1FromHToWW_lnu_qq->p4())); } if (genLepton1FromHToWW_2l2nu->pt() > genLepton2FromHToWW_2l2nu->pt()) { hptGenLep1_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genLepton1FromHToWW_2l2nu->pt()); hptGenLep2_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genLepton2FromHToWW_2l2nu->pt()); hetaGenLep1_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genLepton1FromHToWW_2l2nu->eta()); hetaGenLep2_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genLepton2FromHToWW_2l2nu->eta()); } else { hptGenLep1_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genLepton2FromHToWW_2l2nu->pt()); hptGenLep2_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genLepton1FromHToWW_2l2nu->pt()); hetaGenLep1_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genLepton2FromHToWW_2l2nu->eta()); hetaGenLep2_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(genLepton1FromHToWW_2l2nu->eta()); } std::vector<double> ptGenLeps = {genLepton1FromHToWW_2l2nu->pt(), genLepton2FromHToWW_2l2nu->pt(), genLeptonFromHToWW_lnu_qq->pt()}; std::sort(ptGenLeps.begin(), ptGenLeps.end(), std::greater<double>()); hptGenLepLead_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(ptGenLeps[0]); hptGenLepSublead_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(ptGenLeps[1]); hptGenLepSubsublead_HHTo4W_3l_1qq[genMatchIdx_0]->Fill(ptGenLeps[2]); } if (0==1) { // store GenParticles for events HH->4W -> 3l3nu 2q ----------- Approach-0 old ---------------- const GenParticle* genWHadronicFromH_WW_qqlnu = nullptr; const GenParticle* genJet1FromH_WW_qqlnu = nullptr; const GenParticle* genJet2FromH_WW_qqlnu = nullptr; const GenLepton* genLeptonFromH_WW_qqlnu = nullptr; const GenLepton* genLepton1FromH_WW_lnulnu = nullptr; const GenLepton* genLepton2FromH_WW_lnulnu = nullptr; //const GenParticle* genNu1FromH_WW_lnulnu = nullptr; //const GenParticle* genNu2FromH_WW_lnulnu = nullptr; //size_t idxGenW1lnu_H_WW_lnulnu = 999; // idx of WBoson in genWBosons //size_t idxGenW2lnu_H_WW_lnulnu = 999; //size_t idxGenWlnu_H_WW_qqlnu = 999; //size_t idxGenWqq_H_WW_qqlnu = 999; size_t H_WW_DecayIdx[2][2]; // [i][j]: i: H indix, j: 0,1 1st and 2nd W of ith H int nWLeptonic = 0, nWHadronic = 0, nWFoundBothLepHadronic = 0; for (int i=0; i<2; i++) { for (int j=0; j<2; j++) { H_WW_DecayIdx[i][j] = 999; //std::cout<<"i: "<<i<<", j: "<<j<<", H_WW_DecayIdx[i][j]: "<<H_WW_DecayIdx[i][j]<<std::endl; } } std::pair<const GenLepton*, const GenParticle*> *genLepton_and_NeutrinoFromWBosons; genLepton_and_NeutrinoFromWBosons = new std::pair<const GenLepton*, const GenParticle*>[genWBosons.size()]; std::pair<const GenParticle*, const GenParticle*> *genJetPairFromWBosons; genJetPairFromWBosons = new std::pair<const GenParticle*, const GenParticle*>[genWBosons.size()]; if ( isMC && (int)genHiggses.size()>=2 && (int)genWBosons.size()>=4) { for (size_t igenHiggs = 0; igenHiggs < genHiggses.size(); ++igenHiggs) { Particle::LorentzVector HP4 = genHiggses[igenHiggs].p4(); double minDeltaMass = 1.e+3; double minDeltaR = 1.e+4; for (size_t iWBoson1 = 0; iWBoson1 < genWBosons.size(); ++iWBoson1) { for (size_t iWBoson2 = 0; iWBoson2 < genWBosons.size(); ++iWBoson2) { if (iWBoson1 == iWBoson2) continue; Particle::LorentzVector WWP4 = genWBosons[iWBoson1].p4() + genWBosons[iWBoson2].p4(); double deltaMass = TMath::Abs(HP4.mass() - WWP4.mass()); double dR = deltaR(WWP4, HP4); if ( deltaMass < minDeltaMass && deltaMass < 5. && dR < minDeltaR && dR < 0.8) { minDeltaMass = deltaMass; minDeltaR = dR; H_WW_DecayIdx[igenHiggs][0] = iWBoson1; H_WW_DecayIdx[igenHiggs][1] = iWBoson2; } } } } if (printLevel > 5) { printf("\tH0: W1: %i dR(H,W): %f, W2: %i dR(H,W): %f, mWW: %f, dR(H, WW): %f, dR(H, W'W'): %f\n", (int)H_WW_DecayIdx[0][0], deltaR(genHiggses[0].p4(), genWBosons[H_WW_DecayIdx[0][0]].p4()), (int)H_WW_DecayIdx[0][1], deltaR(genHiggses[0].p4(), genWBosons[H_WW_DecayIdx[0][1]].p4()), (genWBosons[H_WW_DecayIdx[0][0]].p4() + genWBosons[H_WW_DecayIdx[0][1]].p4()).mass(), deltaR(genHiggses[0].p4(), genWBosons[H_WW_DecayIdx[0][0]].p4() + genWBosons[H_WW_DecayIdx[0][1]].p4()), deltaR(genHiggses[0].p4(), genWBosons[H_WW_DecayIdx[1][0]].p4() + genWBosons[H_WW_DecayIdx[1][1]].p4()) ); printf("\tH1: W1: %i dR(H,W): %f, W2: %i dR(H,W): %f, mWW: %f, dR(H, WW): %f, dR(H, W'W'): %f\n", (int)H_WW_DecayIdx[1][0], deltaR(genHiggses[1].p4(), genWBosons[H_WW_DecayIdx[1][0]].p4()), (int)H_WW_DecayIdx[1][1], deltaR(genHiggses[1].p4(), genWBosons[H_WW_DecayIdx[1][1]].p4()), (genWBosons[H_WW_DecayIdx[1][0]].p4() + genWBosons[H_WW_DecayIdx[1][1]].p4()).mass(), deltaR(genHiggses[1].p4(), genWBosons[H_WW_DecayIdx[1][0]].p4() + genWBosons[H_WW_DecayIdx[1][1]].p4()), deltaR(genHiggses[1].p4(), genWBosons[H_WW_DecayIdx[0][0]].p4() + genWBosons[H_WW_DecayIdx[0][1]].p4()) ); } //bool IsEventWBoostedW = false; for (size_t idxWBoson = 0; idxWBoson<genWBosons.size(); ++idxWBoson) { //genLepton_and_NeutrinoFromWBosons[idxWBoson] = findGenLepton_and_NeutrinoFromWBoson(&(genWBosons[idxWBoson]), genLeptons, genNeutrinos); genLepton_and_NeutrinoFromWBosons[idxWBoson] = findGenLepton_and_NeutrinoFromWBoson_1(&(genWBosons[idxWBoson]), genLeptons, genNeutrinos); Particle::LorentzVector genWBosonP4 = genWBosons[idxWBoson].p4(); const GenParticle* genJet1FromWBoson = nullptr; const GenParticle* genJet2FromWBoson = nullptr; double minDeltaMass = 1.e+3; for ( std::vector<GenParticle>::const_iterator genWJet1 = genWJets.begin(); genWJet1 != genWJets.end(); ++genWJet1 ) { for ( std::vector<GenParticle>::const_iterator genWJet2 = genWJet1 + 1; genWJet2 != genWJets.end(); ++genWJet2 ) { double deltaMass = TMath::Abs((genWJet1->p4() + genWJet2->p4()).mass() - genWBosonP4.mass()); double dR = deltaR(genWJet1->p4() + genWJet2->p4(), genWBosonP4); //if ( deltaR(genWJet1->p4() + genWJet2->p4(), genWBosonP4) < 1.e-1 && // std::fabs((genWJet1->p4() + genWJet2->p4()).mass() - genWBosonP4.mass()) < 5. ) { //if ( deltaMass < 5 && deltaMass < minDeltaMass && dR < 1) { if ( deltaMass < 1.5 && deltaMass < minDeltaMass && dR < 0.01) { genJet1FromWBoson = &(*genWJet1); genJet2FromWBoson = &(*genWJet2); minDeltaMass = deltaMass; } } } genJetPairFromWBosons[idxWBoson] = std::pair<const GenParticle*, const GenParticle*>(genJet1FromWBoson, genJet2FromWBoson); if (genJet1FromWBoson && genJet2FromWBoson && printLevel > 5) std::cout<<"idxW: "<<idxWBoson<<", W->qq matching: m(W):"<<genWBosons[idxWBoson].mass()<<", m(qq): "<<(genJet1FromWBoson->p4()+genJet2FromWBoson->p4()).mass()<<", dR(W, qq): "<<deltaR((genJet1FromWBoson->p4()+genJet2FromWBoson->p4()), genWBosons[idxWBoson].p4())<<std::endl; if (genLepton_and_NeutrinoFromWBosons[idxWBoson].first && genLepton_and_NeutrinoFromWBosons[idxWBoson].second && printLevel > 5 ) std::cout<<"idxW: "<<idxWBoson<<", W->l nu matching: m(W):"<<genWBosons[idxWBoson].mass()<<", m(l nu): "<<((genLepton_and_NeutrinoFromWBosons[idxWBoson].first)->p4() + (genLepton_and_NeutrinoFromWBosons[idxWBoson].second)->p4()).mass()<<", dR(W, l nu): "<<deltaR(((genLepton_and_NeutrinoFromWBosons[idxWBoson].first)->p4() + (genLepton_and_NeutrinoFromWBosons[idxWBoson].second)->p4()), genWBosons[idxWBoson].p4())<<std::endl; } for (size_t igenHiggs=0; igenHiggs<2; ++igenHiggs) { for (size_t igenWBoson=0; igenWBoson<2; ++igenWBoson) { size_t idxWBoson = H_WW_DecayIdx[igenHiggs][igenWBoson]; std::pair<const GenLepton*, const GenParticle*> genLepton_and_NeutrinoFromWBoson = genLepton_and_NeutrinoFromWBosons[idxWBoson]; std::pair<const GenParticle*, const GenParticle*> genJetPairFromWBoson = genJetPairFromWBosons[idxWBoson]; const GenLepton* genLepton = genLepton_and_NeutrinoFromWBoson.first; const GenParticle* genNeutrino = genLepton_and_NeutrinoFromWBoson.second; const GenParticle* genJet1 = genJetPairFromWBoson.first; const GenParticle* genJet2 = genJetPairFromWBoson.second; /*std::cout<<"igenHiggs: "<<igenHiggs<<", igenWBoson: "<<igenWBoson <<", genLepton: "<<genLepton<<", genNeutrino: "<<genNeutrino <<", genJet1: "<<genJet1<<", genJet2: "<<genJet2 <<std::endl;*/ if (genLepton && genNeutrino) nWLeptonic++; if (genJet1 &&genJet2 )nWHadronic++; if ((genLepton && genNeutrino) && (genJet1 &&genJet2 )) nWFoundBothLepHadronic++; } } if ( printLevel > 5 ) std::cout<<"nWLeptonic: "<<nWLeptonic<<", nWHadronic: "<<nWHadronic <<", nWFoundBothLepHadronic: "<<nWFoundBothLepHadronic<<std::endl; if (nWLeptonic == 3 && nWHadronic == 1) { size_t igenHiggs_H_WW_lnulnu = 9999; for (size_t igenHiggs=0; igenHiggs<2; ++igenHiggs) { for (size_t igenWBoson=0; igenWBoson<2; ++igenWBoson) { size_t idxWBoson = H_WW_DecayIdx[igenHiggs][igenWBoson]; std::pair<const GenLepton*, const GenParticle*> genLepton_and_NeutrinoFromWBoson = genLepton_and_NeutrinoFromWBosons[idxWBoson]; std::pair<const GenParticle*, const GenParticle*> genJetPairFromWBoson = genJetPairFromWBosons[idxWBoson]; const GenLepton* genLepton = genLepton_and_NeutrinoFromWBoson.first; const GenParticle* genNeutrino = genLepton_and_NeutrinoFromWBoson.second; const GenParticle* genJet1 = genJetPairFromWBoson.first; const GenParticle* genJet2 = genJetPairFromWBoson.second; if (genJet1 && genJet2) { // set H->WW->qqlnu gen-pointer genWHadronicFromH_WW_qqlnu = &(genWBosons[idxWBoson]); genJet1FromH_WW_qqlnu = genJet1; genJet2FromH_WW_qqlnu = genJet2; //idxGenWqq_H_WW_qqlnu = igenWBoson; // index in genWBoson collection size_t igenOtherWBosonFromH = 0; // can be 0, 1 as H->WW //###if (idxWBoson == 0) igenOtherWBosonFromH++; if (igenWBoson == 0) igenOtherWBosonFromH++; size_t idxOtherWBosonFromH = H_WW_DecayIdx[igenHiggs][igenOtherWBosonFromH]; std::pair<const GenLepton*, const GenParticle*> genLepton_and_NeutrinoFromOtherWBosonFromH = genLepton_and_NeutrinoFromWBosons[idxOtherWBosonFromH]; //std::pair<const GenParticle*, const GenParticle*> genJetPairFromOtherWBosonFromH = genJetPairFromWBosons[idxWBoson]; genLeptonFromH_WW_qqlnu = genLepton_and_NeutrinoFromOtherWBosonFromH.first; //idxGenWlnu_H_WW_qqlnu = idxOtherWBosonFromH; // index in genWBoson collection // set H->WW->lnulnu gen-index igenHiggs_H_WW_lnulnu = 0; if (igenHiggs == 0) igenHiggs_H_WW_lnulnu++; } } } if (igenHiggs_H_WW_lnulnu < 2) { // igenHiggs_H_WW_lnulnu < 2: to check igenHiggs_H_WW_lnulnu is been set //idxGenW1lnu_H_WW_lnulnu = H_WW_DecayIdx[igenHiggs_H_WW_lnulnu][0]; // index in genWBoson collection //idxGenW2lnu_H_WW_lnulnu = H_WW_DecayIdx[igenHiggs_H_WW_lnulnu][1]; // index in genWBoson collection /*genLepton1FromH_WW_lnulnu = (genLepton_and_NeutrinoFromWBosons[idxGenW1lnu_H_WW_lnulnu]).first; genLepton2FromH_WW_lnulnu = (genLepton_and_NeutrinoFromWBosons[idxGenW2lnu_H_WW_lnulnu]).first; genNu1FromH_WW_lnulnu = (genLepton_and_NeutrinoFromWBosons[idxGenW1lnu_H_WW_lnulnu]).second; genNu2FromH_WW_lnulnu = (genLepton_and_NeutrinoFromWBosons[idxGenW2lnu_H_WW_lnulnu]).second;*/ genLepton1FromH_WW_lnulnu = (genLepton_and_NeutrinoFromWBosons[H_WW_DecayIdx[igenHiggs_H_WW_lnulnu][0]]).first; genLepton2FromH_WW_lnulnu = (genLepton_and_NeutrinoFromWBosons[H_WW_DecayIdx[igenHiggs_H_WW_lnulnu][1]]).first; //genNu1FromH_WW_lnulnu = (genLepton_and_NeutrinoFromWBosons[H_WW_DecayIdx[igenHiggs_H_WW_lnulnu][0]]).second; //genNu2FromH_WW_lnulnu = (genLepton_and_NeutrinoFromWBosons[H_WW_DecayIdx[igenHiggs_H_WW_lnulnu][1]]).second; } if ( printLevel > 5 ) { printf("===>>> Printing HH->WWWW->qq3l3nu decay chains::\n"); for (size_t igenHiggs=0; igenHiggs<2; ++igenHiggs) { //Particle::LorentzVector HFromDecayP4 printf("\tH%i: W0: %i, W1: %i, mWW: %f, dR(H, WW): %f \n\t", (int)igenHiggs, (int)H_WW_DecayIdx[igenHiggs][0], (int)H_WW_DecayIdx[igenHiggs][1], (genWBosons[H_WW_DecayIdx[igenHiggs][0]].p4() + genWBosons[H_WW_DecayIdx[igenHiggs][1]].p4()).mass(), deltaR(genHiggses[igenHiggs].p4(), genWBosons[H_WW_DecayIdx[igenHiggs][0]].p4() + genWBosons[H_WW_DecayIdx[igenHiggs][1]].p4()) ); Particle::LorentzVector HFromDecayProdP4[2]; Particle::LorentzVector WP4, WFromDecayProdP4; std::string sWDecayType; for (size_t igenWBoson=0; igenWBoson<2; ++igenWBoson) { size_t idxWBoson = H_WW_DecayIdx[igenHiggs][igenWBoson]; WP4 = genWBosons[idxWBoson].p4(); if ((genJetPairFromWBosons[idxWBoson]).first && (genJetPairFromWBosons[idxWBoson]).second) { WFromDecayProdP4 = ((genJetPairFromWBosons[idxWBoson]).first)->p4() + ((genJetPairFromWBosons[idxWBoson]).second)->p4(); sWDecayType = "WHadronicDecay"; } else { if ((genLepton_and_NeutrinoFromWBosons[idxWBoson]).first && (genLepton_and_NeutrinoFromWBosons[idxWBoson]).second) { WFromDecayProdP4 = ((genLepton_and_NeutrinoFromWBosons[idxWBoson]).first)->p4() + ((genLepton_and_NeutrinoFromWBosons[idxWBoson]).second)->p4(); sWDecayType = "WLeptonicDecay"; } } HFromDecayProdP4[igenWBoson] = WFromDecayProdP4; printf("\tW%i: m: %f, mWdecay: %f, dR(W, Wdecay): %f, %s, ", (int)igenWBoson, WP4.mass(), WFromDecayProdP4.mass(), deltaR(WP4, WFromDecayProdP4), sWDecayType.c_str()); } printf("\t mHdecay: %f\n",(HFromDecayProdP4[0] + HFromDecayProdP4[1]).mass()); } std::cout<<"genJet1FromH_WW_qqlnu: "<<genJet1FromH_WW_qqlnu<<", genJet2FromH_WW_qqlnu: "<<genJet2FromH_WW_qqlnu <<", genLeptonFromH_WW_qqlnu: "<<genLeptonFromH_WW_qqlnu <<", genLepton1FromH_WW_lnulnu: "<<genLepton1FromH_WW_lnulnu <<", genLepton2FromH_WW_lnulnu: "<<genLepton2FromH_WW_lnulnu <<std::endl; } if (printLevel > 5) { std::cout << "\nApproch - old HH->4W 3l 2j particles: " << std::endl; dumpGenParticle("genJet1FromH_WW_qqlnu",genJet1FromH_WW_qqlnu,0); dumpGenParticle("genJet2FromH_WW_qqlnu",genJet2FromH_WW_qqlnu,0); dumpGenParticle("genLeptonFromH_WW_qqlnu",genLeptonFromH_WW_qqlnu,0); dumpGenParticle("genLepton1FromH_WW_lnulnu",genLepton1FromH_WW_lnulnu,0); dumpGenParticle("genLepton2FromH_WW_lnulnu",genLepton2FromH_WW_lnulnu,0); } if (printLevel > 5) { std::cout << "\nApproch - new HH->4W 3l 2j particles: " << std::endl; dumpGenParticle("genJet1FromHToWW_lnu_qq",genJet1FromHToWW_lnu_qq,0); dumpGenParticle("genJet2FromHToWW_lnu_qq",genJet2FromHToWW_lnu_qq,0); dumpGenParticle("genLeptonFromHToWW_lnu_qq",genLeptonFromHToWW_lnu_qq,0); //dumpGenParticle("genNutrinoFromHToWW_lnu_qq",genNutrinoFromHToWW_lnu_qq,0); dumpGenParticle("genLepton1FromHToWW_2l2nu",genLepton1FromHToWW_2l2nu,0); //dumpGenParticle("genNutrino1FromHToWW_2l2nu",genNutrino1FromHToWW_2l2nu,0); dumpGenParticle("genLepton2FromHToWW_2l2nu",genLepton2FromHToWW_2l2nu,0); //dumpGenParticle("genNutrino2FromHToWW_2l2nu",genNutrino2FromHToWW_2l2nu,0); } if (printLevel > 1000) { std::cout << genWHadronicFromH_WW_qqlnu->mass() << isGenEvtHHTo4W_4l_0qq << isGenEvtHHTo4W_3l_1qq << isGenEvtHHTo4W_2l_2qq << isGenEvtHHTo4W_1l_3qq << isGenEvtHHTo4W_0l_4qq << isGenEvtCatBoosted << isGenEvtCatResolved << std::endl; } } } } } cutFlowTable.update("gen event selection passed ", evtWeightRecorder.get(central_or_shift_main)); if(isMC) { if(apply_genWeight) evtWeightRecorder.record_genWeight(boost::math::sign(eventInfo.genWeight)); if(eventWeightManager) evtWeightRecorder.record_auxWeight(eventWeightManager); if(l1PreFiringWeightReader) evtWeightRecorder.record_l1PrefireWeight(l1PreFiringWeightReader); if(apply_topPtReweighting) evtWeightRecorder.record_toppt_rwgt(eventInfo.topPtRwgtSF); lheInfoReader->read(); psWeightReader->read(); evtWeightRecorder.record_lheScaleWeight(lheInfoReader); evtWeightRecorder.record_psWeight(psWeightReader); evtWeightRecorder.record_puWeight(&eventInfo); evtWeightRecorder.record_nom_tH_weight(&eventInfo); evtWeightRecorder.record_lumiScale(lumiScale); for(const std::string & central_or_shift: central_or_shifts_local) { if(central_or_shift != central_or_shift_main) { continue; } genEvtHistManager_beforeCuts[central_or_shift]->fillHistograms( genElectrons, genMuons, genHadTaus, genPhotons, genJets, evtWeightRecorder.get_inclusive(central_or_shift) ); if(eventWeightManager) { genEvtHistManager_beforeCuts[central_or_shift]->fillHistograms( eventWeightManager, evtWeightRecorder.get_inclusive(central_or_shift) ); } } } bool isTriggered_1e = hltPaths_isTriggered(triggers_1e, triggerWhiteList, eventInfo, isMC, isDEBUG); bool isTriggered_1mu = hltPaths_isTriggered(triggers_1mu, triggerWhiteList, eventInfo, isMC, isDEBUG); bool isTriggered_2e = hltPaths_isTriggered(triggers_2e, triggerWhiteList, eventInfo, isMC, isDEBUG); bool isTriggered_1e1mu = hltPaths_isTriggered(triggers_1e1mu, triggerWhiteList, eventInfo, isMC, isDEBUG); bool isTriggered_2mu = hltPaths_isTriggered(triggers_2mu, triggerWhiteList, eventInfo, isMC, isDEBUG); bool isTriggered_3e = hltPaths_isTriggered(triggers_3e, triggerWhiteList, eventInfo, isMC, isDEBUG); bool isTriggered_2e1mu = hltPaths_isTriggered(triggers_2e1mu, triggerWhiteList, eventInfo, isMC, isDEBUG); bool isTriggered_1e2mu = hltPaths_isTriggered(triggers_1e2mu, triggerWhiteList, eventInfo, isMC, isDEBUG); bool isTriggered_3mu = hltPaths_isTriggered(triggers_3mu, triggerWhiteList, eventInfo, isMC, isDEBUG); if ( isDEBUG ) { std::cout << "isTriggered:" << " 1e = " << isTriggered_1e << "," << " 1mu = " << isTriggered_1mu << "," << " 2e = " << isTriggered_2e << "," << " 1e1mu = " << isTriggered_1e1mu << "," << " 2mu = " << isTriggered_2mu << "," << " 3e = " << isTriggered_3e << "," << " 2e1mu = " << isTriggered_2e1mu << "," << " 1e2mu = " << isTriggered_1e2mu << "," << " 3mu = " << isTriggered_3mu << std::endl; } bool selTrigger_1e = use_triggers_1e && isTriggered_1e; bool selTrigger_1mu = use_triggers_1mu && isTriggered_1mu; bool selTrigger_2e = use_triggers_2e && isTriggered_2e; bool selTrigger_1e1mu = use_triggers_1e1mu && isTriggered_1e1mu; bool selTrigger_2mu = use_triggers_2mu && isTriggered_2mu; bool selTrigger_3e = use_triggers_3e && isTriggered_3e; bool selTrigger_2e1mu = use_triggers_2e1mu && isTriggered_2e1mu; bool selTrigger_1e2mu = use_triggers_1e2mu && isTriggered_1e2mu; bool selTrigger_3mu = use_triggers_3mu && isTriggered_3mu; if ( !(selTrigger_1e || selTrigger_1mu || selTrigger_2e || selTrigger_1e1mu || selTrigger_2mu || selTrigger_3e || selTrigger_2e1mu || selTrigger_1e2mu || selTrigger_3mu) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS trigger selection." << std::endl; std::cout << " (selTrigger_3mu = " << selTrigger_3mu << ", selTrigger_1e2mu = " << selTrigger_1e2mu << ", selTrigger_2e1mu = " << selTrigger_2e1mu << ", selTrigger_3e = " << selTrigger_3e << ", selTrigger_2mu = " << selTrigger_2mu << ", selTrigger_1e1mu = " << selTrigger_1e1mu << ", selTrigger_2e = " << selTrigger_2e << ", selTrigger_1mu = " << selTrigger_1mu << ", selTrigger_1e = " << selTrigger_1e << ")" << std::endl; } continue; } cutFlowTable.update("trigger_0", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("trigger_0", evtWeightRecorder.get(central_or_shift_main)); //--- rank triggers by priority and ignore triggers of lower priority if a trigger of higher priority has fired for given event; // the triggers are ranked by primary dataset (PD). // The ranking of the PDs is as follows: DoubleMuon, MuonEG, DoubleEG, SingleMuon, SingleElectron // CV: see https://cmssdt.cern.ch/lxr/source/HLTrigger/Configuration/python/HLT_GRun_cff.py?v=CMSSW_8_0_24 for association of triggers paths to PD // this logic is necessary to avoid that the same event is selected multiple times when processing different primary datasets if ( !isMC && !isDEBUG ) { //bool isTriggered_SingleElectron = isTriggered_1e; bool isTriggered_SingleMuon = isTriggered_1mu; bool isTriggered_DoubleEG = isTriggered_2e || isTriggered_3e; bool isTriggered_DoubleMuon = isTriggered_2mu || isTriggered_3mu; bool isTriggered_MuonEG = isTriggered_1e1mu || isTriggered_2e1mu || isTriggered_1e2mu; bool selTrigger_SingleElectron = selTrigger_1e; bool selTrigger_SingleMuon = selTrigger_1mu; bool selTrigger_DoubleEG = selTrigger_2e || selTrigger_3e; //bool selTrigger_DoubleMuon = selTrigger_2mu || selTrigger_3mu; bool selTrigger_MuonEG = selTrigger_1e1mu || selTrigger_2e1mu || selTrigger_1e2mu; if ( selTrigger_SingleElectron && (isTriggered_SingleMuon || isTriggered_DoubleMuon || isTriggered_MuonEG) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS trigger selection." << std::endl; std::cout << " (selTrigger_SingleElectron = " << selTrigger_SingleElectron << ", isTriggered_SingleMuon = " << isTriggered_SingleMuon << ", isTriggered_DoubleMuon = " << isTriggered_DoubleMuon << ", isTriggered_MuonEG = " << isTriggered_MuonEG << ")" << std::endl; } continue; } if ( selTrigger_SingleElectron && isTriggered_DoubleEG && era != Era::k2018 ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS trigger selection." << std::endl; std::cout << " (selTrigger_SingleElectron = " << selTrigger_SingleElectron << ", isTriggered_DoubleEG = " << isTriggered_DoubleEG << ")" << std::endl; } continue; } if ( selTrigger_DoubleEG && (isTriggered_DoubleMuon || isTriggered_MuonEG) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS trigger selection." << std::endl; std::cout << " (selTrigger_DoubleEG = " << selTrigger_DoubleEG << ", isTriggered_DoubleMuon = " << isTriggered_DoubleMuon << ", isTriggered_MuonEG = " << isTriggered_MuonEG << ")" << std::endl; } continue; } if ( selTrigger_SingleMuon && (isTriggered_DoubleEG || isTriggered_DoubleMuon || isTriggered_MuonEG) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS trigger selection." << std::endl; std::cout << " (selTrigger_SingleMuon = " << selTrigger_SingleMuon << ", isTriggered_DoubleEG = " << isTriggered_DoubleEG << ", isTriggered_DoubleMuon = " << isTriggered_DoubleMuon << ", isTriggered_MuonEG = " << isTriggered_MuonEG << ")" << std::endl; } continue; } if ( selTrigger_MuonEG && isTriggered_DoubleMuon ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS trigger selection." << std::endl; std::cout << " (selTrigger_MuonEG = " << selTrigger_MuonEG << ", isTriggered_DoubleMuon = " << isTriggered_DoubleMuon << ")" << std::endl; } continue; } } cutFlowTable.update("trigger", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("trigger", evtWeightRecorder.get(central_or_shift_main)); if ( (selTrigger_3mu && !apply_offline_e_trigger_cuts_3mu) || (selTrigger_2e1mu && !apply_offline_e_trigger_cuts_2e1mu) || (selTrigger_1e2mu && !apply_offline_e_trigger_cuts_1e2mu) || (selTrigger_3e && !apply_offline_e_trigger_cuts_3e) || (selTrigger_2mu && !apply_offline_e_trigger_cuts_2mu) || (selTrigger_1e1mu && !apply_offline_e_trigger_cuts_1e1mu) || (selTrigger_2e && !apply_offline_e_trigger_cuts_2e) || (selTrigger_1mu && !apply_offline_e_trigger_cuts_1mu) || (selTrigger_1e && !apply_offline_e_trigger_cuts_1e) ) { fakeableElectronSelector.disable_offline_e_trigger_cuts(); tightElectronSelector.disable_offline_e_trigger_cuts(); } else { fakeableElectronSelector.enable_offline_e_trigger_cuts(); tightElectronSelector.enable_offline_e_trigger_cuts(); } //--- build collections of electrons, muons and hadronic taus; // resolve overlaps in order of priority: muon, electron, const std::vector<RecoMuon> muons = muonReader->read(); const std::vector<const RecoMuon*> muon_ptrs = convert_to_ptrs(muons); const std::vector<const RecoMuon*> cleanedMuons = muon_ptrs; // CV: no cleaning needed for muons, as they have the highest priority in the overlap removal const std::vector<const RecoMuon*> preselMuons = preselMuonSelector(cleanedMuons, isHigherConePt); const std::vector<const RecoMuon*> fakeableMuons = fakeableMuonSelector(preselMuons, isHigherConePt); const std::vector<const RecoMuon*> tightMuons = tightMuonSelector(fakeableMuons, isHigherConePt); if(isDEBUG || run_lumi_eventSelector) { printCollection("preselMuons", preselMuons); printCollection("fakeableMuons", fakeableMuons); printCollection("tightMuons", tightMuons); } const std::vector<RecoElectron> electrons = electronReader->read(); const std::vector<const RecoElectron*> electron_ptrs = convert_to_ptrs(electrons); const std::vector<const RecoElectron*> cleanedElectrons = electronCleaner(electron_ptrs, preselMuons); const std::vector<const RecoElectron*> preselElectrons = preselElectronSelector(cleanedElectrons, isHigherConePt); const std::vector<const RecoElectron*> preselElectronsUncleaned = preselElectronSelector(electron_ptrs, isHigherConePt); const std::vector<const RecoElectron*> fakeableElectrons = fakeableElectronSelector(preselElectrons, isHigherConePt); const std::vector<const RecoElectron*> tightElectrons = tightElectronSelector(fakeableElectrons, isHigherConePt); if(isDEBUG || run_lumi_eventSelector) { printCollection("preselElectrons", preselElectrons); printCollection("preselElectronsUncleaned", preselElectronsUncleaned); printCollection("fakeableElectrons", fakeableElectrons); printCollection("tightElectrons", tightElectrons); } const std::vector<const RecoLepton*> preselLeptonsFull = mergeLeptonCollections(preselElectrons, preselMuons, isHigherConePt); const std::vector<const RecoLepton*> preselLeptonsFullUncleaned = mergeLeptonCollections(preselElectronsUncleaned, preselMuons, isHigherConePt); const std::vector<const RecoLepton*> fakeableLeptonsFull = mergeLeptonCollections(fakeableElectrons, fakeableMuons, isHigherConePt); const std::vector<const RecoLepton*> tightLeptonsFull = mergeLeptonCollections(tightElectrons, tightMuons, isHigherConePt); const std::vector<const RecoLepton*> preselLeptons = pickFirstNobjects(preselLeptonsFull, 3); const std::vector<const RecoLepton*> fakeableLeptons = pickFirstNobjects(fakeableLeptonsFull, 3); const std::vector<const RecoLepton*> tightLeptons = getIntersection(fakeableLeptons, tightLeptonsFull, isHigherConePt); std::vector<const RecoLepton*> selLeptons; std::vector<const RecoMuon*> selMuons; std::vector<const RecoElectron*> selElectrons; if(electronSelection == muonSelection) { // for SR, flip region and fake CR // doesn't matter if we supply electronSelection or muonSelection here selLeptons = selectObjects(muonSelection, preselLeptons, fakeableLeptons, tightLeptons); selMuons = getIntersection(preselMuons, selLeptons, isHigherConePt); selElectrons = getIntersection(preselElectrons, selLeptons, isHigherConePt); } else { // for MC closure // make sure that neither electron nor muon selections are loose assert(electronSelection != kLoose && muonSelection != kLoose); selMuons = selectObjects(muonSelection, preselMuons, fakeableMuons, tightMuons); selElectrons = selectObjects(electronSelection, preselElectrons, fakeableElectrons, tightElectrons); } const std::vector<const RecoLepton*> selLeptons_full = mergeLeptonCollections(selElectrons, selMuons, isHigherConePt); if(!(electronSelection == muonSelection)) selLeptons = getIntersection(fakeableLeptons, selLeptons_full, isHigherConePt); // Lepton reconstruction std::vector<GenParticle*> genLeptonsFromHHTo4W = {genLepton1FromHToWW_2l2nu, genLepton2FromHToWW_2l2nu, genLeptonFromHToWW_lnu_qq}; std::vector<GenParticle*> genElectronsFromHHTo4W; std::vector<GenParticle*> genMuonsFromHHTo4W; for (size_t i=0; i < genLeptonsFromHHTo4W.size(); i++) { if ( ! genLeptonsFromHHTo4W[i]) continue; if (std::abs(genLeptonsFromHHTo4W[i]->pdgId()) == 11) genElectronsFromHHTo4W.push_back(genLeptonsFromHHTo4W[i]); if (std::abs(genLeptonsFromHHTo4W[i]->pdgId()) == 13) genMuonsFromHHTo4W.push_back(genLeptonsFromHHTo4W[i]); } bool isLeptonSelectionEfficiencyStudy = false; if (isLeptonSelectionEfficiencyStudy) { // lepton selection efficiency double max_jetBtagCSV_mu = get_BtagWP(era, Btag::kDeepJet, BtagWP::kMedium); double mvaTTH_wp_mu = 0.85; int nMuGenMatch = 0; int nMuPassPt = 0; int nMuPassConePt = 0; int nMuPassEta = 0; int nMuPassDxy = 0; int nMuPassDz = 0; int nMuPassSidp3d = 0; int nMuPassRelIso = 0; int nMuPassLooseIdPOG = 0; int nMuPassMediumIdPOG = 0; int nMuPassJetBtagMedium = 0; int nMuPassFakeablePromptMva = 0; int nMuFailFakeablePromptMva = 0; int nMuFailFakeablePromptMvaAndPassJetBtag = 0; int nMuFailFakeablePromptMvaAndPassJetBtagAndJetRelIso = 0; int nMuPassTight = 0; int npreselMuGenMatch = 0; int nfakeableMuGenMatch = 0; int ntightMuGenMatch = 0; int nMuPassMediumIdPOGAndJetBTagMedium = 0; int nMuPassMediumIdPOGAndJetBTagInter = 0; int nMuPassMediumIdPOGAndJetBTagInterAndJetRelIso = 0; /* int = 0; int = 0; int = 0; int = 0; int = 0; int = 0; int = 0; int = 0; */ for (size_t iL=0; iL < cleanedMuons.size(); iL++) { const RecoMuon *lep = cleanedMuons[iL]; GenParticle *genP; //if ( ! (isGenMarchFound(lep->p4(), genLeptonsFromHHTo4W, genP))) continue; if ( ! (isGenMarchFound(lep->p4(), genMuonsFromHHTo4W, genP))) continue; nMuGenMatch++; if (lep->lepton_pt() < 5.) continue; nMuPassPt++; if (lep->cone_pt() < 10.) continue; nMuPassConePt++; if (lep->absEta() > 2.4) continue; nMuPassEta++; if (std::abs(lep->dxy()) > 0.05) continue; nMuPassDxy++; if (std::abs(lep->dz()) > 0.1) continue; nMuPassDz++; if (lep->sip3d() > 8.) continue; nMuPassSidp3d++; if (lep->relIso() > 0.4) continue; nMuPassRelIso++; if ( ! lep->passesLooseIdPOG()) continue; nMuPassLooseIdPOG++; if (lep->passesMediumIdPOG()) { nMuPassMediumIdPOG++; if ( ! (lep->jetBtagCSV() > max_jetBtagCSV_mu)) { nMuPassMediumIdPOGAndJetBTagMedium++; } double max_jetBtagCSV_interp = smoothBtagCut(lep->assocJet_pt()); if (lep->jetBtagCSV() <= max_jetBtagCSV_interp) { nMuPassMediumIdPOGAndJetBTagInter++; if( ! (lep->jetPtRatio() < 2./3)) { nMuPassMediumIdPOGAndJetBTagInterAndJetRelIso++; } } } if (lep->jetBtagCSV() > max_jetBtagCSV_mu) continue; nMuPassJetBtagMedium++; if (lep->mvaRawTTH() > mvaTTH_wp_mu ) { // fakeable passed prompt mva nMuPassFakeablePromptMva++; } else { // fakeable failed prompt mva nMuFailFakeablePromptMva++; double max_jetBtagCSV_interp = smoothBtagCut(lep->assocJet_pt()); if (lep->jetBtagCSV() <= max_jetBtagCSV_interp) { nMuFailFakeablePromptMvaAndPassJetBtag++; if( ! (lep->jetPtRatio() < 2./3)) { nMuFailFakeablePromptMvaAndPassJetBtagAndJetRelIso++; } } } if (lep->passesMediumIdPOG() && !(lep->jetBtagCSV() > max_jetBtagCSV_mu) && (lep->mvaRawTTH() > mvaTTH_wp_mu) ) { nMuPassTight++; } } if (nMuGenMatch >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuGenMatch >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassPt >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassPt >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassConePt >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassConePt >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassEta >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassEta >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassDxy >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassDxy >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassDz >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassDz >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassSidp3d >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassSidp3d >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassRelIso >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassRelIso >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassLooseIdPOG >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassLooseIdPOG >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassMediumIdPOG >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassMediumIdPOG >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassJetBtagMedium >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassJetBtagMedium >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); if (nMuPassFakeablePromptMva >= 1) { cutFlowTable.update("nMuPassFakeablePromptMva >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); knMuPassFakeablePromptMva++; } if (nMuFailFakeablePromptMva >= 1) { cutFlowTable.update("nMuFailFakeablePromptMva >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); knMuFailFakeablePromptMva++; } if (nMuFailFakeablePromptMvaAndPassJetBtag >= 1) { cutFlowTable.update("nMuFailFakeablePromptMvaAndPassJetBtag >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuFailFakeablePromptMvaAndPassJetBtagAndJetRelIso >= 1) { cutFlowTable.update("nMuFailFakeablePromptMvaAndPassJetBtagAndJetRelIso >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } } if (nMuPassTight >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassTight >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassMediumIdPOGAndJetBTagMedium >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassMediumIdPOGAndJetBTagMedium >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassMediumIdPOGAndJetBTagInter >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassMediumIdPOGAndJetBTagInter >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nMuPassMediumIdPOGAndJetBTagInterAndJetRelIso >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nMuPassMediumIdPOGAndJetBTagInterAndJetRelIso >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } for (size_t iL=0; iL < preselMuons.size(); iL++) { const RecoLepton *lep = preselMuons[iL]; GenParticle *genP; if ( ! (isGenMarchFound(lep->p4(), genMuonsFromHHTo4W, genP))) continue; npreselMuGenMatch++; } if (npreselMuGenMatch >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("npreselMuGenMatch >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } for (size_t iL=0; iL < fakeableMuons.size(); iL++) { const RecoLepton *lep1 = fakeableMuons[iL]; GenParticle *genP; if ( ! (isGenMarchFound(lep1->p4(), genMuonsFromHHTo4W, genP))) continue; nfakeableMuGenMatch++; const RecoMuon *lep = dynamic_cast<const RecoMuon *>(lep1); std::string sFailedLep; if (lep->lepton_pt() < 5.) sFailedLep += "(lep->lepton_pt() < 5.), "; if (lep->cone_pt() < 10.) sFailedLep += "(lep->cone_pt() < 10.), "; if (lep->absEta() > 2.4) sFailedLep += "(lep->absEta() > 2.4), "; if (std::abs(lep->dxy()) > 0.05) sFailedLep += "(std::abs(lep->dxy()) > 0.05), "; if (std::abs(lep->dz()) > 0.1) sFailedLep += "(std::abs(lep->dz()) > 0.1), "; if (lep->sip3d() > 8.) sFailedLep += "(lep->sip3d() > 8.), "; if (lep->relIso() > 0.4) sFailedLep += "(lep->relIso() > 0.4), "; if ( ! lep->passesLooseIdPOG()) sFailedLep += "( ! lep->passesLooseIdPOG()), "; if (lep->jetBtagCSV() > max_jetBtagCSV_mu) sFailedLep += "(lep->jetBtagCSV() > max_jetBtagCSV_mu), "; if (lep->jetBtagCSV() <= max_jetBtagCSV_mu) { double max_jetBtagCSV_interp = smoothBtagCut(lep->assocJet_pt()); if (lep->jetBtagCSV() > max_jetBtagCSV_interp) sFailedLep += "(lep->jetBtagCSV() > max_jetBtagCSV_interp), "; if( (lep->jetPtRatio() < 2./3)) sFailedLep += "(lep->jetPtRatio() < 2./3), "; } if ( ! sFailedLep.empty()) { if (printLevel > 4) std::cout << "Fakeable lepton strutiny iL:" << iL << ", failed condition: " << sFailedLep << ", \t lep: " << *lep << std::endl; cutFlowTable.update(Form("FakeableMuon scrutiny: %s",sFailedLep.data()), evtWeightRecorder.get(central_or_shift_main)); } } if (nfakeableMuGenMatch >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("nfakeableMuGenMatch >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } for (size_t iL=0; iL < tightMuons.size(); iL++) { const RecoLepton *lep = tightMuons[iL]; GenParticle *genP; if ( ! (isGenMarchFound(lep->p4(), genMuonsFromHHTo4W, genP))) continue; ntightMuGenMatch++; } if (ntightMuGenMatch >= nGenMuFromHHTo4W && nGenMuFromHHTo4W > 0) { cutFlowTable.update("ntightMuGenMatch >= nGenMuFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } double binning_absEta_ele = 1.479; double min_sigmaEtaEta_trig_ele = 0.011; double max_sigmaEtaEta_trig_ele = 0.019; double max_HoE_trig_ele = 0.10; double min_OoEminusOoP_trig_ele = -0.04; double max_jetBtagCSV_ele = get_BtagWP(era, Btag::kDeepJet, BtagWP::kMedium); double wp_mvaTTH_ele = 0.80; double min_jetPtRatio_ele = (1. / 1.7); int nEleGenMatch = 0; int nElePassPt = 0; int nElePassConePt = 0; int nElePassEta = 0; int nElePassDxy = 0; int nElePassDz = 0; int nElePassSidp3d = 0; int nElePassRelIso = 0; int nElePassNLostHits1 = 0; int nElePassLooseIdPOG = 0; int nElePassNLostHits0 = 0; int nElePassSigmaEtaEta = 0; int nElePassHoE = 0; int nElePassOoEminusOoP = 0; int nElePassConversions = 0; int nElePassWP80IdPOG = 0; int nElePassJetBtagMedium = 0; int nElePassPromptMva = 0; int nEleFailPromptMva = 0; int nEleFailPromptMvaAndPassWP80IdPOG = 0; int nEleFailPromptMvaAndPassWP80IdPOGAndJetRelIso = 0; int nElePassTight = 0; int nElePassWP80IdPOGAndJetBTagMedium = 0; int nElePassWP80IdPOGAndJetBTagMediumAndJetRelIso = 0; int npreselEleGenMatch = 0; int nfakeableEleGenMatch = 0; int ntightEleGenMatch = 0; for (size_t iL=0; iL < cleanedElectrons.size(); iL++) { const RecoElectron *lep = cleanedElectrons[iL]; GenParticle *genP; //if ( ! (isGenMarchFound(lep->p4(), genLeptonsFromHHTo4W, genP))) continue; if ( ! (isGenMarchFound(lep->p4(), genElectronsFromHHTo4W, genP))) continue; nEleGenMatch++; if (lep->lepton_pt() < 5.) continue; nElePassPt++; if (lep->cone_pt() < 10.) continue; nElePassConePt++; if (lep->absEta() > 2.5) continue; nElePassEta++; if (std::abs(lep->dxy()) > 0.05) continue; nElePassDxy++; if (std::abs(lep->dz()) > 0.1) continue; nElePassDz++; if (lep->sip3d() > 8.) continue; nElePassSidp3d++; if (lep->relIso() > 0.4) continue; nElePassRelIso++; if (lep->nLostHits() > 1) continue; nElePassNLostHits1++; if ( ! lep->mvaID_POG(EGammaWP::WPL)) continue; nElePassLooseIdPOG++; if (lep->nLostHits() > 0) continue; nElePassNLostHits0++; double max_sigmaEtaEta_trig = min_sigmaEtaEta_trig_ele + max_sigmaEtaEta_trig_ele * (lep->absEtaSC() > binning_absEta_ele); if (lep->sigmaEtaEta() > max_sigmaEtaEta_trig) continue; nElePassSigmaEtaEta++; if (lep->HoE() > max_HoE_trig_ele) continue; nElePassHoE++; if (lep->OoEminusOoP() < min_OoEminusOoP_trig_ele) continue; nElePassOoEminusOoP++; if ( ! lep->passesConversionVeto()) continue; nElePassConversions++; if(lep->mvaID_POG(EGammaWP::WP80)) { nElePassWP80IdPOG++; if ( ! (lep->jetBtagCSV() > max_jetBtagCSV_ele)) { nElePassWP80IdPOGAndJetBTagMedium++; if ( !(lep->jetPtRatio() < min_jetPtRatio_ele)) { nElePassWP80IdPOGAndJetBTagMediumAndJetRelIso++; } } } if (lep->jetBtagCSV() > max_jetBtagCSV_ele) continue; nElePassJetBtagMedium++; if (lep->mvaRawTTH() > wp_mvaTTH_ele) { // fakeable/tight passed prompt ele mva nElePassPromptMva++; nElePassTight++; } else { // fakeable failed prompt ele mva nEleFailPromptMva++; if (lep->mvaID_POG(EGammaWP::WP80)) { nEleFailPromptMvaAndPassWP80IdPOG++; if ( !(lep->jetPtRatio() < min_jetPtRatio_ele)) { nEleFailPromptMvaAndPassWP80IdPOGAndJetRelIso++; } } } } if (nEleGenMatch >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nEleGenMatch >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassPt >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassPt >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassConePt >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassConePt >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassEta >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassEta >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassDxy >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassDxy >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassDz >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassDz >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassSidp3d >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassSidp3d >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassRelIso >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassRelIso >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassNLostHits1 >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassNLostHits_1 >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassLooseIdPOG >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassLooseIdPOG >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassNLostHits0 >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassNLostHits_0 >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassSigmaEtaEta >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassSigmaEtaEta >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassHoE >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassHoE >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassOoEminusOoP >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassOoEminusOoP >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassConversions >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassConversions >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassWP80IdPOG >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassWP80IdPOG >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassJetBtagMedium >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassJetBtagMedium >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); if (nElePassPromptMva >= 1) { cutFlowTable.update("nElePassPromptMva >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nEleFailPromptMva >= 1) { cutFlowTable.update("nEleFailPromptMva >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nEleFailPromptMvaAndPassWP80IdPOG >= 1) { cutFlowTable.update("nEleFailPromptMvaAndPassWP80IdPOG >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nEleFailPromptMvaAndPassWP80IdPOGAndJetRelIso >= 1) { cutFlowTable.update("nEleFailPromptMvaAndPassWP80IdPOGAndJetRelIso >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } } if (nElePassTight >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassTight >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassWP80IdPOGAndJetBTagMedium >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassWP80IdPOGAndJetBTagMedium >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } if (nElePassWP80IdPOGAndJetBTagMediumAndJetRelIso >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nElePassWP80IdPOGAndJetBTagMediumAndJetRelIso >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } for (size_t iL=0; iL < preselElectrons.size(); iL++) { const RecoLepton *lep = preselElectrons[iL]; GenParticle *genP; if ( ! (isGenMarchFound(lep->p4(), genElectronsFromHHTo4W, genP))) continue; npreselEleGenMatch++; } if (npreselEleGenMatch >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("npreselEleGenMatch >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } for (size_t iL=0; iL < fakeableElectrons.size(); iL++) { const RecoLepton *lep = fakeableElectrons[iL]; GenParticle *genP; if ( ! (isGenMarchFound(lep->p4(), genElectronsFromHHTo4W, genP))) continue; nfakeableEleGenMatch++; } if (nfakeableEleGenMatch >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("nfakeableEleGenMatch >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } for (size_t iL=0; iL < tightElectrons.size(); iL++) { const RecoLepton *lep = tightElectrons[iL]; GenParticle *genP; if ( ! (isGenMarchFound(lep->p4(), genElectronsFromHHTo4W, genP))) continue; ntightEleGenMatch++; } if (ntightEleGenMatch >= nGenEleFromHHTo4W && nGenEleFromHHTo4W > 0) { cutFlowTable.update("ntightEleGenMatch >= nGenEleFromHHTo4W", evtWeightRecorder.get(central_or_shift_main)); } //continue; } int npreselLeptonsFullGenMatch = 0; int npreselLeptonsFullGenMatchHHTo4WLeps = 0; if (printLevel > 5) printf("preselLeptonsFull:\n"); for (size_t iL=0; iL < preselLeptonsFull.size(); iL++) { const RecoLepton *lep = preselLeptonsFull[iL]; GenParticle *genP; if (lep->genLepton()) { npreselLeptonsFullGenMatch++; if (std::abs(lep->pdgId()) == 11) { fillHistogram_ptResolution(hptResolution_preselLeptonsFull_Ele[genMatchIdx_0], lep->p4(), lep->genLepton()->p4()); } if (std::abs(lep->pdgId()) == 13) { fillHistogram_ptResolution(hptResolution_preselLeptonsFull_Mu[genMatchIdx_0], lep->p4(), lep->genLepton()->p4()); } } if (isGenMarchFound(lep->p4(), genLeptonsFromHHTo4W, genP)) { npreselLeptonsFullGenMatchHHTo4WLeps++; if (std::abs(lep->pdgId()) == 11) { fillHistogram_ptResolution(hptResolution_preselLeptonsFull_GenMatchHHTo4WLeps_Ele[genMatchIdx_0], lep->p4(), genP->p4()); } if (std::abs(lep->pdgId()) == 13) { fillHistogram_ptResolution(hptResolution_preselLeptonsFull_GenMatchHHTo4WLeps_Mu[genMatchIdx_0], lep->p4(), genP->p4()); } } if (printLevel > 5) { std::cout << "iL:" << iL << ", recoLep: " << *lep << std::endl; std::cout << "\t isGenMatchFound: " << isGenMarchFound(lep->p4(), genLeptonsFromHHTo4W) << ", genLpton: " << lep->genLepton() << std::endl; } } if (npreselLeptonsFullGenMatch >= 1) { cutFlowTable.update(Form("reco: no. preselLeptonsFull genMatch: >=1"), evtWeightRecorder.get(central_or_shift_main)); if (npreselLeptonsFullGenMatch >= 2) { cutFlowTable.update(Form("reco: no. preselLeptonsFull genMatch: >=2"), evtWeightRecorder.get(central_or_shift_main)); if (npreselLeptonsFullGenMatch >= 3) { cutFlowTable.update(Form("reco: no. preselLeptonsFull genMatch: >=3"), evtWeightRecorder.get(central_or_shift_main)); } } } if (npreselLeptonsFullGenMatchHHTo4WLeps >= 1) { cutFlowTable.update(Form("reco: no. preselLeptonsFull genMatchHHTo4WLeps: >=1"), evtWeightRecorder.get(central_or_shift_main)); if (npreselLeptonsFullGenMatchHHTo4WLeps >= 2) { cutFlowTable.update(Form("reco: no. preselLeptonsFull genMatchHHTo4WLeps: >=2"), evtWeightRecorder.get(central_or_shift_main)); if (npreselLeptonsFullGenMatchHHTo4WLeps >= 3) { cutFlowTable.update(Form("reco: no. preselLeptonsFull genMatchHHTo4WLeps: >=3"), evtWeightRecorder.get(central_or_shift_main)); } } } int nfakeableLeptonsFullGenMatch = 0; int nfakeableLeptonsFullGenMatchHHTo4WLeps = 0; if (printLevel > 5) printf("fakeableLeptonsFull:\n"); for (size_t iL=0; iL < fakeableLeptonsFull.size(); iL++) { const RecoLepton *lep = fakeableLeptonsFull[iL]; GenParticle *genP; if (lep->genLepton()) { nfakeableLeptonsFullGenMatch++; if (std::abs(lep->pdgId()) == 11) { fillHistogram_ptResolution(hptResolution_fakeableLeptonsFull_Ele[genMatchIdx_0], lep->p4(), lep->genLepton()->p4()); } if (std::abs(lep->pdgId()) == 13) { fillHistogram_ptResolution(hptResolution_fakeableLeptonsFull_Mu[genMatchIdx_0], lep->p4(), lep->genLepton()->p4()); } } if (isGenMarchFound(lep->p4(), genLeptonsFromHHTo4W, genP)) { nfakeableLeptonsFullGenMatchHHTo4WLeps++; if (std::abs(lep->pdgId()) == 11) { fillHistogram_ptResolution(hptResolution_fakeableLeptonsFull_GenMatchHHTo4WLeps_Ele[genMatchIdx_0], lep->p4(), genP->p4()); } if (std::abs(lep->pdgId()) == 13) { fillHistogram_ptResolution(hptResolution_fakeableLeptonsFull_GenMatchHHTo4WLeps_Mu[genMatchIdx_0], lep->p4(), genP->p4()); } } if (printLevel > 5) { std::cout << "iL:" << iL << ", recoLep: " << *lep << std::endl; std::cout << "\t isGenMatchFound: " << isGenMarchFound(lep->p4(), genLeptonsFromHHTo4W) << ", genLpton: " << lep->genLepton() << std::endl; } } if (nfakeableLeptonsFullGenMatch >= 1) { cutFlowTable.update(Form("reco: no. fakeableLeptonsFull genMatch: >=1"), evtWeightRecorder.get(central_or_shift_main)); if (nfakeableLeptonsFullGenMatch >= 2) { cutFlowTable.update(Form("reco: no. fakeableLeptonsFull genMatch: >=2"), evtWeightRecorder.get(central_or_shift_main)); if (nfakeableLeptonsFullGenMatch >= 3) { cutFlowTable.update(Form("reco: no. fakeableLeptonsFull genMatch: >=3"), evtWeightRecorder.get(central_or_shift_main)); } } } if (nfakeableLeptonsFullGenMatchHHTo4WLeps >= 1) { cutFlowTable.update(Form("reco: no. fakeableLeptonsFull genMatchHHTo4WLeps: >=1"), evtWeightRecorder.get(central_or_shift_main)); if (nfakeableLeptonsFullGenMatchHHTo4WLeps >= 2) { cutFlowTable.update(Form("reco: no. fakeableLeptonsFull genMatchHHTo4WLeps: >=2"), evtWeightRecorder.get(central_or_shift_main)); if (nfakeableLeptonsFullGenMatchHHTo4WLeps >= 3) { cutFlowTable.update(Form("reco: no. fakeableLeptonsFull genMatchHHTo4WLeps: >=3"), evtWeightRecorder.get(central_or_shift_main)); } } } int ntightLeptonsFullGenMatch = 0; int ntightLeptonsFullGenMatchHHTo4WLeps = 0; if (printLevel > 5) printf("tightLeptonsFull:\n"); for (size_t iL=0; iL < tightLeptonsFull.size(); iL++) { const RecoLepton *lep = tightLeptonsFull[iL]; GenParticle *genP; if (lep->genLepton()) { ntightLeptonsFullGenMatch++; if (std::abs(lep->pdgId()) == 11) { fillHistogram_ptResolution(hptResolution_tightLeptonsFull_Ele[genMatchIdx_0], lep->p4(), lep->genLepton()->p4()); } if (std::abs(lep->pdgId()) == 13) { fillHistogram_ptResolution(hptResolution_tightLeptonsFull_Mu[genMatchIdx_0], lep->p4(), lep->genLepton()->p4()); } } if (isGenMarchFound(lep->p4(), genLeptonsFromHHTo4W, genP)) { ntightLeptonsFullGenMatchHHTo4WLeps++; if (std::abs(lep->pdgId()) == 11) { fillHistogram_ptResolution(hptResolution_tightLeptonsFull_GenMatchHHTo4WLeps_Ele[genMatchIdx_0], lep->p4(), genP->p4()); } if (std::abs(lep->pdgId()) == 13) { fillHistogram_ptResolution(hptResolution_tightLeptonsFull_GenMatchHHTo4WLeps_Mu[genMatchIdx_0], lep->p4(), genP->p4()); } } if (printLevel > 5) { std::cout << "iL:" << iL << ", recoLep: " << *lep << std::endl; std::cout << "\t isGenMatchFound: " << isGenMarchFound(lep->p4(), genLeptonsFromHHTo4W) << ", genLpton: " << lep->genLepton() << std::endl; } } if (ntightLeptonsFullGenMatch >= 1) { cutFlowTable.update(Form("reco: no. tightLeptonsFull genMatch: >=1"), evtWeightRecorder.get(central_or_shift_main)); if (ntightLeptonsFullGenMatch >= 2) { cutFlowTable.update(Form("reco: no. tightLeptonsFull genMatch: >=2"), evtWeightRecorder.get(central_or_shift_main)); if (ntightLeptonsFullGenMatch >= 3) { cutFlowTable.update(Form("reco: no. tightLeptonsFull genMatch: >=3"), evtWeightRecorder.get(central_or_shift_main)); } } } if (ntightLeptonsFullGenMatchHHTo4WLeps >= 1) { cutFlowTable.update(Form("reco: no. tightLeptonsFull genMatchHHTo4WLeps: >=1"), evtWeightRecorder.get(central_or_shift_main)); if (ntightLeptonsFullGenMatchHHTo4WLeps >= 2) { cutFlowTable.update(Form("reco: no. tightLeptonsFull genMatchHHTo4WLeps: >=2"), evtWeightRecorder.get(central_or_shift_main)); if (ntightLeptonsFullGenMatchHHTo4WLeps >= 3) { cutFlowTable.update(Form("reco: no. tightLeptonsFull genMatchHHTo4WLeps: >=3"), evtWeightRecorder.get(central_or_shift_main)); } } } int nselLeptonsGenMatch = 0; int nselLeptonsGenMatchHHTo4WLeps = 0; if (printLevel > 5) printf("selLeptons:\n"); for (size_t iL=0; iL < selLeptons.size(); iL++) { const RecoLepton *lep = selLeptons[iL]; if (lep->genLepton()) nselLeptonsGenMatch++; if (isGenMarchFound(lep->p4(), genLeptonsFromHHTo4W)) nselLeptonsGenMatchHHTo4WLeps++; if (printLevel > 5) { std::cout << "iL:" << iL << ", recoLep: " << *lep << std::endl; std::cout << "\t isGenMatchFound: " << isGenMarchFound(lep->p4(), genLeptonsFromHHTo4W) << ", genLpton: " << lep->genLepton() << std::endl; } } if (nselLeptonsGenMatch >= 1) { cutFlowTable.update(Form("reco: no. selLeptons genMatch: >=1"), evtWeightRecorder.get(central_or_shift_main)); if (nselLeptonsGenMatch >= 2) { cutFlowTable.update(Form("reco: no. selLeptons genMatch: >=2"), evtWeightRecorder.get(central_or_shift_main)); if (nselLeptonsGenMatch >= 3) { cutFlowTable.update(Form("reco: no. selLeptons genMatch: >=3"), evtWeightRecorder.get(central_or_shift_main)); } } } if (nselLeptonsGenMatchHHTo4WLeps >= 1) { cutFlowTable.update(Form("reco: no. selLeptons genMatchHHTo4WLeps: >=1"), evtWeightRecorder.get(central_or_shift_main)); if (nselLeptonsGenMatchHHTo4WLeps >= 2) { cutFlowTable.update(Form("reco: no. selLeptons genMatchHHTo4WLeps: >=2"), evtWeightRecorder.get(central_or_shift_main)); if (nselLeptonsGenMatchHHTo4WLeps >= 3) { cutFlowTable.update(Form("reco: no. selLeptons genMatchHHTo4WLeps: >=3"), evtWeightRecorder.get(central_or_shift_main)); } } } const std::vector<RecoHadTau> hadTaus = hadTauReader->read(); const std::vector<const RecoHadTau*> hadTau_ptrs = convert_to_ptrs(hadTaus); const std::vector<const RecoHadTau*> cleanedHadTaus = hadTauCleaner(hadTau_ptrs, preselMuons, preselElectrons); const std::vector<const RecoHadTau*> fakeableHadTaus = fakeableHadTauSelector(cleanedHadTaus, isHigherPt); const std::vector<const RecoHadTau*> selHadTaus = tightHadTauSelector(cleanedHadTaus, isHigherPt); if(isDEBUG || run_lumi_eventSelector) { printCollection("selMuons", selMuons); printCollection("selElectrons", selElectrons); printCollection("selLeptons", selLeptons); printCollection("selHadTaus", selHadTaus); } //--- build collections of jets and select subset of jets passing b-tagging criteria const std::vector<RecoJet> jets_ak4 = jetReaderAK4->read(); const std::vector<const RecoJet*> jet_ptrs_ak4 = convert_to_ptrs(jets_ak4); const std::vector<const RecoJet*> cleanedJetsAK4_wrtLeptons = jetCleanerAK4_dR04(jet_ptrs_ak4, fakeableLeptons); const std::vector<const RecoJet*> cleanedJetsAK4 = jetCleaningByIndex ? jetCleanerAK4_byIndex(jet_ptrs_ak4, selectBDT ? selLeptons_full : fakeableLeptonsFull, fakeableHadTaus) : jetCleanerAK4_dR04 (jet_ptrs_ak4, selectBDT ? selLeptons_full : fakeableLeptonsFull, fakeableHadTaus) ; const std::vector<const RecoJet*> selJetsAK4 = jetSelectorAK4(cleanedJetsAK4, isHigherPt); const std::vector<const RecoJet*> selBJetsAK4_loose = jetSelectorAK4_bTagLoose(cleanedJetsAK4, isHigherPt); const std::vector<const RecoJet*> selBJetsAK4_medium = jetSelectorAK4_bTagMedium(cleanedJetsAK4, isHigherPt); int numSelJetsPtGt40 = countHighPtObjects(selJetsAK4, 40.); if(isDEBUG || run_lumi_eventSelector) { printCollection("uncleanedJetsAK4", jet_ptrs_ak4); printCollection("selJetsAK4", selJetsAK4); } std::vector<GenParticle*> genJetsFromHHTo4W = {genJet1FromHToWW_lnu_qq, genJet2FromHToWW_lnu_qq}; std::map<int, int> idxselJetsAK4_GenMatched; // <idxGenJet, idxselJet> idxselJetsAK4_GenMatched[0] = -1; idxselJetsAK4_GenMatched[1] = -1; int nselJetsAK4GenMatch = 0; int nselJetsAK4GenMatchHHTo4WJets = 0; if (printLevel > 4) printf("selJetsAK4:\n"); for (size_t iJ=0; iJ < selJetsAK4.size(); iJ++) { const RecoJet *jet = selJetsAK4[iJ]; int idxGenParticleMatch = -1; if (jet->genJet()) { nselJetsAK4GenMatch++; fillHistogram_ptResolution(hptResolution_AK4[genMatchIdx_0], jet->p4(), jet->genJet()->p4()); } if (isGenMarchFound(jet->p4(), genJetsFromHHTo4W, idxGenParticleMatch)) { nselJetsAK4GenMatchHHTo4WJets++; idxselJetsAK4_GenMatched[idxGenParticleMatch] = iJ; fillHistogram_ptResolution(hptResolution_AK4_GenMatchHHTo4WJets[genMatchIdx_0], jet->p4(), genJetsFromHHTo4W[idxGenParticleMatch]->p4()); } if (printLevel > 4) { std::cout << "iJ:" << iJ << ", recoJet: " << *jet << std::endl; std::cout << "\t isGenMatchFound: " << isGenMarchFound(jet->p4(), genJetsFromHHTo4W) << ", genJet: " << jet->genJet() << std::endl; } } if (nselJetsAK4GenMatch >=1) { cutFlowTable.update(Form("reco: no. selJetsAK4 genMatch: >=1"), evtWeightRecorder.get(central_or_shift_main)); if (nselJetsAK4GenMatch >=2) { cutFlowTable.update(Form("reco: no. selJetsAK4 genMatch: >=2"), evtWeightRecorder.get(central_or_shift_main)); } } if (nselJetsAK4GenMatchHHTo4WJets >=1) { cutFlowTable.update(Form("reco: no. selJetsAK4 genMatchHHTo4WJets: >=1"), evtWeightRecorder.get(central_or_shift_main)); if (nselJetsAK4GenMatchHHTo4WJets >=2) { cutFlowTable.update(Form("reco: no. selJetsAK4 genMatchHHTo4WJets: >=2"), evtWeightRecorder.get(central_or_shift_main)); } } std::vector<RecoJetAK8> jets_ak8_Wjj = jetReaderAK8_Wjj->read(); std::vector<const RecoJetAK8*> jet_ptrs_ak8_Wjj = convert_to_ptrs(jets_ak8_Wjj); std::vector<const RecoJetAK8*> selJetsAK8_all = jet_ptrs_ak8_Wjj; std::vector<const RecoJetAK8*> selJetsAK8_selectorAK8 = jetSelectorAK8(jet_ptrs_ak8_Wjj, isHigherPt); if(isDEBUG || run_lumi_eventSelector) { printCollection("uncleaned AK8 jets (Wjj)", jet_ptrs_ak8_Wjj); } //cutFlowTable.update(Form("reco: nAK8: %lu, nAK8 w/ AK8 selector: %lu",jet_ptrs_ak8_Wjj.size(),selJetsAK8_selectorAK8.size()), evtWeightRecorder.get(central_or_shift_main)); std::vector<const RecoJetAK8*> selJetsAK8_all_GenMatched; std::map<int, int> idxSubjetSelJetsAK8_all_GenMatched; // <idxGenJet, idxSubiet of AK8> idxSubjetSelJetsAK8_all_GenMatched[0] = -1; idxSubjetSelJetsAK8_all_GenMatched[1] = -1; int nselJetsAK8_allGenMatch = 0; int nselJetsAK8_allGenMatchHHTo4WJets = 0; if (printLevel > 4) printf("selJetsAK8_all:\n"); for (size_t iJ=0; iJ < selJetsAK8_all.size(); iJ++) { const RecoJetAK8 * jetAK8 = selJetsAK8_all[iJ]; const RecoSubjetAK8* subjet1 = jetAK8->subJet1(); const RecoSubjetAK8* subjet2 = jetAK8->subJet2(); Particle::LorentzVector LVGenWjj; bool isJetAK8GenMatch = false; bool isSubjet1AK8GenMatch = false; bool isSubjet2AK8GenMatch = false; int idxGenParticleMatch_0 = -1; int idxGenParticleMatch_1 = -1; if ( !(subjet1 && subjet2)) continue; if ( ( ! genJet1FromHToWW_lnu_qq) || ( ! genJet2FromHToWW_lnu_qq)) continue; LVGenWjj = genJet1FromHToWW_lnu_qq->p4() + genJet2FromHToWW_lnu_qq->p4(); if ((deltaR(jetAK8->p4(), LVGenWjj) < 0.3) && (std::abs(jetAK8->pt() - LVGenWjj.pt()) < 0.5*LVGenWjj.pt()) ) { isJetAK8GenMatch = true; } if (isGenMarchFound(subjet1->p4(), genJetsFromHHTo4W, idxGenParticleMatch_0)) { isSubjet1AK8GenMatch = true; } if (isGenMarchFound(subjet2->p4(), genJetsFromHHTo4W, idxGenParticleMatch_1)) { isSubjet2AK8GenMatch = true; } if (isJetAK8GenMatch && isSubjet1AK8GenMatch && isSubjet2AK8GenMatch) { selJetsAK8_all_GenMatched.push_back(jetAK8); idxSubjetSelJetsAK8_all_GenMatched[idxGenParticleMatch_0] = 0; idxSubjetSelJetsAK8_all_GenMatched[idxGenParticleMatch_1] = 1; nselJetsAK8_allGenMatchHHTo4WJets++; fillHistogram_ptResolution(hptResolution_AK8subjet_GenMatchHHTo4WJets[genMatchIdx_0], subjet1->p4(), genJetsFromHHTo4W[idxGenParticleMatch_0]->p4()); fillHistogram_ptResolution(hptResolution_AK8subjet_GenMatchHHTo4WJets[genMatchIdx_0], subjet2->p4(), genJetsFromHHTo4W[idxGenParticleMatch_1]->p4()); } if (printLevel > 4) { std::cout << "iJ:" << iJ << ", recoJet: " << *jetAK8 << std::endl; std::cout << "\t isJetAK8GenMatch: " << isJetAK8GenMatch << ", isSubjet1AK8GenMatch: " << isSubjet1AK8GenMatch << ", isSubjet2AK8GenMatch: " << isSubjet2AK8GenMatch << std::endl; } } if (nselJetsAK8_allGenMatchHHTo4WJets >=1) { cutFlowTable.update(Form("reco: no. selJetsAK8_all genMatch From HHTo4W jets: >=1"), evtWeightRecorder.get(central_or_shift_main)); } std::vector<const RecoJetAK8*> selJetsAK8_selectorAK8_GenMatched; std::map<int, int> idxSubjetselJetsAK8_selectorAK8_GenMatched; // <idxGenJet, idxSubiet of AK8> idxSubjetselJetsAK8_selectorAK8_GenMatched[0] = -1; idxSubjetselJetsAK8_selectorAK8_GenMatched[1] = -1; int nselJetsAK8_selectorAK8GenMatch = 0; int nselJetsAK8_selectorAK8GenMatchHHTo4WJets = 0; if (printLevel > 4) printf("selJetsAK8_selectorAK8:\n"); for (size_t iJ=0; iJ < selJetsAK8_selectorAK8.size(); iJ++) { const RecoJetAK8 * jetAK8 = selJetsAK8_selectorAK8[iJ]; const RecoSubjetAK8* subjet1 = jetAK8->subJet1(); const RecoSubjetAK8* subjet2 = jetAK8->subJet2(); Particle::LorentzVector LVGenWjj = genJet1FromHToWW_lnu_qq->p4() + genJet2FromHToWW_lnu_qq->p4(); bool isJetAK8GenMatch = false; bool isSubjet1AK8GenMatch = false; bool isSubjet2AK8GenMatch = false; int idxGenParticleMatch_0 = -1; int idxGenParticleMatch_1 = -1; if ( !(subjet1 && subjet2)) continue; if ((deltaR(jetAK8->p4(), LVGenWjj) < 0.3) && (std::abs(jetAK8->pt() - LVGenWjj.pt()) < 0.5*LVGenWjj.pt()) ) { isJetAK8GenMatch = true; } if (isGenMarchFound(subjet1->p4(), genJetsFromHHTo4W, idxGenParticleMatch_0)) { isSubjet1AK8GenMatch = true; } if (isGenMarchFound(subjet2->p4(), genJetsFromHHTo4W, idxGenParticleMatch_1)) { isSubjet2AK8GenMatch = true; } if (isJetAK8GenMatch && isSubjet1AK8GenMatch && isSubjet2AK8GenMatch) { selJetsAK8_selectorAK8_GenMatched.push_back(jetAK8); idxSubjetselJetsAK8_selectorAK8_GenMatched[idxGenParticleMatch_0] = 0; idxSubjetselJetsAK8_selectorAK8_GenMatched[idxGenParticleMatch_1] = 1; nselJetsAK8_selectorAK8GenMatchHHTo4WJets++; } if (printLevel > 4) { std::cout << "iJ:" << iJ << ", recoJet: " << *jetAK8 << std::endl; std::cout << "\t isJetAK8GenMatch: " << isJetAK8GenMatch << ", isSubjet1AK8GenMatch: " << isSubjet1AK8GenMatch << ", isSubjet2AK8GenMatch: " << isSubjet2AK8GenMatch << std::endl; } } if (nselJetsAK8_selectorAK8GenMatchHHTo4WJets >=1) { cutFlowTable.update(Form("reco: no. selJetsAK8_selectorAK8 genMatch From HHTo4W jets: >=1"), evtWeightRecorder.get(central_or_shift_main)); } if (selJetsAK8_selectorAK8_GenMatched.size() == 1 && idxSubjetselJetsAK8_selectorAK8_GenMatched[0] != -1 && idxSubjetselJetsAK8_selectorAK8_GenMatched[1] != -1 && idxselJetsAK4_GenMatched[0] != -1 && idxselJetsAK4_GenMatched[1] != -1) { const RecoJetAK8 *jetAK8 = selJetsAK8_selectorAK8_GenMatched[0]; std::vector<const RecoSubjetAK8*> subjetsAK8 = {jetAK8->subJet1(), jetAK8->subJet2()}; double mjj_gen = (genJetsFromHHTo4W[0]->p4() + genJetsFromHHTo4W[1]->p4()).mass(); double mjj_AK4 = (selJetsAK4[idxselJetsAK4_GenMatched[0]]->p4() + selJetsAK4[idxselJetsAK4_GenMatched[1]]->p4()).mass(); double mjj_AK8 = (jetAK8->subJet1()->p4() + jetAK8->subJet2()->p4()).mass(); double ptW_gen = (genJetsFromHHTo4W[0]->p4() + genJetsFromHHTo4W[1]->p4()).pt(); hmass_jj_AK4_AK8Overlap[genMatchIdx_0]->Fill(mjj_AK4); hmass_jj_AK8_AK4Overlap[genMatchIdx_0]->Fill(mjj_AK8); hmass_Genjj_AK8_AK4Overlap[genMatchIdx_0]->Fill(mjj_gen); hmassResolutionAK4_AK8Overlap_0[genMatchIdx_0]->Fill((mjj_AK4 - mjj_gen)/mjj_gen); hmassResolutionAK8_AK4Overlap_0[genMatchIdx_0]->Fill((mjj_AK8 - mjj_gen)/mjj_gen); hmassResolutionAK4_0_vs_ptWGen_AK8Overlap[genMatchIdx_0]->Fill(ptW_gen, (mjj_AK4 - mjj_gen)/mjj_gen); hmassResolutionAK8_0_vs_ptWGen_AK4Overlap[genMatchIdx_0]->Fill(ptW_gen, (mjj_AK8 - mjj_gen)/mjj_gen); for (int iGenP=0; iGenP < 2; iGenP++) { GenParticle *genParticle = genJetsFromHHTo4W[iGenP]; const RecoJet *jetAK4 = selJetsAK4[idxselJetsAK4_GenMatched[iGenP]]; const RecoSubjetAK8* subjetAK8 = subjetsAK8[idxSubjetselJetsAK8_selectorAK8_GenMatched[iGenP]]; double pt_gen = genParticle->pt(); double pt_ak4 = jetAK4->pt(); double pt_ak8 = subjetAK8->pt(); double m_gen = genParticle->mass(); double m_ak4 = jetAK4->mass(); double m_ak8 = subjetAK8->mass(); hptResolutionAK4_AK8Overlap[genMatchIdx_0]->Fill((pt_ak4 - pt_gen)/pt_gen); hmassResolutionAK4_AK8Overlap[genMatchIdx_0]->Fill((m_ak4 - m_gen)/m_gen); hptResolutionAK4_vs_ptGen_AK8Overlap[genMatchIdx_0]->Fill(pt_gen, (pt_ak4 - pt_gen)); hmassResolutionAK4_vs_ptGen_AK8Overlap[genMatchIdx_0]->Fill(pt_gen, (m_ak4 - m_gen)); hptResolutionAK8_AK4Overlap[genMatchIdx_0]->Fill((pt_ak8 - pt_gen)/pt_gen); hmassResolutionAK8_AK4Overlap[genMatchIdx_0]->Fill((m_ak8 - m_gen)/m_gen); hptResolutionAK8_vs_ptGen_AK4Overlap[genMatchIdx_0]->Fill(pt_gen, (pt_ak8 - pt_gen)); hmassResolutionAK8_vs_ptGen_AK4Overlap[genMatchIdx_0]->Fill(pt_gen, (m_ak8 - m_gen)); } } //--- build collections of generator level particles (after some cuts are applied, to safe computing time) if(isMC && redoGenMatching && ! fillGenEvtHistograms) { if(genLeptonReader) { genLeptons = genLeptonReader->read(); for(const GenLepton & genLepton: genLeptons) { const int abs_pdgId = std::abs(genLepton.pdgId()); switch(abs_pdgId) { case 11: genElectrons.push_back(genLepton); break; case 13: genMuons.push_back(genLepton); break; default: assert(0); } } } if(genHadTauReader) genHadTaus = genHadTauReader->read(); if(genPhotonReader) genPhotons = genPhotonReader->read(); if(genJetReader) genJets = genJetReader->read(); if(genHiggsReader) genHiggses = genHiggsReader->read(); if(genNeutrinoReader) genNeutrinos = genNeutrinoReader->read(); if(genMatchToMuonReader) muonGenMatch = genMatchToMuonReader->read(); if(genMatchToElectronReader) electronGenMatch = genMatchToElectronReader->read(); if(genMatchToHadTauReader) hadTauGenMatch = genMatchToHadTauReader->read(); if(genMatchToJetReader) jetGenMatch = genMatchToJetReader->read(); } //--- match reconstructed to generator level particles if(isMC && redoGenMatching) { if(genMatchingByIndex) { muonGenMatcher.addGenLeptonMatchByIndex(preselMuons, muonGenMatch, GenParticleType::kGenMuon); muonGenMatcher.addGenHadTauMatch (preselMuons, genHadTaus); muonGenMatcher.addGenJetMatch (preselMuons, genJets); electronGenMatcher.addGenLeptonMatchByIndex(preselElectrons, electronGenMatch, GenParticleType::kGenElectron); electronGenMatcher.addGenPhotonMatchByIndex(preselElectrons, electronGenMatch); electronGenMatcher.addGenHadTauMatch (preselElectrons, genHadTaus); electronGenMatcher.addGenJetMatch (preselElectrons, genJets); hadTauGenMatcher.addGenLeptonMatchByIndex(cleanedHadTaus, hadTauGenMatch, GenParticleType::kGenAnyLepton); hadTauGenMatcher.addGenHadTauMatch (cleanedHadTaus, genHadTaus); hadTauGenMatcher.addGenJetMatch (cleanedHadTaus, genJets); /* jetGenMatcherAK4.addGenLeptonMatch (cleanedJetsAK4_wrtLeptons, genLeptons); jetGenMatcherAK4.addGenHadTauMatch (cleanedJetsAK4_wrtLeptons, genHadTaus); jetGenMatcherAK4.addGenJetMatchByIndex(cleanedJetsAK4_wrtLeptons, jetGenMatch); */ jetGenMatcherAK4.addGenLeptonMatch (selJetsAK4, genLeptons); jetGenMatcherAK4.addGenHadTauMatch (selJetsAK4, genHadTaus); jetGenMatcherAK4.addGenJetMatchByIndex(selJetsAK4, jetGenMatch); } else { muonGenMatcher.addGenLeptonMatch(preselMuons, genMuons); muonGenMatcher.addGenHadTauMatch(preselMuons, genHadTaus); muonGenMatcher.addGenJetMatch (preselMuons, genJets); electronGenMatcher.addGenLeptonMatch(preselElectrons, genElectrons); electronGenMatcher.addGenPhotonMatch(preselElectrons, genPhotons); electronGenMatcher.addGenHadTauMatch(preselElectrons, genHadTaus); electronGenMatcher.addGenJetMatch (preselElectrons, genJets); hadTauGenMatcher.addGenLeptonMatch(cleanedHadTaus, genLeptons); hadTauGenMatcher.addGenHadTauMatch(cleanedHadTaus, genHadTaus); hadTauGenMatcher.addGenJetMatch (cleanedHadTaus, genJets); /* jetGenMatcherAK4.addGenLeptonMatch(cleanedJetsAK4_wrtLeptons, genLeptons); jetGenMatcherAK4.addGenHadTauMatch(cleanedJetsAK4_wrtLeptons, genHadTaus); jetGenMatcherAK4.addGenJetMatch (cleanedJetsAK4_wrtLeptons, genJets); */ jetGenMatcherAK4.addGenLeptonMatch(selJetsAK4, genLeptons); jetGenMatcherAK4.addGenHadTauMatch(selJetsAK4, genHadTaus); jetGenMatcherAK4.addGenJetMatch (selJetsAK4, genJets); } } //--- apply preselection // require exactly three leptons passing loose preselection criteria to avoid overlap with 4l category if ( !(preselLeptonsFull.size() >= 3) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS preselLeptons selection." << std::endl; printCollection("preselLeptons", preselLeptonsFull); } continue; } cutFlowTable.update(">= 3 presel leptons", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms(">= 3 presel leptons", evtWeightRecorder.get(central_or_shift_main)); // require that trigger paths match event category (with event category based on preselLeptons) if ( !((preselElectrons.size() >= 3 && (selTrigger_3e || selTrigger_2e || selTrigger_1e )) || (preselElectrons.size() >= 2 && preselMuons.size() >= 1 && (selTrigger_2e1mu || selTrigger_2e || selTrigger_1e1mu || selTrigger_1mu || selTrigger_1e)) || (preselElectrons.size() >= 1 && preselMuons.size() >= 2 && (selTrigger_1e2mu || selTrigger_2mu || selTrigger_1e1mu || selTrigger_1mu || selTrigger_1e)) || ( preselMuons.size() >= 3 && (selTrigger_3mu || selTrigger_2mu || selTrigger_1mu ))) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS trigger selection for given preselLepton multiplicity." << std::endl; std::cout << " (#preselElectrons = " << preselElectrons.size() << ", #preselMuons = " << preselMuons.size() << ", selTrigger_3mu = " << selTrigger_3mu << ", selTrigger_1e2mu = " << selTrigger_1e2mu << ", selTrigger_2e1mu = " << selTrigger_2e1mu << ", selTrigger_3e = " << selTrigger_3e << ", selTrigger_2mu = " << selTrigger_2mu << ", selTrigger_1e1mu = " << selTrigger_1e1mu << ", selTrigger_2e = " << selTrigger_2e << ", selTrigger_1mu = " << selTrigger_1mu << ", selTrigger_1e = " << selTrigger_1e << ")" << std::endl; } continue; } cutFlowTable.update("presel lepton trigger match", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("presel lepton trigger match", evtWeightRecorder.get(central_or_shift_main)); /* // apply requirement on jets (incl. b-tagged jets) and hadronic taus on preselection level if ( !((int)selJetsAK4.size() >= minNumJets) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS selJets selection." << std::endl; printCollection("selJets", selJetsAK4); } //continue; } cutFlowTable.update(">= N jets", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms(">= N jets", evtWeightRecorder.get(central_or_shift_main)); */ //--- compute MHT and linear MET discriminant (met_LD) const RecoMEt met_uncorr = metReader->read(); const RecoMEt met = recompute_met(met_uncorr, jets_ak4, met_option, isDEBUG); Particle::LorentzVector mht_p4 = compMHT(fakeableLeptonsFull, fakeableHadTaus, selJetsAK4); double met_LD = compMEt_LD(met.p4(), mht_p4); double HT = compHT(fakeableLeptons, {}, selJetsAK4); double STMET = compSTMEt(fakeableLeptons, {}, selJetsAK4, met.p4()); //--- apply final event selection // require exactly three leptons passing tight selection criteria of final event selection if ( !(selLeptons.size() >= 3) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS selLeptons selection." << std::endl; printCollection("selLeptons", selLeptons); //printCollection("preselLeptons", preselLeptons); } continue; } cutFlowTable.update(">= 3 sel leptons", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms(">= 3 sel leptons", evtWeightRecorder.get(central_or_shift_main)); const RecoLepton* selLepton_lead = selLeptons[0]; int selLepton_lead_type = getLeptonType(selLepton_lead->pdgId()); const RecoLepton* selLepton_sublead = selLeptons[1]; int selLepton_sublead_type = getLeptonType(selLepton_sublead->pdgId()); const RecoLepton* selLepton_third = selLeptons[2]; int selLepton_third_type = getLeptonType(selLepton_third->pdgId()); const leptonGenMatchEntry& selLepton_genMatch = getLeptonGenMatch(leptonGenMatch_definitions, selLepton_lead, selLepton_sublead, selLepton_third); //--- retrieve gen-matching flags std::vector<const GenMatchEntry*> genMatches = genMatchInterface.getGenMatch(selLeptons); //int genMatchIdx_0 = 2; // 0: fakes, 1: Convs, 2: non-fakes //cutFlowTable.update(Form("GenMatch entries: %lu",genMatches.size()), evtWeightRecorder.get(central_or_shift_main)); if (genMatches.size() != 1) { std::cout << "analyze_hh_3l_gen: GenMatches in an event: " << genMatches.size() << "\t\t\t ERROR: Code is not ready for it ****" << std::endl; throw cmsException("analyze_hh_3l_gen", __LINE__) << " GenMatches in an event: " << genMatches.size() << "\t\t\t ERROR: Code is not ready for it **** \n"; } for (const GenMatchEntry* genMatch : genMatches) { //cutFlowTable.update(Form("GenMatch entry Idx %i",genMatch->getIdx()), evtWeightRecorder.get(central_or_shift_main)); genMatchIdx_0 = genMatch->getIdx(); } // require exactly three leptons passing tight selection criteria, to avoid overlap with 4l channel if ( !(tightLeptonsFull.size() <= 3) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS tightLeptons selection.\n"; printCollection("tightLeptonsFull", tightLeptonsFull); } continue; } cutFlowTable.update("<= 3 tight sel leptons", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("<= 3 tight sel leptons", evtWeightRecorder.get(central_or_shift_main)); // require that trigger paths match event category (with event category based on fakeableLeptons) if ( !((fakeableElectrons.size() >= 3 && (selTrigger_3e || selTrigger_2e || selTrigger_1e )) || (fakeableElectrons.size() >= 2 && fakeableMuons.size() >= 1 && (selTrigger_2e1mu || selTrigger_2e || selTrigger_1e1mu || selTrigger_1mu || selTrigger_1e)) || (fakeableElectrons.size() >= 1 && fakeableMuons.size() >= 2 && (selTrigger_1e2mu || selTrigger_2mu || selTrigger_1e1mu || selTrigger_1mu || selTrigger_1e)) || ( fakeableMuons.size() >= 3 && (selTrigger_3mu || selTrigger_2mu || selTrigger_1mu ))) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS trigger selection for given fakeableLepton multiplicity." << std::endl; std::cout << " (#fakeableElectrons = " << fakeableElectrons.size() << ", #fakeableMuons = " << fakeableMuons.size() << ", selTrigger_3mu = " << selTrigger_3mu << ", selTrigger_1e2mu = " << selTrigger_1e2mu << ", selTrigger_2e1mu = " << selTrigger_2e1mu << ", selTrigger_3e = " << selTrigger_3e << ", selTrigger_2mu = " << selTrigger_2mu << ", selTrigger_1e1mu = " << selTrigger_1e1mu << ", selTrigger_2e = " << selTrigger_2e << ", selTrigger_1mu = " << selTrigger_1mu << ", selTrigger_1e = " << selTrigger_1e << ")" << std::endl; } continue; } cutFlowTable.update("fakeable lepton trigger match", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("fakeable lepton trigger match", evtWeightRecorder.get(central_or_shift_main)); //--- apply HLT filter if(apply_hlt_filter) { const std::map<hltPathsE, bool> trigger_bits = { { hltPathsE::trigger_1e, selTrigger_1e }, { hltPathsE::trigger_1mu, selTrigger_1mu }, { hltPathsE::trigger_2e, selTrigger_2e }, { hltPathsE::trigger_2mu, selTrigger_2mu }, { hltPathsE::trigger_1e1mu, selTrigger_1e1mu }, { hltPathsE::trigger_1e2mu, selTrigger_1e2mu }, { hltPathsE::trigger_2e1mu, selTrigger_2e1mu }, { hltPathsE::trigger_3e, selTrigger_3e }, { hltPathsE::trigger_3mu, selTrigger_3mu }, }; if(! hltFilter(trigger_bits, fakeableLeptons, {})) { if(run_lumi_eventSelector || isDEBUG) { std::cout << "event " << eventInfo.str() << " FAILS HLT filter matching\n"; } continue; } } cutFlowTable.update("HLT filter matching", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("HLT filter matching", evtWeightRecorder.get(central_or_shift_main)); const double minPt_lead = 25.; const double minPt_sublead = 15.; const double minPt_third = 10.; // CV: according to Giovanni, the pT cuts should be applied on cone_pt // (combined efficiency of single lepton, double lepton, and triple lepton triggers assumed to be high, // even if one or two leptons and fakes and hence cone_pt may be significantly smaller than lepton_pt, // on which pT cuts are applied on trigger level) if ( !(selLepton_lead->cone_pt() > minPt_lead && selLepton_sublead->cone_pt() > minPt_sublead && selLepton_third->cone_pt() > minPt_third) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS lepton pT selection." << std::endl; std::cout << " (leading selLepton pT = " << selLepton_lead->pt() << ", minPt_lead = " << minPt_lead << ", subleading selLepton pT = " << selLepton_sublead->pt() << ", minPt_sublead = " << minPt_sublead << ", third selLepton pT = " << selLepton_third->pt() << ", minPt_third = " << minPt_third << ")" << std::endl; } continue; } cutFlowTable.update("lead lepton pT > 25 GeV && sublead lepton pT > 15 GeV && third lepton pT > 10 GeV", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("lead lepton pT > 25 GeV && sublead lepton pT > 15 GeV && third lepton pT > 10 GeV", evtWeightRecorder.get(central_or_shift_main)); int sumLeptonCharge_3l = selLepton_lead->charge() + selLepton_sublead->charge() + selLepton_third->charge(); bool isCharge_SS = std::abs(sumLeptonCharge_3l) > 1; bool isCharge_OS = std::abs(sumLeptonCharge_3l) <= 1; if ( leptonChargeSelection == kOS && isCharge_SS ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS lepton charge selection." << std::endl; std::cout << " (leading selLepton charge = " << selLepton_lead->charge() << ", subleading selLepton charge = " << selLepton_sublead->charge() << ", third selLepton charge = " << selLepton_third->charge() << ", leptonChargeSelection = OS)" << std::endl; } continue; } if ( leptonChargeSelection == kSS && isCharge_OS ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS lepton charge selection." << std::endl; std::cout << " (leading selLepton charge = " << selLepton_lead->charge() << ", subleading selLepton charge = " << selLepton_sublead->charge() << ", third selLepton charge = " << selLepton_third->charge() << ", leptonChargeSelection = SS)" << std::endl; } continue; } cutFlowTable.update("sel lepton charge", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("sel lepton charge", evtWeightRecorder.get(central_or_shift_main)); // selJet selection for W->jj //cutFlowTable.update("AK8 hh_Wjj selector test1", evtWeightRecorder.get(central_or_shift_main)); bool isWjjBoosted = false; bool isWjjResolved = false; bool isWjjHasOnly1j = false; double AK8JetPt_max = -1.; const RecoJetAK8* AK8JetLead = nullptr; size_t idxLepton_H_WW_ljj_1 = 9999; for (size_t ijet = 0; ijet < jet_ptrs_ak8_Wjj.size(); ++ijet) { //std::cout << "\tijet: " << ijet << ", pt: " << jet_ptrs_ak8_Wjj[ijet]->pt() << std::endl; if (jet_ptrs_ak8_Wjj[ijet]->pt() > AK8JetPt_max) { AK8JetPt_max = jet_ptrs_ak8_Wjj[ijet]->pt(); AK8JetLead = jet_ptrs_ak8_Wjj[ijet]; } } /*if (AK8JetLead) cutFlowTable.update("TestAK8: AK8JetLead found", evtWeightRecorder.get(central_or_shift_main)); if (AK8JetLead && AK8JetLead->subJet1() && AK8JetLead->subJet2()) { cutFlowTable.update("TestAK8: AK8JetLead + 2subjets found", evtWeightRecorder.get(central_or_shift_main)); }*/ // Seperate out H->WW->lNu jj lepton from H->WW->2l2Nu leptons // lepton pair with least dR would be from H->WW->2l2Nu, so the remained lepton would be from H->WW->lNu jj // Approach - 0 : Not used size_t idxLepton_H_WW_ljj = 9999; size_t idxLepton1_H_WW_ll = 9999; size_t idxLepton2_H_WW_ll = 9999; double mindRLepton_H_WW_ll = 9999.; //size_t idxLepton1_H_WW_ll = -1, idxLepton2_H_WW_ll = -1; for (size_t idxLepton1 = 0; idxLepton1 < 3; ++idxLepton1) { //std::cout<<"idxLepton1: "<<idxLepton1<<std::endl; for (size_t idxLepton2 = idxLepton1+1; idxLepton2 < 3; ++idxLepton2) { double dr = deltaR(selLeptons[idxLepton1]->p4(), selLeptons[idxLepton2]->p4()); if ((selLeptons[idxLepton1]->charge() * selLeptons[idxLepton2]->charge() < 0.) && (dr < mindRLepton_H_WW_ll) ) { mindRLepton_H_WW_ll = dr; idxLepton1_H_WW_ll = idxLepton1; idxLepton2_H_WW_ll = idxLepton2; idxLepton_H_WW_ljj = 0; if (idxLepton_H_WW_ljj == idxLepton1) idxLepton_H_WW_ljj++; if (idxLepton_H_WW_ljj == idxLepton2) idxLepton_H_WW_ljj++; //idxLepton1_H_WW_ll = idxLepton1; //idxLepton2_H_WW_ll = idxLepton2; } } } if ( isDEBUG ) { std::cout << "idxLepton_H_WW_ljj: " << idxLepton_H_WW_ljj << ", idxLepton1_H_WW_ll: " << idxLepton1_H_WW_ll << ", idxLepton2_H_WW_ll: " << idxLepton2_H_WW_ll << std::endl; } // Seperate out H->WW->lNu jj lepton from H->WW->2l2Nu leptons // lepton pair with least dR would be from H->WW->2l2Nu, so the remained lepton would be from H->WW->lNu jj // Approach - I if (AK8JetLead) { for (size_t idxLepton1 = 0; idxLepton1 < 3; ++idxLepton1) { for (size_t idxLepton2 = idxLepton1+1; idxLepton2 < 3; ++idxLepton2) { // no need to check opposite-sign lepton pair if (selLeptons[idxLepton1]->charge() * selLeptons[idxLepton2]->charge() < 0.) continue; if ( deltaR(AK8JetLead->p4(), selLeptons[idxLepton1]->p4()) < deltaR(AK8JetLead->p4(), selLeptons[idxLepton2]->p4()) ) { idxLepton_H_WW_ljj_1 = idxLepton1; } else { idxLepton_H_WW_ljj_1 = idxLepton2; } } } } if ( isDEBUG ) std::cout << "idxLepton_H_WW_ljj_1: " << idxLepton_H_WW_ljj_1 << std::endl; const RecoLepton* selLepton_H_WW_ljj = nullptr; const RecoLepton* selLepton1_H_WW_ll = nullptr; const RecoLepton* selLepton2_H_WW_ll = nullptr; std::vector<const RecoJetAK8*> selJetsAK8_Wjj_wSelectorAK8_Wjj; std::vector<const RecoJetAK8*> selJetsAK8_Wjj; std::vector<const RecoJet*> selJetsAK4_Wjj; const RecoJetAK8* selJetAK8_Wjj = nullptr; const RecoJetBase* selJet1_Wjj = nullptr; const RecoJetBase* selJet2_Wjj = nullptr; //bool isAK8_Wjj = false; /* if (idxLepton_H_WW_ljj_1 < 3) { // selLepton_H_WW_ljj = selLeptons[idxLepton_H_WW_ljj]; // Approach - 0 selLepton_H_WW_ljj = selLeptons[idxLepton_H_WW_ljj_1]; // Approach - I jetSelectorAK8_Wjj.getSelector().set_lepton(selLepton_H_WW_ljj); selJetsAK8_Wjj = jetSelectorAK8_Wjj(jet_ptrs_ak8_Wjj, isHigherPt); //selJetsAK4_Wjj = jetSelectorAK4(cleanedJetsAK4_wrtLeptons, isHigherPt); selJetsAK4_Wjj = jetSelectorAK4(cleanedJetsAK4, isHigherPt); cutFlowTable.update("TestAK8: AK8JetLead + selLepton_H_WW_ljj found", evtWeightRecorder.get(central_or_shift_main)); } //selJetsAK8_Wjj = jetSelectorAK8_Wjj(jet_ptrs_ak8_Wjj, isHigherPt); //selJetsAK4_Wjj = jetSelectorAK4(cleanedJetsAK4_wrtLeptons, isHigherPt); //selJetsAK4_Wjj = selJetsAK4; */ if (idxLepton_H_WW_ljj < 3) { // Approach - 0 selLepton_H_WW_ljj = selLeptons[idxLepton_H_WW_ljj]; selLepton1_H_WW_ll = selLeptons[idxLepton1_H_WW_ll]; selLepton2_H_WW_ll = selLeptons[idxLepton2_H_WW_ll]; } jetSelectorAK8_Wjj.getSelector().set_leptons({selLeptons[0], selLeptons[1], selLeptons[2]}); selJetsAK8_Wjj_wSelectorAK8_Wjj = jetSelectorAK8_Wjj(jet_ptrs_ak8_Wjj, isHigherPt); selJetsAK8_Wjj = selJetsAK8_Wjj_wSelectorAK8_Wjj; selJetsAK4_Wjj = jetSelectorAK4(cleanedJetsAK4, isHigherPt); if (selJetsAK8_Wjj.size() >= 1 && selJetsAK8_Wjj[0] && selJetsAK8_Wjj[0]->subJet1() && selJetsAK8_Wjj[0]->subJet2()) { selJetAK8_Wjj = selJetsAK8_Wjj[0]; selJet1_Wjj = selJetAK8_Wjj->subJet1(); selJet2_Wjj = selJetAK8_Wjj->subJet2(); isWjjBoosted = true; assert(selJet1_Wjj && selJet2_Wjj); //cutFlowTable.update("AK8 hh_Wjj selector isWjjBoosted - crosscheck1", evtWeightRecorder.get(central_or_shift_main)); } else { double minRank = 1.e+3; // Question: use selJetsAK4 (cleaned w.r.t fakable lepton and tau jets) or selJetsAK4_Wjj (cleaned w.r.t fakable lepton only) for non-boosted AK4 jets for ( std::vector<const RecoJet*>::const_iterator selJet1 = selJetsAK4_Wjj.begin(); selJet1 != selJetsAK4_Wjj.end(); ++selJet1 ) { for ( std::vector<const RecoJet*>::const_iterator selJet2 = selJet1 + 1; selJet2 != selJetsAK4_Wjj.end(); ++selJet2 ) { Particle::LorentzVector jjP4 = (*selJet1)->p4() + (*selJet2)->p4(); double m_jj = jjP4.mass(); double pT_jj = jjP4.pt(); double rank = TMath::Abs(m_jj - wBosonMass)/TMath::Sqrt(TMath::Max(10., pT_jj)); if ( rank < minRank ) { selJet1_Wjj = (*selJet1); selJet2_Wjj = (*selJet2); minRank = rank; } } } if ( !selJet1_Wjj && selJetsAK4_Wjj.size() >= 1 ) selJet1_Wjj = selJetsAK4_Wjj[0]; if ( !selJet2_Wjj && selJetsAK4_Wjj.size() >= 2 ) selJet2_Wjj = selJetsAK4_Wjj[1]; if ( selJet1_Wjj && selJet2_Wjj ) { isWjjResolved = true; //cutFlowTable.update("AK8 hh_Wjj selector isWjjResolved - crosscheck1", evtWeightRecorder.get(central_or_shift_main)); } else { if (selJetsAK4_Wjj.size() == 1) { selJet1_Wjj = selJetsAK4_Wjj[0]; isWjjHasOnly1j = true; //cutFlowTable.update("AK8 hh_Wjj selector isWjjHasOnly1j - crosscheck1", evtWeightRecorder.get(central_or_shift_main)); } //cutFlowTable.update("AK8 hh_Wjj selector isWjjHasOnly1j - crosscheck2", evtWeightRecorder.get(central_or_shift_main)); //cutFlowTable.update(Form("AK8 hh_Wjj selector isWjjHasOnly1j - crosscheck3 - selJetsAK4_Wjj.size(): %lu",selJetsAK4_Wjj.size()), evtWeightRecorder.get(central_or_shift_main)); } if ( isDEBUG ) { std::cout << "found resolved W->jj decay:" << std::endl; std::cout << "AK4 jet #1:"; if ( selJet1_Wjj ) std::cout << " pT = " << selJet1_Wjj->pt() << ", eta = " << selJet1_Wjj->eta() << ", phi = " << selJet1_Wjj->phi() << std::endl; else std::cout << " N/A" << std::endl; std::cout << "AK4 jet #2:"; if ( selJet2_Wjj ) std::cout << " pT = " << selJet2_Wjj->pt() << ", eta = " << selJet2_Wjj->eta() << ", phi = " << selJet2_Wjj->phi() << std::endl; else std::cout << " N/A" << std::endl; } //cutFlowTable.update("AK8 hh_Wjj selector isWjjResolved || isWjjHasOnly1j ", evtWeightRecorder.get(central_or_shift_main)); } //cutFlowTable.update("AK8 hh_Wjj selector test2", evtWeightRecorder.get(central_or_shift_main)); if (isWjjBoosted) cutFlowTable.update("AK8 hh_Wjj selector isWjjBoosted", evtWeightRecorder.get(central_or_shift_main)); if (isWjjResolved) cutFlowTable.update("AK8 hh_Wjj selector isWjjResolved", evtWeightRecorder.get(central_or_shift_main)); if (isWjjHasOnly1j) cutFlowTable.update("AK8 hh_Wjj selector isWjjHasOnly1j", evtWeightRecorder.get(central_or_shift_main)); if ( !(selJet1_Wjj || selJet2_Wjj) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS >= 1 jets from W->jj selection\n"; } continue; } //cutFlowTable.update("AK8 hh_Wjj selector test3", evtWeightRecorder.get(central_or_shift_main)); cutFlowTable.update(">= 1 jets from W->jj", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms(">= 1 jets from W->jj", evtWeightRecorder.get(central_or_shift_main)); if ( (selJet1_Wjj && !selJet2_Wjj) || (!selJet1_Wjj && selJet2_Wjj)) { cutFlowTable.update("Only 1 W->jj jet", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("Only 1 W->jj jet", evtWeightRecorder.get(central_or_shift_main)); } if (selJet1_Wjj && selJet2_Wjj) { cutFlowTable.update("W->jj jet 1 and 2", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("W->jj jet 1 and 2", evtWeightRecorder.get(central_or_shift_main)); } if(isMC) { //--- compute event-level weight for data/MC correction of b-tagging efficiency and mistag rate // (using the method "Event reweighting using scale factors calculated with a tag and probe method", // described on the BTV POG twiki https://twiki.cern.ch/twiki/bin/view/CMS/BTagShapeCalibration ) evtWeightRecorder.record_btagWeight(selJetsAK4); if(btagSFRatioFacility) { evtWeightRecorder.record_btagSFRatio(btagSFRatioFacility, selJetsAK4.size()); } if(isMC_EWK) { evtWeightRecorder.record_ewk_jet(selJetsAK4); evtWeightRecorder.record_ewk_bjet(selBJetsAK4_medium); } dataToMCcorrectionInterface->setLeptons( selLepton_lead_type, selLepton_lead->pt(), selLepton_lead->cone_pt(), selLepton_lead->eta(), selLepton_sublead_type, selLepton_sublead->pt(), selLepton_sublead->cone_pt(), selLepton_sublead->eta(), selLepton_third_type, selLepton_third->pt(), selLepton_third->cone_pt(), selLepton_third->eta() ); //--- apply data/MC corrections for trigger efficiency evtWeightRecorder.record_leptonTriggerEff(dataToMCcorrectionInterface); //--- apply data/MC corrections for efficiencies for lepton to pass loose identification and isolation criteria evtWeightRecorder.record_leptonIDSF_recoToLoose(dataToMCcorrectionInterface); //--- apply data/MC corrections for efficiencies of leptons passing the loose identification and isolation criteria // to also pass the tight identification and isolation criteria if(electronSelection == kFakeable && muonSelection == kFakeable) { evtWeightRecorder.record_leptonSF(dataToMCcorrectionInterface->getSF_leptonID_and_Iso_fakeable_to_loose()); } else if(electronSelection >= kFakeable && muonSelection >= kFakeable) { // apply loose-to-tight lepton ID SFs if either of the following is true: // 1) both electron and muon selections are tight -> corresponds to SR // 2) electron selection is relaxed to fakeable and muon selection is kept as tight -> corresponds to MC closure w/ relaxed e selection // 3) muon selection is relaxed to fakeable and electron selection is kept as tight -> corresponds to MC closure w/ relaxed mu selection // we allow (2) and (3) so that the MC closure regions would more compatible w/ the SR (1) in comparison evtWeightRecorder.record_leptonIDSF_looseToTight(dataToMCcorrectionInterface); } } if(applyFakeRateWeights == kFR_3lepton) { bool passesTight_lepton_lead = isMatched(*selLepton_lead, tightElectrons) || isMatched(*selLepton_lead, tightMuons); bool passesTight_lepton_sublead = isMatched(*selLepton_sublead, tightElectrons) || isMatched(*selLepton_sublead, tightMuons); bool passesTight_lepton_third = isMatched(*selLepton_third, tightElectrons) || isMatched(*selLepton_third, tightMuons); evtWeightRecorder.record_jetToLepton_FR_lead(leptonFakeRateInterface, selLepton_lead); evtWeightRecorder.record_jetToLepton_FR_sublead(leptonFakeRateInterface, selLepton_sublead); evtWeightRecorder.record_jetToLepton_FR_third(leptonFakeRateInterface, selLepton_third); evtWeightRecorder.compute_FR_3l(passesTight_lepton_lead, passesTight_lepton_sublead, passesTight_lepton_third); } if ( (selBJetsAK4_loose.size() >= 2 || selBJetsAK4_medium.size() >= 1) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS selBJets selection." << std::endl; printCollection("selJetsAK4", selJetsAK4); printCollection("selBJetsAK4_loose", selBJetsAK4_loose); printCollection("selBJetsAK4_medium", selBJetsAK4_medium); } continue; } cutFlowTable.update("b-jet veto", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("b-jet veto", evtWeightRecorder.get(central_or_shift_main)); if ( selHadTaus.size() > 0 ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS selHadTaus veto." << std::endl; printCollection("selHadTaus", selHadTaus); } continue; } cutFlowTable.update("sel tau veto", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("sel tau veto", evtWeightRecorder.get(central_or_shift_main)); //Check: failsLowMassVeto for(auto lepton1_it = preselLeptonsFullUncleaned.begin(); lepton1_it != preselLeptonsFullUncleaned.end(); ++lepton1_it) { const RecoLepton * lepton1 = *lepton1_it; for(auto lepton2_it = lepton1_it + 1; lepton2_it != preselLeptonsFullUncleaned.end(); ++lepton2_it) { const RecoLepton * lepton2 = *lepton2_it; const double mass = (lepton1->p4() + lepton2->p4()).mass(); hm_2lpreselUnclean_0[genMatchIdx_0]->Fill(mass, evtWeightRecorder.get(central_or_shift_main)); } } const bool failsLowMassVeto = isfailsLowMassVeto(preselLeptonsFullUncleaned); if ( failsLowMassVeto ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS low mass lepton pair veto." << std::endl; } continue; } cutFlowTable.update("m(ll) > 12 GeV", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("m(ll) > 12 GeV", evtWeightRecorder.get(central_or_shift_main)); for(auto lepton1_it = preselLeptonsFullUncleaned.begin(); lepton1_it != preselLeptonsFullUncleaned.end(); ++lepton1_it) { const RecoLepton * lepton1 = *lepton1_it; for(auto lepton2_it = lepton1_it + 1; lepton2_it != preselLeptonsFullUncleaned.end(); ++lepton2_it) { const RecoLepton * lepton2 = *lepton2_it; const double mass = (lepton1->p4() + lepton2->p4()).mass(); hm_2lpreselUnclean_1[genMatchIdx_0]->Fill(mass, evtWeightRecorder.get(central_or_shift_main)); } } bool isSameFlavor_OS = false; double massSameFlavor_OS = -1.; int numSameFlavor_OS_Full = 0; for ( std::vector<const RecoLepton*>::const_iterator lepton1 = preselLeptonsFull.begin(); lepton1 != preselLeptonsFull.end(); ++lepton1 ) { for ( std::vector<const RecoLepton*>::const_iterator lepton2 = lepton1 + 1; lepton2 != preselLeptonsFull.end(); ++lepton2 ) { if ( (*lepton1)->pdgId() == -(*lepton2)->pdgId() ) { // pair of same flavor leptons of opposite charge isSameFlavor_OS = true; numSameFlavor_OS_Full++; double mass = ((*lepton1)->p4() + (*lepton2)->p4()).mass(); hm_SFOS2lpresel_0[genMatchIdx_0]->Fill(mass, evtWeightRecorder.get(central_or_shift_main)); if ( std::fabs(mass - z_mass) < std::fabs(massSameFlavor_OS - z_mass) ) massSameFlavor_OS = mass; } } } bool failsZbosonMassVeto = isSameFlavor_OS && std::fabs(massSameFlavor_OS - z_mass) < z_window; if ( failsZbosonMassVeto ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS Z-boson veto." << std::endl; } continue; } cutFlowTable.update("Z-boson mass veto", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("Z-boson mass veto", evtWeightRecorder.get(central_or_shift_main)); for ( std::vector<const RecoLepton*>::const_iterator lepton1 = preselLeptonsFull.begin(); lepton1 != preselLeptonsFull.end(); ++lepton1 ) { for ( std::vector<const RecoLepton*>::const_iterator lepton2 = lepton1 + 1; lepton2 != preselLeptonsFull.end(); ++lepton2 ) { if ( (*lepton1)->pdgId() == -(*lepton2)->pdgId() ) { // pair of same flavor leptons of opposite charge double mass = ((*lepton1)->p4() + (*lepton2)->p4()).mass(); hm_SFOS2lpresel_1[genMatchIdx_0]->Fill(mass, evtWeightRecorder.get(central_or_shift_main)); } } } // Check: isfailsHtoZZVeto for(auto lepton1_it = preselLeptonsFull.begin(); lepton1_it != preselLeptonsFull.end(); ++lepton1_it) { const RecoLepton * lepton1 = *lepton1_it; for(auto lepton2_it = lepton1_it + 1; lepton2_it != preselLeptonsFull.end(); ++lepton2_it) { const RecoLepton * lepton2 = *lepton2_it; if(lepton1->pdgId() == -lepton2->pdgId()) { // first pair of same flavor leptons of opposite charge for(auto lepton3_it = preselLeptonsFull.begin(); lepton3_it != preselLeptonsFull.end(); ++lepton3_it) { const RecoLepton * lepton3 = *lepton3_it; if(lepton3 == lepton1 || lepton3 == lepton2) { continue; } for(auto lepton4_it = lepton3_it + 1; lepton4_it != preselLeptonsFull.end(); ++lepton4_it) { const RecoLepton * lepton4 = *lepton4_it; if(lepton4 == lepton1 || lepton4 == lepton2) { continue; } if(lepton3->pdgId() == -lepton4->pdgId()) { // second pair of same flavor leptons of opposite charge const double mass = (lepton1->p4() + lepton2->p4() + lepton3->p4() + lepton4->p4()).mass(); hm_SFOS4lpresel_0[genMatchIdx_0]->Fill(mass, evtWeightRecorder.get(central_or_shift_main)); } } } } } } const bool failsHtoZZVeto = isfailsHtoZZVeto(preselLeptonsFull); if ( failsHtoZZVeto ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS H->ZZ*->4l veto." << std::endl; } continue; } cutFlowTable.update("H->ZZ*->4l veto", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("H->ZZ*->4l veto", evtWeightRecorder.get(central_or_shift_main)); for(auto lepton1_it = preselLeptonsFull.begin(); lepton1_it != preselLeptonsFull.end(); ++lepton1_it) { const RecoLepton * lepton1 = *lepton1_it; for(auto lepton2_it = lepton1_it + 1; lepton2_it != preselLeptonsFull.end(); ++lepton2_it) { const RecoLepton * lepton2 = *lepton2_it; if(lepton1->pdgId() == -lepton2->pdgId()) { // first pair of same flavor leptons of opposite charge for(auto lepton3_it = preselLeptonsFull.begin(); lepton3_it != preselLeptonsFull.end(); ++lepton3_it) { const RecoLepton * lepton3 = *lepton3_it; if(lepton3 == lepton1 || lepton3 == lepton2) { continue; } for(auto lepton4_it = lepton3_it + 1; lepton4_it != preselLeptonsFull.end(); ++lepton4_it) { const RecoLepton * lepton4 = *lepton4_it; if(lepton4 == lepton1 || lepton4 == lepton2) { continue; } if(lepton3->pdgId() == -lepton4->pdgId()) { // second pair of same flavor leptons of opposite charge const double mass = (lepton1->p4() + lepton2->p4() + lepton3->p4() + lepton4->p4()).mass(); hm_SFOS4lpresel_1[genMatchIdx_0]->Fill(mass, evtWeightRecorder.get(central_or_shift_main)); } } } } } } const bool isSameFlavor_OS_FO = isSFOS(fakeableLeptons); hMEt_All_0[genMatchIdx_0]->Fill(met.pt(), evtWeightRecorder.get(central_or_shift_main)); hHt_All_0[genMatchIdx_0]->Fill(mht_p4.pt(), evtWeightRecorder.get(central_or_shift_main)); hMEt_LD_All_0[genMatchIdx_0]->Fill(met_LD, evtWeightRecorder.get(central_or_shift_main)); hHT_All_0[genMatchIdx_0]->Fill(HT, evtWeightRecorder.get(central_or_shift_main)); hSTMET_All_0[genMatchIdx_0]->Fill(STMET, evtWeightRecorder.get(central_or_shift_main)); if (isSameFlavor_OS_FO) { hMEt_SFOS_0[genMatchIdx_0]->Fill(met.pt(), evtWeightRecorder.get(central_or_shift_main)); hHt_SFOS_0[genMatchIdx_0]->Fill(mht_p4.pt(), evtWeightRecorder.get(central_or_shift_main)); hMEt_LD_SFOS_0[genMatchIdx_0]->Fill(met_LD, evtWeightRecorder.get(central_or_shift_main)); hHT_SFOS_0[genMatchIdx_0]->Fill(HT, evtWeightRecorder.get(central_or_shift_main)); hSTMET_SFOS_0[genMatchIdx_0]->Fill(STMET, evtWeightRecorder.get(central_or_shift_main)); } double met_LD_cut = 0.; if ( selJetsAK4.size() >= 4 ) met_LD_cut = -1.; // MET LD cut not applied else if ( isSameFlavor_OS_FO ) met_LD_cut = 45.; else met_LD_cut = 30.; if ( met_LD_cut > 0 && met_LD < met_LD_cut ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS MET LD selection." << std::endl; std::cout << " (met_LD = " << met_LD << ", met_LD_cut = " << met_LD_cut << ")" << std::endl; } continue; } cutFlowTable.update("met LD", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("met LD", evtWeightRecorder.get(central_or_shift_main)); hMEt_All_1[genMatchIdx_0]->Fill(met.pt(), evtWeightRecorder.get(central_or_shift_main)); hHt_All_1[genMatchIdx_0]->Fill(mht_p4.pt(), evtWeightRecorder.get(central_or_shift_main)); hMEt_LD_All_1[genMatchIdx_0]->Fill(met_LD, evtWeightRecorder.get(central_or_shift_main)); hHT_All_1[genMatchIdx_0]->Fill(HT, evtWeightRecorder.get(central_or_shift_main)); hSTMET_All_1[genMatchIdx_0]->Fill(STMET, evtWeightRecorder.get(central_or_shift_main)); if (isSameFlavor_OS_FO) { hMEt_SFOS_1[genMatchIdx_0]->Fill(met.pt(), evtWeightRecorder.get(central_or_shift_main)); hHt_SFOS_1[genMatchIdx_0]->Fill(mht_p4.pt(), evtWeightRecorder.get(central_or_shift_main)); hMEt_LD_SFOS_1[genMatchIdx_0]->Fill(met_LD, evtWeightRecorder.get(central_or_shift_main)); hHT_SFOS_1[genMatchIdx_0]->Fill(HT, evtWeightRecorder.get(central_or_shift_main)); hSTMET_SFOS_1[genMatchIdx_0]->Fill(STMET, evtWeightRecorder.get(central_or_shift_main)); } if ( apply_met_filters ) { if ( !metFilterSelector(metFilters) ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS MEt filters." << std::endl; } continue; } } cutFlowTable.update("MEt filters", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("MEt filters", evtWeightRecorder.get(central_or_shift_main)); bool failsSignalRegionVeto = false; if ( isMCClosure_e || isMCClosure_m ) { bool applySignalRegionVeto = (isMCClosure_e && countFakeElectrons(selLeptons) >= 1) || (isMCClosure_m && countFakeMuons(selLeptons) >= 1); if ( applySignalRegionVeto && tightLeptons.size() >= 3 ) failsSignalRegionVeto = true; } else if ( electronSelection == kFakeable || muonSelection == kFakeable ) { if ( tightLeptons.size() >= 3 ) failsSignalRegionVeto = true; } if ( failsSignalRegionVeto ) { if ( run_lumi_eventSelector ) { std::cout << "event " << eventInfo.str() << " FAILS overlap w/ the SR: " "# tight leptons = " << tightLeptons.size() << " >= 3\n" ; printCollection("tightLeptons", tightLeptons); } continue; // CV: avoid overlap with signal region } cutFlowTable.update("signal region veto", evtWeightRecorder.get(central_or_shift_main)); cutFlowHistManager->fillHistograms("signal region veto", evtWeightRecorder.get(central_or_shift_main)); cutFlowTable.update("Selected events: all", evtWeightRecorder.get(central_or_shift_main)); if (isWjjBoosted) cutFlowTable.update("Selected events: isWjjBoosted", evtWeightRecorder.get(central_or_shift_main)); if (isWjjResolved) cutFlowTable.update("Selected events: isWjjResolved", evtWeightRecorder.get(central_or_shift_main)); if (isWjjHasOnly1j) cutFlowTable.update("Selected events: isWjjHasOnly1j", evtWeightRecorder.get(central_or_shift_main)); std::vector<double> WeightBM; // weights to do histograms for BMs std::map<std::string, double> Weight_ktScan; // weights to do histograms double HHWeight = 1.0; // X: for the SM point -- the point explicited on this code if(apply_HH_rwgt) { assert(HHWeight_calc); WeightBM = HHWeight_calc->getJHEPWeight(eventInfo.gen_mHH, eventInfo.gen_cosThetaStar, isDEBUG); Weight_ktScan = HHWeight_calc->getScanWeight(eventInfo.gen_mHH, eventInfo.gen_cosThetaStar, isDEBUG); HHWeight = WeightBM[0]; evtWeightRecorder.record_bm(HHWeight); // SM by default if(isDEBUG) { std::cout << "mhh = " << eventInfo.gen_mHH << " : " "cost " << eventInfo.gen_cosThetaStar << " : " "weight = " << HHWeight << '\n' ; std::cout << "Calculated " << Weight_ktScan.size() << " scan weights\n"; for(std::size_t bm_list = 0; bm_list < Weight_ktScan.size(); ++bm_list) { std::cout << "line = " << bm_list << " " << evt_cat_strs[bm_list] << "; Weight = " << Weight_ktScan[evt_cat_strs[bm_list]] << '\n'; } std::cout << '\n'; } } if (isMC) { if (printLevel > 2) { std::cout << "Print Generator level particle collection after passing all selection conditions: " << std::endl; if (genLeptons.size()>0) printCollection("genLeptons", genLeptons); if (genElectrons.size()>0) printCollection("genElectrons", genElectrons); if (genMuons.size()>0) printCollection("genMuons", genMuons); if (genHadTaus.size()>0) printCollection("genHadTaus", genHadTaus); if (genNeutrinos.size()>0) printCollection("genNeutrinos", genNeutrinos); if (genPhotons.size()>0) printCollection("genPhotons", genPhotons); if (genJets.size()>0) printCollection("genJets", genJets); if (genHiggses.size()>0) printCollection("genHiggses", genHiggses); if (genWBosons.size()>0) dumpGenParticles("genWBoson", genWBosons); if (genWJets.size()>0) dumpGenParticles("genWJet", genWJets); std::cout << "GenMatch collection::\n"; if (electronGenMatch.size()>0) printCollection("electronGenMatch", electronGenMatch); if (muonGenMatch.size()>0) printCollection("muonGenMatch", muonGenMatch); if (hadTauGenMatch.size()>0) printCollection("hadTauGenMatch", hadTauGenMatch); if (jetGenMatch.size()>0) printCollection("jetGenMatch", jetGenMatch); } if (printLevel > 2) printf("\nngenHiggs: %lu, ngenW: %lu, ngenLep: %lu, ngenNu: %lu, ngenJet: %lu, ngenWjets: %lu, \t\t ngenHadTaus: %lu, \t\t genMatchIdx_0: %i \n\n\n", genHiggses.size(),genWBosons.size(),genLeptons.size(),genNeutrinos.size(),genJets.size(),genWJets.size(), genHadTaus.size(), genMatchIdx_0); } // SS: Yet to implement this for hh->wwww double dihiggsVisMass_sel = -1., dihiggsMass = -1.; double WTojjMass = -1.; if (selJet1_Wjj && selJet2_Wjj) { dihiggsVisMass_sel = (selLepton_lead->p4() + selLepton_sublead->p4() + selLepton_third->p4() + selJet1_Wjj->p4() + selJet2_Wjj->p4()).mass(); dihiggsMass = (selLepton_lead->p4() + selLepton_sublead->p4() + selLepton_third->p4() + selJet1_Wjj->p4() + selJet2_Wjj->p4() + met.p4()).mass(); WTojjMass = (selJet1_Wjj->p4() + selJet2_Wjj->p4()).mass(); } else if (selJet1_Wjj) { dihiggsVisMass_sel = (selLepton_lead->p4() + selLepton_sublead->p4() + selLepton_third->p4() + selJet1_Wjj->p4()).mass(); dihiggsMass = (selLepton_lead->p4() + selLepton_sublead->p4() + selLepton_third->p4() + selJet1_Wjj->p4() + met.p4()).mass(); WTojjMass = (selJet1_Wjj->p4()).mass(); } int numSameFlavor_OS_3l = 0; double mSFOS2l = 0.; for (int iLepton1 = 0; iLepton1 < 3; iLepton1++) { for (int iLepton2 = iLepton1+1; iLepton2 < 3; iLepton2++) { if ( selLeptons[iLepton1]->pdgId() == - selLeptons[iLepton2]->pdgId() ) { // pair of same flavor leptons of opposite charge numSameFlavor_OS_3l++; mSFOS2l = (selLeptons[iLepton1]->p4() + selLeptons[iLepton2]->p4()).mass(); } } } int numSameFlavor_OS = numSameFlavor_OS_Full; int sumLeptonCharge_FullSel = 0; for (size_t iLepton1 = 0; iLepton1 < selLeptons.size(); iLepton1++) { sumLeptonCharge_FullSel += selLeptons[iLepton1]->charge(); } double mTMetLepton1 = -1.; double mTMetLepton2 = -1.; for (int iLepton1 = 0; iLepton1 < 3; iLepton1++) { if (selLeptons[iLepton1]->charge() == sumLeptonCharge_3l) { //double e = (met.p4() + selLeptons[iLepton1]->p4()).E(); //double z = (met.p4() + selLeptons[iLepton1]->p4()).Pz(); //double mT = std::sqrt(e*e - z*z); double mT = comp_MT_met(selLeptons[iLepton1], met.pt(), met.phi()); if (mT < 0.) std::cout << "analyze_hh_3l_gen:: mT (MET+Lepton) < 0 \t\t *** ERROR ***" << std::endl; if (mTMetLepton1 < 0.) mTMetLepton1 = mT; else if (mTMetLepton2 < 0.) mTMetLepton2 = mT; } } // VBF, nonVBF categorization ----- std::vector<const RecoJetBase*> selJets_Wjj; if ( selJet1_Wjj) { selJets_Wjj.push_back(selJet1_Wjj); } if ( selJet2_Wjj) { selJets_Wjj.push_back(selJet2_Wjj); } //std::vector<const RecoJet*> cleanedJetsVBF = jetCleaner(cleanedJets, selJets_Wjj); //std::vector<const RecoJet*> cleanedJetsVBF = jetCleanerAK4_dR04(cleanedJetsAK4_wrtLeptons, selJets_Wjj); std::vector<const RecoJet*> cleanedJetsVBF = jetCleanerAK4_dR04(selJetsAK4, selJets_Wjj); std::vector<const RecoJet*> selJetsVBF = jetSelectorAK4_vbf(cleanedJetsVBF, isHigherPt); double vbf_dEta_jj = -1.; double vbf_m_jj = -1.; bool isVBF = false; const RecoJet* selJet_vbf_lead = nullptr; const RecoJet* selJet_vbf_sublead = nullptr; for ( std::vector<const RecoJet*>::const_iterator selJetVBF1 = selJetsVBF.begin(); selJetVBF1 != selJetsVBF.end(); ++selJetVBF1 ) { for ( std::vector<const RecoJet*>::const_iterator selJetVBF2 = selJetVBF1 + 1; selJetVBF2 != selJetsVBF.end(); ++selJetVBF2 ) { double dEta_jj = TMath::Abs((*selJetVBF1)->eta() - (*selJetVBF2)->eta()); double m_jj = ((*selJetVBF1)->p4() + (*selJetVBF2)->p4()).mass(); if ( dEta_jj > 4. && m_jj > 500. ) { if ( m_jj > vbf_m_jj ) { // CV: in case of ambiguity, take the jet pair of highest mass vbf_m_jj = m_jj; vbf_dEta_jj = dEta_jj; selJet_vbf_lead = (*selJetVBF1); selJet_vbf_sublead = (*selJetVBF2); isVBF = true; } } } } std::vector<const RecoJet*> selJets_nonVBF; if ( selJet_vbf_lead && selJet_vbf_sublead ) { std::vector<const RecoJet*> overlaps = { selJet_vbf_lead, selJet_vbf_sublead }; //std::vector<const RecoJet*> cleanedJets_wrtVBF = jetCleanerAK4_dR04(cleanedJetsAK4_wrtLeptons, overlaps); std::vector<const RecoJet*> cleanedJets_wrtVBF = jetCleanerAK4_dR04(selJetsAK4, overlaps); selJets_nonVBF = jetSelectorAK4(cleanedJets_wrtVBF, isHigherPt); } int eventCategory = -1; if (isWjjBoosted) eventCategory = 1; else if (isWjjResolved) eventCategory = 2; else if (isWjjHasOnly1j) eventCategory = 3; int numSelJets_nonVBF = ( selJets_nonVBF.size() >= 1 ) ? selJets_nonVBF.size() : selJetsAK4.size(); //--- compute output of BDTs used to discriminate ttH vs. ttV and ttH vs. ttbar // in 3l category of ttH multilepton analysis const double lep1_conePt = comp_lep_conePt(*selLepton_lead); const double lep2_conePt = comp_lep_conePt(*selLepton_sublead); const double lep3_conePt = comp_lep_conePt(*selLepton_third); const double mindr_lep1_jet = comp_mindr_jet(*selLepton_lead, selJetsAK4); const double mindr_lep2_jet = comp_mindr_jet(*selLepton_sublead, selJetsAK4); const double mindr_lep3_jet = comp_mindr_jet(*selLepton_third, selJetsAK4); const double avg_dr_jet = comp_avg_dr_jet(selJetsAK4); double dr_l12 = deltaR(selLepton_lead -> p4(), selLepton_sublead -> p4()); double dr_l23 = deltaR(selLepton_sublead -> p4(), selLepton_third -> p4()); double dr_l13 = deltaR(selLepton_lead -> p4(), selLepton_third -> p4()); double dr_lss = -1.; double dr_los_min = -1.; double dr_los_max = -1.; // it does not assume mis-charge identification if (selLepton_lead->charge()*selLepton_sublead->charge() > 0){ dr_lss = deltaR(selLepton_lead -> p4(), selLepton_sublead -> p4()); double dr1 = deltaR(selLepton_lead -> p4(), selLepton_third -> p4()); double dr2 = deltaR(selLepton_sublead -> p4(), selLepton_third -> p4()); if (dr1 < dr2) { dr_los_min = dr1; dr_los_max = dr2; } else { dr_los_min = dr2; dr_los_max = dr1; } } else if (selLepton_sublead->charge()*selLepton_third->charge() > 0){ dr_lss = deltaR(selLepton_sublead -> p4(), selLepton_third -> p4()); double dr1 = deltaR(selLepton_lead -> p4(), selLepton_sublead -> p4()); double dr2 = deltaR(selLepton_lead -> p4(), selLepton_third -> p4()); if (dr1 < dr2) { dr_los_min = dr1; dr_los_max = dr2; } else { dr_los_min = dr2; dr_los_max = dr1; } } else if (selLepton_lead->charge()*selLepton_third->charge() > 0){ dr_lss = deltaR(selLepton_lead -> p4(), selLepton_third -> p4()); double dr1 = deltaR(selLepton_lead -> p4(), selLepton_sublead -> p4()); double dr2 = deltaR(selLepton_sublead -> p4(), selLepton_third -> p4()); if (dr1 < dr2) { dr_los_min = dr1; dr_los_max = dr2; } else { dr_los_min = dr2; dr_los_max = dr1; } } else { std::cout << "analyze_hh_3l_gen: Error in calculating dr_os " << std::endl; throw cmsException("analyze_hh_3l_gen", __LINE__) << "Error in calculating dr_os \n"; } double dr_WjjLepIdx3 = -1.; double dr_Wjet1LepIdx3 = -1.; double dr_Wjet2LepIdx3 = -1.; double dr_LepIdx3WjetNear = -1.; double dr_LepIdx3WjetFar = -1.; double dr_Wjj = -1.; dr_Wjet1LepIdx3 = (selJet1_Wjj && selLepton_H_WW_ljj) ? deltaR((selJet1_Wjj->p4()), selLepton_H_WW_ljj->p4()) : -1.; dr_Wjet2LepIdx3 = (isWjjBoosted && selJet2_Wjj && selLepton_H_WW_ljj) ? deltaR((selJet2_Wjj->p4()), selLepton_H_WW_ljj->p4()) : -1.; if (dr_Wjet1LepIdx3 < dr_Wjet2LepIdx3) { dr_LepIdx3WjetNear = dr_Wjet1LepIdx3; dr_LepIdx3WjetFar = dr_Wjet2LepIdx3; } else { dr_LepIdx3WjetNear = dr_Wjet2LepIdx3; dr_LepIdx3WjetFar = dr_Wjet1LepIdx3; } if (isWjjBoosted) { dr_WjjLepIdx3 = (selJetAK8_Wjj && selLepton_H_WW_ljj) ? deltaR((selJetAK8_Wjj->p4()), selLepton_H_WW_ljj->p4()) : -1.; } else if (isWjjResolved) { dr_WjjLepIdx3 = (selJet1_Wjj && selJet2_Wjj && selLepton_H_WW_ljj) ? deltaR((selJet1_Wjj->p4() + selJet2_Wjj->p4()), selLepton_H_WW_ljj->p4()) : -1.; } else { dr_WjjLepIdx3 = (selJet1_Wjj && selLepton_H_WW_ljj) ? deltaR((selJet1_Wjj->p4()), selLepton_H_WW_ljj->p4()) : -1.; } if (selJet1_Wjj && selJet2_Wjj) dr_Wjj = deltaR(selJet1_Wjj->p4(), selJet2_Wjj->p4()); double jet1_pt = selJet1_Wjj ? selJet1_Wjj->pt() : 0.; double jet2_pt = selJet2_Wjj ? selJet2_Wjj->pt() : 0.; double jet1plus2pt; double jet1_m = selJet1_Wjj ? selJet1_Wjj->p4().mass() : 0.; double jet2_m = selJet2_Wjj ? selJet1_Wjj->p4().mass() : 0.; if (selJetAK8_Wjj) { jet1plus2pt = selJetAK8_Wjj->pt(); } else if (selJet1_Wjj && selJet2_Wjj) { jet1plus2pt = (selJet1_Wjj->p4() + selJet2_Wjj->p4()).pt(); } else { jet1plus2pt = (selJet1_Wjj->p4()).pt(); } // just to avoid 'variables defined but not used' error TString sTmp123 = Form("selLepton1_H_WW_ll pt: %f, selLepton2_H_WW_ll: %f, vbf_dEta_jj: %f",selLepton1_H_WW_ll->pt(),selLepton2_H_WW_ll->pt(), vbf_dEta_jj); sTmp123 += ""; // Variables using lepton1/2/3 indexed following Approach-0 const RecoLepton* selLepton_H_WW_ljj_Approach0 = selLepton_H_WW_ljj; const RecoLepton* selLepton1_H_WW_ll_Approach0 = selLepton1_H_WW_ll; const RecoLepton* selLepton2_H_WW_ll_Approach0 = selLepton2_H_WW_ll; // double mT_LeptonIdx1_Met_Approach0 = comp_MT_met(selLepton1_H_WW_ll_Approach0, met.pt(), met.phi()); double mT_LeptonIdx2_Met_Approach0 = comp_MT_met(selLepton2_H_WW_ll_Approach0, met.pt(), met.phi()); double mT_LeptonIdx3_Met_Approach0 = comp_MT_met(selLepton_H_WW_ljj_Approach0, met.pt(), met.phi()); // double m_LeptonIdx1_LeptonIdx2_Approach0 = (selLepton1_H_WW_ll_Approach0->p4() + selLepton2_H_WW_ll_Approach0->p4()).mass(); double m_LeptonIdx2_LeptonIdx3_Approach0 = (selLepton2_H_WW_ll_Approach0->p4() + selLepton_H_WW_ljj_Approach0->p4()).mass(); double m_LeptonIdx1_LeptonIdx3_Approach0 = (selLepton1_H_WW_ll_Approach0->p4() + selLepton_H_WW_ljj_Approach0->p4()).mass(); // double dPhi_LeptonIdx1_LeptonIdx2_Approach0 = std::abs(selLepton1_H_WW_ll_Approach0->phi() - selLepton2_H_WW_ll_Approach0->phi()); double dPhi_LeptonIdx2_LeptonIdx3_Approach0 = std::abs(selLepton2_H_WW_ll_Approach0->phi() - selLepton_H_WW_ljj_Approach0->phi()); double dPhi_LeptonIdx1_LeptonIdx3_Approach0 = std::abs(selLepton1_H_WW_ll_Approach0->phi() - selLepton_H_WW_ljj_Approach0->phi()); // double dr_LeptonIdx1_LeptonIdx2_Approach0 = deltaR(selLepton1_H_WW_ll_Approach0->p4(), selLepton2_H_WW_ll_Approach0->p4()); double dr_LeptonIdx2_LeptonIdx3_Approach0 = deltaR(selLepton2_H_WW_ll_Approach0->p4(), selLepton_H_WW_ljj_Approach0->p4()); double dr_LeptonIdx1_LeptonIdx3_Approach0 = deltaR(selLepton1_H_WW_ll_Approach0->p4(), selLepton_H_WW_ljj_Approach0->p4()); // double m_LeptonIdx3_Jet1_Approach0 = (selLepton_H_WW_ljj_Approach0->p4() + selJet1_Wjj->p4()).mass(); double dr_LeptonIdx3_Jet1_Approach0 = deltaR(selLepton_H_WW_ljj_Approach0->p4(), selJet1_Wjj->p4()); double m_LeptonIdx3_JetNear_Approach0; double dr_LeptonIdx3_JetNear_Approach0; if (selJet2_Wjj) { if (deltaR(selLepton_H_WW_ljj_Approach0->p4(), selJet1_Wjj->p4()) < deltaR(selLepton_H_WW_ljj_Approach0->p4(), selJet2_Wjj->p4()) ) { dr_LeptonIdx3_JetNear_Approach0 = deltaR(selLepton_H_WW_ljj_Approach0->p4(), selJet1_Wjj->p4()); m_LeptonIdx3_JetNear_Approach0 = (selLepton_H_WW_ljj_Approach0->p4() + selJet1_Wjj->p4()).mass(); } else { dr_LeptonIdx3_JetNear_Approach0 = deltaR(selLepton_H_WW_ljj_Approach0->p4(), selJet2_Wjj->p4()); m_LeptonIdx3_JetNear_Approach0 = (selLepton_H_WW_ljj_Approach0->p4() + selJet2_Wjj->p4()).mass(); } } else { dr_LeptonIdx3_JetNear_Approach0 = dr_LeptonIdx3_Jet1_Approach0; m_LeptonIdx3_JetNear_Approach0 = m_LeptonIdx3_Jet1_Approach0; } //-------------------------------- // Assume event topology deciding variable labels: H->WW->l1(+) l2(-) and other H->WW->l3(+) qq size_t idxLepton_H_WW_ljj_Approach2 = 9999; size_t idxLepton1_H_WW_ll_Approach2 = 9999; size_t idxLepton2_H_WW_ll_Approach2 = 9999; const RecoLepton* selLepton_H_WW_ljj_Approach2 = nullptr; const RecoLepton* selLepton1_H_WW_ll_Approach2 = nullptr; const RecoLepton* selLepton2_H_WW_ll_Approach2 = nullptr; for (size_t iLepton1 = 0; iLepton1 < 3; iLepton1++) { if ((selLeptons[iLepton1]->charge() * sumLeptonCharge_3l) < 0.) { idxLepton2_H_WW_ll_Approach2 = iLepton1; selLepton2_H_WW_ll_Approach2 = selLeptons[iLepton1]; } } for (size_t iLepton1 = 0; iLepton1 < 3; iLepton1++) { if (iLepton1 == idxLepton2_H_WW_ll_Approach2) continue; size_t iLepton3 = 0; if (iLepton3 == iLepton1) iLepton3++; if (iLepton3 == idxLepton2_H_WW_ll_Approach2) iLepton3++; if (iLepton3 == iLepton1) iLepton3++; if ((selLepton2_H_WW_ll_Approach2->p4() + selLeptons[iLepton1]->p4()).mass() < (selLepton2_H_WW_ll_Approach2->p4() + selLeptons[iLepton3]->p4()).mass() ) { // assume m(l1+l2) < m(l2+l3) idxLepton1_H_WW_ll_Approach2 = iLepton1; idxLepton_H_WW_ljj_Approach2 = iLepton3; } else { idxLepton1_H_WW_ll_Approach2 = iLepton3; idxLepton_H_WW_ljj_Approach2 = iLepton1; } } selLepton1_H_WW_ll_Approach2 = selLeptons[idxLepton1_H_WW_ll_Approach2]; selLepton_H_WW_ljj_Approach2 = selLeptons[idxLepton_H_WW_ljj_Approach2]; // Complain if there is a mistake in picking leptons in Approach 2 if ((selLepton2_H_WW_ll_Approach2->p4() + selLepton1_H_WW_ll_Approach2->p4()).mass() > (selLepton2_H_WW_ll_Approach2->p4() + selLepton_H_WW_ljj_Approach2->p4()).mass() ) { // mistake in picking leptons in Approach 2 std::cout << "analyze_hh_3l_gen: mistake in picking leptons in Approach 2" << std::endl; throw cmsException("analyze_hh_3l_gen", __LINE__) << "Error in calculating dr_os n"; } double mT_LeptonIdx1_Met_Approach2 = comp_MT_met(selLepton1_H_WW_ll_Approach2, met.pt(), met.phi()); double mT_LeptonIdx2_Met_Approach2 = comp_MT_met(selLepton2_H_WW_ll_Approach2, met.pt(), met.phi()); double mT_LeptonIdx3_Met_Approach2 = comp_MT_met(selLepton_H_WW_ljj_Approach2, met.pt(), met.phi()); // double m_LeptonIdx1_LeptonIdx2_Approach2 = (selLepton1_H_WW_ll_Approach2->p4() + selLepton2_H_WW_ll_Approach2->p4()).mass(); double m_LeptonIdx2_LeptonIdx3_Approach2 = (selLepton2_H_WW_ll_Approach2->p4() + selLepton_H_WW_ljj_Approach2->p4()).mass(); double m_LeptonIdx1_LeptonIdx3_Approach2 = (selLepton1_H_WW_ll_Approach2->p4() + selLepton_H_WW_ljj_Approach2->p4()).mass(); // double dPhi_LeptonIdx1_LeptonIdx2_Approach2 = std::abs(selLepton1_H_WW_ll_Approach2->phi() - selLepton2_H_WW_ll_Approach2->phi()); double dPhi_LeptonIdx2_LeptonIdx3_Approach2 = std::abs(selLepton2_H_WW_ll_Approach2->phi() - selLepton_H_WW_ljj_Approach2->phi()); double dPhi_LeptonIdx1_LeptonIdx3_Approach2 = std::abs(selLepton1_H_WW_ll_Approach2->phi() - selLepton_H_WW_ljj_Approach2->phi()); // double dr_LeptonIdx1_LeptonIdx2_Approach2 = deltaR(selLepton1_H_WW_ll_Approach2->p4(), selLepton2_H_WW_ll_Approach2->p4()); double dr_LeptonIdx2_LeptonIdx3_Approach2 = deltaR(selLepton2_H_WW_ll_Approach2->p4(), selLepton_H_WW_ljj_Approach2->p4()); double dr_LeptonIdx1_LeptonIdx3_Approach2 = deltaR(selLepton1_H_WW_ll_Approach2->p4(), selLepton_H_WW_ljj_Approach2->p4()); // double m_LeptonIdx3_Jet1_Approach2 = (selLepton_H_WW_ljj_Approach2->p4() + selJet1_Wjj->p4()).mass(); double dr_LeptonIdx3_Jet1_Approach2 = deltaR(selLepton_H_WW_ljj_Approach2->p4(), selJet1_Wjj->p4()); double m_LeptonIdx3_JetNear_Approach2; double dr_LeptonIdx3_JetNear_Approach2; if (selJet2_Wjj) { if (deltaR(selLepton_H_WW_ljj_Approach2->p4(), selJet1_Wjj->p4()) < deltaR(selLepton_H_WW_ljj_Approach2->p4(), selJet2_Wjj->p4()) ) { dr_LeptonIdx3_JetNear_Approach2 = deltaR(selLepton_H_WW_ljj_Approach2->p4(), selJet1_Wjj->p4()); m_LeptonIdx3_JetNear_Approach2 = (selLepton_H_WW_ljj_Approach2->p4() + selJet1_Wjj->p4()).mass(); } else { dr_LeptonIdx3_JetNear_Approach2 = deltaR(selLepton_H_WW_ljj_Approach2->p4(), selJet2_Wjj->p4()); m_LeptonIdx3_JetNear_Approach2 = (selLepton_H_WW_ljj_Approach2->p4() + selJet2_Wjj->p4()).mass(); } } else { dr_LeptonIdx3_JetNear_Approach2 = dr_LeptonIdx3_Jet1_Approach2; m_LeptonIdx3_JetNear_Approach2 = m_LeptonIdx3_Jet1_Approach2; } //-------------------------------- int idxGenParticleMatch_tmp = -1; if (isGenMarchFound(selLepton_H_WW_ljj_Approach0->p4(), genLeptonsFromHHTo4W, idxGenParticleMatch_tmp)) { if (idxGenParticleMatch_tmp == 2) { // lep3 is at genLeptonsFromHHTo4W[2] cutFlowTable.update("Selected events: lep3 match with genLep3 - Approach0", evtWeightRecorder.get(central_or_shift_main)); } } idxGenParticleMatch_tmp = -1; if (isGenMarchFound(selLepton_H_WW_ljj_Approach2->p4(), genLeptonsFromHHTo4W, idxGenParticleMatch_tmp)) { if (idxGenParticleMatch_tmp == 2) { // lep3 is at genLeptonsFromHHTo4W[2] cutFlowTable.update("Selected events: lep3 match with genLep3 - Approach2", evtWeightRecorder.get(central_or_shift_main)); } } const std::map<std::string, double> mvaInputVariables_hh_3l_SUMBk_HH = { {"lep1_conePt", lep1_conePt}, {"lep1_eta", selLepton_lead -> eta()}, {"mindr_lep1_jet", TMath::Min(10., mindr_lep1_jet)}, {"mT_lep1", comp_MT_met(selLepton_lead, met.pt(), met.phi())}, {"lep2_conePt", lep2_conePt}, {"lep2_eta", selLepton_sublead -> eta()}, {"mindr_lep2_jet", TMath::Min(10., mindr_lep2_jet)}, {"mT_lep2", comp_MT_met(selLepton_sublead, met.pt(), met.phi())}, {"lep3_conePt", lep3_conePt}, {"lep3_eta", selLepton_third -> eta()}, {"mindr_lep3_jet", TMath::Min(10., mindr_lep3_jet)}, {"mT_lep3", comp_MT_met(selLepton_third, met.pt(), met.phi())}, {"avg_dr_jet", avg_dr_jet}, {"dr_leps", deltaR(selLepton_lead -> p4(), selLepton_sublead -> p4())}, {"dr_lss", dr_lss}, {"dr_los1", dr_los_min}, {"dr_los2", dr_los_max}, {"met_LD", met_LD}, {"m_jj", WTojjMass}, {"diHiggsMass", dihiggsMass}, {"mTMetLepton1", mTMetLepton1}, {"mTMetLepton2", mTMetLepton2}, {"nJet", selJetsAK4.size()}, {"nElectron", selElectrons.size()}, {"sumLeptonCharge", sumLeptonCharge_3l}, {"numSameFlavor_OS", numSameFlavor_OS} }; const double mvaOutput_xgb_hh_3l_SUMBk_HH = mva_xgb_hh_3l_SUMBk_HH(mvaInputVariables_hh_3l_SUMBk_HH); //--- retrieve gen-matching flags //std::vector<const GenMatchEntry*> genMatches = genMatchInterface.getGenMatch(selLeptons); //--- fill histograms with events passing final selection std::vector<std::string> evtCategories; if (isWjjBoosted) evtCategories.push_back("hh_WjjBoosted"); else if (isWjjResolved) evtCategories.push_back("hh_WjjResolved"); else if (isWjjHasOnly1j) evtCategories.push_back("hh_WjjHasOnly1j"); /*if ( sumLeptonCharge_3l < 0 ) evtCategories.push_back("hh_3lneg"); else if ( sumLeptonCharge_3l > 0 ) evtCategories.push_back("hh_3lpos"); if (isVBF) evtCategories.push_back("hh_3l_VBF"); else evtCategories.push_back("hh_3l_nonVBF");*/ sTmp123 += Form(" isVBF: %i, ",(int)isVBF); double lep1_genLepPt = ( selLepton_lead->genLepton() ) ? selLepton_lead->genLepton()->pt() : 0.; double lep2_genLepPt = ( selLepton_sublead->genLepton() ) ? selLepton_sublead->genLepton()->pt() : 0.; double lep3_genLepPt = ( selLepton_third->genLepton() ) ? selLepton_third->genLepton()->pt() : 0.; //FR weights for bdt ntuple double prob_fake_lepton_lead, prob_fake_lepton_sublead, prob_fake_lepton_third; /* // Run-time error: weights_FR_lepton_lead_.empty() double prob_fake_lepton_lead = evtWeightRecorder.get_jetToLepton_FR_lead(central_or_shift_main) ? evtWeightRecorder.get_jetToLepton_FR_lead(central_or_shift_main) : -1; //std::cout << "Siddh here12_5" << std::endl; double prob_fake_lepton_sublead = evtWeightRecorder.get_jetToLepton_FR_sublead(central_or_shift_main) ? evtWeightRecorder.get_jetToLepton_FR_sublead(central_or_shift_main) : -1; //std::cout << "Siddh here12_6" << std::endl; double prob_fake_lepton_third = evtWeightRecorder.get_jetToLepton_FR_third(central_or_shift_main) ? evtWeightRecorder.get_jetToLepton_FR_third(central_or_shift_main) : -1; std::cout << "Siddh here13" << std::endl; */ prob_fake_lepton_lead = prob_fake_lepton_sublead = prob_fake_lepton_third = -1.; for(const std::string & central_or_shift: central_or_shifts_local) { const double evtWeight = evtWeightRecorder.get(central_or_shift); const bool skipFilling = central_or_shift != central_or_shift_main; for (const GenMatchEntry* genMatch : genMatches) { //std::cout << "genMatch Idx: " << genMatch->getIdx() << ", name: " << genMatch->getName() << std::endl; selHistManagerType* selHistManager = selHistManagers[central_or_shift][genMatch->getIdx()]; assert(selHistManager); if(! skipFilling) { selHistManager->electrons_->fillHistograms(selElectrons, evtWeight); selHistManager->muons_->fillHistograms(selMuons, evtWeight); selHistManager->hadTaus_->fillHistograms(selHadTaus, evtWeight); selHistManager->jetsAK4_->fillHistograms(selJetsAK4, evtWeight); selHistManager->leadJetAK4_->fillHistograms(selJetsAK4, evtWeight); selHistManager->subleadJetAK4_->fillHistograms(selJetsAK4, evtWeight); selHistManager->BJetsAK4_loose_->fillHistograms(selBJetsAK4_loose, evtWeight); selHistManager->leadBJetAK4_loose_->fillHistograms(selBJetsAK4_loose, evtWeight); selHistManager->subleadBJetAK4_loose_->fillHistograms(selBJetsAK4_loose, evtWeight); selHistManager->BJetsAK4_medium_->fillHistograms(selBJetsAK4_medium, evtWeight); selHistManager->met_->fillHistograms(met, mht_p4, met_LD, evtWeight); selHistManager->metFilters_->fillHistograms(metFilters, evtWeight); } std::map<std::string, double> rwgt_map; for(const std::string & evt_cat_str: evt_cat_strs) { if(skipFilling && evt_cat_str != default_cat_str) { continue; } if(apply_HH_rwgt) { rwgt_map[evt_cat_str] = evtWeight * Weight_ktScan[evt_cat_str] / HHWeight; } else { rwgt_map[evt_cat_str] = evtWeight; } //std::cout << "\t evt_cat_str: " << evt_cat_str << ", rwgt_map: " << rwgt_map[evt_cat_str] << std::endl; } for(const auto & kv: rwgt_map) { //std::cout << "\t kv: " << kv.first << std::endl; selHistManager->evt_[kv.first]->fillHistograms( selElectrons.size(), selMuons.size(), selLeptons.size(), sumLeptonCharge_3l, sumLeptonCharge_FullSel, numSameFlavor_OS_3l, numSameFlavor_OS_Full, selJetsAK4.size(), selBJetsAK4_loose.size(), selBJetsAK4_medium.size(), jet_ptrs_ak8_Wjj.size(), selJetsAK8_Wjj_wSelectorAK8_Wjj.size(), // selLepton_lead -> pt(), lep1_conePt, selLepton_lead -> eta(), TMath::Min(10., mindr_lep1_jet), comp_MT_met(selLepton_lead, met.pt(), met.phi()), // selLepton_sublead -> pt(), lep2_conePt, selLepton_sublead -> eta(), TMath::Min(10., mindr_lep2_jet), comp_MT_met(selLepton_sublead, met.pt(), met.phi()), // selLepton_third -> pt(), lep3_conePt, selLepton_third -> eta(), TMath::Min(10., mindr_lep3_jet), comp_MT_met(selLepton_third, met.pt(), met.phi()), // jet1_pt, jet2_pt, jet1plus2pt, jet1_m, jet2_m, // avg_dr_jet, dr_Wjj, // dr_l12, dr_l23, dr_l13, dr_lss, dr_los_min, dr_los_max, // dr_WjjLepIdx3, dr_Wjet1LepIdx3, dr_Wjet2LepIdx3, dr_LepIdx3WjetNear, dr_LepIdx3WjetFar, // met.pt(), mht_p4.pt(), met_LD, HT, STMET, // mSFOS2l, WTojjMass, dihiggsVisMass_sel, dihiggsMass, mTMetLepton1, mTMetLepton2, // int(selLepton_lead -> isTight()), int(selLepton_sublead -> isTight()), int(selLepton_third -> isTight()), // lep1_genLepPt, lep2_genLepPt, lep3_genLepPt, lep1_genLepPt > 0 ? 1.0 : prob_fake_lepton_lead, lep2_genLepPt > 0 ? 1.0 : prob_fake_lepton_sublead, lep3_genLepPt > 0 ? 1.0 : prob_fake_lepton_third, prob_fake_lepton_lead, prob_fake_lepton_sublead, prob_fake_lepton_third, // mT_LeptonIdx1_Met_Approach0, mT_LeptonIdx2_Met_Approach0, mT_LeptonIdx3_Met_Approach0, // m_LeptonIdx1_LeptonIdx2_Approach0, m_LeptonIdx2_LeptonIdx3_Approach0, m_LeptonIdx1_LeptonIdx3_Approach0, // dPhi_LeptonIdx1_LeptonIdx2_Approach0, dPhi_LeptonIdx2_LeptonIdx3_Approach0, dPhi_LeptonIdx1_LeptonIdx3_Approach0, // dr_LeptonIdx1_LeptonIdx2_Approach0, dr_LeptonIdx2_LeptonIdx3_Approach0, dr_LeptonIdx1_LeptonIdx3_Approach0, // m_LeptonIdx3_Jet1_Approach0, dr_LeptonIdx3_Jet1_Approach0, // m_LeptonIdx3_JetNear_Approach0, dr_LeptonIdx3_JetNear_Approach0, // mT_LeptonIdx1_Met_Approach2, mT_LeptonIdx2_Met_Approach2, mT_LeptonIdx3_Met_Approach2, // m_LeptonIdx1_LeptonIdx2_Approach2, m_LeptonIdx2_LeptonIdx3_Approach2, m_LeptonIdx1_LeptonIdx3_Approach2, // dPhi_LeptonIdx1_LeptonIdx2_Approach2, dPhi_LeptonIdx2_LeptonIdx3_Approach2, dPhi_LeptonIdx1_LeptonIdx3_Approach2, // dr_LeptonIdx1_LeptonIdx2_Approach2, dr_LeptonIdx2_LeptonIdx3_Approach2, dr_LeptonIdx1_LeptonIdx3_Approach2, // m_LeptonIdx3_Jet1_Approach2, dr_LeptonIdx3_Jet1_Approach2, // m_LeptonIdx3_JetNear_Approach2, dr_LeptonIdx3_JetNear_Approach2, // eventCategory, // mvaOutput_xgb_hh_3l_SUMBk_HH, kv.second ); if(isSignal && !skipHHDecayModeHistograms) { const std::string decayModeStr = eventInfo.getDiHiggsDecayModeString(); //std::cout << "\t\t decayModeStr: " << decayModeStr << std::endl; if(! decayModeStr.empty()) { selHistManager -> evt_in_decayModes_[kv.first][decayModeStr] -> fillHistograms( selElectrons.size(), selMuons.size(), selLeptons.size(), sumLeptonCharge_3l, sumLeptonCharge_FullSel, numSameFlavor_OS_3l, numSameFlavor_OS_Full, selJetsAK4.size(), selBJetsAK4_loose.size(), selBJetsAK4_medium.size(), jet_ptrs_ak8_Wjj.size(), selJetsAK8_Wjj_wSelectorAK8_Wjj.size(), // selLepton_lead -> pt(), lep1_conePt, selLepton_lead -> eta(), TMath::Min(10., mindr_lep1_jet), comp_MT_met(selLepton_lead, met.pt(), met.phi()), // selLepton_sublead -> pt(), lep2_conePt, selLepton_sublead -> eta(), TMath::Min(10., mindr_lep2_jet), comp_MT_met(selLepton_sublead, met.pt(), met.phi()), // selLepton_third -> pt(), lep3_conePt, selLepton_third -> eta(), TMath::Min(10., mindr_lep3_jet), comp_MT_met(selLepton_third, met.pt(), met.phi()), // jet1_pt, jet2_pt, jet1plus2pt, jet1_m, jet2_m, // avg_dr_jet, dr_Wjj, // dr_l12, dr_l23, dr_l13, dr_lss, dr_los_min, dr_los_max, // dr_WjjLepIdx3, dr_Wjet1LepIdx3, dr_Wjet2LepIdx3, dr_LepIdx3WjetNear, dr_LepIdx3WjetFar, // met.pt(), mht_p4.pt(), met_LD, HT, STMET, // mSFOS2l, WTojjMass, dihiggsVisMass_sel, dihiggsMass, mTMetLepton1, mTMetLepton2, // int(selLepton_lead -> isTight()), int(selLepton_sublead -> isTight()), int(selLepton_third -> isTight()), // lep1_genLepPt, lep2_genLepPt, lep3_genLepPt, lep1_genLepPt > 0 ? 1.0 : prob_fake_lepton_lead, lep2_genLepPt > 0 ? 1.0 : prob_fake_lepton_sublead, lep3_genLepPt > 0 ? 1.0 : prob_fake_lepton_third, prob_fake_lepton_lead, prob_fake_lepton_sublead, prob_fake_lepton_third, // mT_LeptonIdx1_Met_Approach0, mT_LeptonIdx2_Met_Approach0, mT_LeptonIdx3_Met_Approach0, // m_LeptonIdx1_LeptonIdx2_Approach0, m_LeptonIdx2_LeptonIdx3_Approach0, m_LeptonIdx1_LeptonIdx3_Approach0, // dPhi_LeptonIdx1_LeptonIdx2_Approach0, dPhi_LeptonIdx2_LeptonIdx3_Approach0, dPhi_LeptonIdx1_LeptonIdx3_Approach0, // dr_LeptonIdx1_LeptonIdx2_Approach0, dr_LeptonIdx2_LeptonIdx3_Approach0, dr_LeptonIdx1_LeptonIdx3_Approach0, // m_LeptonIdx3_Jet1_Approach0, dr_LeptonIdx3_Jet1_Approach0, // m_LeptonIdx3_JetNear_Approach0, dr_LeptonIdx3_JetNear_Approach0, // mT_LeptonIdx1_Met_Approach2, mT_LeptonIdx2_Met_Approach2, mT_LeptonIdx3_Met_Approach2, // m_LeptonIdx1_LeptonIdx2_Approach2, m_LeptonIdx2_LeptonIdx3_Approach2, m_LeptonIdx1_LeptonIdx3_Approach2, // dPhi_LeptonIdx1_LeptonIdx2_Approach2, dPhi_LeptonIdx2_LeptonIdx3_Approach2, dPhi_LeptonIdx1_LeptonIdx3_Approach2, // dr_LeptonIdx1_LeptonIdx2_Approach2, dr_LeptonIdx2_LeptonIdx3_Approach2, dr_LeptonIdx1_LeptonIdx3_Approach2, // m_LeptonIdx3_Jet1_Approach2, dr_LeptonIdx3_Jet1_Approach2, // m_LeptonIdx3_JetNear_Approach2, dr_LeptonIdx3_JetNear_Approach2, // eventCategory, // mvaOutput_xgb_hh_3l_SUMBk_HH, kv.second ); } } } for(const std::string & category: evtCategories) { //std::cout << "\t category: " << category << std::endl; ElectronHistManager* selHistManager_electrons_category = selHistManager->electrons_in_categories_[category]; if ( selHistManager_electrons_category ) { selHistManager_electrons_category->fillHistograms(selElectrons, evtWeight); } MuonHistManager* selHistManager_muons_category = selHistManager->muons_in_categories_[category]; if ( selHistManager_muons_category ) { selHistManager_muons_category->fillHistograms(selMuons, evtWeight); } for(const auto & kv: rwgt_map) { //std::cout << "\t\t kv: " << kv.first << std::endl; EvtHistManager_hh_3l* selHistManager_evt_category = selHistManager->evt_in_categories_[kv.first][category]; if ( selHistManager_evt_category ) { // CV: pointer is zero when running on OS control region to estimate "charge_flip" background selHistManager_evt_category->fillHistograms( selElectrons.size(), selMuons.size(), selLeptons.size(), sumLeptonCharge_3l, sumLeptonCharge_FullSel, numSameFlavor_OS_3l, numSameFlavor_OS_Full, selJetsAK4.size(), selBJetsAK4_loose.size(), selBJetsAK4_medium.size(), jet_ptrs_ak8_Wjj.size(), selJetsAK8_Wjj_wSelectorAK8_Wjj.size(), // selLepton_lead -> pt(), lep1_conePt, selLepton_lead -> eta(), TMath::Min(10., mindr_lep1_jet), comp_MT_met(selLepton_lead, met.pt(), met.phi()), // selLepton_sublead -> pt(), lep2_conePt, selLepton_sublead -> eta(), TMath::Min(10., mindr_lep2_jet), comp_MT_met(selLepton_sublead, met.pt(), met.phi()), // selLepton_third -> pt(), lep3_conePt, selLepton_third -> eta(), TMath::Min(10., mindr_lep3_jet), comp_MT_met(selLepton_third, met.pt(), met.phi()), // jet1_pt, jet2_pt, jet1plus2pt, jet1_m, jet2_m, // avg_dr_jet, dr_Wjj, // dr_l12, dr_l23, dr_l13, dr_lss, dr_los_min, dr_los_max, // dr_WjjLepIdx3, dr_Wjet1LepIdx3, dr_Wjet2LepIdx3, dr_LepIdx3WjetNear, dr_LepIdx3WjetFar, // met.pt(), mht_p4.pt(), met_LD, HT, STMET, // mSFOS2l, WTojjMass, dihiggsVisMass_sel, dihiggsMass, mTMetLepton1, mTMetLepton2, // int(selLepton_lead -> isTight()), int(selLepton_sublead -> isTight()), int(selLepton_third -> isTight()), // lep1_genLepPt, lep2_genLepPt, lep3_genLepPt, lep1_genLepPt > 0 ? 1.0 : prob_fake_lepton_lead, lep2_genLepPt > 0 ? 1.0 : prob_fake_lepton_sublead, lep3_genLepPt > 0 ? 1.0 : prob_fake_lepton_third, prob_fake_lepton_lead, prob_fake_lepton_sublead, prob_fake_lepton_third, // mT_LeptonIdx1_Met_Approach0, mT_LeptonIdx2_Met_Approach0, mT_LeptonIdx3_Met_Approach0, // m_LeptonIdx1_LeptonIdx2_Approach0, m_LeptonIdx2_LeptonIdx3_Approach0, m_LeptonIdx1_LeptonIdx3_Approach0, // dPhi_LeptonIdx1_LeptonIdx2_Approach0, dPhi_LeptonIdx2_LeptonIdx3_Approach0, dPhi_LeptonIdx1_LeptonIdx3_Approach0, // dr_LeptonIdx1_LeptonIdx2_Approach0, dr_LeptonIdx2_LeptonIdx3_Approach0, dr_LeptonIdx1_LeptonIdx3_Approach0, // m_LeptonIdx3_Jet1_Approach0, dr_LeptonIdx3_Jet1_Approach0, // m_LeptonIdx3_JetNear_Approach0, dr_LeptonIdx3_JetNear_Approach0, // mT_LeptonIdx1_Met_Approach2, mT_LeptonIdx2_Met_Approach2, mT_LeptonIdx3_Met_Approach2, // m_LeptonIdx1_LeptonIdx2_Approach2, m_LeptonIdx2_LeptonIdx3_Approach2, m_LeptonIdx1_LeptonIdx3_Approach2, // dPhi_LeptonIdx1_LeptonIdx2_Approach2, dPhi_LeptonIdx2_LeptonIdx3_Approach2, dPhi_LeptonIdx1_LeptonIdx3_Approach2, // dr_LeptonIdx1_LeptonIdx2_Approach2, dr_LeptonIdx2_LeptonIdx3_Approach2, dr_LeptonIdx1_LeptonIdx3_Approach2, // m_LeptonIdx3_Jet1_Approach2, dr_LeptonIdx3_Jet1_Approach2, // m_LeptonIdx3_JetNear_Approach2, dr_LeptonIdx3_JetNear_Approach2, // eventCategory, // mvaOutput_xgb_hh_3l_SUMBk_HH, kv.second ); } if(isSignal && !skipHHDecayModeHistograms) { const std::string decayModeStr = eventInfo.getDiHiggsDecayModeString(); //std::cout << "\t\t\t decayModeStr: " << decayModeStr << std::endl; if (! decayModeStr.empty()) { EvtHistManager_hh_3l* selHistManager_evt_category_decMode = selHistManager->evt_in_categories_and_decayModes_[kv.first][category][decayModeStr]; if ( selHistManager_evt_category_decMode ) { // CV: pointer is zero when running on OS control region to estimate "charge_flip" background selHistManager_evt_category_decMode-> fillHistograms( selElectrons.size(), selMuons.size(), selLeptons.size(), sumLeptonCharge_3l, sumLeptonCharge_FullSel, numSameFlavor_OS_3l, numSameFlavor_OS_Full, selJetsAK4.size(), selBJetsAK4_loose.size(), selBJetsAK4_medium.size(), jet_ptrs_ak8_Wjj.size(), selJetsAK8_Wjj_wSelectorAK8_Wjj.size(), // selLepton_lead -> pt(), lep1_conePt, selLepton_lead -> eta(), TMath::Min(10., mindr_lep1_jet), comp_MT_met(selLepton_lead, met.pt(), met.phi()), // selLepton_sublead -> pt(), lep2_conePt, selLepton_sublead -> eta(), TMath::Min(10., mindr_lep2_jet), comp_MT_met(selLepton_sublead, met.pt(), met.phi()), // selLepton_third -> pt(), lep3_conePt, selLepton_third -> eta(), TMath::Min(10., mindr_lep3_jet), comp_MT_met(selLepton_third, met.pt(), met.phi()), // jet1_pt, jet2_pt, jet1plus2pt, jet1_m, jet2_m, // avg_dr_jet, dr_Wjj, // dr_l12, dr_l23, dr_l13, dr_lss, dr_los_min, dr_los_max, // dr_WjjLepIdx3, dr_Wjet1LepIdx3, dr_Wjet2LepIdx3, dr_LepIdx3WjetNear, dr_LepIdx3WjetFar, // met.pt(), mht_p4.pt(), met_LD, HT, STMET, // mSFOS2l, WTojjMass, dihiggsVisMass_sel, dihiggsMass, mTMetLepton1, mTMetLepton2, // int(selLepton_lead -> isTight()), int(selLepton_sublead -> isTight()), int(selLepton_third -> isTight()), // lep1_genLepPt, lep2_genLepPt, lep3_genLepPt, lep1_genLepPt > 0 ? 1.0 : prob_fake_lepton_lead, lep2_genLepPt > 0 ? 1.0 : prob_fake_lepton_sublead, lep3_genLepPt > 0 ? 1.0 : prob_fake_lepton_third, prob_fake_lepton_lead, prob_fake_lepton_sublead, prob_fake_lepton_third, // mT_LeptonIdx1_Met_Approach0, mT_LeptonIdx2_Met_Approach0, mT_LeptonIdx3_Met_Approach0, // m_LeptonIdx1_LeptonIdx2_Approach0, m_LeptonIdx2_LeptonIdx3_Approach0, m_LeptonIdx1_LeptonIdx3_Approach0, // dPhi_LeptonIdx1_LeptonIdx2_Approach0, dPhi_LeptonIdx2_LeptonIdx3_Approach0, dPhi_LeptonIdx1_LeptonIdx3_Approach0, // dr_LeptonIdx1_LeptonIdx2_Approach0, dr_LeptonIdx2_LeptonIdx3_Approach0, dr_LeptonIdx1_LeptonIdx3_Approach0, // m_LeptonIdx3_Jet1_Approach0, dr_LeptonIdx3_Jet1_Approach0, // m_LeptonIdx3_JetNear_Approach0, dr_LeptonIdx3_JetNear_Approach0, // mT_LeptonIdx1_Met_Approach2, mT_LeptonIdx2_Met_Approach2, mT_LeptonIdx3_Met_Approach2, // m_LeptonIdx1_LeptonIdx2_Approach2, m_LeptonIdx2_LeptonIdx3_Approach2, m_LeptonIdx1_LeptonIdx3_Approach2, // dPhi_LeptonIdx1_LeptonIdx2_Approach2, dPhi_LeptonIdx2_LeptonIdx3_Approach2, dPhi_LeptonIdx1_LeptonIdx3_Approach2, // dr_LeptonIdx1_LeptonIdx2_Approach2, dr_LeptonIdx2_LeptonIdx3_Approach2, dr_LeptonIdx1_LeptonIdx3_Approach2, // m_LeptonIdx3_Jet1_Approach2, dr_LeptonIdx3_Jet1_Approach2, // m_LeptonIdx3_JetNear_Approach2, dr_LeptonIdx3_JetNear_Approach2, // eventCategory, // mvaOutput_xgb_hh_3l_SUMBk_HH, kv.second ); } } } } } if(! skipFilling) { selHistManager->evtYield_->fillHistograms(eventInfo, evtWeight); selHistManager->weights_->fillHistograms("genWeight", eventInfo.genWeight); selHistManager->weights_->fillHistograms("pileupWeight", evtWeightRecorder.get_puWeight(central_or_shift)); selHistManager->weights_->fillHistograms("triggerWeight", evtWeightRecorder.get_sf_triggerEff(central_or_shift)); selHistManager->weights_->fillHistograms("data_to_MC_correction", evtWeightRecorder.get_data_to_MC_correction(central_or_shift)); selHistManager->weights_->fillHistograms("fakeRate", evtWeightRecorder.get_FR(central_or_shift)); } } if(isMC && ! skipFilling) { genEvtHistManager_afterCuts[central_or_shift]->fillHistograms( genElectrons, genMuons, genHadTaus, genPhotons, genJets, evtWeightRecorder.get_inclusive(central_or_shift) ); lheInfoHistManager[central_or_shift]->fillHistograms(*lheInfoReader, evtWeight); if(eventWeightManager) { genEvtHistManager_afterCuts[central_or_shift]->fillHistograms( eventWeightManager, evtWeightRecorder.get_inclusive(central_or_shift) ); } } } if ( selEventsFile ) { (*selEventsFile) << eventInfo.run << ':' << eventInfo.lumi << ':' << eventInfo.event << '\n'; } if ( bdt_filler ) { /* double lep1_genLepPt = ( selLepton_lead->genLepton() ) ? selLepton_lead->genLepton()->pt() : 0.; double lep2_genLepPt = ( selLepton_sublead->genLepton() ) ? selLepton_sublead->genLepton()->pt() : 0.; double lep3_genLepPt = ( selLepton_third->genLepton() ) ? selLepton_third->genLepton()->pt() : 0.; //FR weights for bdt ntuple double prob_fake_lepton_lead = evtWeightRecorder.get_jetToLepton_FR_lead(central_or_shift_main); double prob_fake_lepton_sublead = evtWeightRecorder.get_jetToLepton_FR_sublead(central_or_shift_main); double prob_fake_lepton_third = evtWeightRecorder.get_jetToLepton_FR_third(central_or_shift_main); */ bdt_filler -> operator()({ eventInfo.run, eventInfo.lumi, eventInfo.event }) ("nElectron", selElectrons.size()) ("nMuon", selMuons.size()) ("nLepton", selLeptons.size()) ("sumLeptonCharge_3l", sumLeptonCharge_3l) ("sumLeptonCharge_FullSel", sumLeptonCharge_FullSel) ("numSameFlavor_OS_3l", numSameFlavor_OS_3l) ("numSameFlavor_OS_FullPresel", numSameFlavor_OS_Full) ("nJetAK4", selJetsAK4.size()) ("nBJetLoose", selBJetsAK4_loose.size()) ("nBJetMedium", selBJetsAK4_medium.size()) ("nJetAK8", jet_ptrs_ak8_Wjj.size()) ("nJetAK8_wSelectorAK8_Wjj", selJetsAK8_Wjj_wSelectorAK8_Wjj.size()) // ("lep1_pt", selLepton_lead -> pt()) ("lep1_conePt", lep1_conePt) ("lep1_eta", selLepton_lead -> eta()) ("mindr_lep1_jet", TMath::Min(10., mindr_lep1_jet)) ("mT_MEtLep1", comp_MT_met(selLepton_lead, met.pt(), met.phi())) // ("lep2_pt", selLepton_sublead -> pt()) ("lep2_conePt", lep2_conePt) ("lep2_eta", selLepton_sublead -> eta()) ("mindr_lep2_jet", TMath::Min(10., mindr_lep2_jet)) ("mT_MEtLep2", comp_MT_met(selLepton_sublead, met.pt(), met.phi())) // ("lep3_pt", selLepton_third -> pt()) ("lep3_conePt", lep3_conePt) ("lep3_eta", selLepton_third -> eta()) ("mindr_lep3_jet", TMath::Min(10., mindr_lep3_jet)) ("mT_MEtLep3", comp_MT_met(selLepton_third, met.pt(), met.phi())) // ("jet1_pt", jet1_pt) ("jet2_pt", jet2_pt) ("jet1plus2pt", jet1plus2pt) ("jet1_m", jet1_m) ("jet2_m", jet2_m) // ("avg_dr_jet", avg_dr_jet) ("dr_Wjj", dr_Wjj) // ("dr_l12", dr_l12) ("dr_l23", dr_l23) ("dr_l13", dr_l13) ("dr_lss", dr_lss) ("dr_los_min", dr_los_min) ("dr_los_max", dr_los_max) // ("dr_WjjLepIdx3", dr_WjjLepIdx3) ("dr_Wjet1LepIdx3", dr_Wjet1LepIdx3) ("dr_Wjet2LepIdx3", dr_Wjet2LepIdx3) ("dr_LepIdx3WjetNear", dr_LepIdx3WjetNear) ("dr_LepIdx3WjetFar", dr_LepIdx3WjetFar) // ("met", met.pt()) ("mht", mht_p4.pt()) ("met_LD", met_LD) ("HT", HT) ("STMET", STMET) // ("mSFOS2l", mSFOS2l) ("m_jj", WTojjMass) ("diHiggsVisMass", dihiggsVisMass_sel) ("diHiggsMass", dihiggsMass) ("mTMetLepton1", mTMetLepton1) ("mTMetLepton2", mTMetLepton2) // ("lep1_isTight", int(selLepton_lead -> isTight())) ("lep2_isTight", int(selLepton_sublead -> isTight())) ("lep3_isTight", int(selLepton_third -> isTight())) // ("lep1_genLepPt", lep1_genLepPt) ("lep2_genLepPt", lep2_genLepPt) ("lep3_genLepPt", lep3_genLepPt) ("lep1_frWeight", lep1_genLepPt > 0 ? 1.0 : prob_fake_lepton_lead) ("lep2_frWeight", lep2_genLepPt > 0 ? 1.0 : prob_fake_lepton_sublead) ("lep3_frWeight", lep3_genLepPt > 0 ? 1.0 : prob_fake_lepton_third) ("lep1_fake_prob", prob_fake_lepton_lead) ("lep2_fake_prob", prob_fake_lepton_sublead) ("lep3_fake_prob", prob_fake_lepton_third) // ("eventCategory", eventCategory) // ("lumiScale", evtWeightRecorder.get_lumiScale(central_or_shift_main)) ("genWeight", eventInfo.genWeight) ("evtWeight", evtWeightRecorder.get(central_or_shift_main)) .fill() ; } ++selectedEntries; selectedEntries_weighted += evtWeightRecorder.get(central_or_shift_main); std::string process_and_genMatch = process_string; process_and_genMatch += selLepton_genMatch.name_; ++selectedEntries_byGenMatchType[process_and_genMatch]; for(const std::string & central_or_shift: central_or_shifts_local) { selectedEntries_weighted_byGenMatchType[central_or_shift][process_and_genMatch] += evtWeightRecorder.get(central_or_shift); } histogram_selectedEntries->Fill(0.); if (isSignal && !skipHHDecayModeHistograms) { std::string decayMode_and_genMatch = process_string; decayMode_and_genMatch += ("_DecayMode_" + eventInfo.getDiHiggsDecayModeString()); ++selectedEntries_byDecayModeType[decayMode_and_genMatch]; for(const std::string & central_or_shift: central_or_shifts_local) { selectedEntries_weighted_byDecayModeType[central_or_shift][decayMode_and_genMatch] += evtWeightRecorder.get(central_or_shift); } } } std::cout << "max num. Entries = " << inputTree -> getCumulativeMaxEventCount() << " (limited by " << maxEvents << ") processed in " << inputTree -> getProcessedFileCount() << " file(s) (out of " << inputTree -> getFileCount() << ")\n" << " analyzed = " << analyzedEntries << '\n' << " selected = " << selectedEntries << " (weighted = " << selectedEntries_weighted << ")\n\n" << "cut-flow table" << std::endl; cutFlowTable.print(std::cout); std::cout << std::endl; std::cout << "sel. Entries by gen. matching:" << std::endl; for(const std::string & central_or_shift: central_or_shifts_local) { std::cout << "central_or_shift = " << central_or_shift << '\n'; std::cout << "Lepton genMatch-wise:\n"; for(const leptonGenMatchEntry & leptonGenMatch_definition: leptonGenMatch_definitions) { std::string process_and_genMatch = process_string; process_and_genMatch += leptonGenMatch_definition.name_; std::cout << " " << process_and_genMatch << " = " << selectedEntries_byGenMatchType[process_and_genMatch] << " (weighted = " << selectedEntries_weighted_byGenMatchType[central_or_shift][process_and_genMatch] << ")\n"; } if (isSignal && !skipHHDecayModeHistograms) { std::cout << "Lepton DecayMode-wise:\n"; const vstring decayModes_evt = eventInfo.getDiHiggsDecayModes(); for(const std::string & decayMode_evt: decayModes_evt) { std::string decayMode_and_genMatch = process_string; decayMode_and_genMatch += ("_DecayMode_" + decayMode_evt); std::cout << " " << decayMode_and_genMatch << " = " << selectedEntries_byDecayModeType[decayMode_and_genMatch] << " (weighted = " << selectedEntries_weighted_byDecayModeType[central_or_shift][decayMode_and_genMatch] << ")\n"; } } } std::cout << std::endl; printf("knMuPassJetBtagMedium: %i, knMuPassFakeablePromptMva: %i, knMuFailFakeablePromptMva %i \t missmatch: %i\n",knMuPassJetBtagMedium,knMuPassFakeablePromptMva,knMuFailFakeablePromptMva, (knMuPassFakeablePromptMva+knMuFailFakeablePromptMva - knMuPassJetBtagMedium)); //--- manually write histograms to output file fs.file().cd(); //histogram_analyzedEntries->Write(); //histogram_selectedEntries->Write(); HistManagerBase::writeHistograms(); //--- memory clean-up delete dataToMCcorrectionInterface; delete leptonFakeRateInterface; delete run_lumi_eventSelector; delete selEventsFile; delete muonReader; delete electronReader; delete hadTauReader; delete jetReaderAK4; delete metReader; delete metFilterReader; delete genLeptonReader; delete genHadTauReader; delete genPhotonReader; delete genJetReader; delete lheInfoReader; delete psWeightReader; for(auto & kv: genEvtHistManager_beforeCuts) { delete kv.second; } for(auto & kv: genEvtHistManager_afterCuts) { delete kv.second; } for(auto & kv: lheInfoHistManager) { delete kv.second; } delete cutFlowHistManager; delete eventWeightManager; hltPaths_delete(triggers_1e); hltPaths_delete(triggers_2e); hltPaths_delete(triggers_1mu); hltPaths_delete(triggers_2mu); hltPaths_delete(triggers_1e1mu); delete inputTree; clock.Show("analyze_hh_3l_gen"); return EXIT_SUCCESS; }
#include "object\Telop.h" #include "Config.h" #include "Resource.h" Telop::Telop() : Telop({ Ref::FLD_W * (1.0F + Config::GetInstance()->GetResolutionNo() / 2.0F) / 2.0F, 128 * (1.0F + Config::GetInstance()->GetResolutionNo() / 2.0F) }) { } Telop::Telop(Vector2 pos) : Object(pos) { } void Telop::Init() { } void Telop::Fin() { counter = -1; } void Telop::Update() { if (counter != -1) { counter++; if (counter == 300) { Fin(); } } } void Telop::Draw() const { if (counter != -1) { int handle = Resource::GetFont(); int width = GetDrawStringWidthToHandle(str, strlen(str), handle); float res = Config::GetInstance()->GetResolutionNo() * 8.0F; DrawStringFToHandle(16 + res + position.x - width, position.y + res, str, GetColor(255, 255, 255), handle); } } Telop* Telop::WithString(const char strIn[32]) { counter = 0; strcpy_s(str, strIn); return this; }
#include "PrettyPrinter.h" #include <iostream> #include "GrammaticRules.h" #include <cassert> using namespace std; std::string CPrettyPrinter::marginString = " "; void CPrettyPrinter::PrintTabs( size_t tabs ) const { for ( size_t i = 0; i < tabs; i++ ) { cout << marginString; } } void CPrettyPrinter::PrintMargin() const { for ( size_t i = 0; i < marginInTabs; i++ ) { cout << marginString; } } void CPrettyPrinter::Visit( const CProgram* node ) { IMainClassDeclaration* mainClass = node->GetMainClassDeclaration(); if ( mainClass ) { mainClass->Accept( this ); } IClassDeclaration* classDeclarations = node->GetClassDeclarationsList(); if ( classDeclarations ) { classDeclarations->Accept( this ); } } void CPrettyPrinter::Visit( const CMainClassDeclaration* node ) { cout << "class " << node->GetClassName() << endl; cout << "{" << endl; IStatement* statements = node->GetClassStatements(); PrintTabs( 1 ); cout << "public static void main(String[] " << node->GetArgumentName() << ")" << endl; PrintTabs( 1 ); cout << "{" << endl; if ( statements ) { PrintTabs( 2 ); statements->Accept( this ); } PrintTabs( 1 ); cout << "}" << endl; cout << "}" << endl; } void CPrettyPrinter::Visit( const CClassDeclaration* node ) { cout << "class " << node->GetClassName() << endl; cout << "{" << endl; IVariableDeclaration* fieldsList = node->GetFieldsList(); if ( fieldsList ) { fieldsList->Accept( this ); } IMethodDeclaration* methodsList = node->GetMethodsList(); if ( methodsList ) { methodsList->Accept( this ); } cout << "}" << endl; } void CPrettyPrinter::Visit( const CClassExtendsDeclaration* node ) { cout << "class " << node->GetClassName() << " extends " << node->GetSuperClassName() << endl; cout << "{" << endl; IVariableDeclaration* fieldsList = node->GetFieldsList(); if ( fieldsList ) { fieldsList->Accept( this ); } IMethodDeclaration* methodsList = node->GetMethodsList(); if ( methodsList ) { methodsList->Accept( this ); } cout << "}" << endl; } void CPrettyPrinter::Visit( const CClassDeclarationList* node ) { IClassDeclaration* classDeclaration = node->GetClassDeclaration(); classDeclaration->Accept( this ); IClassDeclaration* nextClassDeclaration = node->GetNextClassDeclaration(); if ( nextClassDeclaration ) { nextClassDeclaration->Accept( this ); } } void CPrettyPrinter::Visit( const CVariableDeclaration* node ) { string name = node->GetName(); IType* type = node->GetType(); type->Accept( this ); cout << " " << name; } void CPrettyPrinter::Visit( const CVariableDeclarationList* node ) { IVariableDeclaration* variableDeclaration = node->GetVariableDeclaration(); CVariableDeclarationList* nextVariableDeclaration = node->GetNextVariableDeclaration(); if ( nextVariableDeclaration ) { nextVariableDeclaration->Accept( this ); } PrintTabs( 1 ); variableDeclaration->Accept( this ); cout << ";" << endl; } void CPrettyPrinter::Visit( const CMethodDeclaration* node ) { PrintTabs( 1 ); string name = node->GetMethodName(); IType* type = node->GetType(); // cout << "Method "; cout << "public "; type->Accept( this ); cout << " " << name << "("; IFormalList* formalList = node->GetFormalList(); if ( formalList ) { formalList->Accept( this ); } cout << ")" << endl; PrintTabs( 1 ); cout << "{" << endl; IStatement *statementList = node->GetStatements(); if ( statementList ) { SetMargin( 2 ); statementList->Accept( this ); cout << endl; } IExpression* returnExpression = node->GetReturnExpression(); PrintTabs( 2 ); cout << "return "; returnExpression->Accept( this ); cout << ";" << endl; PrintTabs( 1 ); cout << "}" << endl; } void CPrettyPrinter::Visit( const CMethodDeclarationList* node ) { IMethodDeclaration* methodDeclaraion = node->GetMethodDeclaration(); // PrintMargin(); methodDeclaraion->Accept( this ); IMethodDeclaration* nextMethodDeclaration = node->GetNextMethodDeclaration(); if ( nextMethodDeclaration ) { nextMethodDeclaration->Accept( this ); } } void CPrettyPrinter::Visit( const CFormalList* node ) { string name = node->GetParameterName(); IType* type = node->GetType(); type->Accept( this ); cout << " " << name; } void CPrettyPrinter::Visit( const CFormalRestList* node ) { IFormalList* formalRest = node->GetFormalRest(); formalRest->Accept( this ); IFormalList* nextFormalRest = node->GetNextFormalRest(); if ( nextFormalRest ) { cout << ", "; nextFormalRest->Accept( this ); } } void CPrettyPrinter::Visit( const CBuiltInType* node ) { switch ( node->GetType() ) { case BT_BOOLEAN: cout << "boolean"; break; case BT_INTEGER: cout << "int"; break; case BT_INTEGER_ARRAY: cout << "int[]"; default: break; } } void CPrettyPrinter::Visit( const CUserType* node ) { cout << node->GetTypeName(); } void CPrettyPrinter::Visit( const CStatementList* node ) { IStatement* statement = node->GetStatement(); IStatement* nextStatement = node->GetNextStatement(); statement->Accept( this ); if ( nextStatement ) { nextStatement->Accept( this ); } } void CPrettyPrinter::Visit( const CStatementBlock* node ) { IStatement* block = node->GetStatementList(); if ( block ) { PrintMargin(); cout << "{" << endl; IncreaseMargin(); block->Accept( this ); DecreaseMargin(); PrintMargin(); cout << "}" << endl; } } void CPrettyPrinter::Visit( const CIfStatement* node ) { IStatement* trueStatement = node->GetTrueStatement(); IStatement* falseStatement = node->GetFalseStatement(); IExpression* condition = node->GetCondition(); PrintMargin(); cout << "if ("; condition->Accept( this ); cout << ")" << endl; PrintMargin(); cout << "{" << endl; IncreaseMargin(); // PrintMargin(); trueStatement->Accept( this ); DecreaseMargin(); PrintMargin(); cout << "}" << endl; PrintMargin(); cout << "else" << endl; PrintMargin(); cout << "{" << endl; IncreaseMargin(); // PrintMargin(); falseStatement->Accept( this ); DecreaseMargin(); PrintMargin(); cout << "}" << endl; } void CPrettyPrinter::Visit( const CWhileStatement* node ) { IExpression* condition = node->GetCondition(); IStatement* statement = node->GetStatement(); PrintMargin(); cout << "while ("; condition->Accept( this ); cout << " )" << endl; PrintMargin(); cout << "{" << endl; IncreaseMargin(); statement->Accept( this ); DecreaseMargin(); PrintMargin(); cout << "}" << endl; } void CPrettyPrinter::Visit( const CPrintStatement* node ) { IExpression *expression = node->GetExpression(); PrintMargin(); cout << "System.out.println("; expression->Accept( this ); cout << ");" << endl; } void CPrettyPrinter::Visit( const CAssignmentStatement* node ) { IExpression *expression = node->GetRightValue(); PrintMargin(); cout << node->GetVariableName() << " = "; expression->Accept( this ); cout << ";" << endl; } void CPrettyPrinter::Visit( const CArrayElementAssignmentStatement* node ) { IExpression* index = node->GetIndexExpression(); IExpression* value = node->GetRightValue(); PrintMargin(); cout << node->GetArrayName() << "["; index->Accept( this ); cout << "] = "; value->Accept( this ); cout << ";" << endl; } void CPrettyPrinter::Visit( const CBinaryOperatorExpression* node ) { IExpression* leftValue = node->GetLeftValue(); IExpression* rightValue = node->GetRightValue(); leftValue->Accept( this ); switch ( node->GetOperator() ) { case BO_PLUS: cout << " + "; break; case BO_MINUS: cout << " - "; break; case BO_MULTIPLY: cout << " * "; break; case BO_LESS: cout << " < "; break; case BO_LOGICAL_AND: cout << " && "; break; default: assert( false );; } rightValue->Accept( this ); } void CPrettyPrinter::Visit( const CIndexAccessExpression* node ) { IExpression *arrayExpression = node->GetArrayExpression(); IExpression *index = node->GetIndex(); arrayExpression->Accept( this ); cout << "[ "; index->Accept( this ); cout << " ]"; } void CPrettyPrinter::Visit( const CLengthExpression* node ) { IExpression* arrayExpression = node->GetArray(); arrayExpression->Accept( this ); cout << ".length()"; } void CPrettyPrinter::Visit( const CMethodCallExpression* node ) { IExpression* object = node->GetObject(); IExpression* params = node->GetParams(); std::string methodName = node->GetMethodName(); object->Accept( this ); cout << "." << methodName << "("; if ( params ) { params->Accept( this ); } cout << ")"; } void CPrettyPrinter::Visit( const CIntegerOrBooleanExpression* node ) { int value = node->GetValue(); TValueType type = node->GetValueType(); if ( type == VT_BOOLEAN ) { if ( value == 0 ) { cout << "false"; } else { cout << "true"; } } else { cout << value; } } void CPrettyPrinter::Visit( const CIdentifierExpression* node ) { std::string name = node->GetVariableName(); cout << name; } void CPrettyPrinter::Visit( const CThisExpression* node ) { cout << "this"; } void CPrettyPrinter::Visit( const CNewIntegerArrayExpression* node ) { IExpression* size = node->GetArraySize(); cout << "int[ "; size->Accept( this ); cout << " ]"; } void CPrettyPrinter::Visit( const CNewObjectExpression* node ) { std::string className = node->GetClass(); cout << "new " << className << "()"; } void CPrettyPrinter::Visit( const CNegationExpression* node ) { IExpression* argument = node->GetArgument(); cout << " -"; argument->Accept( this ); } void CPrettyPrinter::Visit( const CParenthesesExpression* node ) { IExpression* expression = node->GetExpression(); cout << "( "; expression->Accept( this ); cout << " )"; } void CPrettyPrinter::Visit( const CExpressionList* node ) { IExpression *expression = node->GetExpression(); IExpression *nextExpression = node->GetNextExpression(); expression->Accept( this ); if ( nextExpression ) { nextExpression->Accept( this ); } }
#include<iostream> #include<fstream> #include<string> #include<sstream> #include<stdlib.h> #include"IndexManager.h" #include"defination.h" using namespace std; BPLUSTREE::BPLUSTREE(int block_size) : block_size(block_size) { ifstream file("allindex.idx", ios::app); file.seekg(0, ios::beg); string file_name; int type; while (1) { file >> file_name; if (file.eof()) break; file >> type; //cout<<file_name<<" "<<type;//............................ if (type == TYPE_INT) { //Create int B+Tree and add root node pointer into map CreateTree(type, &file_name); } else if (type == TYPE_FLOAT) { CreateTree(type, &file_name); //Create float B+Tree and add root node pointer into map } else if (type == TYPE_CHAR) { CreateTree(type, &file_name); //Create char B+Tree and add root node pointer into map }; } file.close(); } BPLUSTREE::~BPLUSTREE() { } int BPLUSTREE::CreateTree(int type, string *file_name) { ifstream index(*file_name); if (!index) { cerr << "Error: No file named " << *file_name << "!" << endl; return ERROR_FILE; } if (type == TYPE_INT) { INTNODE *root = new INTNODE(); root->father = NULL; root->next = root->prev = NULL; //Create an empty root node and add it into map int_map[*file_name] = root; //cout << "Create a node";//...................................... string key; int offset, block; while (1) { index >> key; if (index.eof()) break; index >> block >> offset; AddNode(type, file_name, &key, block, offset); } } else if (type == TYPE_FLOAT) { FLOATNODE *root = new FLOATNODE(); root->father = NULL; root->next = root->prev = NULL; //Create an empty root node and add it into map float_map[*file_name] = root; //cout << "Create a node";//...................................... string key; int offset, block; while (1) { index >> key; if (index.eof()) break; index >> block >> offset; AddNode(type, file_name, &key, block, offset); } } else if (type == TYPE_CHAR) { CHARNODE *root = new CHARNODE(); root->father = NULL; root->next = root->prev = NULL; //Create an empty root node and add it into map char_map[*file_name] = root; //cout << "Create a node";//...................................... string key; int offset, block; while (1) { index >> key; if (index.eof()) break; index >> block >> offset; AddNode(type, file_name, &key, block, offset); } } else { index.close(); cerr << "Error: Type error!" << endl; return ERROR_UNKNOWN; } index.close(); return SUCCESS; } int BPLUSTREE::CreateIndex(string *file_name, int type) { //If there exits index on this attribute or with the same index_name string s1, s2; int temp; //Add this index into manager file ofstream allindex("allindex.idx", ios::app); ifstream tmp(*file_name, ios::app); tmp.close(); allindex << *file_name << " " << type << endl; allindex.close(); //Create B+Tree if (CreateTree(type, file_name) < 0) return ERROR_UNKNOWN; return SUCCESS; } int BPLUSTREE::DropIndex(string *file_name, int type) { string cmd, filen; // cmd = "DEL " + *file_name; // system(cmd.c_str()); remove((*file_name).c_str()); // cmd = "rename allindex.idx all.idx"; // system(cmd.c_str()); rename("allindex.idx", "all.idx"); ifstream old("all.idx"); ofstream file("allindex.idx"); int ttype; while (1) { old >> filen; if (old.eof()) break; old >> ttype; if (filen == *file_name) continue; file << filen << " " << ttype << endl; } old.close(); file.close(); // cmd = "DEL all.idx"; // system(cmd.c_str()); remove("all.idx"); if (type == TYPE_INT) int_map.erase(*file_name); else if (type == TYPE_FLOAT) float_map.erase(*file_name); else if (type == TYPE_CHAR) char_map.erase(*file_name); else { cerr << "Error: No such file!" << endl; return ERROR_FILE; } return SUCCESS; } int BPLUSTREE::Insert(int type, string *file_name, string *skey, int block, int offset) { stringstream ss(*skey); ofstream record(*file_name, ios::app); int key; ss >> key; record << *skey << " " << block << " " << offset << endl; record.close(); //Add to file //cout<<skey<<endl; if (AddNode(type, file_name, skey, block, offset) == SUCCESS) return SUCCESS; else return ERROR_UNKNOWN; } int BPLUSTREE::Delete(int type, string *file_name, vector<string> &deleted) {//1 for open; 0 for close stringstream skey; // string cmd; // cmd = "rename " + *file_name + " old.idx"; // system(cmd.c_str()); rename(file_name->c_str(), "old.idx"); ifstream old("old.idx"); ofstream updated(*file_name); if (type == TYPE_INT) { int key, temp; int block, offset; while (1) { old >> key; if (old.eof()) break; old >> block >> offset; bool flag = 0; for (int i = 0; i < deleted.size(); i++) { stringstream skey(deleted[i]); // skey.str(""); // skey << deleted[i]; skey >> temp; if (key == temp) { // deleted.erase(deleted.begin() + i); flag = 1; break; } } if (!flag) updated << key << " " << block << " " << offset << endl; } old.close(); updated.close(); // cmd = "del old.idx"; // system(cmd.c_str()); remove("old.idx"); int_map.erase(*file_name); if (CreateTree(type, file_name) == SUCCESS) return SUCCESS; else return ERROR_UNKNOWN; } else if (type == TYPE_FLOAT) { float key, temp; int block, offset; while (1) { old >> key; if (old.eof()) break; old >> block >> offset; bool flag = 0; for (int i = 0; i < deleted.size(); i++) { stringstream skey(deleted[i]); // skey.str(""); // skey << deleted[i]; skey >> temp; if (key == temp) { deleted.erase(deleted.begin() + i); flag = 1; break; } } if (!flag) updated << key << " " << block << " " << offset << endl; } old.close(); updated.close(); // cmd = "del old.idx"; // system(cmd.c_str()); remove("old.idx"); float_map.erase(*file_name); if (CreateTree(type, file_name) == SUCCESS) return SUCCESS; else return ERROR_UNKNOWN; } else if (type == TYPE_CHAR) { string key, temp; int block, offset; while (1) { old >> key; if (old.eof()) break; old >> block >> offset; bool flag = 0; for (int i = 0; i < deleted.size(); i++) { stringstream skey(deleted[i]); // skey.str(""); // skey << deleted[i]; skey >> temp; if (key == temp) { deleted.erase(deleted.begin() + i); flag = 1; break; } } if (!flag) updated << key << " " << block << " " << offset << endl; } old.close(); updated.close(); // cmd = "del old.idx"; // system(cmd.c_str()); remove("old.idx"); char_map.erase(*file_name); if (CreateTree(type, file_name) == SUCCESS) return SUCCESS; else return ERROR_UNKNOWN; } else return ERROR_TYPE; return SUCCESS; } int BPLUSTREE::Find(int type, string *file_name, string *lbound, string *rbound, int lopen, int ropen) { stringstream ls(*lbound), rs(*rbound); //Clear select.tmp ofstream tmp("select.tmp"); tmp.close(); if (type == TYPE_INT) { INTNODE *p, *left, *right; int lb, rb, li, ri, i; ls >> lb; rs >> rb; //No result if (lb > rb || (lb == rb && (lopen || ropen))) return SUCCESS; p = int_map[*file_name]; if (p->key.size() == 0 && p->pointer.size() == 0) return SUCCESS; li = 0; left = right = NULL; //Find the left node while (p->offset.size() == 0) { int i = 0; while (i + 1 < p->key.size() && p->key[i + 1] <= lb) i++; i++; if (p->key[0] > lb) i = 0; p = p->pointer[i]; } left = p; if (lopen)//Left open { while (left->key[li] <= lb) { li++; if (li >= left->key.size()) { li = 0; if (left->next) left = left->next; else//No result return SUCCESS; } } } else//Left close { while (left->key[li] < lb) { li++; if (li >= left->key.size()) { li = 0; if (left->next) left = left->next; else//No result return SUCCESS; } } } //Find the right node p = int_map[*file_name]; while (p->offset.size() == 0) { int i = 0; while (i + 1 < p->key.size() && p->key[i + 1] <= rb) i++; i++; if (p->key[0] > rb) i = 0; p = p->pointer[i]; } right = p; ri = right->key.size() - 1; if (ropen)//Right open { while (right->key[ri] >= rb) { ri--; if (ri < 0) { if (right->prev) right = right->prev; else//No result return SUCCESS; ri = right->key.size() - 1; } } } else//Right close { while (right->key[ri] > rb) { ri--; if (ri < 0) { if (right->prev) right = right->prev; else//No result return SUCCESS; ri = right->key.size() - 1; } } } p = left; i = li; ofstream tmp("select.tmp"); while (1) { if ((p == right && i > ri) || (right->next == left)) break; tmp << p->block[i] << " " << p->offset[i] << endl; if (p == right && i == ri) break; i++; if (i == p->key.size()) { i = 0; p = p->next; } } tmp.close(); } else if (type == TYPE_FLOAT) { FLOATNODE *p, *left, *right; float lb, rb; int li, ri, i; ls >> lb; rs >> rb; //No result if (lb > rb || (lb == rb && (lopen || ropen))) return SUCCESS; p = float_map[*file_name]; if (p->key.size() == 0 && p->pointer.size() == 0) return SUCCESS; li = 0; left = right = NULL; //Find the left node while (p->offset.size() == 0) { int i = 0; while (i + 1 < p->key.size() && p->key[i + 1] <= lb) i++; i++; if (p->key[0] > lb) i = 0; p = p->pointer[i]; } left = p; if (lopen)//Left open { while (left->key[li] <= lb) { li++; if (li >= left->key.size()) { li = 0; if (left->next) left = left->next; else//No result return SUCCESS; } } } else//Left close { while (left->key[li] < lb) { li++; if (li >= left->key.size()) { li = 0; if (left->next) left = left->next; else//No result return SUCCESS; } } } //Find the right node p = float_map[*file_name]; while (p->offset.size() == 0) { int i = 0; while (i + 1 < p->key.size() && p->key[i + 1] <= rb) i++; i++; if (p->key[0] > rb) i = 0; p = p->pointer[i]; } right = p; ri = right->key.size() - 1; if (ropen)//Right open { while (right->key[ri] >= rb) { ri--; if (ri < 0) { if (right->prev) right = right->prev; else//No result return SUCCESS; ri = right->key.size() - 1; } } } else//Right close { while (right->key[ri] > rb) { ri--; if (ri < 0) { if (right->prev) right = right->prev; else//No result return SUCCESS; ri = right->key.size() - 1; } } } p = left; i = li; ofstream tmp("select.tmp"); while (1) { if ((p == right && i > ri) || (right->next == left)) break; tmp << p->block[i] << " " << p->offset[i] << endl; if (p == right && i == ri) break; i++; if (i == p->key.size()) { i = 0; p = p->next; } } tmp.close(); } else if (type == TYPE_CHAR) { CHARNODE *p, *left, *right; string lb, rb; int li, ri, i; ls >> lb; rs >> rb; //No result if (lb > rb || (lb == rb && (lopen || ropen))) return SUCCESS; p = char_map[*file_name]; if (p->key.size() == 0 && p->pointer.size() == 0) return SUCCESS; li = 0; left = right = NULL; //Find the left node while (p->offset.size() == 0) { int i = 0; while (i + 1 < p->key.size() && p->key[i + 1] <= lb) i++; i++; if (p->key[0] > lb) i = 0; p = p->pointer[i]; } left = p; if (lopen)//Left open { while (left->key[li] <= lb) { li++; if (li >= left->key.size()) { li = 0; if (left->next) left = left->next; else//No result return SUCCESS; } } } else//Left close { while (left->key[li] < lb) { li++; if (li >= left->key.size()) { li = 0; if (left->next) left = left->next; else//No result return SUCCESS; } } } //Find the right node p = char_map[*file_name]; while (p->offset.size() == 0) { int i = 0; while (i + 1 < p->key.size() && p->key[i + 1] <= rb) i++; i++; if (p->key[0] > rb) i = 0; p = p->pointer[i]; } right = p; ri = right->key.size() - 1; if (ropen)//Right open { while (right->key[ri] >= rb) { ri--; if (ri < 0) { if (right->prev) right = right->prev; else//No result return SUCCESS; ri = right->key.size() - 1; } } } else//Right close { while (right->key[ri] > rb) { ri--; if (ri < 0) { if (right->prev) right = right->prev; else//No result return SUCCESS; ri = right->key.size() - 1; } } } p = left; i = li; ofstream tmp("select.tmp"); while (1) { if ((p == right && i > ri) || (right->next == left)) break; tmp << p->block[i] << " " << p->offset[i] << endl; if (p == right && i == ri) break; i++; if (i == p->key.size()) { i = 0; p = p->next; } } tmp.close(); } else { cerr << "Error: No such type!" << endl; return ERROR_TYPE; } return SUCCESS; } int BPLUSTREE::AddNode(int type, string *file_name, string *skey, int block, int offset) { int degree = GetDegree(block_size, type); if (type == TYPE_INT) { INTNODE *root = int_map[*file_name]; INTNODE *p; int key; stringstream ss(*skey); p = root; ss >> key; //cout << degree << endl;//........................................... //The first node if (root->key.size() == 0) { root->key.push_back(key); root->offset.push_back(offset); root->block.push_back(block); return SUCCESS; } //Add node to a non-empty tree while (p->offset.size() == 0) { int i = 0; while (i + 1 < p->key.size() && p->key[i + 1] <= key) i++; i++; if (p->key[0] > key) i = 0; p = p->pointer[i]; } int i = 0; while (i + 1 < p->key.size() && p->key[i] <= key) i++; if (p->key[i] > key) { p->key.insert(p->key.begin() + i, key); p->offset.insert(p->offset.begin() + i, offset); p->block.insert(p->block.begin() + i, block); } else { p->key.push_back(key); p->block.push_back(block); p->offset.push_back(offset); } //Split from leaf while (p->key.size() == degree) { //Split root if (p == root) { INTNODE *t1, *t2; t2 = new INTNODE; t1 = new INTNODE; t1->prev = t2->next = t1->next = t2->prev = NULL; //Only root if (p->offset.size() != 0) { //Copy left half to t1 for (int i = 0; i < (degree + 1) / 2; i++) { t1->key.push_back(p->key[i]); t1->offset.push_back(p->offset[i]); t1->block.push_back(p->block[i]); } //Copy right half to t2 for (int i = (degree + 1) / 2; i < degree; i++) { t2->key.push_back(p->key[i]); t2->offset.push_back(p->offset[i]); t2->block.push_back(p->block[i]); } //Link t1 and t2 as they are leaves t1->next = t2; t2->prev = t1; p->key.clear(); p->key.push_back(t2->key[0]); } else {//Root is not leaf //Copy left half to t1 for (int i = 0; i < degree / 2; i++) { t1->key.push_back(p->key[i]); t1->pointer.push_back(p->pointer[i]); p->pointer[i]->father = t1; } p->pointer[degree / 2]->father = t1; t1->pointer.push_back(p->pointer[degree / 2]); //Copy right half to t2 for (int i = degree / 2 + 1; i < degree; i++) { t2->key.push_back(p->key[i]); t2->pointer.push_back(p->pointer[i]); p->pointer[i]->father = t2; } t2->pointer.push_back(p->pointer[degree]); p->pointer[degree]->father = t2; //Add one key to root int temp = p->key[degree / 2]; p->key.clear(); p->key.push_back(temp); } t1->father = t2->father = p; //Clear root p->block.clear(); p->offset.clear(); p->pointer.clear(); p->pointer.push_back(t1); p->pointer.push_back(t2); break; } else { INTNODE *t; //Split leaf node if (p->offset.size() != 0) { t = new INTNODE; t->father = p->father; t->next = p->next; p->next = t; if (t->next) t->next->prev = t; t->prev = p; //Cut [m/2] to m-1 to t int temp = (degree + 1) / 2; while (p->key.size() > temp) { t->key.push_back(p->key[temp]); t->block.push_back(p->block[temp]); t->offset.push_back(p->offset[temp]); p->key.erase(p->key.begin() + temp); p->block.erase(p->block.begin() + temp); p->offset.erase(p->offset.begin() + temp); } //Add t to their father's pointer list temp = 0; while (p->father->pointer[temp] != p) temp++; p = p->father; temp++; if (temp != p->pointer.size()) { p->pointer.insert(p->pointer.begin() + temp, t); p->key.insert(p->key.begin() + temp - 1, t->key[0]); } else { p->pointer.push_back(t); p->key.push_back(t->key[0]); } } //Split non-leaf node else { t = new INTNODE; t->father = p->father; int temp = degree / 2 + 1; while (p->key.size() > temp) { t->key.push_back(p->key[temp]); t->pointer.push_back(p->pointer[temp]); p->pointer[temp]->father = t; p->key.erase(p->key.begin() + temp); p->pointer.erase(p->pointer.begin() + temp); } t->pointer.push_back(p->pointer[temp]); p->pointer[temp]->father = t; p->pointer.erase(p->pointer.begin() + temp); temp = 0; while (p->father->pointer[temp++] != p); /* p->father->pointer.insert(p->father->pointer.begin() + temp, t); temp--; p->father->key.insert(p->father->key.begin() + temp, p->key[degree / 2]); p->key.pop_back(); p = p->father;*/ //&)*%^)&(@^*(_$&^_*(&^_*(%^&*(@^$&%^&%_^$*(@&^*(!^*(@*(%$&@(&$@)(^$)*^$)(@*^_& if (temp != p->father->pointer.size()) { p->father->pointer.insert(p->father->pointer.begin() + temp, t); p->father->key.insert(p->father->key.begin() + temp - 1, p->key[degree / 2]); } else { p->father->pointer.push_back(t); p->father->key.push_back(p->key[degree / 2]); } p->key.pop_back(); p = p->father; //&)*%^)&(@^*(_$&^_*(&^_*(%^&*(@^$&%^&%_^$*(@&^*(!^*(@*(%$&@(&$@)(^$)*^$)(@*^_& } } } } else if (type == TYPE_FLOAT) { FLOATNODE *root = float_map[*file_name]; FLOATNODE *p; float key; stringstream ss(*skey); p = root; ss >> key; //cout << degree << endl;//........................................... //The first node if (root->key.size() == 0) { root->key.push_back(key); root->offset.push_back(offset); root->block.push_back(block); return SUCCESS; } //Add node to a non-empty tree while (p->offset.size() == 0) { int i = 0; while (i + 1 < p->key.size() && p->key[i + 1] <= key) i++; i++; if (p->key[0] > key) i = 0; p = p->pointer[i]; } int i = 0; while (i + 1 < p->key.size() && p->key[i] <= key) i++; if (p->key[i] > key) { p->key.insert(p->key.begin() + i, key); p->offset.insert(p->offset.begin() + i, offset); p->block.insert(p->block.begin() + i, block); } else { p->key.push_back(key); p->block.push_back(block); p->offset.push_back(offset); } //Split from leaf while (p->key.size() == degree) { //Split root if (p == root) { FLOATNODE *t1, *t2; t2 = new FLOATNODE; t1 = new FLOATNODE; t1->prev = t2->next = t1->next = t2->prev = NULL; //Only root if (p->offset.size() != 0) { //Copy left half to t1 for (int i = 0; i < (degree + 1) / 2; i++) { t1->key.push_back(p->key[i]); t1->offset.push_back(p->offset[i]); t1->block.push_back(p->block[i]); } //Copy right half to t2 for (int i = (degree + 1) / 2; i < degree; i++) { t2->key.push_back(p->key[i]); t2->offset.push_back(p->offset[i]); t2->block.push_back(p->block[i]); } //Link t1 and t2 as they are leaves t1->next = t2; t2->prev = t1; p->key.clear(); p->key.push_back(t2->key[0]); } else {//Root is not leaf //Copy left half to t1 for (int i = 0; i < degree / 2; i++) { t1->key.push_back(p->key[i]); t1->pointer.push_back(p->pointer[i]); p->pointer[i]->father = t1; } p->pointer[degree / 2]->father = t1; t1->pointer.push_back(p->pointer[degree / 2]); //Copy right half to t2 for (int i = degree / 2 + 1; i < degree; i++) { t2->key.push_back(p->key[i]); t2->pointer.push_back(p->pointer[i]); p->pointer[i]->father = t2; } t2->pointer.push_back(p->pointer[degree]); p->pointer[degree]->father = t2; //Add one key to root float temp = p->key[degree / 2]; p->key.clear(); p->key.push_back(temp); } t1->father = t2->father = p; //Clear root p->block.clear(); p->offset.clear(); p->pointer.clear(); p->pointer.push_back(t1); p->pointer.push_back(t2); break; } else { FLOATNODE *t; //Split leaf node if (p->offset.size() != 0) { t = new FLOATNODE; t->father = p->father; t->next = p->next; p->next = t; if (t->next) t->next->prev = t; t->prev = p; //Cut [m/2] to m-1 to t int temp = (degree + 1) / 2; while (p->key.size() > temp) { t->key.push_back(p->key[temp]); t->block.push_back(p->block[temp]); t->offset.push_back(p->offset[temp]); p->key.erase(p->key.begin() + temp); p->block.erase(p->block.begin() + temp); p->offset.erase(p->offset.begin() + temp); } //Add t to their father's pointer list temp = 0; while (p->father->pointer[temp] != p) temp++; p = p->father; temp++; if (temp != p->pointer.size()) { p->pointer.insert(p->pointer.begin() + temp, t); p->key.insert(p->key.begin() + temp - 1, t->key[0]); } else { p->pointer.push_back(t); p->key.push_back(t->key[0]); } } //Split non-leaf node else { t = new FLOATNODE; t->father = p->father; int temp = degree / 2 + 1; while (p->key.size() > temp) { t->key.push_back(p->key[temp]); t->pointer.push_back(p->pointer[temp]); p->pointer[temp]->father = t; p->key.erase(p->key.begin() + temp); p->pointer.erase(p->pointer.begin() + temp); } t->pointer.push_back(p->pointer[temp]); p->pointer[temp]->father = t; p->pointer.erase(p->pointer.begin() + temp); temp = 0; while (p->father->pointer[temp++] != p); if (temp != p->father->pointer.size()) { p->father->pointer.insert(p->father->pointer.begin() + temp, t); p->father->key.insert(p->father->key.begin() + temp - 1, p->key[degree / 2]); } else { p->father->pointer.push_back(t); p->father->key.push_back(p->key[degree / 2]); } p->key.pop_back(); p = p->father; } } } } else if (type == TYPE_CHAR) { CHARNODE *root = char_map[*file_name]; CHARNODE *p; string key; stringstream ss(*skey); p = root; ss >> key; //cout << degree << endl;//........................................... //The first node if (root->key.size() == 0) { root->key.push_back(key); root->offset.push_back(offset); root->block.push_back(block); return SUCCESS; } //Add node to a non-empty tree while (p->offset.size() == 0) { int i = 0; while (i + 1 < p->key.size() && p->key[i + 1] <= key) i++; i++; if (p->key[0] > key) i = 0; p = p->pointer[i]; } int i = 0; while (i + 1 < p->key.size() && p->key[i] <= key) i++; if (p->key[i] > key) { p->key.insert(p->key.begin() + i, key); p->offset.insert(p->offset.begin() + i, offset); p->block.insert(p->block.begin() + i, block); } else { p->key.push_back(key); p->block.push_back(block); p->offset.push_back(offset); } //Split from leaf while (p->key.size() == degree) { //Split root if (p == root) { CHARNODE *t1, *t2; t2 = new CHARNODE; t1 = new CHARNODE; t1->prev = t2->next = t1->next = t2->prev = NULL; //Only root if (p->offset.size() != 0) { //Copy left half to t1 for (int i = 0; i < (degree + 1) / 2; i++) { t1->key.push_back(p->key[i]); t1->offset.push_back(p->offset[i]); t1->block.push_back(p->block[i]); } //Copy right half to t2 for (int i = (degree + 1) / 2; i < degree; i++) { t2->key.push_back(p->key[i]); t2->offset.push_back(p->offset[i]); t2->block.push_back(p->block[i]); } //Link t1 and t2 as they are leaves t1->next = t2; t2->prev = t1; p->key.clear(); p->key.push_back(t2->key[0]); } else {//Root is not leaf //Copy left half to t1 for (int i = 0; i < degree / 2; i++) { t1->key.push_back(p->key[i]); t1->pointer.push_back(p->pointer[i]); p->pointer[i]->father = t1; } p->pointer[degree / 2]->father = t1; t1->pointer.push_back(p->pointer[degree / 2]); //Copy right half to t2 for (int i = degree / 2 + 1; i < degree; i++) { t2->key.push_back(p->key[i]); t2->pointer.push_back(p->pointer[i]); p->pointer[i]->father = t2; } t2->pointer.push_back(p->pointer[degree]); p->pointer[degree]->father = t2; //Add one key to root string temp = p->key[degree / 2]; p->key.clear(); p->key.push_back(temp); } t1->father = t2->father = p; //Clear root p->block.clear(); p->offset.clear(); p->pointer.clear(); p->pointer.push_back(t1); p->pointer.push_back(t2); break; } else { CHARNODE *t; //Split leaf node if (p->offset.size() != 0) { t = new CHARNODE; t->father = p->father; t->next = p->next; p->next = t; if (t->next) t->next->prev = t; t->prev = p; //Cut [m/2] to m-1 to t int temp = (degree + 1) / 2; while (p->key.size() > temp) { t->key.push_back(p->key[temp]); t->block.push_back(p->block[temp]); t->offset.push_back(p->offset[temp]); p->key.erase(p->key.begin() + temp); p->block.erase(p->block.begin() + temp); p->offset.erase(p->offset.begin() + temp); } //Add t to their father's pointer list temp = 0; while (p->father->pointer[temp] != p) temp++; p = p->father; temp++; if (temp != p->pointer.size()) { p->pointer.insert(p->pointer.begin() + temp, t); p->key.insert(p->key.begin() + temp - 1, t->key[0]); } else { p->pointer.push_back(t); p->key.push_back(t->key[0]); } } //Split non-leaf node else { t = new CHARNODE; t->father = p->father; int temp = degree / 2 + 1; while (p->key.size() > temp) { t->key.push_back(p->key[temp]); t->pointer.push_back(p->pointer[temp]); p->pointer[temp]->father = t; p->key.erase(p->key.begin() + temp); p->pointer.erase(p->pointer.begin() + temp); } t->pointer.push_back(p->pointer[temp]); p->pointer[temp]->father = t; p->pointer.erase(p->pointer.begin() + temp); temp = 0; while (p->father->pointer[temp++] != p); if (temp != p->father->pointer.size()) { p->father->pointer.insert(p->father->pointer.begin() + temp, t); p->father->key.insert(p->father->key.begin() + temp - 1, p->key[degree / 2]); } else { p->father->pointer.push_back(t); p->father->key.push_back(p->key[degree / 2]); } p->key.pop_back(); p = p->father; } } } } else { cerr << "Error: No such type!" << endl; return ERROR_TYPE; } return SUCCESS; } int BPLUSTREE::DeleteNode(int type, string *file_name, string *skey) { int degree = GetDegree(block_size, type); stringstream ss(*skey); string output; if (type == TYPE_INT) { int key; INTNODE *p, *pre_node = NULL, *next_node = NULL, *root; ss >> key; root = p = int_map[*file_name]; //Find the leaf node which contains the key while (p->offset.size() == 0) { int i = 0; while (i + 1 < p->key.size() && p->key[i + 1] <= key) i++; i++; if (p->key[0] > key) i = 0; if (i > 0) pre_node = p->pointer[i - 1]; else if (i + 1 < p->key.size()) next_node = p->pointer[i + 1]; p = p->pointer[i]; } //Find the key int i = 0; while (i < p->key.size() && p->key[i] != key) i++; if (i == p->key.size()) { cerr << "Error: No such turple!" << endl; return ERROR_OFFSET_NOT_EXISTS; } output = to_string(p->block[i]) + " " + to_string(p->offset[i]); //Delete it from B+ tree and file p->key.erase(p->key.begin() + i); p->block.erase(p->block.begin() + i); p->offset.erase(p->offset.begin() + i); // string cmd; // cmd = "rename " + *file_name + " temp.idx"; // system(cmd.c_str()); rename(file_name->c_str(), "temp.idx"); ifstream old("temp.idx"); ofstream nfile(*file_name); int toffset, tkey, tblock; while (1) { old >> tkey; if (old.eof()) break; old >> tblock >> toffset; if (key == tkey) continue; nfile << tkey << " " << tblock << " " << toffset << endl; } old.close(); nfile.close(); // cmd = "del temp.idx"; // system(cmd.c_str()); remove("temp.idx"); if (p->key.size() >= degree / 2 || p == root) goto end; //Adjust B+ tree if (!pre_node && (next_node && next_node->key.size() + p->key.size() < degree)) pre_node = p; p = next_node; while (p->key.size() < degree / 2) { //If p's father is root if (p->father == root) { if (root->pointer.size() != 1) break; //Only son in root, p becomes the root int_map[*file_name] = p; p->father = NULL; free(root); } //Merge two nodes to the left node if (pre_node && pre_node->key.size() + p->key.size() < degree) { //Merge leaf nodes if (p->offset.size() == 0) { //Copy keys and offsets to the left node for (int i = 0; i < p->key.size(); i++) { pre_node->key.push_back(p->key[i]); pre_node->block.push_back(p->block[i]); pre_node->offset.push_back(p->offset[i]); } pre_node->next = p->next; if (p->next) p->next->prev = pre_node; p->key.clear(); p->block.clear(); p->offset.clear(); pre_node = p; //p is the first pointer of its father if (p->father != pre_node->father) { p = p->father; p->key.erase(p->key.begin()); p->pointer.erase(p->pointer.begin()); } else {//p is not the first pointer of its father int i = 0; while (p->father->pointer[i] != p) i++; p = p->father; p->pointer.erase(p->pointer.begin() + i); i--; p->key.erase(p->key.begin() + i); } free(pre_node); } else//Merge non-leaf nodes { //Copy keys and pointers to the left node for (int i = 0; i < p->key.size(); i++) { pre_node->key.push_back(p->key[i]); pre_node->pointer.push_back(p->pointer[i]); } pre_node->pointer.push_back(p->pointer[i]); p->key.clear(); p->pointer.clear(); pre_node = p; if (p->father != pre_node->father) {//p is the first pointer of its father p = p->father; p->key.erase(p->key.begin()); p->pointer.erase(p->pointer.begin()); } else {//p is not the first pointer of its father int i = 0; while (p->father->pointer[i] != p) i++; p = p->father; p->pointer.erase(p->pointer.begin() + i); i--; p->key.erase(p->key.begin() + i); } free(pre_node); } } else//Redistribute pointers { if (p->offset.size() != 0) {//Leaf nodes if (pre_node)//Take one key from pre_node_node to p { p->key.insert(p->key.begin(), pre_node->key[pre_node->key.size() - 1]); p->block.insert(p->block.begin(), pre_node->block[pre_node->block.size() - 1]); p->offset.insert(p->offset.begin(), pre_node->offset[pre_node->offset.size() - 1]); pre_node->key.pop_back(); pre_node->block.pop_back(); pre_node->offset.pop_back(); } else//Take one key from next_node_node to p { p->key.push_back(next_node->key[0]); p->block.push_back(next_node->block[0]); p->offset.push_back(next_node->offset[0]); next_node->key.erase(next_node->key.begin()); next_node->block.erase(next_node->block.begin()); next_node->offset.erase(next_node->offset.begin()); } } else//Non-leaf nodes { if (pre_node)//Take one key from pre_node_node to p { p->key.insert(p->key.begin(), pre_node->key[pre_node->key.size() - 1]); p->pointer.insert(p->pointer.begin(), pre_node->pointer[pre_node->pointer.size() - 1]); pre_node->key.pop_back(); pre_node->pointer.pop_back(); } else//Take one key from next_node_node to p { p->key.push_back(next_node->key[0]); p->pointer.push_back(next_node->pointer[0]); next_node->key.erase(next_node->key.begin()); next_node->pointer.erase(next_node->pointer.begin()); } } } } } else if (type == TYPE_FLOAT) { float key; FLOATNODE *p, *pre_node = NULL, *next_node = NULL, *root; ss >> key; root = p = float_map[*file_name]; //Find the leaf node which contains the key while (p->offset.size() == 0) { int i = 0; while (i + 1 < p->key.size() && p->key[i + 1] <= key) i++; i++; if (p->key[0] > key) i = 0; if (i > 0) pre_node = p->pointer[i - 1]; else if (i + 1 < p->key.size()) next_node = p->pointer[i + 1]; p = p->pointer[i]; } //Find the key int i = 0; while (i < p->key.size() && p->key[i] != key) i++; if (i == p->key.size()) { cerr << "Error: No such turple!" << endl; return ERROR_OFFSET_NOT_EXISTS; } output = to_string(p->block[i]) + " " + to_string(p->offset[i]); //Delete it from B+ tree and file p->key.erase(p->key.begin() + i); p->block.erase(p->block.begin() + i); p->offset.erase(p->offset.begin() + i); // string cmd; // cmd = "rename " + *file_name + " temp.idx"; // system(cmd.c_str()); rename(file_name->c_str(), "temp.idx"); ifstream old("temp.idx"); ofstream nfile(*file_name); int toffset, tblock; float tkey; while (1) { old >> tkey; if (old.eof()) break; old >> tblock >> toffset; if (key == tkey) continue; nfile << tkey << " " << tblock << " " << toffset << endl; } old.close(); nfile.close(); // cmd = "del temp.idx"; // system(cmd.c_str()); remove("temp.idx"); if (p->key.size() >= degree / 2 || p == root) goto end; //Adjust B+ tree if (!pre_node && (next_node && next_node->key.size() + p->key.size() < degree)) pre_node = p; p = next_node; while (p->key.size() < degree / 2) { //If p's father is root if (p->father == root) { if (root->pointer.size() != 1) break; //Only son in root, p becomes the root float_map[*file_name] = p; p->father = NULL; free(root); } //Merge two nodes to the left node if (pre_node && pre_node->key.size() + p->key.size() < degree) { //Merge leaf nodes if (p->offset.size() == 0) { //Copy keys and offsets to the left node for (int i = 0; i < p->key.size(); i++) { pre_node->key.push_back(p->key[i]); pre_node->block.push_back(p->block[i]); pre_node->offset.push_back(p->offset[i]); } pre_node->next = p->next; if (p->next) p->next->prev = pre_node; p->key.clear(); p->block.clear(); p->offset.clear(); pre_node = p; //p is the first pointer of its father if (p->father != pre_node->father) { p = p->father; p->key.erase(p->key.begin()); p->pointer.erase(p->pointer.begin()); } else {//p is not the first pointer of its father int i = 0; while (p->father->pointer[i] != p) i++; p = p->father; p->pointer.erase(p->pointer.begin() + i); i--; p->key.erase(p->key.begin() + i); } free(pre_node); } else//Merge non-leaf nodes { //Copy keys and pointers to the left node for (int i = 0; i < p->key.size(); i++) { pre_node->key.push_back(p->key[i]); pre_node->pointer.push_back(p->pointer[i]); } pre_node->pointer.push_back(p->pointer[i]); p->key.clear(); p->pointer.clear(); pre_node = p; if (p->father != pre_node->father) {//p is the first pointer of its father p = p->father; p->key.erase(p->key.begin()); p->pointer.erase(p->pointer.begin()); } else {//p is not the first pointer of its father int i = 0; while (p->father->pointer[i] != p) i++; p = p->father; p->pointer.erase(p->pointer.begin() + i); i--; p->key.erase(p->key.begin() + i); } free(pre_node); } } else//Redistribute pointers { if (p->offset.size() != 0) {//Leaf nodes if (pre_node)//Take one key from pre_node_node to p { p->key.insert(p->key.begin(), pre_node->key[pre_node->key.size() - 1]); p->block.insert(p->block.begin(), pre_node->block[pre_node->block.size() - 1]); p->offset.insert(p->offset.begin(), pre_node->offset[pre_node->offset.size() - 1]); pre_node->key.pop_back(); pre_node->block.pop_back(); pre_node->offset.pop_back(); } else//Take one key from next_node_node to p { p->key.push_back(next_node->key[0]); p->block.push_back(next_node->block[0]); p->offset.push_back(next_node->offset[0]); next_node->key.erase(next_node->key.begin()); next_node->block.erase(next_node->block.begin()); next_node->offset.erase(next_node->offset.begin()); } } else//Non-leaf nodes { if (pre_node)//Take one key from pre_node_node to p { p->key.insert(p->key.begin(), pre_node->key[pre_node->key.size() - 1]); p->pointer.insert(p->pointer.begin(), pre_node->pointer[pre_node->pointer.size() - 1]); pre_node->key.pop_back(); pre_node->pointer.pop_back(); } else//Take one key from next_node_node to p { p->key.push_back(next_node->key[0]); p->pointer.push_back(next_node->pointer[0]); next_node->key.erase(next_node->key.begin()); next_node->pointer.erase(next_node->pointer.begin()); } } } } } else if (type == TYPE_CHAR) { string key; CHARNODE *p, *pre_node = NULL, *next_node = NULL, *root; ss >> key; root = p = char_map[*file_name]; //Find the leaf node which contains the key while (p->offset.size() == 0) { int i = 0; while (i + 1 < p->key.size() && p->key[i + 1] <= key) i++; i++; if (p->key[0] > key) i = 0; if (i > 0) pre_node = p->pointer[i - 1]; else if (i + 1 < p->key.size()) next_node = p->pointer[i + 1]; p = p->pointer[i]; } //Find the key int i = 0; while (i < p->key.size() && p->key[i] != key) i++; if (i == p->key.size()) { cerr << "Error: No such turple!" << endl; return ERROR_OFFSET_NOT_EXISTS; } output = to_string(p->block[i]) + " " + to_string(p->offset[i]); //Delete it from B+ tree and file p->key.erase(p->key.begin() + i); p->block.erase(p->block.begin() + i); p->offset.erase(p->offset.begin() + i); // string cmd; // cmd = "rename " + *file_name + " temp.idx"; // system(cmd.c_str()); rename(file_name->c_str(), "temp.idx"); ifstream old("temp.idx"); ofstream nfile(*file_name); int toffset, tblock; string tkey; while (1) { old >> tkey; if (old.eof()) break; old >> tblock >> toffset; if (key == tkey) continue; nfile << tkey << " " << tblock << " " << toffset << endl; } old.close(); nfile.close(); // cmd = "del temp.idx"; // system(cmd.c_str()); remove("temp.idx"); if (p->key.size() >= degree / 2 || p == root) goto end; //Adjust B+ tree if (!pre_node && (next_node && next_node->key.size() + p->key.size() < degree)) pre_node = p; p = next_node; while (p->key.size() < degree / 2) { //If p's father is root if (p->father == root) { if (root->pointer.size() != 1) break; //Only son in root, p becomes the root char_map[*file_name] = p; p->father = NULL; free(root); } //Merge two nodes to the left node if (pre_node && pre_node->key.size() + p->key.size() < degree) { //Merge leaf nodes if (p->offset.size() == 0) { //Copy keys and offsets to the left node for (int i = 0; i < p->key.size(); i++) { pre_node->key.push_back(p->key[i]); pre_node->block.push_back(p->block[i]); pre_node->offset.push_back(p->offset[i]); } pre_node->next = p->next; if (p->next) p->next->prev = pre_node; p->key.clear(); p->block.clear(); p->offset.clear(); pre_node = p; //p is the first pointer of its father if (p->father != pre_node->father) { p = p->father; p->key.erase(p->key.begin()); p->pointer.erase(p->pointer.begin()); } else {//p is not the first pointer of its father int i = 0; while (p->father->pointer[i] != p) i++; p = p->father; p->pointer.erase(p->pointer.begin() + i); i--; p->key.erase(p->key.begin() + i); } free(pre_node); } else//Merge non-leaf nodes { //Copy keys and pointers to the left node for (int i = 0; i < p->key.size(); i++) { pre_node->key.push_back(p->key[i]); pre_node->pointer.push_back(p->pointer[i]); } pre_node->pointer.push_back(p->pointer[i]); p->key.clear(); p->pointer.clear(); pre_node = p; if (p->father != pre_node->father) {//p is the first pointer of its father p = p->father; p->key.erase(p->key.begin()); p->pointer.erase(p->pointer.begin()); } else {//p is not the first pointer of its father int i = 0; while (p->father->pointer[i] != p) i++; p = p->father; p->pointer.erase(p->pointer.begin() + i); i--; p->key.erase(p->key.begin() + i); } free(pre_node); } } else//Redistribute pointers { if (p->offset.size() != 0) {//Leaf nodes if (pre_node)//Take one key from pre_node_node to p { p->key.insert(p->key.begin(), pre_node->key[pre_node->key.size() - 1]); p->block.insert(p->block.begin(), pre_node->block[pre_node->block.size() - 1]); p->offset.insert(p->offset.begin(), pre_node->offset[pre_node->offset.size() - 1]); pre_node->key.pop_back(); pre_node->block.pop_back(); pre_node->offset.pop_back(); } else//Take one key from next_node_node to p { p->key.push_back(next_node->key[0]); p->block.push_back(next_node->block[0]); p->offset.push_back(next_node->offset[0]); next_node->key.erase(next_node->key.begin()); next_node->block.erase(next_node->block.begin()); next_node->offset.erase(next_node->offset.begin()); } } else//Non-leaf nodes { if (pre_node)//Take one key from pre_node_node to p { p->key.insert(p->key.begin(), pre_node->key[pre_node->key.size() - 1]); p->pointer.insert(p->pointer.begin(), pre_node->pointer[pre_node->pointer.size() - 1]); pre_node->key.pop_back(); pre_node->pointer.pop_back(); } else//Take one key from next_node_node to p { p->key.push_back(next_node->key[0]); p->pointer.push_back(next_node->pointer[0]); next_node->key.erase(next_node->key.begin()); next_node->pointer.erase(next_node->pointer.begin()); } } } } } else { cerr << "Error: Unknown!" << endl; return ERROR_UNKNOWN; } end: ofstream tempf("delete.tmp"); tempf << output << endl; tempf.close(); return SUCCESS; } int GetDegree(int block_size, int type) { int degree, type_size; //int -> 4bytes float -> 4bytes char[] -> 255bytes if (type == TYPE_INT || type == TYPE_FLOAT) type_size = 4; else if (type == TYPE_CHAR) type_size = 255; else { cerr << "Error: No such type!" << endl; return ERROR_TYPE; } degree = (block_size + type_size) / (POINTERSIZE + type_size); //Degree >= 16 return degree;//#################################################################DEBUG }
#pragma once #ifndef GLFW_INCLUDE_VULKAN #define GLFW_INCLUDE_VULKAN #endif #include <GLFW/glfw3.h> #include <vector> #include <string> struct InstanceVersion { uint32_t major, minor, patch; }; std::vector<std::string> fromExtPropertiesList(std::vector<VkExtensionProperties> prop_vec); class VulkanInstance { private: std::vector<std::string> m_InstanceExtensionNames; std::vector<VkExtensionProperties> m_AvailableInstanceExtensions; bool gatheredInstanceExtensions; std::vector<std::string> m_LayerNames; bool gatheredLayerNames; std::string m_AppName, m_EngineName; InstanceVersion m_AppVersion, m_EngineVersion; uint32_t m_VulkanAPIVerison; VkInstance m_VkInstance; bool m_Built; public: VulkanInstance(std::string appName, InstanceVersion appVersion, std::string engineName, InstanceVersion engineVersion, uint32_t vulkanApiVersion, bool enableValidationLayers); VulkanInstance(); void setAppName(std::string appName); void setAppVersion(InstanceVersion appVersion); void setEngineName(std::string engineName); void setEngineVersion(InstanceVersion engineVersion); void setVulkanApiVersion(uint32_t vulkanApiVersion); std::string getAppName(); std::string getEngineName(); InstanceVersion getAppVersion(); InstanceVersion getEngineVersion(); std::vector<VkExtensionProperties> getAvailableInstanceExtensions(); std::vector<std::string> getRequiredInstanceExtensions(); std::vector<std::string> getRequstedInstanceExtensions(); bool verifyExtensionCompatibility(std::string extensionName); void requireExtension(std::string extensionName); void build(); bool isBuilt(); void setUseValidationLayers(bool useValidationLayers); bool getUseValidationLayers(); bool areValidationLayersSupported(); std::vector<VkLayerProperties> getAvailableLayers(); std::vector<std::string> getRequestedLayers(); VkInstance getInternalInstance(); };
#include "pch.h" #ifndef SSAOINSTANCE_H #define SSAOINSTANCE_H #include "ViewHelper.h" #include "ConstantBuffer.h" #include "Shaders.h" const int SSAO_SAMPLE_DIRECTIONS = 14; struct PS_SSAO_BUFFER { XMFLOAT4 sampleDirections[SSAO_SAMPLE_DIRECTIONS]; XMFLOAT2 ditherScale; XMFLOAT2 pad; }; struct PS_SSAO_CAMERA_BUFFER { XMMATRIX viewToTexMatrix; XMMATRIX projectionMatrix; XMMATRIX viewMatrix; }; class SSAOInstance { private: // Device ID3D11DeviceContext* m_deviceContext; // Constant Buffers PS_SSAO_BUFFER m_SSAOData; PS_SSAO_CAMERA_BUFFER m_SSAOCameraData; XMMATRIX m_invProjectionMatrix; ConstBuffer<PS_SSAO_BUFFER> m_SSAOBuffer; ConstBuffer<PS_SSAO_CAMERA_BUFFER> m_SSAOCameraBuffer; ConstBuffer<XMMATRIX> m_SSAOMatrixBuffer; // Texture RenderTexture m_texture; ID3D11RenderTargetView* m_renderTargetNullptr = nullptr; // Shader Shaders m_SSAOPassShaders; // Sampler Microsoft::WRL::ComPtr< ID3D11SamplerState > m_depthNormalSamplerState; Microsoft::WRL::ComPtr< ID3D11SamplerState > m_randomSamplerState; // Dither Texture Microsoft::WRL::ComPtr< ID3D11Texture2D > m_ditherTexture; Microsoft::WRL::ComPtr< ID3D11ShaderResourceView > m_ditherTextureSRV; // Functions void initSSAOTexture(ID3D11Device* device, int width, int height) { std::string name = "SSAO Map0"; strncpy_s(m_texture.name, name.c_str(), name.length()); m_texture.name[name.length()] = '\0'; // Texture D3D11_TEXTURE2D_DESC textureDesc; ZeroMemory(&textureDesc, sizeof(D3D11_TEXTURE2D_DESC)); textureDesc.Width = width; textureDesc.Height = height; textureDesc.MipLevels = 1; textureDesc.ArraySize = 1; textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; textureDesc.SampleDesc.Count = 1; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; HRESULT hr = device->CreateTexture2D(&textureDesc, NULL, &m_texture.rtt); assert(SUCCEEDED(hr) && "Error, render target texture could not be created!"); // Render Rarget View D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc; ZeroMemory(&renderTargetViewDesc, sizeof(D3D11_RENDER_TARGET_VIEW_DESC)); renderTargetViewDesc.Format = textureDesc.Format; renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; renderTargetViewDesc.Texture2D.MipSlice = 0; hr = device->CreateRenderTargetView(m_texture.rtt, &renderTargetViewDesc, &m_texture.rtv); assert(SUCCEEDED(hr) && "Error, render target view could not be created!"); // Shader Resource View D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; ZeroMemory(&srvDesc, sizeof(D3D11_SHADER_RESOURCE_VIEW_DESC)); srvDesc.Format = textureDesc.Format; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = 1; hr = device->CreateShaderResourceView(m_texture.rtt, &srvDesc, &m_texture.srv); assert(SUCCEEDED(hr) && "Error, shader resource view could not be created!"); // Unordered Access View D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc = {}; uavDesc.Format = textureDesc.Format; uavDesc.ViewDimension = D3D11_UAV_DIMENSION::D3D11_UAV_DIMENSION_TEXTURE2D; uavDesc.Texture2D.MipSlice = 0; hr = device->CreateUnorderedAccessView(m_texture.rtt, &uavDesc, &m_texture.uav); assert(SUCCEEDED(hr) && "Error, unordered access view could not be created!"); } void initRandomTexture(ID3D11Device* device) { //HRESULT hr; // Dither Texture int ditherWidth = 4; int ditherHeight = 4; D3D11_TEXTURE2D_DESC texDesc; texDesc.Width = ditherWidth; texDesc.Height = ditherHeight; texDesc.MipLevels = 1; texDesc.ArraySize = 1; texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; texDesc.SampleDesc.Count = 1; texDesc.SampleDesc.Quality = 0; texDesc.Usage = D3D11_USAGE_DEFAULT; texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; texDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; texDesc.MiscFlags = 0; int len = ditherWidth * ditherHeight; std::vector<XMFLOAT4> data(len); std::vector<float> offsets1; std::vector<float> offsets2; for (size_t i = 0; i < len; ++i) { offsets1.push_back((float)i / len); offsets2.push_back((float)i / len - 1); } unsigned seed = (unsigned)std::chrono::system_clock::now().time_since_epoch().count(); std::shuffle(offsets1.begin(), offsets1.end(), std::default_random_engine(seed)); seed = (unsigned)std::chrono::system_clock::now().time_since_epoch().count(); std::shuffle(offsets2.begin(), offsets2.end(), std::default_random_engine(seed)); int i = 0; for (int y = 0; y < ditherHeight; ++y) { for (int x = 0; x < ditherWidth; ++x) { float r = offsets1[i]; float g = offsets2[i]; data[i] = XMFLOAT4(r, g, 1.f, 1.f); ++i; } } D3D11_SUBRESOURCE_DATA subData; subData.pSysMem = data.data(); subData.SysMemPitch = texDesc.Width * sizeof(XMFLOAT4); subData.SysMemSlicePitch = subData.SysMemPitch * texDesc.Height; /*int dimensions = 256; D3D11_TEXTURE2D_DESC texDesc; texDesc.Width = dimensions; texDesc.Height = dimensions; texDesc.MipLevels = 1; texDesc.ArraySize = 1; texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; texDesc.SampleDesc.Count = 1; texDesc.SampleDesc.Quality = 0; texDesc.Usage = D3D11_USAGE_DYNAMIC; texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; texDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; texDesc.MiscFlags = 0; XMVECTOR* randomColors = new XMVECTOR[dimensions * dimensions]; for (int i = 0; i < dimensions; i++) { for (int j = 0; j < dimensions; j++) randomColors[i * dimensions + j] = XMVectorSet(((float)(rand()) / (float)RAND_MAX), ((float)(rand()) / (float)RAND_MAX), ((float)(rand()) / (float)RAND_MAX), ((float)(rand()) / (float)RAND_MAX)); } D3D11_SUBRESOURCE_DATA subData; subData.pSysMem = randomColors; subData.SysMemPitch = texDesc.Width * sizeof(XMVECTOR); subData.SysMemSlicePitch = subData.SysMemPitch * texDesc.Height;*/ //hr = device->CreateTexture2D(&texDesc, &subData, m_ditherTexture.GetAddressOf()); //assert(SUCCEEDED(hr) && "Error, failed to create dither texture!"); D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; srvDesc.Format = texDesc.Format; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = 1; //hr = device->CreateShaderResourceView(m_ditherTexture.Get(), &srvDesc, m_ditherTextureSRV.GetAddressOf()); //assert(SUCCEEDED(hr) && "Error, failed to create dither texture shader resource view!"); } void initSamplerStates(ID3D11Device* device) { D3D11_SAMPLER_DESC samplerStateDesc; samplerStateDesc.Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; samplerStateDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerStateDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerStateDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; samplerStateDesc.MinLOD = (-FLT_MAX); samplerStateDesc.MaxLOD = (FLT_MAX); samplerStateDesc.MipLODBias = 0.0f; samplerStateDesc.MaxAnisotropy = 1; samplerStateDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; samplerStateDesc.BorderColor[0] = 1.f; samplerStateDesc.BorderColor[1] = 1.f; samplerStateDesc.BorderColor[2] = 1.f; samplerStateDesc.BorderColor[3] = 1.f; HRESULT hr = device->CreateSamplerState(&samplerStateDesc, &m_randomSamplerState); assert(SUCCEEDED(hr) && "Error, failed to create depth normal sampler state!"); samplerStateDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER; samplerStateDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER; samplerStateDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER; samplerStateDesc.BorderColor[0] = 1.f; samplerStateDesc.BorderColor[1] = 1.f; samplerStateDesc.BorderColor[2] = 1.f; samplerStateDesc.BorderColor[3] = 1.f; hr = device->CreateSamplerState(&samplerStateDesc, &m_depthNormalSamplerState); assert(SUCCEEDED(hr) && "Error, failed to create random sampler state!"); m_deviceContext->PSSetSamplers(3, 1, m_depthNormalSamplerState.GetAddressOf()); m_deviceContext->PSSetSamplers(4, 1, m_randomSamplerState.GetAddressOf()); } void initSampleDirections() { // 8 cube corners m_SSAOData.sampleDirections[0] = XMFLOAT4(+1.0f, +1.0f, +1.0f, 0.f); m_SSAOData.sampleDirections[1] = XMFLOAT4(-1.0f, -1.0f, -1.0f, 0.f); m_SSAOData.sampleDirections[2] = XMFLOAT4(-1.0f, +1.0f, +1.0f, 0.f); m_SSAOData.sampleDirections[3] = XMFLOAT4(+1.0f, -1.0f, -1.0f, 0.f); m_SSAOData.sampleDirections[4] = XMFLOAT4(+1.0f, +1.0f, -1.0f, 0.f); m_SSAOData.sampleDirections[5] = XMFLOAT4(-1.0f, -1.0f, +1.0f, 0.f); m_SSAOData.sampleDirections[6] = XMFLOAT4(-1.0f, +1.0f, -1.0f, 0.f); m_SSAOData.sampleDirections[7] = XMFLOAT4(+1.0f, -1.0f, +1.0f, 0.f); // 6 centers of cube faces m_SSAOData.sampleDirections[8] = XMFLOAT4(-1.0f, 0.0f, 0.0f, 0.f); m_SSAOData.sampleDirections[9] = XMFLOAT4(+1.0f, 0.0f, 0.0f, 0.f); m_SSAOData.sampleDirections[10] = XMFLOAT4(0.0f, -1.0f, 0.0f, 0.f); m_SSAOData.sampleDirections[11] = XMFLOAT4(0.0f, +1.0f, 0.0f, 0.f); m_SSAOData.sampleDirections[12] = XMFLOAT4(0.0f, 0.0f, -1.0f, 0.f); m_SSAOData.sampleDirections[13] = XMFLOAT4(0.0f, 0.0f, +1.0f, 0.f); for (int i = 0; i < SSAO_SAMPLE_DIRECTIONS; ++i) { float s = pMath::frand(0.25f, 1.0f); XMVECTOR vec = XMVector3Normalize(XMLoadFloat4(&m_SSAOData.sampleDirections[i])); vec *= s; XMStoreFloat4(&m_SSAOData.sampleDirections[i], vec); } } public: SSAOInstance() {} ~SSAOInstance() { if (m_texture.rtt) m_texture.rtt->Release(); m_texture.rtt = nullptr; if (m_texture.rtv) m_texture.rtv->Release(); m_texture.rtv = nullptr; if (m_texture.srv) m_texture.srv->Release(); m_texture.srv = nullptr; if (m_texture.uav) m_texture.uav->Release(); m_texture.uav = nullptr; } void initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, int width, int height) { // DeviceConstext m_deviceContext = deviceContext; // Shader ShaderFiles shaderFiles; shaderFiles.vs = L"Shader Files\\SsaoVS.hlsl"; shaderFiles.ps = L"Shader Files\\SsaoPS.hlsl"; m_SSAOPassShaders.initialize(device, deviceContext, shaderFiles, LayoutType::POS_TEX); // SSAO Texture initSSAOTexture(device, width, height); // Random Texture initRandomTexture(device); // Sampler State Setup initSamplerStates(device); // Constant Buffers // - SSAO Buffer Sample Directions initSampleDirections(); // - Dither Scale for Random Texture m_SSAOData.ditherScale = XMFLOAT2((float)width / 4, (float)height / 4); m_SSAOBuffer.init(device, deviceContext); m_SSAOBuffer.m_data = m_SSAOData; m_SSAOBuffer.upd(); // - SSAO Matrix Buffer m_SSAOMatrixBuffer.init(device, deviceContext); // - SSAO Camera Buffer m_SSAOCameraBuffer.init(device, deviceContext); } RenderTexture& getAORenderTexture() { return m_texture; } void updateProjMatrix(XMMATRIX projectionMatrix) { m_invProjectionMatrix = XMMatrixTranspose(XMMatrixInverse(nullptr, projectionMatrix)); m_SSAOMatrixBuffer.m_data = m_invProjectionMatrix; m_SSAOMatrixBuffer.upd(); XMMATRIX T( 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.0f, 1.0f); XMMATRIX P = projectionMatrix; XMMATRIX pt = XMMatrixMultiply(P, T); m_SSAOCameraData.viewToTexMatrix = XMMatrixTranspose(pt); m_SSAOCameraData.projectionMatrix = XMMatrixTranspose(projectionMatrix); } void updateViewMatrix(XMMATRIX viewMatrix) { m_SSAOCameraData.viewMatrix = XMMatrixTranspose(viewMatrix); m_SSAOCameraBuffer.m_data = m_SSAOCameraData; m_SSAOCameraBuffer.upd(); } void updateShaders() { m_SSAOPassShaders.reloadShaders(); } void render() { // Set Render Target m_deviceContext->OMSetRenderTargets(1, &m_texture.rtv, nullptr); // Shader m_SSAOPassShaders.setShaders(); // Constant Buffers m_deviceContext->VSSetConstantBuffers(0, 1, m_SSAOMatrixBuffer.GetAddressOf()); m_deviceContext->PSSetConstantBuffers(0, 1, m_SSAOCameraBuffer.GetAddressOf()); m_deviceContext->PSSetConstantBuffers(1, 1, m_SSAOBuffer.GetAddressOf()); // Dither Texture //m_deviceContext->PSSetShaderResources(2, 1, m_ditherTextureSRV.GetAddressOf()); ID3D11ShaderResourceView* srv = nullptr; m_deviceContext->PSSetShaderResources(2, 1, &srv); // Draw Fullscreen Quad m_deviceContext->Draw(4, 0); // Reset m_deviceContext->OMSetRenderTargets(1, &m_renderTargetNullptr, nullptr); } }; #endif // !SSAOINSTANCE_H
/** \file movingAverage.hpp \author UnBeatables \date LARC2018 \name movingAverage */ #pragma once #include <iostream> #include <vector> class movingAverage { public: /** \brief Class constructor. */ movingAverage(); /** \brief This function determines newAverage. \details newAverage = oldAverage +(newData - lastData)/(50). \param oldAverage float. \param newData float. \param lastData float. \param size float. \return Transition state. */ float mean(float oldAverage, float newData, float lastData, float size); /** \brief This function determines newAverage \details newAverage = (newData - oldAverage)*(2/(size+1))+oldAverage. \param oldAverage float. \param newData float. \param lastData float. \param size float. \return newAverage. */ float expoAverage(float oldAverage, float newData, float lastData, float size); /** \brief This function determines if newAverage is newData or oldAverage. \details If newData is bigger than 1, newAverage is equal to oldAverage, else it is equal to newData. \param oldAverage float. \param newData float. \return newAverage. */ float delData(float oldAverage, float newData); /** \brief This function determines the arithmetic mean between the ten first elements of a vector. \param data vector of floats. \return arithmetic mean between the ten first elements of the vector. */ float medianFilter( std::vector<float> data); private: };
#ifndef PSEUDOGENOMEBASE_H_INCLUDED #define PSEUDOGENOMEBASE_H_INCLUDED #include "../readsset/ReadsSetBase.h" #include "../readsset/DefaultReadsSet.h" using namespace PgSAReadsSet; namespace PgSAIndex { class PseudoGenomeBase: public ReadsSetBase { protected: const uint_pg_len_max length; PseudoGenomeBase(uint_pg_len_max length, ReadsSetProperties* properties) : ReadsSetBase(properties), length(length) { }; PseudoGenomeBase(uint_pg_len_max length, std::istream& src) : ReadsSetBase(src), length(length) { }; public: virtual ~PseudoGenomeBase() { }; bool isPGLengthStd() { return PgSAIndex::isPGLengthStd(length); }; bool isPGLengthMax() { return PgSAIndex::isPGLengthMax(length); }; const uint_pg_len_max getPseudoGenomeLength() { return this->length; }; virtual string getTypeID() = 0; virtual void write(std::ostream& dest) = 0; virtual bool validateUsing(DefaultReadsSet* readsSet) { fprintf(stderr, "Error: validation is not implemented.\n"); return false; } virtual void buildRepetitiveReadsFilter() { throw(errno); }; virtual const string getPseudoGenomeVirtual() = 0; const static string PSEUDOGENOME_FILE_SUFFIX; }; class PseudoGenomeHeader { private: string type; bool constantReadLength = true; uint_read_len_max maxReadLength; uint_reads_cnt_max readsCount; uint_pg_len_max pgLength; public: static const string PSEUDOGENOME_HEADER; PseudoGenomeHeader() {} PseudoGenomeHeader(PseudoGenomeBase* base) { this->type = base->getTypeID(); this->constantReadLength = base->getReadsSetProperties()->constantReadLength; this->maxReadLength = base->getReadsSetProperties()->maxReadLength; this->readsCount = base->getReadsSetProperties()->readsCount; this->pgLength = base->getPseudoGenomeLength(); } PseudoGenomeHeader(std::istream& src) { string line; src >> line; if (line != PSEUDOGENOME_HEADER) cout << "WARNING: wrong PSEUDOGENOME_HEADER"; src >> type; src >> constantReadLength; src >> maxReadLength; src >> readsCount; src >> pgLength; src.get(); } ~PseudoGenomeHeader() { }; void write(std::ostream& dest) { dest << PSEUDOGENOME_HEADER << "\n"; dest << type << "\n"; dest << constantReadLength << "\n"; dest << maxReadLength << "\n"; dest << readsCount << "\n"; dest << pgLength << "\n"; } string getType() { return this->type; }; bool isReadLengthConstant() { return constantReadLength; }; bool isReadLengthMin() { return PgSAReadsSet::isReadLengthMin(maxReadLength); }; bool isReadLengthStd() { return PgSAReadsSet::isReadLengthStd(maxReadLength); }; bool isReadsCountStd() { return PgSAReadsSet::isReadsCountStd(readsCount); }; bool isReadsCountMax() { return PgSAReadsSet::isReadsCountMax(readsCount); }; bool isPGLengthStd() { return PgSAIndex::isPGLengthStd(pgLength); }; bool isPGLengthMax() { return PgSAIndex::isPGLengthMax(pgLength); }; uint_reads_cnt_max getReadsCount() const { return readsCount; } void setReadsCount(uint_reads_cnt_max readsCount) { PseudoGenomeHeader::readsCount = readsCount; } void setPseudoGenomeLength(uint_pg_len_max pgLength) { PseudoGenomeHeader::pgLength = pgLength; } uint_read_len_max getMaxReadLength() const { return maxReadLength; }; uint_pg_len_max getPseudoGenomeLength() { return this->pgLength; }; ReadsSetProperties* generateReadsSetProperties() { ReadsSetProperties* rsProp = new ReadsSetProperties(); rsProp->constantReadLength = this->constantReadLength; rsProp->minReadLength = this->constantReadLength?this->maxReadLength:1; rsProp->maxReadLength = this->maxReadLength; rsProp->allReadsLength = this->constantReadLength?(size_t) this->readsCount*this->maxReadLength:-1; rsProp->readsCount = this->readsCount; return rsProp; } }; } #endif // PSEUDOGENOMEBASE_H_INCLUDED
#include <iostream> #include <fstream> void checkForName(std::string str) { std::ifstream file("diary.txt"); // pass file name as argment std::string linebuffer; bool isName = false; while (file && std::getline(file, linebuffer)) { int i = 0; while (' ' != linebuffer[i]) { i++; } if (str == linebuffer.substr(0, (i))) { std::cout << "Met " << linebuffer << "\n"; isName = true; } else if (str == linebuffer.substr(i + 1, linebuffer.length())) { std::cout << "Met " << linebuffer << "\n"; isName = true; } } if (false == isName) { std::cout << "No such name or date in diary."; } } void inputStr(std::string & str) { //I need '&' here so that I can pass 'str' by reference. std::cout << "Input a name or date please: "; getline(std::cin, str); } int main() { std::string str; inputStr(str); checkForName(str); return 0; }
#include <CommonHeader.h> #include <iostream> #include <string> #include <thread> #pragma comment(lib, "kernelhelper.lib") void Usage(const char * p) { printf("Usage:\n\t%s from_file [from_db]\n" "\tExamples:[from_db=telephone-in.db]\n" "\t%s 100.txt my.db\n" "\t%s 100.txt\n", p, p, p ); } int main(int argc, char ** argv) { STRINGVECTOR sv; CSqlite3DB sqldb; size_t stidx = 0; CSqlite3Query query; std::string strResult; std::string strData; std::string strFrom; std::string strINFileName = ""; std::string strOutFileName = ""; std::string strDBFileName = ""; std::string strDBCommand = "CREATE TABLE IF NOT EXISTS `urls`(url TEXT NOT NULL PRIMARY KEY, type INTEGER NOT NULL DEFAULT 0, comment TEXT, update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP);" // type = 0,未采集过;type = 1,已采集过 "CREATE TABLE IF NOT EXISTS `suburls`(url TEXT NOT NULL PRIMARY KEY, from_url TEXT NOT NULL, type INTEGER NOT NULL DEFAULT 0, comment TEXT, update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP);" // type = 0,未采集过;type = 1,已采集过 "CREATE TABLE IF NOT EXISTS `phone`(phone INTEGER NOT NULL PRIMARY KEY, from_url TEXT NOT NULL, comment TEXT, update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP);"; std::string strDBErrorText = ""; printf("%s\n", sqldb.SQLiteVersion()); switch (argc) { case 2: strINFileName = argv[1]; strOutFileName = strINFileName + ".csv"; strDBFileName = "telephone-in.db"; break; case 3: strINFileName = argv[1]; strOutFileName = strINFileName + ".csv"; strDBFileName = argv[2]; break; default: Usage(argv[0]); return 0; break; } try { sqldb.open(strDBFileName.c_str()); sqldb.execDML(PPSHUAI::Convert::ANSI2UTF8(strDBCommand).c_str()); } catch (CSqlite3Exception e) { ;//no op } try { //strDBCommand = "SELECT p.phone,s.from_url FROM phone p,suburls s WHERE p.from_url==s.url GROUP BY phone ORDER BY p.update_time;"; PPSHUAI::String::file_reader(strData, strINFileName); PPSHUAI::String::string_split_to_vector(sv, strData, "\r\n"); strData = ""; for (stidx = 0; stidx < sv.size(); stidx++) { if (sv.at(stidx).at(0)) { strDBCommand = "SELECT p.phone,s.from_url FROM phone p,suburls s WHERE p.from_url==s.url AND p.phone=" + sv.at(stidx) + " GROUP BY phone ORDER BY p.update_time;"; query = sqldb.execQuery(PPSHUAI::Convert::ANSI2UTF8(strDBCommand).c_str()); if (!query.eof()) { strFrom = query.getStringField(1); PPSHUAI::String::string_regex_replace_all(strResult, strFrom, "", "(.*?//.*?\\.)"); if (strFrom.find("/") != std::string::npos) { strFrom = strFrom.substr(0, strFrom.find("/")); } strData += sv.at(stidx) + "," + strFrom + "\r\n"; } } } sv.clear(); PPSHUAI::String::string_split_to_vector(sv, strData, "\r\n"); printf("Output %ld resources!\n", sv.size()); if (strData.size()) { PPSHUAI::String::file_writer(strData, strOutFileName); printf("Write to file ok!\n"); } } catch (CSqlite3Exception e) { strDBErrorText = e.errorMessage(); printf("%s\n", strDBErrorText.c_str()); } try { sqldb.close(); } catch (CSqlite3Exception e) { ;//no op } return 0; }
// Created on: 1992-11-17 // Created by: Christian CAILLET // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IFSelect_SelectBase_HeaderFile #define _IFSelect_SelectBase_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <IFSelect_Selection.hxx> class IFSelect_SelectionIterator; class IFSelect_SelectBase; DEFINE_STANDARD_HANDLE(IFSelect_SelectBase, IFSelect_Selection) //! SelectBase works directly from an InterfaceModel : it is the //! first base for other Selections. class IFSelect_SelectBase : public IFSelect_Selection { public: //! Puts in an Iterator the Selections from which "me" depends //! This list is empty for all SelectBase type Selections Standard_EXPORT void FillIterator (IFSelect_SelectionIterator& iter) const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(IFSelect_SelectBase,IFSelect_Selection) protected: private: }; #endif // _IFSelect_SelectBase_HeaderFile
#include "movie.h" using namespace std; Movie::Movie(const std::string category, const std::string name, double price, int qty, std::string genre, std::string rating) : Product (category, name, price, qty) { genre_ = convToLower(genre); rating_ = rating; } Movie::~Movie() { } std::set<std::string> Movie::keywords() const { /* Valid keywords are: * product name * genre */ std::set<std::string> nameKeywords = parseStringToWords(name_); std::set<std::string> movieKeywords = nameKeywords; movieKeywords.insert(genre_); return movieKeywords; } bool Movie::isMatch(std::vector<std::string>& searchTerms) const { return false; } std::string Movie::displayString() const { return name_ + "\n" + "Genre: " + genre_ + " " + "Rating: " + rating_; } void Movie::dump(std::ostream& os) const { Product::dump(os); os << genre_ << "\n" << rating_ << "\n"; } std::string Movie::getGenre() const { return genre_; } std::string Movie::getRating() const { return rating_; }
#include <iostream> int INF=999999; using namespace std; struct edge{ int u; int v; int value; edge *next; }; edge *start=NULL; void add(int u,int v,int value) { edge *e=new edge; e->u=u; e->v=v; e->value=value; e->next=NULL; edge* q=new edge; q->next=start; edge* p=q; while(p->next!=NULL) { if(p->next->value>=value) break; p=p->next; } e->next=p->next; p->next=e; start=q->next; delete q; } void wypisz() { cout<<"u->v, value\n"; for(edge*e=start;e!=NULL;e=e->next) { cout<<e->u<<"->"<<e->v<<", "<<e->value<<endl; } } struct vertex{ int pred; double dist; }; vertex* BF(edge *E,int V,int S) { vertex *output=new vertex[10]; for(int i=0;i<V;i++) { output[i].pred=-1; output[i].dist=INF; } output[0].pred=0; output[0].dist=0; for(int i=0;i<V;i++) { for(edge *e=E;e!=NULL;e=e->next) { if(output[e->v].dist>output[e->u].dist+e->value) { output[e->v].dist=output[e->u].dist+e->value; output[e->v].pred=e->u; } } } for(edge*e=E;e!=NULL;e=e->next) { if(output[e->v].dist>output[e->u].dist+e->value) { delete[] output; return NULL; } } return output; } int main() { add(0,1,5); add(1,4,9); add(1,3,3); add(2,0,3); add(2,1,-4); add(3,4,3); add(3,5,2); add(4,2,-1); add(4,5,-5); add(5,0,9); add(5,2,8); wypisz(); vertex *output=BF(start,6,0); for(int i=0;i<6;i++) { cout<<output[i].dist<<" "; } cout<<endl; for(int i=0;i<6;i++) { cout<<output[i].pred<<" "; } cout<<endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef FONTDB_H #define FONTDB_H #include "modules/util/str.h" #include "modules/util/OpHashTable.h" #include "modules/windowcommander/WritingSystem.h" class OpFontManager; /** Holds information about a font in the system. Given this information, you can get a clue to what font you should instantiate. An instantiated font is represented by an OpFont object. //rg move part of the implementation of this to "platform layer". */ class OpFontInfo { private: OpFontInfo(const OpFontInfo& other); // Not implemented, to prevent accidential copying OpFontInfo& operator=(const OpFontInfo& other); // Not implemented, to prevent accidential copying public: enum FontType { PLATFORM = 0, PLATFORM_WEBFONT, PLATFORM_LOCAL_WEBFONT, SVG_WEBFONT }; #define NUM_CODEPAGES_DEFINED 6 /** Constructs a new OpFontInfo object. */ OpFontInfo() : face(NULL) , has_weight(0) , packed_init(0) , font_number(0) , m_webfont(0) { parsed_font_size = -1; blocks_available[0] = 0; blocks_available[1] = 0; blocks_available[2] = 0; blocks_available[3] = 0; int i; for (i = 0; i < (int)WritingSystem::NumScripts; i++) { m_scripts[i] = FALSE; m_script_preference[i] = 0; } #ifdef _GLYPHTESTING_SUPPORT_ m_glyphtab = NULL; #endif }; /** Frees all memory used by this object. */ ~OpFontInfo() { OP_DELETEA(face); #ifdef _GLYPHTESTING_SUPPORT_ if(m_glyphtab) OP_DELETEA(m_glyphtab); #endif } enum CodePage { OP_DEFAULT_CODEPAGE = 0, OP_SIMPLIFIED_CHINESE_CODEPAGE, OP_TRADITIONAL_CHINESE_CODEPAGE, OP_JAPANESE_CODEPAGE, OP_KOREAN_CODEPAGE, OP_CYRILLIC_CODEPAGE }; /** @return the name of the font */ inline const uni_char* GetFace() const { return face; }; /** @return a unique number wich can be used to create the font */ inline UINT32 GetFontNumber() const { return font_number; }; /** @param weight the weight (0-9), where 4 is Normal, and 7 Bold. @return wheter the font supports the specified weight or not (0-9) */ BOOL HasWeight(UINT8 weight); #ifdef _GLYPHTESTING_SUPPORT_ /** @return whether the font supports testing specified character glyph mappings */ inline BOOL HasGlyphTable(int block) { UpdateGlyphTableIfNeeded(); return (m_glyphtab != NULL) && (block != 57);}; /** Check if the font has glyph support for a unicode character. NB! Currently we will only check for single 16-bits unicode characters. At a later stage we may have to check for longer characters, for sequences and ligaturs. @param uc unicode character @return whether the font supports the specified characters */ BOOL HasGlyph(const UnicodePoint uc); /** @param uc unicode character supported by the font @return OK if the setting worked */ OP_STATUS SetGlyph(const UnicodePoint uc); /** @param uc unicode character not supported by the font @return OK if the clearing worked */ OP_STATUS ClearGlyph(const UnicodePoint uc); #endif // _GLYPHTESTING_SUPPORT_ /** Merge the glyphtable and blocks_available from another font info into the current one. Used for SVG fonts when an font-face reference another external font-face for additional glyphs, and that external font-face is loaded later. @param other The font info that should be merged @return OK if the merging worked */ OP_STATUS MergeFontInfo(const OpFontInfo& other); /** @param blocknr the unicode block we wonder about @return whether the font supports the specified block */ inline BOOL HasBlock(INT blocknr) { #ifdef _GLYPHTESTING_SUPPORT_ UpdateGlyphTableIfNeeded(); #endif // _GLYPHTESTING_SUPPORT_ return 0 != ((blocks_available[(blocknr & 0x60) >> 5] >> (blocknr & 0x1F)) & 0x1); }; /** @return whether the font is monospace */ inline BOOL Monospace() const { return packed.monospace; }; /** @return whether the font contains italic glyphs */ inline BOOL HasItalic() const { return packed.italic; }; /** @return whether the font contains/can create oblique (slanted) glyphs */ inline BOOL HasOblique() const { return packed.oblique; }; /** @return whether the font contains normal glyphs */ inline BOOL HasNormal() const { return packed.normal; }; /** @return whether the font contains small caps glyphs */ inline BOOL Smallcaps() const { return packed.smallcaps; }; enum FontSerifs { UnknownSerifs=0, WithSerifs, WithoutSerifs }; /** @return wich type of serifs the font has */ inline FontSerifs GetSerifs() const { return (FontSerifs)packed.serifs; }; /** @return if the font is vertical or not (most common in the western world) */ inline BOOL Vertical() const { return packed.vertical; }; /** @return if the font supports the specified codepage or not */ inline BOOL HasScript(const WritingSystem::Script script) const { return m_scripts[script]; }; ///////// setters come here. nothing to see here, folks, unless you're hacking the fontmanager. ///////// /** Sets the name of the font. This method is for OpFontManager implementations ONLY! */ OP_STATUS SetFace(const OpStringC& aFace) { return UniSetStr(face,aFace.CStr()); } void SetFaceL(const OpStringC& aFace) { LEAVE_IF_ERROR(UniSetStr(face,aFace.CStr())); } /** Sets the (unique!) number of the font. This method is for OpFontManager implementations ONLY! */ inline void SetFontNumber(UINT32 font_number) { this->font_number=font_number; }; /** Sets that the font supports a specific weight or not. This method is for OpFontManager implementations ONLY! @param weight the weight (0-9), where 4 is Normal, and 7 Bold. @param val whether we supports the weight or not */ inline void SetWeight(UINT8 weight, UINT32 val) { OP_ASSERT(weight <= 9); has_weight += ((val << weight) - (has_weight & (0x1 << weight))); has_weight += ((1 << (weight + 10)) - (has_weight & (0x1 << (weight + 10)))); }; /** Sets that the font supports the specified page or not. This method is for OpFontManager implementations ONLY! @param pagennr the page @param val whether we supports the page or not */ inline void SetBlock(INT blocknr, UINT32 val) { // The block info has been optimized and is using 4 UINT32's => 128 bits. // This means 1/32 as much memory is used for the block info. // With 50 fonts the gain is about 24 kb. int array_index = (blocknr & 0x60) >> 5; int bit = (blocknr & 0x1F); int newvalue = val << bit; int oldvalue = blocks_available[array_index] & (0x1 << bit); blocks_available[array_index] += (newvalue - oldvalue); }; inline void SetDirectBlock( UINT32 lower, UINT32 upper ) { blocks_available[0] = lower; blocks_available[1] = upper; } /** Setter for the monospace attribute of the font. This method is for OpFontManager implementations ONLY! @param monospace monospace or not */ inline void SetMonospace(BOOL monospace) { this->packed.monospace=monospace; }; /** Sets whether the font supports italic. This method is for OpFontManager implementations ONLY! @param italic supports italic or not */ inline void SetItalic(BOOL italic) { this->packed.italic=italic; }; /** Sets whether the font supports oblique or not. This method is for OpFontManager implementations ONLY! @param oblique oblique or not */ inline void SetOblique(BOOL oblique) { this->packed.oblique=oblique; }; /** Sets whether the font supports normal glyphs or not. This method is for OpFontManager implementations ONLY! @param normal normal or not */ inline void SetNormal(BOOL normal) { this->packed.normal=normal; }; /** Sets whether the font supports small caps or not. This method is for OpFontManager implementations ONLY! @param smallcaps has smallcaps or not */ inline void SetSmallcaps(BOOL smallcaps) { this->packed.smallcaps=smallcaps; }; /** Sets wich type of serifs the font has. This method is for OpFontManager implementations ONLY! */ inline void SetSerifs(FontSerifs serifs) { this->packed.serifs=serifs; }; /** Sets if the font is vertical or not. This method is for OpFontManager implementations ONLY! */ inline void SetVertical(BOOL vertical) { this->packed.vertical = vertical; }; /** Sets that the font supports the given script. This method is for OpFontManager implementations ONLY! */ inline void SetScript(const WritingSystem::Script script, BOOL state = TRUE) { m_scripts[script] = state; } /** Sets that the font should be preferred for the script. @param script the prefered script @param point the preference of the font for this script */ inline void SetScriptPreference(const WritingSystem::Script script, char point) { m_script_preference[script] = point; } /** @param script the prefered script @return the preference of the font for this script */ inline char GetScriptPreference(const WritingSystem::Script script) const { return m_script_preference[script]; } /** Convert a script system to which preferred script this corresponds to @param script the script */ static CodePage CodePageFromScript(WritingSystem::Script script); // temporarily introduced while not all modules are multistyle-aware - don't use! static WritingSystem::Script DEPRECATED(ScriptFromCodePage(const OpFontInfo::CodePage codepage)); /** sets all scripts represented in codepages as supported (doesn't set not represented as unsupported). if match_score is non-zero, sets score for all represented scripts. */ void SetScriptsFromOS2CodePageRanges(const UINT32* codepages, const UINT8 match_score = 0); static WritingSystem::Script ScriptFromOS2CodePageBit(const UINT8 bit); inline void SetWebFont(UINTPTR webfont) { m_webfont = webfont; } UINTPTR GetWebFont() const { return m_webfont; } void SetFontType(OpFontInfo::FontType type) { packed.font_type = type; } OpFontInfo::FontType Type() { return (OpFontInfo::FontType)packed.font_type; } void SetParsedFontSize(int size) { parsed_font_size = size; } int ParsedFontSize() { return parsed_font_size; } void SetHasLigatures(BOOL has_ligatures) { packed.has_ligatures = has_ligatures? 1 : 0; } BOOL HasLigatures() { return packed.has_ligatures; } #ifdef _GLYPHTESTING_SUPPORT_ /** Semi-private method for updating the glyph table, used by the font switching code (and the WebFontManager) */ void UpdateGlyphTableIfNeeded(); void InvalidateGlyphTable(); #endif // _GLYPHTESTING_SUPPORT_ private: uni_char* face; ///< holds the font face (the name of the font) UINT32 blocks_available[4];///< What unicode blocks that the font contains (128 bits) /** Which weights the font supports. It is using 20 bits. Bit 0-9 to tell if a weight is available. But 10-19 to tell if it is set or if it has to ask OpFontManager. */ UINT32 has_weight; union { struct { unsigned int monospace:1; ///< whether the font is monospace or not unsigned int italic:1; ///< whether the font contains italic glyphs unsigned int oblique:1; ///< whether the font supports oblique glyphs unsigned int normal:1; ///< whether the font contains normal glyphs unsigned int smallcaps:1; ///< whether the font contains small caps unsigned int serifs:2; ///< whether the font has serifs or not (or unknown) unsigned int vertical:1; ///< if the font is vertical or not. unsigned int has_scanned_for_glyphs:1; unsigned int font_type:2; ///< the type of font unsigned int has_ligatures: 1; ///< whether the font contains ligatures (needed for acid3 and svgfonts at the moment, to workaround fontswitching issues) } packed; /** 12 bits used **/ unsigned int packed_init; }; int parsed_font_size; ///< used for svg fonts only, contains the parsed font-size UINT32 font_number; ///< a unique number wich can be used to create the font. BOOL m_scripts[WritingSystem::NumScripts]; ///< used to store what scripts the font supports char m_script_preference[WritingSystem::NumScripts]; ///< used to store the preference of a font for a certain script #ifdef _GLYPHTESTING_SUPPORT_ OP_STATUS CreateGlyphTable(); void ClearGlyphTable(); // binary table indexed by UnicodePoint (BMP, SMP and SIP only) represented as UINT32 array indexed by 13 bits UINT32 * m_glyphtab; #endif // _GLYPHTESTING_SUPPORT_ UINTPTR m_webfont; ///< the font handle issued by the fontmanager. Note: it is volatile (there can be more than one webfont face per OpFontInfo), only to be used for UpdateGlyphMask }; /** OpFontDatabase represents a database over all of the fonts that are available in the system. After it is instantiated, you can ask for information on all the fonts. Such information is held by OpFontInfo. This is needed to be able to pass the correct name to OpFontManager::CreateFont(...). */ class OpFontDatabase { public: OpFontDatabase(); ~OpFontDatabase(); /** Construct the object based on the fontmanager parameter. Code moved from the constructor since it allocates memory. */ OP_STATUS Construct(OpFontManager* fontmanager); /** Get info about a certain font @param fontnr the font that you want info about @return info about the requested font */ OpFontInfo* GetFontInfo(UINT32 fontnr); UINT32 GetNumFonts(); UINT32 GetNumSystemFonts(); UINT32 AllocateFontNumber(); OP_STATUS AddFontInfo(OpFontInfo* fi); OP_STATUS RemoveFontInfo(OpFontInfo* fi); OP_STATUS DeleteFontInfo(OpFontInfo* fi, BOOL release_fontnumber = TRUE); OpHashIterator* GetIterator(){return m_font_list.GetIterator();} void ReleaseFontNumber(UINT32 fontnumber); private: OpAutoINT32HashTable<OpFontInfo> m_font_list; OpINT32Vector m_webfont_list; UINT32 numSystemFonts; // The number of system fonts in the system, not counting svg and web fonts #ifdef DISPLAY_FONT_NAME_OVERRIDE BOOL LoadFontOverrideFile(PrefsFile* prefs_obj); #endif }; #endif // FONTDB_H
/* * FirebaseJson, version 3.0.7 * * The Easiest Arduino library to parse, create and edit JSON object using a relative path. * * Created June 14, 2023 * * Features * - Using path to access node element in search style e.g. json.get(result,"a/b/c") * - Serializing to writable objects e.g. String, C/C++ string, Clients (WiFi, Ethernet, and GSM), File and Hardware Serial. * - Deserializing from const char, char array, string literal and stream e.g. Clients (WiFi, Ethernet, and GSM), File and * Hardware Serial. * - Use managed class, FirebaseJsonData to keep the deserialized result, which can be casted to any primitive data types. * * * The MIT License (MIT) * Copyright (c) 2023 K. Suwatchai (Mobizt) * Copyright (c) 2009-2017 Dave Gamble and cJSON contributors * * * Permission is hereby granted, free of charge, to any person returning 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. */ #ifndef FirebaseJson_CPP #define FirebaseJson_CPP #include "FirebaseJson.h" FirebaseJsonBase::FirebaseJsonBase() { MB_JSON_InitHooks(&MB_JSON_hooks); } FirebaseJsonBase::~FirebaseJsonBase() { mClear(); } FirebaseJsonBase &FirebaseJsonBase::mClear() { mIteratorEnd(); if (root != NULL) MB_JSON_Delete(root); root = NULL; buf.clear(); errorPos = -1; return *this; } void FirebaseJsonBase::mCopy(FirebaseJsonBase &other) { mClear(); this->root = MB_JSON_Duplicate(other.root, true); this->doubleDigits = other.doubleDigits; this->floatDigits = other.floatDigits; this->httpCode = other.httpCode; this->serData = other.serData; this->root_type = other.root_type; this->iterator_data = other.iterator_data; this->buf = other.buf; } bool FirebaseJsonBase::setRaw(const char *raw) { mClear(); if (raw) { size_t i = 0; while (i < strlen(raw) && raw[i] == ' ') { i++; } if (raw[i] == '{' || raw[i] == '[') { this->root_type = (raw[i] == '{') ? Root_Type_JSON : Root_Type_JSONArray; root = parse(raw); } else { this->root_type = Root_Type_Raw; root = MB_JSON_CreateRaw(raw); } } return root != NULL; } MB_JSON *FirebaseJsonBase::parse(const char *raw) { const char *s = NULL; MB_JSON *e = MB_JSON_ParseWithOpts(raw, &s, 1); errorPos = (s - raw != (int)strlen(raw)) ? s - raw : -1; return e; } void FirebaseJsonBase::prepareRoot() { if (root == NULL) { if (root_type == Root_Type_JSONArray) root = MB_JSON_CreateArray(); else root = MB_JSON_CreateObject(); } } void FirebaseJsonBase::searchElements(MB_VECTOR<MB_String> &keys, MB_JSON *parent, struct search_result_t &r) { MB_JSON *e = parent; for (size_t i = 0; i < keys.size(); i++) { r.status = key_status_not_existed; e = getElement(parent, keys[i].c_str(), r); r.stopIndex = i; if (r.status != key_status_existed) { if (i == 0) r.parent = parent; break; } r.parent = parent; r.foundIndex = i; parent = e; } } MB_JSON *FirebaseJsonBase::getElement(MB_JSON *parent, const char *key, struct search_result_t &r) { MB_JSON *e = NULL; bool isArrKey = isArrayKey(key); int index = isArrKey ? getArrIndex(key) : -1; if ((isArray(parent) && !isArrKey) || (isObject(parent) && isArrKey)) r.status = key_status_mistype; else if (isArray(parent) && isArrKey) { e = MB_JSON_GetArrayItem(parent, index); if (e == NULL) r.status = key_status_out_of_range; } else if (isObject(parent) && !isArrKey) { e = MB_JSON_GetObjectItemCaseSensitive(parent, key); if (e == NULL) r.status = key_status_not_existed; } if (e == NULL) return parent; r.status = key_status_existed; return e; } void FirebaseJsonBase::mAdd(MB_VECTOR<MB_String> keys, MB_JSON **parent, int beginIndex, MB_JSON *value) { MB_JSON *m_parent = *parent; for (size_t i = beginIndex; i < keys.size(); i++) { bool isArrKey = isArrayKey(keys[i].c_str()); int index = isArrKey ? getArrIndex(keys[i].c_str()) : -1; MB_JSON *e = (i < keys.size() - 1) ? (isArrayKey(keys[i + 1].c_str()) ? MB_JSON_CreateArray() : MB_JSON_CreateObject()) : value; if (isArray(m_parent)) { if (isArrKey) m_parent = addArray(m_parent, e, index + 1); else MB_JSON_AddItemToArray(m_parent, e); } else { if (isArrKey) { if ((int)i == beginIndex) { m_parent = MB_JSON_CreateArray(); MB_JSON_Delete(*parent); *parent = m_parent; } m_parent = addArray(m_parent, e, index + 1); } else { MB_JSON_AddItemToObject(m_parent, keys[i].c_str(), e); m_parent = e; } } } } void FirebaseJsonBase::makeList(const MB_String &str, MB_VECTOR<MB_String> &keys, char delim) { clearList(keys); size_t current, previous = 0; current = str.find(delim, previous); MB_String s; while (current != MB_String::npos) { pushLish(str.substr(previous, current - previous), keys); previous = current + 1; current = str.find(delim, previous); } pushLish(str.substr(previous, current - previous), keys); } void FirebaseJsonBase::pushLish(const MB_String &str, MB_VECTOR<MB_String> &keys) { MB_String s = str; s.trim(); if (s.length() > 0) keys.push_back(s); } void FirebaseJsonBase::clearList(MB_VECTOR<MB_String> &keys) { size_t len = keys.size(); for (size_t i = 0; i < len; i++) keys[i].clear(); for (int i = len - 1; i >= 0; i--) keys.erase(keys.begin() + i); keys.clear(); #if defined(MB_USE_STD_VECTOR) MB_VECTOR<MB_String>().swap(keys); #endif } bool FirebaseJsonBase::isArray(MB_JSON *e) { return MB_JSON_IsArray(e); } bool FirebaseJsonBase::isObject(MB_JSON *e) { return MB_JSON_IsObject(e); } MB_JSON *FirebaseJsonBase::addArray(MB_JSON *parent, MB_JSON *e, size_t size) { for (size_t i = 0; i < size - 1; i++) MB_JSON_AddItemToArray(parent, MB_JSON_CreateNull()); MB_JSON_AddItemToArray(parent, e); return e; } void FirebaseJsonBase::appendArray(MB_VECTOR<MB_String> &keys, struct search_result_t &r, MB_JSON *parent, MB_JSON *value) { MB_JSON *item = NULL; int index = getArrIndex(keys[r.stopIndex].c_str()); if (r.foundIndex > -1) { if (isArray(parent)) parent = MB_JSON_GetArrayItem(parent, getArrIndex(keys[r.foundIndex].c_str())); else parent = MB_JSON_GetObjectItemCaseSensitive(parent, keys[r.foundIndex].c_str()); } if (isArray(parent)) { int arrSize = MB_JSON_GetArraySize(parent); if (r.stopIndex < (int)keys.size() - 1) { item = isArrayKey(keys[r.stopIndex + 1].c_str()) ? MB_JSON_CreateArray() : MB_JSON_CreateObject(); mAdd(keys, &item, r.stopIndex + 1, value); } else item = value; for (int i = arrSize; i < index; i++) MB_JSON_AddItemToArray(parent, MB_JSON_CreateNull()); MB_JSON_AddItemToArray(parent, item); } else MB_JSON_Delete(value); } void FirebaseJsonBase::replaceItem(MB_VECTOR<MB_String> &keys, struct search_result_t &r, MB_JSON *parent, MB_JSON *value) { if (r.foundIndex == -1) { if (r.status == key_status_not_existed) mAdd(keys, &parent, 0, value); else if (r.status == key_status_mistype) { MB_JSON *m_parent = MB_JSON_CreateObject(); mAdd(keys, &m_parent, 0, value); *parent = *m_parent; } else MB_JSON_Delete(value); } else { if (r.status == key_status_not_existed && !isArrayKey(keys[r.stopIndex].c_str())) { MB_JSON *curItem = isArray(parent) ? MB_JSON_GetArrayItem(parent, getArrIndex(keys[r.foundIndex].c_str())) : MB_JSON_GetObjectItem(parent, keys[r.foundIndex].c_str()); if (isObject(curItem)) { mAdd(keys, &curItem, r.foundIndex + 1, value); return; } } MB_JSON *item = NULL; if ((r.status == key_status_mistype ? r.stopIndex : r.foundIndex) < (int)keys.size() - 1) { item = isArrayKey(keys[r.stopIndex].c_str()) ? MB_JSON_CreateArray() : MB_JSON_CreateObject(); mAdd(keys, &item, r.stopIndex, value); } else item = value; replace(keys, r, parent, item); } } void FirebaseJsonBase::replace(MB_VECTOR<MB_String> &keys, struct search_result_t &r, MB_JSON *parent, MB_JSON *item) { if (isArray(parent)) MB_JSON_ReplaceItemInArray(parent, getArrIndex(keys[r.foundIndex].c_str()), item); else MB_JSON_ReplaceItemInObject(parent, keys[r.foundIndex].c_str(), item); } size_t FirebaseJsonBase::mIteratorBegin(MB_JSON *parent) { mIteratorEnd(); char *p = MB_JSON_PrintUnformatted(parent); if (p == NULL) return 0; buf = p; MB_JSON_free(p); iterator_data.buf_size = buf.length(); int index = -1; mIterate(parent, index); return iterator_data.result.size(); } size_t FirebaseJsonBase::mIteratorBegin(MB_JSON *parent, MB_VECTOR<MB_String> *keys) { mIteratorEnd(); if (keys == NULL) return 0; int index = -1; mIterate(parent, index); return iterator_data.result.size(); } void FirebaseJsonBase::mIteratorEnd(bool clearBuf) { if (clearBuf) buf.clear(); iterator_data.path.clear(); iterator_data.buf_size = 0; iterator_data.buf_offset = 0; iterator_data.result.clear(); iterator_data.depth = -1; iterator_data._depth = 0; if (iterator_data.parentArr != NULL) MB_JSON_Delete(iterator_data.parentArr); iterator_data.parentArr = NULL; } void FirebaseJsonBase::mIterate(MB_JSON *parent, int &arrIndex) { if (!parent) return; bool isAr = isArray(parent); if (isAr) arrIndex = 0; MB_JSON *e = parent->child; if (e) { iterator_data.depth++; while (e) { if (isArray(e) || isObject(e)) mCollectIterator(e, e->string ? JSON_OBJECT : JSON_ARRAY, arrIndex); if (isArray(e)) { MB_JSON *item = e->child; int _arrIndex = 0; if (e->child) { iterator_data.depth++; while (item) { if (isArray(item) || isObject(item)) mIterate(item, _arrIndex); else mCollectIterator(item, item->string ? JSON_OBJECT : JSON_ARRAY, _arrIndex); item = item->next; _arrIndex++; } } } else if (isObject(e)) mIterate(e, arrIndex); else mCollectIterator(e, e->string ? JSON_OBJECT : JSON_ARRAY, arrIndex); e = e->next; if (isAr) arrIndex++; } } } void FirebaseJsonBase::mCollectIterator(MB_JSON *e, int type, int &arrIndex) { struct iterator_result_t result; if (e->string) { size_t pos = buf.find((const char *)e->string, iterator_data.buf_offset); if (pos != MB_String::npos) { result.ofs1 = pos; result.len1 = strlen(e->string); iterator_data.buf_offset = (e->type != MB_JSON_Object && e->type != MB_JSON_Array) ? pos + result.len1 : pos; } } char *p = MB_JSON_PrintUnformatted(e); if (p) { int i = iterator_data.buf_offset; size_t pos = buf.find(p, i); if (pos != MB_String::npos) { result.ofs2 = pos - result.ofs1 - result.len1; result.len2 = strlen(p); MB_JSON_free(p); iterator_data.buf_offset = (e->type != MB_JSON_Object && e->type != MB_JSON_Array) ? pos + result.len2 : pos; } } result.type = type; result.depth = iterator_data.depth; iterator_data.result.push_back(result); } int FirebaseJsonBase::mIteratorGet(size_t index, int &type, String &key, String &value) { key.remove(0, key.length()); value.remove(0, value.length()); int depth = -1; if (buf.length() == iterator_data.buf_size) { if (index > iterator_data.result.size() - 1) return depth; if (iterator_data.result[index].len1 > 0) { char *m_key = (char *)newP(iterator_data.result[index].len1 + 1); if (m_key) { memset(m_key, 0, iterator_data.result[index].len1 + 1); strncpy(m_key, &buf[iterator_data.result[index].ofs1], iterator_data.result[index].len1); key = m_key; delP(&m_key); } } char *m_val = (char *)newP(iterator_data.result[index].len2 + 1); if (m_val) { memset(m_val, 0, iterator_data.result[index].len2 + 1); int ofs = iterator_data.result[index].ofs1 + iterator_data.result[index].len1 + iterator_data.result[index].ofs2; int len = iterator_data.result[index].len2; if (iterator_data.result[index].type == JSON_STRING) { if (buf[ofs] == '"') ofs++; if (buf[ofs + len - 1] == '"') len--; } strncpy(m_val, &buf[ofs], len); value = m_val; delP(&m_val); } type = iterator_data.result[index].type; depth = iterator_data.result[index].depth; } return depth; } struct FirebaseJsonBase::fb_js_iterator_value_t FirebaseJsonBase::mValueAt(size_t index) { struct fb_js_iterator_value_t value; int depth = mIteratorGet(index, value.type, value.key, value.value); value.depth = depth; return value; } void FirebaseJsonBase::toBuf(fb_json_serialize_mode mode) { if (root != NULL) { char *out = mode == fb_json_serialize_mode_pretty ? MB_JSON_Print(root) : MB_JSON_PrintUnformatted(root); if (out) { buf = out; MB_JSON_free(out); } } } bool FirebaseJsonBase::mReadClient(Client *client) { // blocking read buf.clear(); if (readClient(client, buf)) { if (root != NULL) MB_JSON_Delete(root); root = parse(buf.c_str()); buf.clear(); return root != NULL; } return false; } bool FirebaseJsonBase::mReadStream(Stream *s, int timeoutMS) { // non-blocking read if (readStream(s, serData, buf, true, timeoutMS)) { if (root != NULL) MB_JSON_Delete(root); root = parse(buf.c_str()); buf.clear(); return root != NULL; } return false; } #if defined(ESP32_SD_FAT_INCLUDED) bool FirebaseJsonBase::mReadSdFat(SD_FAT_FILE &file, int timeoutMS) { // non-blocking read if (readSdFatFile(file, serData, buf, true, timeoutMS)) { if (root != NULL) MB_JSON_Delete(root); root = parse(buf.c_str()); buf.clear(); return root != NULL; } return false; } #endif const char *FirebaseJsonBase::mRaw() { toBuf(fb_json_serialize_mode_plain); return buf.c_str(); } bool FirebaseJsonBase::mRemove(const char *path) { bool ret = false; prepareRoot(); MB_VECTOR<MB_String> keys = MB_VECTOR<MB_String>(); makeList(path, keys, '/'); if (keys.size() > 0) { if (isArrayKey(keys[0].c_str()) && root_type == Root_Type_JSON) { clearList(keys); return false; } } MB_JSON *parent = root; struct search_result_t r; searchElements(keys, parent, r); parent = r.parent; if (r.status == key_status_existed) { ret = true; if (isArray(parent)) MB_JSON_DeleteItemFromArray(parent, getArrIndex(keys[r.stopIndex].c_str())); else { MB_JSON_DeleteItemFromObjectCaseSensitive(parent, keys[r.stopIndex].c_str()); if (parent->child == NULL && r.stopIndex > 0) { MB_String path; mGetPath(path, keys, 0, r.stopIndex - 1); mRemove(path.c_str()); } } } clearList(keys); return ret; } void FirebaseJsonBase::mGetPath(MB_String &path, MB_VECTOR<MB_String> paths, int begin, int end) { if (end < 0 || end >= (int)paths.size()) end = paths.size() - 1; if (begin < 0 || begin > end) begin = 0; for (int i = begin; i <= end; i++) { if (i > 0) path += (const char *)MBSTRING_FLASH_MCR("/"); path += paths[i].c_str(); } } size_t FirebaseJsonBase::mGetSerializedBufferLength(bool prettify) { if (!root) return 0; return MB_JSON_SerializedBufferLength(root, prettify); } void FirebaseJsonBase::mSetFloatDigits(uint8_t digits) { floatDigits = digits; } void FirebaseJsonBase::mSetDoubleDigits(uint8_t digits) { doubleDigits = digits; } int FirebaseJsonBase::mResponseCode() { return httpCode; } bool FirebaseJsonBase::mGet(MB_JSON *parent, FirebaseJsonData *result, const char *path, bool prettify) { bool ret = false; prepareRoot(); MB_VECTOR<MB_String> keys = MB_VECTOR<MB_String>(); makeList(path, keys, '/'); if (keys.size() > 0) { if (isArrayKey(keys[0].c_str()) && root_type == Root_Type_JSON) { clearList(keys); return false; } } MB_JSON *_parent = parent; struct search_result_t r; searchElements(keys, parent, r); _parent = r.parent; if (r.status == key_status_existed) { MB_JSON *data = NULL; if (isArray(_parent)) data = MB_JSON_GetArrayItem(_parent, getArrIndex(keys[r.stopIndex].c_str())); else data = MB_JSON_GetObjectItemCaseSensitive(_parent, keys[r.stopIndex].c_str()); if (data != NULL) { if (result != NULL) { result->clear(); char *p = prettify ? MB_JSON_Print(data) : MB_JSON_PrintUnformatted(data); result->stringValue = p; MB_JSON_free(p); result->type_num = data->type; result->success = true; mSetElementType(result); } ret = true; } } clearList(keys); return ret; } void FirebaseJsonBase::mSetResInt(FirebaseJsonData *data, const char *value) { if (strlen(value) > 0) { char *pEnd; #if !defined(__AVR__) value[0] == '-' ? data->iVal.int64 = strtoll(value, &pEnd, 10) : data->iVal.uint64 = strtoull(value, &pEnd, 10); #else value[0] == '-' ? data->iVal.int64 = strtol(value, &pEnd, 10) : data->iVal.uint64 = strtoull_alt(value); #endif } else data->iVal = {0}; data->intValue = data->iVal.int32; data->boolValue = data->iVal.int32 > 0; } void FirebaseJsonBase::mSetResFloat(FirebaseJsonData *data, const char *value) { if (strlen(value) > 0) { char *pEnd; data->fVal.setd(strtod(value, &pEnd)); } else data->fVal.setd(0); data->doubleValue = data->fVal.d; data->floatValue = data->fVal.f; } void FirebaseJsonBase::mSetElementType(FirebaseJsonData *result) { char *buf = (char *)newP(32); if (result->type_num == MB_JSON_Invalid) { strcpy(buf, (const char *)MBSTRING_FLASH_MCR("undefined")); result->typeNum = JSON_UNDEFINED; } else if (result->type_num == MB_JSON_Object) { strcpy(buf, (const char *)MBSTRING_FLASH_MCR("object")); result->typeNum = JSON_OBJECT; } else if (result->type_num == MB_JSON_Array) { strcpy(buf, (const char *)MBSTRING_FLASH_MCR("array")); result->typeNum = JSON_ARRAY; } else if (result->type_num == MB_JSON_String) { if (result->stringValue.c_str()[0] == '"') result->stringValue.remove(0, 1); if (result->stringValue.c_str()[result->stringValue.length() - 1] == '"') result->stringValue.remove(result->stringValue.length() - 1, 1); strcpy(buf, (const char *)MBSTRING_FLASH_MCR("string")); result->typeNum = JSON_STRING; // try casting the string to numbers if (result->stringValue.length() <= 32) { mSetResInt(result, result->stringValue.c_str()); mSetResFloat(result, result->stringValue.c_str()); } } else if (result->type_num == MB_JSON_NULL) { strcpy(buf, (const char *)MBSTRING_FLASH_MCR("null")); result->typeNum = JSON_NULL; } else if (result->type_num == MB_JSON_False || result->type_num == MB_JSON_True) { strcpy(buf, (const char *)MBSTRING_FLASH_MCR("boolean")); bool t = strcmp(result->stringValue.c_str(), (const char *)MBSTRING_FLASH_MCR("true")) == 0; result->typeNum = JSON_BOOL; result->iVal = {t}; result->fVal.setd(t); result->boolValue = t; result->intValue = t; result->floatValue = t; result->doubleValue = t; } else if (result->type_num == MB_JSON_Number || result->type_num == MB_JSON_Raw) { mSetResInt(result, result->stringValue.c_str()); mSetResFloat(result, result->stringValue.c_str()); if (strpos(result->stringValue.c_str(), (const char *)MBSTRING_FLASH_MCR("."), 0) > -1) { double d = atof(result->stringValue.c_str()); if (d > 0x7fffffff) { strcpy(buf, (const char *)MBSTRING_FLASH_MCR("double")); result->typeNum = JSON_DOUBLE; } else { strcpy(buf, (const char *)MBSTRING_FLASH_MCR("float")); result->typeNum = JSON_FLOAT; } } else { strcpy(buf, (const char *)MBSTRING_FLASH_MCR("int")); result->typeNum = JSON_INT; } } result->type = buf; delP(&buf); } void FirebaseJsonBase::mSet(const char *path, MB_JSON *value) { prepareRoot(); MB_VECTOR<MB_String> keys = MB_VECTOR<MB_String>(); makeList(path, keys, '/'); if (keys.size() > 0) { if ((isArrayKey(keys[0].c_str()) && root_type == Root_Type_JSON) || (!isArrayKey(keys[0].c_str()) && root_type == Root_Type_JSONArray)) { MB_JSON_Delete(value); clearList(keys); return; } } MB_JSON *parent = root; struct search_result_t r; searchElements(keys, parent, r); parent = r.parent; if (value == NULL) value = MB_JSON_CreateNull(); if (r.status == key_status_mistype || r.status == key_status_not_existed) replaceItem(keys, r, parent, value); else if (r.status == key_status_out_of_range) appendArray(keys, r, parent, value); else if (r.status == key_status_existed) replace(keys, r, parent, value); else MB_JSON_Delete(value); clearList(keys); } #if defined(__AVR__) unsigned long long FirebaseJsonBase::strtoull_alt(const char *s) { unsigned long long sum = 0; while (*s) { sum = sum * 10 + (*s++ - '0'); } return sum; } #endif FirebaseJson &FirebaseJson::operator=(FirebaseJson other) { if (isObject(other.root)) mCopy(other); return *this; } FirebaseJson::FirebaseJson(FirebaseJson &other) { if (isObject(other.root)) mCopy(other); } FirebaseJson::~FirebaseJson() { clear(); } FirebaseJson &FirebaseJson::nAdd(const char *key, MB_JSON *value) { prepareRoot(); MB_VECTOR<MB_String> keys = MB_VECTOR<MB_String>(); // makeList(key, keys, '/'); MB_String ky = key; keys.push_back(ky); if (value == NULL) value = MB_JSON_CreateNull(); if (keys.size() > 0) { if (!isArrayKey(keys[0].c_str()) || root_type == Root_Type_JSONArray) mAdd(keys, &root, 0, value); } clearList(keys); return *this; } FirebaseJson &FirebaseJson::clear() { mClear(); return *this; } FirebaseJsonArray::~FirebaseJsonArray() { mClear(); }; FirebaseJsonArray &FirebaseJsonArray::operator=(FirebaseJsonArray other) { if (isArray(other.root)) mCopy(other); return *this; } FirebaseJsonArray::FirebaseJsonArray(FirebaseJsonArray &other) { if (isArray(other.root)) mCopy(other); } FirebaseJsonArray &FirebaseJsonArray::nAdd(MB_JSON *value) { if (root_type != Root_Type_JSONArray) mClear(); root_type = Root_Type_JSONArray; prepareRoot(); if (value == NULL) value = MB_JSON_CreateNull(); MB_JSON_AddItemToArray(root, value); return *this; } bool FirebaseJsonArray::mGetIdx(FirebaseJsonData *result, int index, bool prettify) { bool ret = false; prepareRoot(); result->clear(); MB_JSON *data = NULL; if (isArray(root)) data = MB_JSON_GetArrayItem(root, index); if (data != NULL) { char *p = prettify ? MB_JSON_Print(data) : MB_JSON_PrintUnformatted(data); result->stringValue = p; MB_JSON_free(p); result->type_num = data->type; result->success = true; mSetElementType(result); ret = true; } return ret; } bool FirebaseJsonArray::mSetIdx(int index, MB_JSON *value) { if (root_type != Root_Type_JSONArray) mClear(); root_type = Root_Type_JSONArray; prepareRoot(); int size = MB_JSON_GetArraySize(root); if (index < size) return MB_JSON_ReplaceItemInArray(root, index, value); else { while (size < index) { MB_JSON_AddItemToArray(root, MB_JSON_CreateNull()); size++; } MB_JSON_AddItemToArray(root, value); } return true; } bool FirebaseJsonArray::mRemoveIdx(int index) { int size = MB_JSON_GetArraySize(root); if (index < size) { MB_JSON_DeleteItemFromArray(root, index); return size != MB_JSON_GetArraySize(root); } return false; } FirebaseJsonArray &FirebaseJsonArray::clear() { mClear(); return *this; } FirebaseJsonArray &FirebaseJsonArray::add(FirebaseJson &value) { MB_JSON *e = MB_JSON_Duplicate(value.root, true); nAdd(e); return *this; } FirebaseJsonArray &FirebaseJsonArray::add(FirebaseJsonArray &value) { MB_JSON *e = MB_JSON_Duplicate(value.root, true); nAdd(e); return *this; } FirebaseJsonData::FirebaseJsonData() { } FirebaseJsonData::~FirebaseJsonData() { clear(); } bool FirebaseJsonData::getArray(FirebaseJsonArray &jsonArray) { if (typeNum != FirebaseJson::JSON_ARRAY || !success || stringValue.length() == 0) return false; return getArray(stringValue.c_str(), jsonArray); } bool FirebaseJsonData::mGetArray(const char *source, FirebaseJsonArray &jsonArray) { if (jsonArray.root != NULL) MB_JSON_Delete(jsonArray.root); jsonArray.root = jsonArray.parse(source); return jsonArray.root != NULL; } bool FirebaseJsonData::getJSON(FirebaseJson &json) { if (typeNum != FirebaseJson::JSON_OBJECT || !success || stringValue.length() == 0) return false; return getJSON(stringValue.c_str(), json); } bool FirebaseJsonData::mGetJSON(const char *source, FirebaseJson &json) { if (json.root != NULL) MB_JSON_Delete(json.root); json.root = json.parse(source); return json.root != NULL; } size_t FirebaseJsonData::getReservedLen(size_t len) { int blen = len + 1; int newlen = (blen / 4) * 4; if (newlen < blen) newlen += 4; return (size_t)newlen; } void FirebaseJsonData::delP(void *ptr) { void **p = (void **)ptr; if (*p) { free(*p); *p = 0; } } void *FirebaseJsonData::newP(size_t len) { void *p; size_t newLen = getReservedLen(len); #if defined(BOARD_HAS_PSRAM) && defined(MB_STRING_USE_PSRAM) if (ESP.getPsramSize() > 0) p = (void *)ps_malloc(newLen); else p = (void *)malloc(newLen); if (!p) return NULL; #else #if defined(ESP8266_USE_EXTERNAL_HEAP) ESP.setExternalHeap(); #endif p = (void *)malloc(newLen); bool nn = p ? true : false; #if defined(ESP8266_USE_EXTERNAL_HEAP) ESP.resetHeap(); #endif if (!nn) return NULL; #endif memset(p, 0, newLen); return p; } void FirebaseJsonData::clear() { stringValue.remove(0, stringValue.length()); iVal = {0}; fVal.setd(0); intValue = 0; floatValue = 0; doubleValue = 0; boolValue = false; type.remove(0, type.length()); typeNum = 0; success = false; } #endif
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <folly/Expected.h> #include <quic/QuicException.h> #include <quic/codec/ConnectionIdAlgo.h> #include <quic/codec/QuicConnectionId.h> namespace quic { /** * Default implementation with algorithms to encode and decode for * ConnectionId given routing info (embedded in ServerConnectionIdParams) * * The schema for connection id is defined as follows: * * First 2 (0 - 1) bits are reserved for short version id of the connection id * If the load balancer (e.g. L4 lb) doesn't understand this version, * it can fallback to default routing * Depending on version following mappings: * Version 1: * Next 16 bits (2 - 17) are reserved for host id (L4 LB use) * Next 8 bits (18 - 25) are reserved for worker id * Next bit 26 is reserved for the process id: process id is used to * distinguish between the takeover instance and the taken over one 0 1 2 3 4 .. 17 18 .. 25 26 27 28 .. 63 |VERSION| For L4 LB | WORKER_ID | PROC_ID | .. * * Version 2: * Next 6 bits (2 - 7) are not used (random) * Next 24 bits (8 - 31) are reserved for host id * Next 8 bits (32 - 39) are reserved for worker id * Next bit 40 is reserved for the process id 0 1 2 .. 7 8 .. 31 32 .. 39 40 41 ... 63 |VERSION| UNUSED | For L4 LB | WORKER_ID | PROC_ID | .. * * Version 3: * Next 6 bits (2 - 7) are not used (random) * Next 32 bits (8 - 39) and bits(48 - 55) are reserved for host id * Next 8 bits (40 - 47) are reserved for worker id * Next bit 48 is reserved for the process id 0 1 2 .. 7 8 .. 39 40 .. 47 48 49 ... 63 |VERSION| UNUSED | For L4 LB | WORKER_ID | PROC_ID | .. */ class DefaultConnectionIdAlgo : public ConnectionIdAlgo { public: ~DefaultConnectionIdAlgo() override = default; static folly::Expected<ServerConnectionIdParams, QuicInternalException> parseConnectionIdDefault(const ConnectionId& id) noexcept; /** * Check if this implementation of algorithm can parse the given ConnectionId */ bool canParse(const ConnectionId& id) const noexcept override; /** * Parses ServerConnectionIdParams from the given connection id. */ folly::Expected<ServerConnectionIdParams, QuicInternalException> parseConnectionId(const ConnectionId& id) noexcept override; /** * Encodes the given ServerConnectionIdParams into connection id */ folly::Expected<ConnectionId, QuicInternalException> encodeConnectionId( const ServerConnectionIdParams& params) noexcept override; }; /** * Factory Interface to create ConnectionIdAlgo instance. */ class DefaultConnectionIdAlgoFactory : public ConnectionIdAlgoFactory { public: ~DefaultConnectionIdAlgoFactory() override = default; std::unique_ptr<ConnectionIdAlgo> make() override { return std::make_unique<DefaultConnectionIdAlgo>(); } }; } // namespace quic
#pragma once #include <math.h> #include <vector> #include "Vector2D.h" class Arrival { public: Vector2D arrival(Vector2D target, Vector2D position, Vector2D velocity, float maxspeed, float maxforce) { Vector2D mol = position.operator-(target); mol.normalize(); Vector2D desired = mol.operator*(maxspeed); Vector2D steer = desired.operator- (velocity); //steer.limit(maxforce); return steer; } };
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> #include <usModuleRegistry.h> #include <QMessageBox> #include <ExampleImageFilter.h> #include <ExampleImageInteractor.h> #include "QmitkExampleView.h" namespace { // Helper function to create a fully set up instance of our // ExampleImageInteractor, based on the state machine specified in Paint.xml // as well as its configuration in PaintConfig.xml. Both files are compiled // into ExtExampleModule as resources. static ExampleImageInteractor::Pointer CreateExampleImageInteractor() { auto exampleModule = us::ModuleRegistry::GetModule("MitkExampleModule"); if (nullptr != exampleModule) { auto interactor = ExampleImageInteractor::New(); interactor->LoadStateMachine("Paint.xml", exampleModule); interactor->SetEventConfig("PaintConfig.xml", exampleModule); return interactor; } return nullptr; } } // Don't forget to initialize the VIEW_ID. const std::string QmitkExampleView::VIEW_ID = "org.mitk.views.exampleview"; void QmitkExampleView::CreateQtPartControl(QWidget* parent) { // Setting up the UI is a true pleasure when using .ui files, isn't it? m_Controls.setupUi(parent); // Wire up the UI widgets with our functionality. connect(m_Controls.processImageButton, SIGNAL(clicked()), this, SLOT(ProcessSelectedImage())); } void QmitkExampleView::SetFocus() { m_Controls.processImageButton->setFocus(); } void QmitkExampleView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList<mitk::DataNode::Pointer>& dataNodes) { for (const auto& dataNode : dataNodes) { // Write robust code. Always check pointers before using them. If the // data node pointer is null, the second half of our condition isn't // even evaluated and we're safe (C++ short-circuit evaluation). if (dataNode.IsNotNull() && nullptr != dynamic_cast<mitk::Image*>(dataNode->GetData())) { m_Controls.selectImageLabel->setVisible(false); return; } } // Nothing is selected or the selection doesn't contain an image. m_Controls.selectImageLabel->setVisible(true); } void QmitkExampleView::ProcessSelectedImage() { // Before we even think about processing something, we need to make sure // that we have valid input. Don't be sloppy, this is a main reason // for application crashes if neglected. auto selectedDataNodes = this->GetDataManagerSelection(); if (selectedDataNodes.empty()) return; auto firstSelectedDataNode = selectedDataNodes.front(); if (firstSelectedDataNode.IsNull()) { QMessageBox::information(nullptr, "Example View", "Please load and select an image before starting image processing."); return; } auto data = firstSelectedDataNode->GetData(); // Something is selected, but does it contain data? if (data != nullptr) { // We don't use the auto keyword here, which would evaluate to a native // image pointer. Instead, we want a smart pointer in order to ensure that // the image isn't deleted somewhere else while we're using it. mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(data); // Something is selected and it contains data, but is it an image? if (image.IsNotNull()) { auto imageName = firstSelectedDataNode->GetName(); auto offset = m_Controls.offsetSpinBox->value(); MITK_INFO << "Process image \"" << imageName << "\" ..."; // We're finally using the ExampleImageFilter from ExtExampleModule. auto filter = ExampleImageFilter::New(); filter->SetInput(image); filter->SetOffset(offset); filter->Update(); mitk::Image::Pointer processedImage = filter->GetOutput(); if (processedImage.IsNull() || !processedImage->IsInitialized()) return; MITK_INFO << " done"; // Stuff the resulting image into a data node, set some properties, // and add it to the data storage, which will eventually display the // image in the application. auto processedImageDataNode = mitk::DataNode::New(); processedImageDataNode->SetData(processedImage); QString name = QString("%1 (Offset: %2)").arg(imageName.c_str()).arg(offset); processedImageDataNode->SetName(name.toStdString()); // We don't really need to copy the level window, but if we wouldn't // do it, the new level window would be initialized to display the image // with optimal contrast in order to capture the whole range of pixel // values. This is also true for the input image as long as one didn't // modify its level window manually. Thus, the images would appear // identical unless you compare the level window widget for both images. mitk::LevelWindow levelWindow; if (firstSelectedDataNode->GetLevelWindow(levelWindow)) processedImageDataNode->SetLevelWindow(levelWindow); // We also attach our ExampleImageInteractor, which allows us to paint // on the resulting images by using the mouse as long as the CTRL key // is pressed. auto interactor = CreateExampleImageInteractor(); if (interactor.IsNotNull()) interactor->SetDataNode(processedImageDataNode); this->GetDataStorage()->Add(processedImageDataNode); } } // Now it's your turn. This class/method has lots of room for improvements, // for example: // // - What happens when multiple items are selected but the first one isn't // an image? - There isn't any feedback for the user at all. // - What's the front item of a selection? Does it depend on the order // of selection or the position in the Data Manager? - Isn't it // better to process all selected images? Don't forget to adjust the // titles of the UI widgets. // - In addition to the the displayed label, it's probably a good idea to // enable or disable the button depending on the selection. }
#include <iostream> #include <cmath> #include <stdexcept> #include <string> using namespace std; class bad_hmean:public logic_error { private: double v1; double v2; string error="hmean invalid arguments: a=" + to_string(v1) + " b=" + to_string(v2) + " a=-b";; public: bad_hmean(double a = 0, double b = 0) :v1(a), v2(b), logic_error("hmean invalid arguments") { } const char* what() const { cout << error << endl; return "bullshit1"; } }; class bad_gmean:public logic_error { private: double v1; double v2; string error = "gmean invalid arguments: a=" + to_string(v1) + " b=" + to_string(v2) + " a or b<0"; public: bad_gmean(double a = 0, double b = 0) :v1(a), v2(b), logic_error("gmean invalid arguments") {} const char* what() const { cout << error << endl; return "bullshit2"; } }; auto hmean(double a, double b) ->double { if (a == -b) throw bad_hmean(a, b); return 2.0 * a * b / (a + b); } auto gmean(double a, double b) ->double { if (a < 0 || b < 0) throw bad_gmean(a, b); return sqrt(a * b); } int main() { double x, y, z; cout << "Enter two numbers: "; while (cin >> x >> y) { try { z = hmean(x, y); cout << "Harmonic mean of " << x << " and " << y << " is " << z << endl; cout << "Geometric mean of " << x << " and " << y << " is " << gmean(x, y) << endl; cout << "Enter next set of numbers <q to quit>: "; } catch (logic_error& lg) { lg.what(); cout << "Try again.\n"; continue; } } cout << "Bye!\n"; }
#include <unordered_set> int solution(vector<int> &A) { // write your code in C++14 (g++ 6.2.0) unordered_set <int> rec; //int cur_max_n = 1; for (auto a : A) { if (rec.count(a)==0) rec.insert(a); } int i = 1; while (i<A.size()){ if (rec.count(i)==0) return i; i++; } return rec.count(1)? i+1 : 1; } int solution(vector<int> &A) { // write your code in C++14 (g++ 6.2.0) bool has_pos = 0; vector<bool> B(A.size(),0); //int idx=0; for (int a : A) { if(a>0 && a<(int)(A.size()+1)) {B[a-1] = 1; has_pos=1; } } for (size_t j =0; j<B.size(); j++) { if(!B[j]) return (int)(j+1); } return has_pos? int(B.size()+1) : 1; }
// Created on: 1991-02-26 // Created by: Isabelle GRIGNON // Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Extrema_PCFOfEPCOfELPCOfLocateExtPC_HeaderFile #define _Extrema_PCFOfEPCOfELPCOfLocateExtPC_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <gp_Pnt.hxx> #include <TColStd_SequenceOfReal.hxx> #include <TColStd_SequenceOfInteger.hxx> #include <Extrema_SequenceOfPOnCurv.hxx> #include <Standard_Integer.hxx> #include <math_FunctionWithDerivative.hxx> class Standard_OutOfRange; class Standard_TypeMismatch; class Adaptor3d_Curve; class Extrema_CurveTool; class Extrema_POnCurv; class gp_Pnt; class gp_Vec; class Extrema_PCFOfEPCOfELPCOfLocateExtPC : public math_FunctionWithDerivative { public: DEFINE_STANDARD_ALLOC Standard_EXPORT Extrema_PCFOfEPCOfELPCOfLocateExtPC(); Standard_EXPORT Extrema_PCFOfEPCOfELPCOfLocateExtPC(const gp_Pnt& P, const Adaptor3d_Curve& C); //! sets the field mycurve of the function. Standard_EXPORT void Initialize (const Adaptor3d_Curve& C); //! sets the field P of the function. Standard_EXPORT void SetPoint (const gp_Pnt& P); //! Calculation of F(U). Standard_EXPORT Standard_Boolean Value (const Standard_Real U, Standard_Real& F) Standard_OVERRIDE; //! Calculation of F'(U). Standard_EXPORT Standard_Boolean Derivative (const Standard_Real U, Standard_Real& DF) Standard_OVERRIDE; //! Calculation of F(U) and F'(U). Standard_EXPORT Standard_Boolean Values (const Standard_Real U, Standard_Real& F, Standard_Real& DF) Standard_OVERRIDE; //! Save the found extremum. Standard_EXPORT virtual Standard_Integer GetStateNumber() Standard_OVERRIDE; //! Return the number of found extrema. Standard_EXPORT Standard_Integer NbExt() const; //! Returns the Nth distance. Standard_EXPORT Standard_Real SquareDistance (const Standard_Integer N) const; //! Shows if the Nth distance is a minimum. Standard_EXPORT Standard_Boolean IsMin (const Standard_Integer N) const; //! Returns the Nth extremum. Standard_EXPORT const Extrema_POnCurv& Point (const Standard_Integer N) const; //! Determines boundaries of subinterval for find of root. Standard_EXPORT void SubIntervalInitialize (const Standard_Real theUfirst, const Standard_Real theUlast); //! Computes a Tol value. If 1st derivative of curve //! |D1|<Tol, it is considered D1=0. Standard_EXPORT Standard_Real SearchOfTolerance(); protected: private: gp_Pnt myP; Standard_Address myC; Standard_Real myU; gp_Pnt myPc; Standard_Real myD1f; TColStd_SequenceOfReal mySqDist; TColStd_SequenceOfInteger myIsMin; Extrema_SequenceOfPOnCurv myPoint; Standard_Boolean myPinit; Standard_Boolean myCinit; Standard_Boolean myD1Init; Standard_Real myTol; Standard_Integer myMaxDerivOrder; Standard_Real myUinfium; Standard_Real myUsupremum; }; #endif // _Extrema_PCFOfEPCOfELPCOfLocateExtPC_HeaderFile
#include "Keyboard.h" #include "xuartlite_l.h" Keyboard::Keyboard(uint32_t baseaddr) : baseaddr(baseaddr) { } uint8_t Keyboard::IsKeyPressed() { if (!XUartLite_IsReceiveEmpty(baseaddr)) { key = XUartLite_RecvByte(baseaddr); return 1; } return 0; } uint8_t Keyboard::GetKey() const { return key; }
#include "rendercl.h" #include "renderjob.h" #include "renderjobqueue.h" #include "shared/platform.h" #include <cl/cl.h> #include <iostream> #include <string> #if _DEBUG #define CL_CHECK_ERROR(x) { assert(x == CL_SUCCESS); } #else #define CL_CHECK_ERROR(x) x #endif inline void build(cl_program program, cl_device_id* devices, const char* options = "") { // build cl_int ret_val = clBuildProgram(program, 1, devices, options, NULL, NULL); // avoid abortion due to CL_BILD_PROGRAM_FAILURE if (ret_val != CL_SUCCESS && ret_val != CL_BUILD_PROGRAM_FAILURE) CL_CHECK_ERROR(ret_val); cl_build_status build_status; CL_CHECK_ERROR(clGetProgramBuildInfo(program, *devices, CL_PROGRAM_BUILD_STATUS, sizeof(cl_build_status), &build_status, NULL)); if (build_status == CL_SUCCESS) return; char *build_log; size_t ret_val_size; CL_CHECK_ERROR(clGetProgramBuildInfo(program, *devices, CL_PROGRAM_BUILD_LOG, 0, NULL, &ret_val_size)); build_log = new char[ret_val_size+1]; CL_CHECK_ERROR(clGetProgramBuildInfo(program, *devices, CL_PROGRAM_BUILD_LOG, ret_val_size, build_log, NULL)); // to be carefully, terminate with \0 // there's no information in the reference whether the string is 0 terminated or not build_log[ret_val_size] = '\0'; std::cout << build_log << std::endl; delete[] build_log; } using namespace std; void* RenderJobThreadFuncOpenCL(void* param) { RenderJobQueue* queue = (RenderJobQueue*)(param); // pop off render tiles until there are none left RenderJob* job = queue->Pop(); if (!job) return 0; cl_int status = 0; cl_device_type dType = CL_DEVICE_TYPE_GPU; cl_context context = clCreateContextFromType(0, dType, NULL, NULL, &status); if (status != CL_SUCCESS) { cout << "clCreateContextFromType failed." << endl; return 0; } size_t contextDescriptorSize; status = clGetContextInfo(context, CL_CONTEXT_DEVICES,0, 0, &contextDescriptorSize); if (status != CL_SUCCESS) { cout << "clCreateContextFromType failed." << endl; return 0; } cl_device_id* devices = (cl_device_id*)malloc(contextDescriptorSize); status = clGetContextInfo(context, CL_CONTEXT_DEVICES, contextDescriptorSize, devices, 0); if (status != CL_SUCCESS) { cout << "clGetContextInfo failed." << endl; return 0; } // some stats size_t paramAddressBits; clGetDeviceInfo(devices[0], CL_DEVICE_ADDRESS_BITS, sizeof(paramAddressBits), &paramAddressBits, NULL); cout << "CL_DEVICE_ADDRESS_BITS: " << paramAddressBits << endl; cl_command_queue cmdQueue; cmdQueue = clCreateCommandQueue(context, devices[0], 0, 0); // create cl buffer for render job output const uint32_t bufSize = job->m_renderRect.Width() * job->m_renderRect.Height() * 4 * sizeof(cl_float); cl_mem outputBuffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, bufSize, NULL, &status); if (status != CL_SUCCESS) { cout << "clCreateBuffer failed." << endl; return 0; } string sfile = LoadFileToString("RenderJob.cl"); const char* source = sfile.c_str(); size_t sourceSize[] = { sfile.length() }; cl_program program = clCreateProgramWithSource(context, 1, &source, sourceSize, &status); if (status != CL_SUCCESS) { cout << "clCreateProgramWithSource failed." << endl; return 0; } // build the program build(program, devices, "-I."); // get a kernel object handle for a kernel with the given name cl_kernel kernel = clCreateKernel(program, "renderKernel", &status); if (status != CL_SUCCESS) { cout << "clCreateKernel failed." << endl; return 0; } // set kernel params clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&outputBuffer); if (status != CL_SUCCESS) { cout << "clSetKernelArg failed." << endl; return 0; } size_t globalThreads[1]; size_t localThreads[1]; cl_event events[2]; globalThreads[0] = job->m_renderRect.Width()*job->m_renderRect.Height(); localThreads[0] = 1; status = clEnqueueNDRangeKernel(cmdQueue, kernel, 1, NULL, globalThreads, localThreads, 0, NULL, &events[0]); if(status != CL_SUCCESS) { cout << "clEnqueueNDRangeKernel failed" << endl; return 0; } status = clWaitForEvents(1, &events[0]); if(status != CL_SUCCESS) { cout << "clWaitForEvents failed" << endl; return 0; } clReleaseEvent(events[0]); // read buffer back status = clEnqueueReadBuffer(cmdQueue, outputBuffer, CL_TRUE, 0, bufSize, job->m_output, 0, 0, 0); if(status != CL_SUCCESS) { cout << "clEnqueueReadBuffer failed" << endl; return 0; } Sleep(2.0); return NULL; }
/* * Header file for the board.cells, cell and move classes and functions to validate moves and * other useful things used by both the main game and the AI. */ #ifndef DRAUGHTSMODULE_H #define DRAUGHTSMODULE_H #include <vector> //For vector #include <fstream> //For ifstream #include <string> #define BOARD_WIDTH 8 #define BOARD_HEIGHT 8 //Each possible state for a board.cells cell enum cellState {EMPTY,M_WHITE,K_WHITE,M_BLACK,K_BLACK}; //Converts a king to a man if a king is passed to the function cellState DeKing(cellState cell); //Returns the opposite player to the one given cellState otherplayer(cellState); //Represents the board struct Board { cellState cells[8][8]; }; //Represents a board cell struct Cell { int x; int y; Cell() {} Cell(int X,int Y): x(X),y(Y) {} }; //Represents a move class DraughtsMove { public: Cell start; Cell destination; DraughtsMove(); DraughtsMove(Cell strt, Cell dest, bool cap = false); //~DraughtsMove(); //DraughtsMove* nextMove; bool capture; //True if the move is a capture bool isValid(Board,cellState); //Returns true if the move is a valid draughts move std::vector<Cell> getAffectedCells(); //Returns a vector containing all of the cells the move affects }; //A struct for a series of moves in succession (serial captures) struct MoveSequence { std::vector<DraughtsMove> moves; MoveSequence(DraughtsMove first); MoveSequence(): exists(false) {}; bool exists; }; //Returns true if the piece at (x,y) on the board can capture bool CanCapture(Board,int x,int y); //Returns true if a capture is available to the player bool PlayerCanCapture(Board,cellState player); //Returns true if the cell is within the board boundaries bool CellInBounds(Cell); //Returns true if player has won the game bool HasWon(cellState player, Board board); Board ExecuteMove(DraughtsMove move, Board board); Board ExecuteMoveSequence(MoveSequence moves, Board board); void ResetBoard(Board &board); #endif
#pragma once #include <cstring> namespace prv { namespace lex { class token_view { public: explicit constexpr token_view(const char* ptr, std::size_t size) noexcept : ptr_(ptr) , size_(size) { } constexpr char operator[](std::size_t i) const noexcept { return ptr_[i]; } constexpr const char* begin() const noexcept { return ptr_; } constexpr const char* end() const noexcept { return ptr_ + size_; } constexpr const char* data() const noexcept { return ptr_; } constexpr std::size_t size() const noexcept { return size_; } private: const char* ptr_; std::size_t size_; }; inline constexpr bool operator==(token_view lhs, token_view rhs) noexcept { if (lhs.size() != rhs.size()) return false; for (auto i = 0u; i != lhs.size(); ++i) if (lhs[i] != rhs[i]) return false; return true; } inline constexpr bool operator!=(token_view lhs, token_view rhs) noexcept { return !(lhs == rhs); } inline constexpr bool operator==(token_view lhs, const char* rhs) noexcept { auto iter = lhs.begin(); while (iter != lhs.end() && *rhs) { if (*iter != *rhs) return false; ++iter; ++rhs; } auto iter_done = iter == lhs.end(); auto rhs_done = *rhs == '\0'; return iter_done == rhs_done; } inline constexpr bool operator==(const char* lhs, token_view rhs) noexcept { return rhs == lhs; } inline constexpr bool operator!=(token_view lhs, const char* rhs) noexcept { return !(lhs == rhs); } inline constexpr bool operator!=(const char* lhs, token_view rhs) noexcept { return !(lhs == rhs); } } // namespace lex } // namespace prv
#include <iostream> #define NUM 1 + 2 using namespace std; int main() { cout << NUM * NUM << endl; return 0; }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <folly/portability/GMock.h> #include <folly/portability/GTest.h> #include <quic/api/QuicTransportBase.h> #include <folly/io/async/test/MockAsyncUDPSocket.h> #include <quic/api/test/Mocks.h> #include <quic/client/QuicClientTransport.h> #include <quic/codec/DefaultConnectionIdAlgo.h> #include <quic/common/QuicAsyncUDPSocketWrapper.h> #include <quic/common/QuicEventBase.h> #include <quic/common/test/TestClientUtils.h> #include <quic/common/test/TestUtils.h> #include <quic/fizz/client/handshake/FizzClientHandshake.h> #include <quic/fizz/client/handshake/FizzClientQuicHandshakeContext.h> #include <quic/state/test/MockQuicStats.h> #include <utility> namespace quic::test { class TestingQuicClientTransport : public QuicClientTransport { public: class DestructionCallback : public std::enable_shared_from_this<DestructionCallback> { public: void markDestroyed() { destroyed_ = true; } bool isDestroyed() { return destroyed_; } private: bool destroyed_{false}; }; TestingQuicClientTransport( folly::EventBase* evb, std::unique_ptr<QuicAsyncUDPSocketType> socket, std::shared_ptr<ClientHandshakeFactory> handshakeFactory, size_t connIdSize = kDefaultConnectionIdSize, bool useConnectionEndWithErrorCallback = false) : QuicClientTransport( evb, std::move(socket), std::move(handshakeFactory), connIdSize, useConnectionEndWithErrorCallback) {} ~TestingQuicClientTransport() override { if (destructionCallback_) { destructionCallback_->markDestroyed(); } } QuicTransportBase* getTransport() { return this; } const QuicClientConnectionState& getConn() const { return *dynamic_cast<QuicClientConnectionState*>(conn_.get()); } QuicClientConnectionState& getNonConstConn() { return *dynamic_cast<QuicClientConnectionState*>(conn_.get()); } const auto& getReadCallbacks() const { return readCallbacks_; } const auto& getDeliveryCallbacks() const { return deliveryCallbacks_; } auto getConnPendingWriteCallback() const { return connWriteCallback_; } auto getStreamPendingWriteCallbacks() const { return pendingWriteCallbacks_; } auto& idleTimeout() { return idleTimeout_; } auto& lossTimeout() { return lossTimeout_; } auto& ackTimeout() { return ackTimeout_; } auto& happyEyeballsConnAttemptDelayTimeout() { return happyEyeballsConnAttemptDelayTimeout_; } auto& drainTimeout() { return drainTimeout_; } bool isClosed() const { return closeState_ == CloseState::CLOSED; } bool isDraining() const { return drainTimeout_.isScheduled(); } auto& serverInitialParamsSet() { return getNonConstConn().serverInitialParamsSet_; } auto& peerAdvertisedInitialMaxData() { return getConn().peerAdvertisedInitialMaxData; } auto& peerAdvertisedInitialMaxStreamDataBidiLocal() const { return getConn().peerAdvertisedInitialMaxStreamDataBidiLocal; } auto& peerAdvertisedInitialMaxStreamDataBidiRemote() const { return getConn().peerAdvertisedInitialMaxStreamDataBidiRemote; } auto& peerAdvertisedInitialMaxStreamDataUni() const { return getConn().peerAdvertisedInitialMaxStreamDataUni; } void setDestructionCallback( std::shared_ptr<DestructionCallback> destructionCallback) { destructionCallback_ = std::move(destructionCallback); } void invokeOnDataAvailable( const folly::SocketAddress& addr, size_t len, bool truncated) { onDataAvailable(addr, len, truncated, OnDataAvailableParams()); } void invokeOnNotifyDataAvailable(QuicAsyncUDPSocketType& sock) { onNotifyDataAvailable(sock); } private: std::shared_ptr<DestructionCallback> destructionCallback_; }; // Simulates a simple 1rtt handshake without needing to get any handshake bytes // from the server. class FakeOneRttHandshakeLayer : public FizzClientHandshake { public: explicit FakeOneRttHandshakeLayer( QuicClientConnectionState* conn, std::shared_ptr<FizzClientQuicHandshakeContext> fizzContext) : FizzClientHandshake( conn, std::move(fizzContext), std::make_unique<FizzCryptoFactory>()) {} folly::Optional<CachedServerTransportParameters> connectImpl( folly::Optional<std::string> hostname) override { // Look up psk folly::Optional<QuicCachedPsk> quicCachedPsk = getPsk(hostname); folly::Optional<CachedServerTransportParameters> transportParams; if (quicCachedPsk) { transportParams = quicCachedPsk->transportParams; } getFizzState().sni() = hostname; connected_ = true; writeDataToQuicStream( getClientConn()->cryptoState->initialStream, folly::IOBuf::copyBuffer("CHLO")); createServerTransportParameters(); return transportParams; } void createServerTransportParameters() { TransportParameter maxStreamDataBidiLocal = encodeIntegerParameter( TransportParameterId::initial_max_stream_data_bidi_local, maxInitialStreamData); TransportParameter maxStreamDataBidiRemote = encodeIntegerParameter( TransportParameterId::initial_max_stream_data_bidi_remote, maxInitialStreamData); TransportParameter maxStreamDataUni = encodeIntegerParameter( TransportParameterId::initial_max_stream_data_uni, maxInitialStreamData); TransportParameter maxStreamsBidi = encodeIntegerParameter( TransportParameterId::initial_max_streams_bidi, maxInitialStreamsBidi); TransportParameter maxStreamsUni = encodeIntegerParameter( TransportParameterId::initial_max_streams_uni, maxInitialStreamsUni); TransportParameter maxData = encodeIntegerParameter( TransportParameterId::initial_max_data, connWindowSize); std::vector<TransportParameter> parameters; parameters.push_back(std::move(maxStreamDataBidiLocal)); parameters.push_back(std::move(maxStreamDataBidiRemote)); parameters.push_back(std::move(maxStreamDataUni)); parameters.push_back(std::move(maxStreamsBidi)); parameters.push_back(std::move(maxStreamsUni)); parameters.push_back(std::move(maxData)); parameters.push_back(encodeIntegerParameter( TransportParameterId::idle_timeout, kDefaultIdleTimeout.count())); parameters.push_back(encodeIntegerParameter( TransportParameterId::max_packet_size, maxRecvPacketSize)); ServerTransportParameters params; StatelessResetToken testStatelessResetToken = generateStatelessResetToken(); TransportParameter statelessReset; statelessReset.parameter = TransportParameterId::stateless_reset_token; statelessReset.value = folly::IOBuf::copyBuffer(testStatelessResetToken); parameters.push_back(std::move(statelessReset)); params.parameters = std::move(parameters); params_ = std::move(params); } void setServerTransportParams(ServerTransportParameters params) { params_ = std::move(params); } void setOneRttWriteCipher(std::unique_ptr<Aead> oneRttWriteCipher) { oneRttWriteCipher_ = std::move(oneRttWriteCipher); } void setOneRttReadCipher(std::unique_ptr<Aead> oneRttReadCipher) { getClientConn()->readCodec->setOneRttReadCipher( std::move(oneRttReadCipher)); } void setHandshakeReadCipher(std::unique_ptr<Aead> handshakeReadCipher) { getClientConn()->readCodec->setHandshakeReadCipher( std::move(handshakeReadCipher)); } void setHandshakeWriteCipher(std::unique_ptr<Aead> handshakeWriteCipher) { getClientConn()->handshakeWriteCipher = std::move(handshakeWriteCipher); } void setZeroRttWriteCipher(std::unique_ptr<Aead> zeroRttWriteCipher) { getClientConn()->zeroRttWriteCipher = std::move(zeroRttWriteCipher); } void setZeroRttWriteHeaderCipher( std::unique_ptr<PacketNumberCipher> zeroRttWriteHeaderCipher) { getClientConn()->zeroRttWriteHeaderCipher = std::move(zeroRttWriteHeaderCipher); } void setHandshakeReadHeaderCipher( std::unique_ptr<PacketNumberCipher> handshakeReadHeaderCipher) { getClientConn()->readCodec->setHandshakeHeaderCipher( std::move(handshakeReadHeaderCipher)); } void setHandshakeWriteHeaderCipher( std::unique_ptr<PacketNumberCipher> handshakeWriteHeaderCipher) { getClientConn()->handshakeWriteHeaderCipher = std::move(handshakeWriteHeaderCipher); } void setOneRttWriteHeaderCipher( std::unique_ptr<PacketNumberCipher> oneRttWriteHeaderCipher) { oneRttWriteHeaderCipher_ = std::move(oneRttWriteHeaderCipher); } void setOneRttReadHeaderCipher( std::unique_ptr<PacketNumberCipher> oneRttReadHeaderCipher) { getClientConn()->readCodec->setOneRttHeaderCipher( std::move(oneRttReadHeaderCipher)); } void setZeroRttRejected(bool rejected) { setZeroRttRejectedForTest(rejected); if (rejected) { createServerTransportParameters(); } } void doHandshake(std::unique_ptr<folly::IOBuf> buf, EncryptionLevel level) override { EXPECT_EQ(writeBuf.get(), nullptr); QuicClientConnectionState* conn = getClientConn(); if (!conn->oneRttWriteCipher) { conn->oneRttWriteCipher = std::move(oneRttWriteCipher_); conn->oneRttWriteHeaderCipher = std::move(oneRttWriteHeaderCipher_); } if (getPhase() == Phase::Initial) { conn->handshakeWriteCipher = test::createNoOpAead(); conn->handshakeWriteHeaderCipher = test::createNoOpHeaderCipher(); conn->readCodec->setHandshakeReadCipher(test::createNoOpAead()); conn->readCodec->setHandshakeHeaderCipher(test::createNoOpHeaderCipher()); writeDataToQuicStream( conn->cryptoState->handshakeStream, folly::IOBuf::copyBuffer("ClientFinished")); handshakeInitiated(); } readBuffers[level].append(std::move(buf)); } bool connectInvoked() { return connected_; } const folly::Optional<ServerTransportParameters>& getServerTransportParams() override { return params_; } void triggerOnNewCachedPsk() { fizz::client::NewCachedPsk psk; onNewCachedPsk(psk); } std::unique_ptr<folly::IOBuf> writeBuf; bool connected_{false}; QuicVersion negotiatedVersion{QuicVersion::MVFST}; uint64_t maxRecvPacketSize{kDefaultMaxUDPPayload}; uint64_t maxInitialStreamData{kDefaultStreamFlowControlWindow}; uint64_t connWindowSize{kDefaultConnectionFlowControlWindow}; uint64_t maxInitialStreamsBidi{std::numeric_limits<uint32_t>::max()}; uint64_t maxInitialStreamsUni{std::numeric_limits<uint32_t>::max()}; folly::Optional<ServerTransportParameters> params_; EnumArray<EncryptionLevel, BufQueue> readBuffers{}; std::unique_ptr<Aead> oneRttWriteCipher_; std::unique_ptr<PacketNumberCipher> oneRttWriteHeaderCipher_; FizzCryptoFactory cryptoFactory_; const CryptoFactory& getCryptoFactory() const override { return cryptoFactory_; } // Implement virtual methods we don't intend to use. bool isTLSResumed() const override { throw std::runtime_error("isTLSResumed not implemented"); } EncryptionLevel getReadRecordLayerEncryptionLevel() override { throw std::runtime_error( "getReadRecordLayerEncryptionLevel not implemented"); } const folly::Optional<std::string>& getApplicationProtocol() const override { throw std::runtime_error("getApplicationProtocol not implemented"); } void processSocketData(folly::IOBufQueue&) override { throw std::runtime_error("processSocketData not implemented"); } bool matchEarlyParameters() override { throw std::runtime_error("matchEarlyParameters not implemented"); } std::pair<std::unique_ptr<Aead>, std::unique_ptr<PacketNumberCipher>> buildCiphers(CipherKind, folly::ByteRange) override { throw std::runtime_error("buildCiphers not implemented"); } }; class QuicClientTransportTestBase : public virtual testing::Test { public: QuicClientTransportTestBase() : eventbase_(std::make_unique<folly::EventBase>()) {} virtual ~QuicClientTransportTestBase() = default; struct TestReadData { std::unique_ptr<folly::IOBuf> data; folly::SocketAddress addr; folly::Optional<int> err; TestReadData(folly::ByteRange dataIn, folly::SocketAddress addrIn) : data(folly::IOBuf::copyBuffer(dataIn)), addr(std::move(addrIn)) {} explicit TestReadData(int errIn) : err(errIn) {} }; std::shared_ptr<FizzClientQuicHandshakeContext> getFizzClientContext() { if (!fizzClientContext) { fizzClientContext = FizzClientQuicHandshakeContext::Builder() .setCertificateVerifier(createTestCertificateVerifier()) .setPskCache(getPskCache()) .build(); } return fizzClientContext; } virtual std::shared_ptr<QuicPskCache> getPskCache() { return nullptr; } void SetUp() { auto socket = std::make_unique<testing::NiceMock<folly::test::MockAsyncUDPSocket>>( eventbase_.get()); sock = socket.get(); client = TestingQuicClientTransport::newClient<TestingQuicClientTransport>( eventbase_.get(), std::move(socket), getFizzClientContext()); destructionCallback = std::make_shared<TestingQuicClientTransport::DestructionCallback>(); client->setDestructionCallback(destructionCallback); client->setSupportedVersions( {QuicVersion::MVFST, MVFST1, QuicVersion::QUIC_V1, QuicVersion::QUIC_V1_ALIAS, QuicVersion::QUIC_DRAFT}); connIdAlgo_ = std::make_unique<DefaultConnectionIdAlgo>(); ON_CALL(*sock, resumeRead(testing::_)) .WillByDefault(testing::SaveArg<0>(&networkReadCallback)); ON_CALL(*sock, address()).WillByDefault(testing::ReturnRef(serverAddr)); ON_CALL(*sock, recvmsg(testing::_, testing::_)) .WillByDefault(testing::Invoke([&](struct msghdr* msg, int) -> ssize_t { DCHECK_GT(msg->msg_iovlen, 0); if (socketReads.empty()) { errno = EAGAIN; return -1; } if (socketReads[0].err) { errno = *socketReads[0].err; return -1; } auto testData = std::move(socketReads[0].data); testData->coalesce(); size_t testDataLen = testData->length(); memcpy( msg->msg_iov[0].iov_base, testData->data(), testData->length()); if (msg->msg_name) { socklen_t msg_len = socketReads[0].addr.getAddress( static_cast<sockaddr_storage*>(msg->msg_name)); msg->msg_namelen = msg_len; } socketReads.pop_front(); return testDataLen; })); EXPECT_EQ(client->getConn().selfConnectionIds.size(), 1); EXPECT_EQ( client->getConn().selfConnectionIds[0].connId, *client->getConn().clientConnectionId); EXPECT_EQ(client->getConn().peerConnectionIds.size(), 0); quicStats_ = std::make_shared<testing::NiceMock<MockQuicStats>>(); client->setTransportStatsCallback(quicStats_); SetUpChild(); } virtual void SetUpChild() {} void startTransport() { client->addNewPeerAddress(serverAddr); client->setHostname(hostname_); ON_CALL(*sock, write(testing::_, testing::_)) .WillByDefault( testing::Invoke([&](const folly::SocketAddress&, const std::unique_ptr<folly::IOBuf>& buf) { socketWrites.push_back(buf->clone()); return buf->computeChainDataLength(); })); ON_CALL(*sock, address()).WillByDefault(testing::ReturnRef(serverAddr)); setupCryptoLayer(); start(); client->getNonConstConn().streamManager->setMaxLocalBidirectionalStreams( std::numeric_limits<uint32_t>::max()); client->getNonConstConn().streamManager->setMaxLocalUnidirectionalStreams( std::numeric_limits<uint32_t>::max()); } void destroyTransport() { client->unbindConnection(); client = nullptr; } QuicTransportBase* getTransport() { return client->getTransport(); } std::shared_ptr<TestingQuicClientTransport> getTestTransport() { return client; } const QuicClientConnectionState& getConn() const { return client->getConn(); } QuicClientConnectionState& getNonConstConn() { return client->getNonConstConn(); } MockConnectionSetupCallback& getConnSetupCallback() { return clientConnSetupCallback; } MockConnectionCallback& getConnCallback() { return clientConnCallback; } virtual void setupCryptoLayer() { // Fake that the handshake has already occurred and fix the keys. mockClientHandshake = new FakeOneRttHandshakeLayer( &client->getNonConstConn(), getFizzClientContext()); client->getNonConstConn().clientHandshakeLayer = mockClientHandshake; client->getNonConstConn().handshakeLayer.reset(mockClientHandshake); setFakeHandshakeCiphers(); // Allow ignoring path mtu for testing negotiation. client->getNonConstConn().transportSettings.canIgnorePathMTU = true; } virtual void setFakeHandshakeCiphers() { auto readAead = test::createNoOpAead(); auto writeAead = test::createNoOpAead(); auto handshakeReadAead = test::createNoOpAead(); auto handshakeWriteAead = test::createNoOpAead(); mockClientHandshake->setHandshakeReadCipher(std::move(handshakeReadAead)); mockClientHandshake->setHandshakeWriteCipher(std::move(handshakeWriteAead)); mockClientHandshake->setOneRttReadCipher(std::move(readAead)); mockClientHandshake->setOneRttWriteCipher(std::move(writeAead)); mockClientHandshake->setHandshakeReadHeaderCipher( test::createNoOpHeaderCipher()); mockClientHandshake->setHandshakeWriteHeaderCipher( test::createNoOpHeaderCipher()); mockClientHandshake->setOneRttWriteHeaderCipher( test::createNoOpHeaderCipher()); mockClientHandshake->setOneRttReadHeaderCipher( test::createNoOpHeaderCipher()); } virtual void setUpSocketExpectations() { EXPECT_CALL(*sock, setReuseAddr(false)); EXPECT_CALL(*sock, bind(testing::_, testing::_)); EXPECT_CALL(*sock, setDFAndTurnOffPMTU()); EXPECT_CALL(*sock, setErrMessageCallback(client.get())); EXPECT_CALL(*sock, resumeRead(client.get())); EXPECT_CALL(*sock, setErrMessageCallback(nullptr)); EXPECT_CALL(*sock, write(testing::_, testing::_)) .Times(testing::AtLeast(1)); } virtual void start() { EXPECT_CALL(clientConnSetupCallback, onTransportReady()); EXPECT_CALL(clientConnSetupCallback, onReplaySafe()); setUpSocketExpectations(); client->start(&clientConnSetupCallback, &clientConnCallback); setConnectionIds(); EXPECT_TRUE(client->idleTimeout().isScheduled()); EXPECT_EQ(socketWrites.size(), 1); EXPECT_TRUE( verifyLongHeader(*socketWrites.at(0), LongHeader::Types::Initial)); socketWrites.clear(); performFakeHandshake(); EXPECT_TRUE( client->getConn().readCodec->getStatelessResetToken().has_value()); EXPECT_TRUE(client->getConn().statelessResetToken.has_value()); } void setConnectionIds() { originalConnId = client->getConn().clientConnectionId; ServerConnectionIdParams params(0, 0, 0); serverChosenConnId = *connIdAlgo_->encodeConnectionId(params); } void recvServerHello(const folly::SocketAddress& addr) { auto serverHello = folly::IOBuf::copyBuffer("Fake SHLO"); PacketNum nextPacketNum = initialPacketNum++; auto& aead = getInitialCipher(); auto packet = packetToBufCleartext( createCryptoPacket( *serverChosenConnId, *originalConnId, nextPacketNum, version, ProtectionType::Initial, *serverHello, aead, 0 /* largestAcked */), aead, getInitialHeaderCipher(), nextPacketNum); deliverData(addr, packet->coalesce()); } ConnectionId recvServerRetry(const folly::SocketAddress& addr) { // Make the server send a retry packet to the client. The server chooses a // connection id that the client must use in all future initial packets. std::vector<uint8_t> serverConnIdVec = { 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5}; ConnectionId serverCid(serverConnIdVec); std::string retryToken = "token"; std::string integrityTag = "\xd1\x69\x26\xd8\x1f\x6f\x9c\xa2\x95\x3a\x8a\xa4\x57\x5e\x1e\x49"; folly::IOBuf retryPacketBuf; BufAppender appender(&retryPacketBuf, 100); appender.writeBE<uint8_t>(0xFF); appender.writeBE<QuicVersionType>(static_cast<QuicVersionType>(0xFF00001D)); appender.writeBE<uint8_t>(0); appender.writeBE<uint8_t>(serverConnIdVec.size()); appender.push(serverConnIdVec.data(), serverConnIdVec.size()); appender.push((const uint8_t*)retryToken.data(), retryToken.size()); appender.push((const uint8_t*)integrityTag.data(), integrityTag.size()); deliverData(addr, retryPacketBuf.coalesce()); return serverCid; } void recvServerHello() { recvServerHello(serverAddr); } void recvTicket(folly::Optional<uint64_t> offsetOverride = folly::none) { auto negotiatedVersion = *client->getConn().version; auto ticket = folly::IOBuf::copyBuffer("NST"); auto packet = packetToBuf(createCryptoPacket( *serverChosenConnId, *originalConnId, appDataPacketNum++, negotiatedVersion, ProtectionType::KeyPhaseZero, *ticket, *createNoOpAead(), 0 /* largestAcked */, offsetOverride ? *offsetOverride : client->getConn().cryptoState->oneRttStream.currentReadOffset)); deliverData(packet->coalesce()); } void performFakeHandshake(const folly::SocketAddress& addr) { // Create a fake server response to trigger fetching keys. recvServerHello(addr); assertWritten(false, LongHeader::Types::Handshake); verifyTransportParameters( kDefaultConnectionFlowControlWindow, kDefaultStreamFlowControlWindow, kDefaultIdleTimeout, kDefaultAckDelayExponent, mockClientHandshake->maxRecvPacketSize); verifyCiphers(); socketWrites.clear(); } void performFakeHandshake() { performFakeHandshake(serverAddr); } void verifyTransportParameters( uint64_t connFlowControl, uint64_t initialStreamFlowControl, std::chrono::milliseconds idleTimeout, uint64_t ackDelayExponent, uint64_t maxPacketSize) { EXPECT_EQ( client->getConn().flowControlState.peerAdvertisedMaxOffset, connFlowControl); EXPECT_EQ( client->getConn() .flowControlState.peerAdvertisedInitialMaxStreamOffsetBidiLocal, initialStreamFlowControl); EXPECT_EQ( client->getConn() .flowControlState.peerAdvertisedInitialMaxStreamOffsetBidiRemote, initialStreamFlowControl); EXPECT_EQ( client->getConn() .flowControlState.peerAdvertisedInitialMaxStreamOffsetUni, initialStreamFlowControl); EXPECT_EQ(client->getConn().peerIdleTimeout.count(), idleTimeout.count()); EXPECT_EQ(client->getConn().peerAckDelayExponent, ackDelayExponent); EXPECT_EQ(client->getConn().udpSendPacketLen, maxPacketSize); } void verifyCiphers() { EXPECT_NE(client->getConn().oneRttWriteCipher, nullptr); EXPECT_NE(client->getConn().handshakeWriteCipher, nullptr); EXPECT_NE(client->getConn().handshakeWriteHeaderCipher, nullptr); EXPECT_NE(client->getConn().oneRttWriteHeaderCipher, nullptr); EXPECT_NE(client->getConn().readCodec->getHandshakeHeaderCipher(), nullptr); EXPECT_NE(client->getConn().readCodec->getOneRttHeaderCipher(), nullptr); } void deliverNetworkError(int err) { ASSERT_TRUE(networkReadCallback); socketReads.emplace_back(err); networkReadCallback->onNotifyDataAvailable(*sock); } void deliverDataWithoutErrorCheck( const folly::SocketAddress& addr, folly::ByteRange data, bool writes = true) { ASSERT_TRUE(networkReadCallback); socketReads.emplace_back(data, addr); networkReadCallback->onNotifyDataAvailable(*sock); if (writes) { loopForWrites(); } } void deliverDataWithoutErrorCheck( folly::ByteRange data, bool writes = true, folly::SocketAddress* peer = nullptr) { deliverDataWithoutErrorCheck( peer == nullptr ? serverAddr : *peer, data, writes); } void deliverDataWithoutErrorCheck( NetworkData&& data, bool writes = true, folly::SocketAddress* peer = nullptr) { for (const auto& packetBuf : data.packets) { deliverDataWithoutErrorCheck( peer == nullptr ? serverAddr : *peer, packetBuf->coalesce(), writes); } } void deliverData( const folly::SocketAddress& addr, folly::ByteRange data, bool writes = true) { deliverDataWithoutErrorCheck(addr, data, writes); if (client->getConn().localConnectionError) { bool idleTimeout = false; const LocalErrorCode* localError = client->getConn().localConnectionError->code.asLocalErrorCode(); if (localError) { idleTimeout = (*localError == LocalErrorCode::IDLE_TIMEOUT); } if (!idleTimeout) { throw std::runtime_error( toString(client->getConn().localConnectionError->code)); } } } void deliverData( folly::ByteRange data, bool writes = true, folly::SocketAddress* peer = nullptr) { deliverData(peer == nullptr ? serverAddr : *peer, data, writes); } void deliverData( NetworkData&& data, bool writes = true, folly::SocketAddress* peer = nullptr) { for (const auto& packetBuf : data.packets) { deliverData( peer == nullptr ? serverAddr : *peer, packetBuf->coalesce(), writes); } } void loopForWrites() { // Loop the evb once to give writes some time to do their thing. eventbase_->loopOnce(EVLOOP_NONBLOCK); } void assertWritten( bool shortHeader, folly::Optional<LongHeader::Types> longHeader) { size_t numShort = 0; size_t numLong = 0; size_t numOthers = 0; if (!socketWrites.empty()) { auto& write = socketWrites.back(); if (shortHeader && verifyShortHeader(*write)) { numShort++; } else if (longHeader && verifyLongHeader(*write, *longHeader)) { numLong++; } else { numOthers++; } } if (shortHeader) { EXPECT_GT(numShort, 0); } if (longHeader) { EXPECT_GT(numLong, 0); } EXPECT_EQ(numOthers, 0); } RegularQuicPacket* parseRegularQuicPacket(CodecResult& codecResult) { return codecResult.regularPacket(); } void verifyShortPackets(AckBlocks& sentPackets) { AckStates ackStates; for (auto& write : socketWrites) { auto packetQueue = bufToQueue(write->clone()); auto codecResult = makeEncryptedCodec(true)->parsePacket(packetQueue, ackStates); auto parsedPacket = parseRegularQuicPacket(codecResult); if (!parsedPacket) { continue; } PacketNum packetNumSent = parsedPacket->header.getPacketSequenceNum(); sentPackets.insert(packetNumSent); verifyShortHeader(*write); } } bool verifyLongHeader( folly::IOBuf& buf, typename LongHeader::Types headerType) { AckStates ackStates; auto packetQueue = bufToQueue(buf.clone()); auto codecResult = makeEncryptedCodec(true)->parsePacket(packetQueue, ackStates); auto parsedPacket = parseRegularQuicPacket(codecResult); if (!parsedPacket) { return false; } auto longHeader = parsedPacket->header.asLong(); return longHeader && longHeader->getHeaderType() == headerType; } bool verifyShortHeader(folly::IOBuf& buf) { AckStates ackStates; auto packetQueue = bufToQueue(buf.clone()); auto codecResult = makeEncryptedCodec(true)->parsePacket(packetQueue, ackStates); auto parsedPacket = parseRegularQuicPacket(codecResult); if (!parsedPacket) { return false; } return parsedPacket->header.asShort(); } std::unique_ptr<QuicReadCodec> makeHandshakeCodec() { FizzCryptoFactory cryptoFactory; auto codec = std::make_unique<QuicReadCodec>(QuicNodeType::Server); codec->setClientConnectionId(*originalConnId); codec->setInitialReadCipher(cryptoFactory.getClientInitialCipher( *client->getConn().initialDestinationConnectionId, QuicVersion::MVFST)); codec->setInitialHeaderCipher(cryptoFactory.makeClientInitialHeaderCipher( *client->getConn().initialDestinationConnectionId, QuicVersion::MVFST)); codec->setHandshakeReadCipher(test::createNoOpAead()); codec->setHandshakeHeaderCipher(test::createNoOpHeaderCipher()); return codec; } std::unique_ptr<QuicReadCodec> makeEncryptedCodec( bool handshakeCipher = false) { FizzCryptoFactory cryptoFactory; auto codec = std::make_unique<QuicReadCodec>(QuicNodeType::Server); std::unique_ptr<Aead> handshakeReadCipher; codec->setClientConnectionId(*originalConnId); codec->setOneRttReadCipher(test::createNoOpAead()); codec->setOneRttHeaderCipher(test::createNoOpHeaderCipher()); codec->setZeroRttReadCipher(test::createNoOpAead()); codec->setZeroRttHeaderCipher(test::createNoOpHeaderCipher()); if (handshakeCipher) { codec->setInitialReadCipher(cryptoFactory.getClientInitialCipher( *client->getConn().initialDestinationConnectionId, QuicVersion::MVFST)); codec->setInitialHeaderCipher(cryptoFactory.makeClientInitialHeaderCipher( *client->getConn().initialDestinationConnectionId, QuicVersion::MVFST)); codec->setHandshakeReadCipher(test::createNoOpAead()); codec->setHandshakeHeaderCipher(test::createNoOpHeaderCipher()); } return codec; } const Aead& getInitialCipher() { return *client->getConn().readCodec->getInitialCipher(); } const PacketNumberCipher& getInitialHeaderCipher() { return *client->getConn().readCodec->getInitialHeaderCipher(); } void expectQuicStatsPacketDrop(PacketDropReason expectedReason) { quicStats_ = std::make_shared<testing::NiceMock<MockQuicStats>>(); EXPECT_CALL(*quicStats_, onPacketDropped(testing::_)) .WillOnce(testing::Invoke([=](PacketDropReason reason) { EXPECT_EQ(expectedReason, reason); })); client->setTransportStatsCallback(quicStats_); } protected: std::vector<std::unique_ptr<folly::IOBuf>> socketWrites; std::deque<TestReadData> socketReads; testing::NiceMock<MockDeliveryCallback> deliveryCallback; testing::NiceMock<MockReadCallback> readCb; testing::NiceMock<MockConnectionSetupCallback> clientConnSetupCallback; testing::NiceMock<MockConnectionCallback> clientConnCallback; folly::test::MockAsyncUDPSocket* sock; std::shared_ptr<TestingQuicClientTransport::DestructionCallback> destructionCallback; std::unique_ptr<folly::EventBase> eventbase_; folly::SocketAddress serverAddr{"127.0.0.1", 443}; QuicAsyncUDPSocketWrapper::ReadCallback* networkReadCallback{nullptr}; FakeOneRttHandshakeLayer* mockClientHandshake; std::shared_ptr<FizzClientQuicHandshakeContext> fizzClientContext; std::shared_ptr<TestingQuicClientTransport> client; PacketNum initialPacketNum{0}, handshakePacketNum{0}, appDataPacketNum{0}; std::unique_ptr<ConnectionIdAlgo> connIdAlgo_; folly::Optional<ConnectionId> originalConnId; folly::Optional<ConnectionId> serverChosenConnId; QuicVersion version{QuicVersion::QUIC_V1}; std::shared_ptr<testing::NiceMock<MockQuicStats>> quicStats_; std::string hostname_{"TestHost"}; }; class QuicClientTransportAfterStartTestBase : public QuicClientTransportTestBase { public: void SetUpChild() override { startTransport(); } }; } // namespace quic::test
// // main.cpp // Homework 1 // // Created by Hender Lin on 4/11/21. // #include <iostream> #include <string> #include "Set.h" using namespace std; Set::Set() { m_length = 0; } bool Set::empty() const { if (m_length == 0) { return true; } return false; } int Set::size() const { return m_length; } bool Set::insert(const ItemType& value) { if (m_length >= DEFAULT_MAX_ITEMS) { return false; } if (m_length == 0) { m_set[0] = value; m_length++; return true; } if (contains(value)) { return false; } for (int i = 0; i < m_length; i++) { if (m_set[i] > value) { for (int j = m_length; j > i; j--) { m_set[j] = m_set[j - 1]; } m_set[i] = value; m_length++; return true; } } m_set[m_length] = value; m_length++; return true; } bool Set::erase(const ItemType& value) { for (int i = 0; i < m_length; i++) { if (m_set[i] == value) { for (int j = i; j < m_length - 1; j++) { m_set[j] = m_set[j + 1]; } m_length--; return true; } } return false; } bool Set::contains(const ItemType& value) const { for (int i = 0; i < m_length; i++) { if (m_set[i] == value) { return true; } } return false; } bool Set::get(int i, ItemType& value) const { if (i < 0 || i >= m_length) { return false; } value = m_set[m_length-1-i]; return true; } void Set::swap(Set& other) { int max; if (this->size() > other.size()) { max = this->size(); } else { max = other.size(); } for (int i = 0; i < max; i++) { std::swap(this->m_set[i], other.m_set[i]); } std::swap(this->m_length, other.m_length); }