text
string
size
int64
token_count
int64
// The MIT License (MIT) // // Copyright (c) 2017 Henk-Jan Lebbink // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <stdio.h> // for printf // stdio functions are used since C++ streams aren't necessarily thread safe //#include <intrin.h> // needed for compiler intrinsics #include <array> #include "../../Spike-Tools-LIB/SpikeSet1Sec.hpp" #include "../../Spike-Tools-LIB/Constants.hpp" #include "../../Spike-Izhikevich-LIB/SpikeTypesIzhikevich.hpp" namespace spike { namespace v1 { static inline int ltpIndex(const int neuronId, const int time, const int N) { return (time * N) + neuronId; } template <size_t nNeurons> static inline void updateState_X64_Blitz(float v[], float u[], const float ic[], const float is[], const float a[]) { for (size_t i = 0; i < nNeurons; ++i) { const float tt = 140 - u[i] + (is[i] * ic[i]); //const float tt = 140 - u[i] + ic[i]; v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + tt); // for numerical stability v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + tt); // time step is 0.5 ms u[i] += a[i] * ((0.2f * v[i]) - u[i]); } } template <size_t nNeurons> static inline void updateState_X64(float v[], float u[], const float ic[], const float is[], const float a[], const float b[]) { //__debugbreak(); //#pragma loop(hint_parallel(4)) for (size_t i = 0; i < nNeurons; ++i) { BOOST_ASSERT_MSG_HJ(!std::isfinite(v[i]), "v[" << i << "] is not finite"); BOOST_ASSERT_MSG_HJ(!std::isfinite(u[i]), "u[" << i << "] is not finite"); //const float tt = 140 - u[i] + (is[i] * ic[i]); const float tt = 140 - u[i] + ic[i]; v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + tt); // for numerical stability v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + tt); // time step is 0.5 ms u[i] += a[i] * ((b[i] * v[i]) - u[i]); if (u[i] > 50) { u[i] = 50; } if (v[i] > 100) { v[i] = 100; } } } template <size_t N, size_t D> static inline void updateStdp_X64(const unsigned int t, float ltd[N], float ltp[N][1001 + D]) { for (unsigned int i = 0; i < N; ++i) { ltd[i] *= 0.95f; ltp[i][t + D + 1] = 0.95f * ltp[i][t + D]; } } template <size_t nNeurons> static inline void updateState_Sse(float v[], float u[], const float ic[], const float is[], const float a[], const float b[]) { const __m128 c1 = _mm_set1_ps(0.5f); const __m128 c2 = _mm_set1_ps(0.04f); const __m128 c3 = _mm_set1_ps(5.0f); const __m128 c4 = _mm_set1_ps(140.0f); for (size_t i = 0; i < nNeurons; i += 4) { const __m128 ici = _mm_load_ps(&ic[i]); //const __m128 isi = _mm_load_ps(&is[i]); __m128 vi = _mm_load_ps(&v[i]); __m128 ui = _mm_load_ps(&u[i]); // + 140 - u[i] + (is[i] * ic[i]) // const __m128 tt = _mm_add_ps(_mm_sub_ps(_mm_mul_ps(isi, ici), ui), c4); // + 140 - u[i] + ic[i] const __m128 tt = _mm_add_ps(_mm_sub_ps(ici, ui), c4); ////////////////////////////////////////// // v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + tt); // for numerical stability const __m128 x1a = _mm_mul_ps(vi, c2); const __m128 x2a = _mm_add_ps(x1a, c3); const __m128 x3a = _mm_mul_ps(x2a, vi); const __m128 x4a = _mm_add_ps(x3a, tt); const __m128 x5a = _mm_mul_ps(x4a, c1); vi = _mm_add_ps(x5a, vi); ////////////////////////////////////////// // v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + tt); // time step is 0.5 ms const __m128 x1b = _mm_mul_ps(vi, c2); const __m128 x2b = _mm_add_ps(x1b, c3); const __m128 x3b = _mm_mul_ps(x2b, vi); const __m128 x4b = _mm_add_ps(x3b, tt); const __m128 x5b = _mm_mul_ps(x4b, c1); vi = _mm_add_ps(x5b, vi); ////////////////////////////////////////// // u[i] += a[i] * ((b[i] * v[i]) - u[i]); const __m128 bi = _mm_load_ps(&b[i]); const __m128 y1 = _mm_mul_ps(vi, bi); const __m128 y2 = _mm_sub_ps(y1, ui); const __m128 ai = _mm_load_ps(&a[i]); const __m128 y3 = _mm_mul_ps(y2, ai); ui = _mm_add_ps(y3, ui); /* BOOST_ASSERT_MSG_HJ(std::isfinite(vi.m128_f32[0]), "v[" << i << "][0] = " << vi.m128_f32[0] << " is not finite"); BOOST_ASSERT_MSG_HJ(std::isfinite(vi.m128_f32[1]), "v[" << i << "][1] = " << vi.m128_f32[1] << " is not finite"); BOOST_ASSERT_MSG_HJ(std::isfinite(vi.m128_f32[2]), "v[" << i << "][2] = " << vi.m128_f32[2] << " is not finite"); BOOST_ASSERT_MSG_HJ(std::isfinite(vi.m128_f32[3]), "v[" << i << "][3] = " << vi.m128_f32[3] << " is not finite"); BOOST_ASSERT_MSG_HJ(std::isfinite(ui.m128_f32[0]), "u[" << i << "][0] = " << ui.m128_f32[0] << " is not finite"); BOOST_ASSERT_MSG_HJ(std::isfinite(ui.m128_f32[1]), "u[" << i << "][1] = " << ui.m128_f32[1] << " is not finite"); BOOST_ASSERT_MSG_HJ(std::isfinite(ui.m128_f32[2]), "u[" << i << "][2] = " << ui.m128_f32[2] << " is not finite"); BOOST_ASSERT_MSG_HJ(std::isfinite(ui.m128_f32[3]), "u[" << i << "][3] = " << ui.m128_f32[3] << " is not finite"); */ _mm_store_ps(&v[i], vi); _mm_store_ps(&u[i], ui); } } template <size_t N, Delay D> static inline void updateStdp_Sse(const unsigned int t, float ltd[N], float ltp[N][1001 + D]) { for (unsigned int i = 0; i < N; i += 4) { // ltd[i] *= 0.95f; _mm_store_ps(&ltd[i], _mm_mul_ps(_mm_set1_ps(0.95f), _mm_load_ps(&ltd[i]))); // ltp[ltpIndex(i, t+D+1)+0] = 0.95f * ltp[ltpIndex(i, t+D)+0]; _mm_store_ps(&ltp[i][t + D + 1], _mm_mul_ps(_mm_set1_ps(0.95f), _mm_load_ps(&ltp[i][t + D]))); } } template <size_t nNeurons> static inline void updateState_Avx(float v[], float u[], const float ic[], const float is[], const float a[]) { for (size_t i = 0; i < nNeurons; i += 8) { const __m256 ai = _mm256_load_ps(&a[i]); const __m256 ici = _mm256_load_ps(&ic[i]); const __m256 isi = _mm256_load_ps(&is[i]); __m256 vi = _mm256_load_ps(&v[i]); __m256 ui = _mm256_load_ps(&u[i]); const __m256 c1 = _mm256_set1_ps(0.5f); const __m256 c2 = _mm256_set1_ps(0.04f); const __m256 c3 = _mm256_set1_ps(5.0f); const __m256 c4 = _mm256_set1_ps(140.0f); // + 140 - u[i] + (is[i] * ic[i]) // const __m256 tt = _mm256_add_ps(_mm256_sub_ps(_mm256_mul_ps(isi, ici), ui), c4); // + 140 - u[i] + ic[i] const __m256 tt = _mm256_add_ps(_mm256_sub_ps(ici, ui), c4); ////////////////////////////////////////// // v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + 140 - u[i] + ic[i]); // for numerical stability const __m256 x1a = _mm256_mul_ps(vi, c2); const __m256 x2a = _mm256_add_ps(x1a, c3); const __m256 x3a = _mm256_mul_ps(x2a, vi); const __m256 x4a = _mm256_add_ps(x3a, tt); const __m256 x5a = _mm256_mul_ps(x4a, c1); vi = _mm256_add_ps(x5a, vi); ////////////////////////////////////////// // v[i] += 0.5f * ((((0.04f * v[i]) + 5) * v[i]) + 140 - u[i] + ic[i]); // time step is 0.5 ms const __m256 x1b = _mm256_mul_ps(vi, c2); const __m256 x2b = _mm256_add_ps(x1b, c3); const __m256 x3b = _mm256_mul_ps(x2b, vi); const __m256 x4b = _mm256_add_ps(x3b, tt); const __m256 x5b = _mm256_mul_ps(x4b, c1); vi = _mm256_add_ps(x5b, vi); ////////////////////////////////////////// // u[i] += a[i] * ((0.2f * v[i]) - u[i]); const __m256 c5 = _mm256_set1_ps(0.2f); const __m256 y1 = _mm256_mul_ps(vi, c5); const __m256 y2 = _mm256_sub_ps(y1, ui); const __m256 y3 = _mm256_mul_ps(y2, ai); ui = _mm256_add_ps(y3, ui); _mm256_store_ps(&v[i], vi); _mm256_store_ps(&u[i], ui); } } template <size_t nNeurons, Delay D> static inline void updateStdp_Avx(const unsigned int t, float ltd[], float ltp[][1001 + D]) { for (unsigned int i = 0; i < nNeurons; i += 8) { // ltd[i] *= 0.95f; _mm256_store_ps(&ltd[i], _mm256_mul_ps(_mm256_set1_ps(0.95f), _mm256_load_ps(&ltd[i]))); // ltp[ltpIndex(i, t+D+1)+0] = 0.95f * ltp[ltpIndex(i, t+D)+0]; _mm256_store_ps(&ltp[i][t + D + 1], _mm256_mul_ps(_mm256_set1_ps(0.95f), _mm256_load_ps(&ltp[i][t + D]))); } } } }
9,122
4,927
#include "stdafx.h" #include <iostream> #include <stdexcept> #include "Database.h" #include"pch.h" #include "Flight.h" using namespace std; namespace AirlineRSystem { void Database::addFlight(Flight& flight) { mflights.push_back(flight); } Flight& Database::getFlight(int flightno) { for (auto& flight : mflights) { if (flight.Getflightno() == flightno) { return flight; } } throw logic_error("This flight number doesn't exist, please check your records."); } vector<Flight>& Database::getallFlights() { return mflights; } }
558
225
#include <iostream> using namespace std; class Box { int l, b, h; public: void set_dimension(int x, int y, int z) { l = x; b = y; h = z; } void show_dimension() { cout << "l = " << l << " b = " << b << " h = " << h << endl; } }; int main(void) { Box *p, small_box; p = &small_box; p->set_dimension(12, 10, 5); p->show_dimension(); return 0; }
418
173
#include <bits/stdc++.h> using namespace std; #define pb push_back typedef long long ll; const ll INF = 1000000000000000000ll; const ll MOD = 1000000007ll; const double EPS = 1e-8; int main(void) { //ios_base::sync_with_stdio(false); //cin.tie(0); return 0; }
276
139
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2013 LRI UMR 8623 CNRS/Univ Paris Sud XI // Copyright 2011 - 2013 MetaScale SAS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_FORWARD_ALLOCATOR_HPP_INCLUDED #define BOOST_SIMD_FORWARD_ALLOCATOR_HPP_INCLUDED #include <boost/simd/preprocessor/parameters.hpp> #if !defined(DOXYGEN_ONLY) namespace boost { namespace simd { template<typename T, std::size_t N = BOOST_SIMD_CONFIG_ALIGNMENT> struct allocator; template<typename A, std::size_t N = BOOST_SIMD_CONFIG_ALIGNMENT> struct allocator_adaptor; } } #endif #endif
976
347
// // main.cpp // 35 - Search Insert Position // // Created by ynfMac on 2019/6/26. // Copyright © 2019 ynfMac. All rights reserved. // 直接一趟循环根据值的大小进行比较 时间复杂度0(n),空间复杂度0(1) #include <iostream> #include <vector> using namespace std; class Solution { public: int searchInsert(vector<int> &nums, int target){ int length = nums.size(); if( length == 0 ){ return 0;} if(target <= nums[0]) { return 0; } for(int i = 1; i < length;i ++) { if ( target == nums[i] || target > nums[i - 1] && target < nums[i] ) { return i; } } return length; } }; int main(int argc, const char * argv[]) { // insert code here... vector<int> a = vector<int>{1,3,5,6}; cout << Solution().searchInsert(a, 5); std::cout << "Hello, World!\n"; return 0; }
870
351
#include "CNetworkServerDispatcher.h" #include "CNetworkServer.h" #include "CLog.h" #include <boost/tokenizer.hpp> #include <vector> #include <string> /////////////////////////////////////////////////////////////////////////////// /// \brief Constructs a dispatcher /////////////////////////////////////////////////////////////////////////////// CNetworkServerDispatcher::CNetworkServerDispatcher(CNetworkServer *owner) : m_owner(owner), m_methodTable() { /// Fill in the table of commands to handle in this state /// m_methodTable["LOGIN"] = boost::bind(&CWaitForPlayers_Dispatcher::handleLogin, this, _1, _2); } /////////////////////////////////////////////////////////////////////////////// /// \brief Destructs a dispatcher /////////////////////////////////////////////////////////////////////////////// CNetworkServerDispatcher::~CNetworkServerDispatcher() { } /////////////////////////////////////////////////////////////////////////////// /// \brief Runs operations for this state of the dispatcher /// /// \returns Next dispatcher that will continue event processing /////////////////////////////////////////////////////////////////////////////// CNetworkServerDispatcher* CNetworkServerDispatcher::run(){ return this; } /////////////////////////////////////////////////////////////////////////////// /// \brief Manages client connetion events /// /// \param event Enet event struct with all the information of the connection /////////////////////////////////////////////////////////////////////////////// void CNetworkServerDispatcher::onConnect(const ENetEvent& event) { m_owner->addClient(event.peer); CLOG.print("DISPATCHER: New client connected from [%u:%u]\n", event.peer->address.host, event.peer->address.port); } /////////////////////////////////////////////////////////////////////////////// /// \brief Manages reception of client messages /// /// \param event Enet event struct with all the information about the message /////////////////////////////////////////////////////////////////////////////// void CNetworkServerDispatcher::onReceiveMessage(const ENetEvent& event) { CLOG.print("DISPATCHER: [%s] received from %u:%u (%s) \n", event.packet->data, event.peer->address.host, event.peer->address.port, event.peer->data); } /////////////////////////////////////////////////////////////////////////////// /// \brief Manages client disconnections /// /// \param event Enet event struct with all the information about the disconnection /////////////////////////////////////////////////////////////////////////////// void CNetworkServerDispatcher::onDisconnect(const ENetEvent& event) { m_owner->removeClient(event.peer); CLOG.print("DISPATCHER: Client disconnected [%u:%u]\n", event.peer->address.host, event.peer->address.port); } /////////////////////////////////////////////////////////////////////////////// /// \brief Analizes an incoming message from a client and calls a handle if any /// /// This method analizes an incoming message from a client and generates /// corresponding method call to handle the message, if there is a defined /// handler. /// /// \param event Enet event struct with all the information about the message /////////////////////////////////////////////////////////////////////////////// void CNetworkServerDispatcher::analizeAndHandleMessage(const ENetEvent &event) { // Get the client, if exists. If it does not exist, we ignore it. NSClient *c = m_owner->getClient(event.peer); if ( c ) { // Tokenize input std::vector<std::string> vTokens; std::string str((const char*)event.packet->data); boost::tokenizer<> t(str); boost::tokenizer<>::iterator it = t.begin(); CLOG.print("DISPATCHER[TOKENIZING]: %s\n", str.c_str()); while (it != t.end()) { CLOG.print("DISPATCHER[TOKEN]: %s\n", it->c_str()); vTokens.push_back(*it); it++; } // Call handler method if correct syntax (COMMAND ARG) if (vTokens.size() == 2 && m_methodTable.count(vTokens[0]) ) { m_methodTable[vTokens[0]](*c, vTokens[1]); } else { defaultMessageHandler(*c, str); } } } /////////////////////////////////////////////////////////////////////////////// /// \brief Handles messages by default, when no other handle does. /// /// This method is intended to be called to handle messages comming from client /// when no other handle is available to handle them. This is, if the server /// receives an erroneous or unexpected message, this handle will take care /// to notify the client and or take necessary actions. /// Default action will be to notify them of their error and disconnect them. /// /// \param c Client sending the message /// \param str String with the complete message received /////////////////////////////////////////////////////////////////////////////// void CNetworkServerDispatcher::defaultMessageHandler(NSClient &c, std::string str) { // Notify the client of incorrect message and disconnect m_owner->disconnect(c, "ERROR 1 Message_Incorrect_or_Unexpected (" + str + ")"); } /////////////////////////////////////////////////////////////////////////////// /// \brief Sets the server that owns this dispatcher /// /// \param owner The server that now owns this dispatcher /////////////////////////////////////////////////////////////////////////////// void CNetworkServerDispatcher::setOwner(CNetworkServer* owner) { m_owner = owner; }
5,581
1,360
#include <iostream> #include <fstream> #include <vector> #include <string> #include <cstdlib> #include <algorithm> #include <queue> using namespace std; /* Dane wczytywane z pliku: n - ilosc zadan r - termin dostepnosci p - czas obslugi q - czas dostarczenia */ /* Klasa modelujaca obiekt zadania, przechowuje informacje o czasie przybycia, wykonania (poczatkowym i pozostalym) i dostarczenia zadania oraz zmienne typu bool mowiace o tym czy dane zadanie jest juz gotowe oraz czy zostalo juz wykonane. Nie zawiera metod, wylacznie konstruktory. */ class Zadanie { public: int _r, _p, _q, _s, _k, _f, _z; bool _done, _ready; Zadanie() {_r = _p = _s = _q = _f = _z =0; _done = false; _ready = false;} Zadanie(int R, int P, int Q) { _r = R; // czas przybycia _p = P; // czas wykonania _q = Q; // czas dostarczenia _s = _r; // czas startu _z = _p; // czas pozostaly do wykonania _k = _s + _p; // czas zakonczenia _f = _k + _q; // moment dostarczenia _done = false; // czy zostalo juz wykonane _ready = false; // czy jest juz gotowe do wykonania } }; /* Funkcja sprawdzajaca czy wszystkie zadania z wektora podanego jako argument zostaly juz wykonane. */ bool czyWszystkie(vector<Zadanie> wektor) { for (int i = 0; i < wektor.size(); i++) if (!wektor[i]._done) return false; return true; } /* Funkcja porownujaca czasy przybycia dwoch podanych jako argumenty zadan. */ bool porownajR(Zadanie zad1, Zadanie zad2) { return zad1._r < zad2._r; } /* Struktura sluzaca do porwnywania dwoch zadan i szeregowania ich wg malejacego Q. */ struct porownajQ { bool operator () (Zadanie zad1, Zadanie zad2) { return zad1._q < zad2._q; } }; /* Funkcja sortujaca podany jako argument wektor rosnaco wg R. Uzywa funkcji bilbiotecznej sort. */ void sortowanie(vector<Zadanie> &wektor) { sort(wektor.begin(),wektor.end(),porownajR); } /* Funkcja sprawdzajaca czy plik o nazwie podanej jako argument istnieje. */ bool plikIstnieje(const char *fileName) { fstream infile(fileName); return infile.good(); } /* Funkcja generujaca plik z rozwiazaniem - podanym jako argument wynikiem. */ void generujPlikZRozwiazaniem(int wynik) { if (plikIstnieje("wynik.txt")) remove("wynik.txt"); ofstream PLIK("wynik.txt"); PLIK << wynik; PLIK.close(); } /* Funkcja wczytujaca dane z zadanego pliku do podanego jako argument wektora. */ bool wczytaj(vector<Zadanie> &wektor) { Zadanie noweZadanie; // zmienna pomocnicza do wczytywania zadan fstream PlikDanych; // strumien plikowy - udostepnia plik z danymi int r, p, q, n; char nazwa[32]; cout << endl << "Podaj nazwe pliku z danymi: "; // pobranie nazwy pliku od uzytkownika scanf("%s",nazwa); if (!plikIstnieje(nazwa)) { // zabezpieczenie przed bledna nazwa pliku cout << "Bledna nazwa pliku." << endl; return false; } PlikDanych.open(nazwa,ios::in); // otwarcie pliku z danymi w trybie do odczytu PlikDanych >> n; cout << endl << "Wczytuje " << n << " danych" << endl; for (int i = 0; i < n; i++) { // wrzucanie kolejnych zadan do wektora PlikDanych >> r; PlikDanych >> p; PlikDanych >> q; wektor.push_back(Zadanie(r,p,q)); } PlikDanych.close(); // zamkniecie strumienia plikowego return true; } /* Funkcja wypisujaca na standardowe wyjscie zawartosc podanego jako argument wektora - listy zadan, w formacie "R P Q". */ void wypisz(vector<Zadanie> &wektor) { for (int i = 0; i < wektor.size(); i++) cout << wektor[i]._r << " " << wektor[i]._p << " " << wektor[i]._q << endl; } void wykonane(vector<Zadanie> &wektor, Zadanie zad, int czas) { for (int i = 0; i < wektor.size(); i++) if (wektor[i]._r == zad._r && wektor[i]._p == zad._p && wektor[i]._q == zad._q) { wektor[i]._done = true; wektor[i]._k = czas; wektor[i]._f = wektor[i]._k + wektor[i]._q; return; } } /* Funkcja implementujaca algorytm Schrage. Jako argument przyjmuje wektor przechowujacy liste wszystkich zadan. */ int schrageP(vector<Zadanie> &wektor) { int czas = -1; // zmienna przechowujaca obecny czas priority_queue<Zadanie,vector<Zadanie>,porownajQ> gotowe; // kolejka priorytetowa zadan gotowych do wykonania sortowanie(wektor); // sortowanie zadan wg R for (czas = 0; !czyWszystkie(wektor); czas++) { // petle wykonujemy dopoki wszystkie zadania nie zostana wykonane for (int i = 0; i < wektor.size() && wektor[i]._r <= czas; i++) if (!wektor[i]._ready) { wektor[i]._ready = true; // dodawanie zadan do zbioru gotowych do wykonania gotowe.push(wektor[i]); } if (!gotowe.empty()) { // jesli istnieje zadanie do wykonania to robimy jeden takt Zadanie pom = gotowe.top(); gotowe.pop(); pom._z--; if (pom._z > 0) gotowe.push(pom); // jesli to jeszcze nie koniec zadania to wraca do kolejki else wykonane(wektor,pom,czas+1); // zaznaczanie ze zadanie zostalo wykonane } } for (int i = 0; i < wektor.size(); i++) // szukamy czasu dostarczenia ktory moglby wydluzyc koncowy czas if (wektor[i]._f > czas) czas = wektor[i]._f; return czas; } int main() { int wynik; // zmienna przechowujaca koncowy wynik vector<Zadanie> ListaZadan; // wektor przechowujacy wszystkie zadania if (!wczytaj(ListaZadan)) // w przypadku nieudanego wczytania pliku konczymy dzialanie programu return -1; wynik = schrageP(ListaZadan); // wywolanie wlasciwego algorytmu cout << endl << "Dostarczenie ostatniego zadania: " << wynik << endl << endl; // wyswietlenie wyniku generujPlikZRozwiazaniem(wynik); // generowanie pliku z wynikiem return 0; }
5,553
2,447
/** * # 'This' keyword is a OBJECT POINTER present inside the INSTANCE_MEMBER FUNCTION * block of a CLASS and it stores the ADDRESS of CALLER OBJECT. * * # It's value cannot be modified. * * # USES : * -> used to refer current class instance variable / When local variable’s name is same as member’s name * -> To return reference to the calling object * -> To pass refrence of itself as an arguement * */ #include<bits/stdc++.h> using namespace std; class Demo { private : Demo* caller_ob_ref; Demo* other_ob_ref; public : Demo () { caller_ob_ref = this; other_ob_ref = NULL; } // Refrencing current object reference Demo* GetObjRef () { // this object pointer stores add of caller object return this; } void RecObjRef (Demo* other_ob_ref) { this->other_ob_ref = other_ob_ref; } void ShowValues () { cout << "Caller Object Add :" << caller_ob_ref << endl; cout << "Other Object Add :" << other_ob_ref << endl; } }; int main () { Demo objectA; objectA.ShowValues(); cout << endl; Demo objectB; objectA.RecObjRef(&objectB); objectA.ShowValues(); }
1,358
400
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// \file /// /// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <info@cososys.com>\n /// Licensed under the Apache License, Version 2.0 (the "License");\n /// you may not use this file except in compliance with the License.\n /// You may obtain a copy of the License at\n /// http://www.apache.org/licenses/LICENSE-2.0\n /// Unless required by applicable law or agreed to in writing, software\n /// distributed under the License is distributed on an "AS IS" BASIS,\n /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n /// See the License for the specific language governing permissions and\n /// limitations under the License.\n /// Please see the file COPYING. /// /// \authors Cristian ANITA <cristian.anita@cososys.com>, <cristian_anita@yahoo.com> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if (!(defined(CPPDEVTK_DETAIL_BUILD) || defined(CPPDEVTK_BASE_MUTEX_HPP_INCLUDED_))) # error "Do not include directly (non-std file); please include <cppdevtk/base/mutex.hpp> instead!!!" #endif #ifndef CPPDEVTK_BASE_GENERIC_LOCKING_ALGORITHMS_HPP_INCLUDED_ #define CPPDEVTK_BASE_GENERIC_LOCKING_ALGORITHMS_HPP_INCLUDED_ #include "config.hpp" #include "locks.hpp" #include "lock_exception.hpp" #include "deadlock_exception.hpp" #include "cassert.hpp" namespace cppdevtk { namespace base { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// \defgroup generic_locking_algorithms Generic locking algorithms /// \sa C++ 11, 30.4.3 Generic locking algorithms /// @{ template <class TL1, class TL2> int TryLock(TL1& l1, TL2& l2); template <class TL1, class TL2, class TL3> int TryLock(TL1& l1, TL2& l2, TL3& l3); template <class TL1, class TL2, class TL3, class TL4> int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4); template <class TL1, class TL2, class TL3, class TL4, class TL5> int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6> int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7> int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8> int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9> int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9, class TL10> int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9, TL10& l10); template <class TL1, class TL2> void Lock(TL1& l1, TL2& l2); template <class TL1, class TL2, class TL3> void Lock(TL1& l1, TL2& l2, TL3& l3); template <class TL1, class TL2, class TL3, class TL4> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4); template <class TL1, class TL2, class TL3, class TL4, class TL5> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9, class TL10> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9, TL10& l10); namespace detail { template <class TL1, class TL2> int LockHelper(TL1& l1, TL2& l2); template <class TL1, class TL2, class TL3> int LockHelper(TL1& l1, TL2& l2, TL3& l3); template <class TL1, class TL2, class TL3, class TL4> int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4); template <class TL1, class TL2, class TL3, class TL4, class TL5> int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6> int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7> int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8> int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9> int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9); template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9, class TL10> int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9, TL10& l10); } // namespace detail /// @} // generic_locking_algorithms ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Inline functions / template definitions. template <class TL1, class TL2> inline int TryLock(TL1& l1, TL2& l2) { UniqueLock<TL1> uniqueLock(l1, tryToLock); if (uniqueLock.OwnsLock()) { if (l2.TryLock()) { uniqueLock.Release(); return -1; } return 1; } return 0; } template <class TL1, class TL2, class TL3> inline int TryLock(TL1& l1, TL2& l2, TL3& l3) { UniqueLock<TL1> uniqueLock(l1, tryToLock); if (uniqueLock.OwnsLock()) { const int kIdx = TryLock(l2, l3); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } return 0; } template <class TL1, class TL2, class TL3, class TL4> inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4) { UniqueLock<TL1> uniqueLock(l1, tryToLock); if (uniqueLock.OwnsLock()) { const int kIdx = TryLock(l2, l3, l4); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } return 0; } template <class TL1, class TL2, class TL3, class TL4, class TL5> inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5) { UniqueLock<TL1> uniqueLock(l1, tryToLock); if (uniqueLock.OwnsLock()) { const int kIdx = TryLock(l2, l3, l4, l5); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } return 0; } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6> inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6) { UniqueLock<TL1> uniqueLock(l1, tryToLock); if (uniqueLock.OwnsLock()) { const int kIdx = TryLock(l2, l3, l4, l5, l6); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } return 0; } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7> inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7) { UniqueLock<TL1> uniqueLock(l1, tryToLock); if (uniqueLock.OwnsLock()) { const int kIdx = TryLock(l2, l3, l4, l5, l6, l7); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } return 0; } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8> inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8) { UniqueLock<TL1> uniqueLock(l1, tryToLock); if (uniqueLock.OwnsLock()) { const int kIdx = TryLock(l2, l3, l4, l5, l6, l7, l8); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } return 0; } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9> inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9) { UniqueLock<TL1> uniqueLock(l1, tryToLock); if (uniqueLock.OwnsLock()) { const int kIdx = TryLock(l2, l3, l4, l5, l6, l7, l8, l9); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } return 0; } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9, class TL10> inline int TryLock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9, TL10& l10) { UniqueLock<TL1> uniqueLock(l1, tryToLock); if (uniqueLock.OwnsLock()) { const int kIdx = TryLock(l2, l3, l4, l5, l6, l7, l8, l9, l10); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } return 0; } template <class TL1, class TL2> void Lock(TL1& l1, TL2& l2) { const int kNumLockables = 2; int lockableIdx = 0; do { switch (lockableIdx) { case 0: lockableIdx = detail::LockHelper(l1, l2); if (lockableIdx == -1) { return; } break; case 1: lockableIdx = detail::LockHelper(l2, l1); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 1) % kNumLockables; break; default: // silence compiler warning about missing default in switch CPPDEVTK_ASSERT(0 && "we should never get here"); break; } } while (true); } template <class TL1, class TL2, class TL3> void Lock(TL1& l1, TL2& l2, TL3& l3) { const int kNumLockables = 3; int lockableIdx = 0; do { switch (lockableIdx) { case 0: lockableIdx = detail::LockHelper(l1, l2, l3); if (lockableIdx == -1) { return; } break; case 1: lockableIdx = detail::LockHelper(l2, l3, l1); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 1) % kNumLockables; break; case 2: lockableIdx = detail::LockHelper(l3, l1, l2); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 2) % kNumLockables; break; default: // silence compiler warning about missing default in switch CPPDEVTK_ASSERT(0 && "we should never get here"); break; } } while (true); } template <class TL1, class TL2, class TL3, class TL4> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4) { const int kNumLockables = 4; int lockableIdx = 0; do { switch (lockableIdx) { case 0: lockableIdx = detail::LockHelper(l1, l2, l3, l4); if (lockableIdx == -1) { return; } break; case 1: lockableIdx = detail::LockHelper(l2, l3, l4, l1); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 1) % kNumLockables; break; case 2: lockableIdx = detail::LockHelper(l3, l4, l1, l2); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 2) % kNumLockables; break; case 3: lockableIdx = detail::LockHelper(l4, l1, l2, l3); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 3) % kNumLockables; break; default: // silence compiler warning about missing default in switch CPPDEVTK_ASSERT(0 && "we should never get here"); break; } } while (true); } template <class TL1, class TL2, class TL3, class TL4, class TL5> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5) { const int kNumLockables = 5; int lockableIdx = 0; do { switch (lockableIdx) { case 0: lockableIdx = detail::LockHelper(l1, l2, l3, l4, l5); if (lockableIdx == -1) { return; } break; case 1: lockableIdx = detail::LockHelper(l2, l3, l4, l5, l1); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 1) % kNumLockables; break; case 2: lockableIdx = detail::LockHelper(l3, l4, l5, l1, l2); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 2) % kNumLockables; break; case 3: lockableIdx = detail::LockHelper(l4, l5, l1, l2, l3); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 3) % kNumLockables; break; case 4: lockableIdx = detail::LockHelper(l5, l1, l2, l3, l4); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 4) % kNumLockables; break; default: // silence compiler warning about missing default in switch CPPDEVTK_ASSERT(0 && "we should never get here"); break; } } while (true); } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6) { const int kNumLockables = 6; int lockableIdx = 0; do { switch (lockableIdx) { case 0: lockableIdx = detail::LockHelper(l1, l2, l3, l4, l5, l6); if (lockableIdx == -1) { return; } break; case 1: lockableIdx = detail::LockHelper(l2, l3, l4, l5, l6, l1); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 1) % kNumLockables; break; case 2: lockableIdx = detail::LockHelper(l3, l4, l5, l6, l1, l2); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 2) % kNumLockables; break; case 3: lockableIdx = detail::LockHelper(l4, l5, l6, l1, l2, l3); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 3) % kNumLockables; break; case 4: lockableIdx = detail::LockHelper(l5, l6, l1, l2, l3, l4); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 4) % kNumLockables; break; case 5: lockableIdx = detail::LockHelper(l6, l1, l2, l3, l4, l5); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 5) % kNumLockables; break; default: // silence compiler warning about missing default in switch CPPDEVTK_ASSERT(0 && "we should never get here"); break; } } while (true); } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7) { const int kNumLockables = 7; int lockableIdx = 0; do { switch (lockableIdx) { case 0: lockableIdx = detail::LockHelper(l1, l2, l3, l4, l5, l6, l7); if (lockableIdx == -1) { return; } break; case 1: lockableIdx = detail::LockHelper(l2, l3, l4, l5, l6, l7, l1); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 1) % kNumLockables; break; case 2: lockableIdx = detail::LockHelper(l3, l4, l5, l6, l7, l1, l2); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 2) % kNumLockables; break; case 3: lockableIdx = detail::LockHelper(l4, l5, l6, l7, l1, l2, l3); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 3) % kNumLockables; break; case 4: lockableIdx = detail::LockHelper(l5, l6, l7, l1, l2, l3, l4); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 4) % kNumLockables; break; case 5: lockableIdx = detail::LockHelper(l6, l7, l1, l2, l3, l4, l5); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 5) % kNumLockables; break; case 6: lockableIdx = detail::LockHelper(l7, l1, l2, l3, l4, l5, l6); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 6) % kNumLockables; break; default: // silence compiler warning about missing default in switch CPPDEVTK_ASSERT(0 && "we should never get here"); break; } } while (true); } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8) { const int kNumLockables = 8; int lockableIdx = 0; do { switch (lockableIdx) { case 0: lockableIdx = detail::LockHelper(l1, l2, l3, l4, l5, l6, l7, l8); if (lockableIdx == -1) { return; } break; case 1: lockableIdx = detail::LockHelper(l2, l3, l4, l5, l6, l7, l8, l1); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 1) % kNumLockables; break; case 2: lockableIdx = detail::LockHelper(l3, l4, l5, l6, l7, l8, l1, l2); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 2) % kNumLockables; break; case 3: lockableIdx = detail::LockHelper(l4, l5, l6, l7, l8, l1, l2, l3); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 3) % kNumLockables; break; case 4: lockableIdx = detail::LockHelper(l5, l6, l7, l8, l1, l2, l3, l4); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 4) % kNumLockables; break; case 5: lockableIdx = detail::LockHelper(l6, l7, l8, l1, l2, l3, l4, l5); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 5) % kNumLockables; break; case 6: lockableIdx = detail::LockHelper(l7, l8, l1, l2, l3, l4, l5, l6); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 6) % kNumLockables; break; case 7: lockableIdx = detail::LockHelper(l8, l1, l2, l3, l4, l5, l6, l7); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 7) % kNumLockables; break; default: // silence compiler warning about missing default in switch CPPDEVTK_ASSERT(0 && "we should never get here"); break; } } while (true); } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9) { const int kNumLockables = 9; int lockableIdx = 0; do { switch (lockableIdx) { case 0: lockableIdx = detail::LockHelper(l1, l2, l3, l4, l5, l6, l7, l8, l9); if (lockableIdx == -1) { return; } break; case 1: lockableIdx = detail::LockHelper(l2, l3, l4, l5, l6, l7, l8, l9, l1); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 1) % kNumLockables; break; case 2: lockableIdx = detail::LockHelper(l3, l4, l5, l6, l7, l8, l9, l1, l2); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 2) % kNumLockables; break; case 3: lockableIdx = detail::LockHelper(l4, l5, l6, l7, l8, l9, l1, l2, l3); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 3) % kNumLockables; break; case 4: lockableIdx = detail::LockHelper(l5, l6, l7, l8, l9, l1, l2, l3, l4); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 4) % kNumLockables; break; case 5: lockableIdx = detail::LockHelper(l6, l7, l8, l9, l1, l2, l3, l4, l5); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 5) % kNumLockables; break; case 6: lockableIdx = detail::LockHelper(l7, l8, l9, l1, l2, l3, l4, l5, l6); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 6) % kNumLockables; break; case 7: lockableIdx = detail::LockHelper(l8, l9, l1, l2, l3, l4, l5, l6, l7); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 7) % kNumLockables; break; case 8: lockableIdx = detail::LockHelper(l9, l1, l2, l3, l4, l5, l6, l7, l8); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 8) % kNumLockables; break; default: // silence compiler warning about missing default in switch CPPDEVTK_ASSERT(0 && "we should never get here"); break; } } while (true); } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9, class TL10> void Lock(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9, TL10& l10) { const int kNumLockables = 10; int lockableIdx = 0; do { switch (lockableIdx) { case 0: lockableIdx = detail::LockHelper(l1, l2, l3, l4, l5, l6, l7, l8, l9, l10); if (lockableIdx == -1) { return; } break; case 1: lockableIdx = detail::LockHelper(l2, l3, l4, l5, l6, l7, l8, l9, l10, l1); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 1) % kNumLockables; break; case 2: lockableIdx = detail::LockHelper(l3, l4, l5, l6, l7, l8, l9, l10, l1, l2); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 2) % kNumLockables; break; case 3: lockableIdx = detail::LockHelper(l4, l5, l6, l7, l8, l9, l10, l1, l2, l3); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 3) % kNumLockables; break; case 4: lockableIdx = detail::LockHelper(l5, l6, l7, l8, l9, l10, l1, l2, l3, l4); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 4) % kNumLockables; break; case 5: lockableIdx = detail::LockHelper(l6, l7, l8, l9, l10, l1, l2, l3, l4, l5); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 5) % kNumLockables; break; case 6: lockableIdx = detail::LockHelper(l7, l8, l9, l10, l1, l2, l3, l4, l5, l6); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 6) % kNumLockables; break; case 7: lockableIdx = detail::LockHelper(l8, l9, l10, l1, l2, l3, l4, l5, l6, l7); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 7) % kNumLockables; break; case 8: lockableIdx = detail::LockHelper(l9, l10, l1, l2, l3, l4, l5, l6, l7, l8); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 8) % kNumLockables; break; case 9: lockableIdx = detail::LockHelper(l10, l1, l2, l3, l4, l5, l6, l7, l8, l9); if (lockableIdx == -1) { return; } lockableIdx = (lockableIdx + 9) % kNumLockables; break; default: // silence compiler warning about missing default in switch CPPDEVTK_ASSERT(0 && "we should never get here"); break; } } while (true); } namespace detail { template <class TL1, class TL2> inline int LockHelper(TL1& l1, TL2& l2) { UniqueLock<TL1> uniqueLock(l1); if (l2.TryLock()) { uniqueLock.Release(); return -1; } return 1; } template <class TL1, class TL2, class TL3> inline int LockHelper(TL1& l1, TL2& l2, TL3& l3) { UniqueLock<TL1> uniqueLock(l1); const int kIdx = TryLock(l2, l3); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } template <class TL1, class TL2, class TL3, class TL4> inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4) { UniqueLock<TL1> uniqueLock(l1); const int kIdx = TryLock(l2, l3, l4); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } template <class TL1, class TL2, class TL3, class TL4, class TL5> inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5) { UniqueLock<TL1> uniqueLock(l1); const int kIdx = TryLock(l2, l3, l4, l5); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6> inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6) { UniqueLock<TL1> uniqueLock(l1); const int kIdx = TryLock(l2, l3, l4, l5, l6); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7> inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7) { UniqueLock<TL1> uniqueLock(l1); const int kIdx = TryLock(l2, l3, l4, l5, l6, l7); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8> inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8) { UniqueLock<TL1> uniqueLock(l1); const int kIdx = TryLock(l2, l3, l4, l5, l6, l7, l8); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9> inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9) { UniqueLock<TL1> uniqueLock(l1); const int kIdx = TryLock(l2, l3, l4, l5, l6, l7, l8, l9); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } template <class TL1, class TL2, class TL3, class TL4, class TL5, class TL6, class TL7, class TL8, class TL9, class TL10> inline int LockHelper(TL1& l1, TL2& l2, TL3& l3, TL4& l4, TL5& l5, TL6& l6, TL7& l7, TL8& l8, TL9& l9, TL10& l10) { UniqueLock<TL1> uniqueLock(l1); const int kIdx = TryLock(l2, l3, l4, l5, l6, l7, l8, l9, l10); if (kIdx == -1) { uniqueLock.Release(); return kIdx; } return (kIdx + 1); } } // namespace detail } // namespace base } // namespace cppdevtk #endif // CPPDEVTK_BASE_GENERIC_LOCKING_ALGORITHMS_HPP_INCLUDED_
26,548
13,453
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/search_engines/search_engine_utils.h" #include "components/google/core/common/google_util.h" #include "components/search_engines/prepopulated_engines.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "url/gurl.h" namespace SearchEngineUtils { namespace { bool SameDomain(const GURL& given_url, const GURL& prepopulated_url) { return prepopulated_url.is_valid() && net::registry_controlled_domains::SameDomainOrHost( given_url, prepopulated_url, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); } } // namespace // Global functions ----------------------------------------------------------- SearchEngineType GetEngineType(const GURL& url) { DCHECK(url.is_valid()); // Check using TLD+1s, in order to more aggressively match search engine types // for data imported from other browsers. // // First special-case Google, because the prepopulate URL for it will not // convert to a GURL and thus won't have an origin. Instead see if the // incoming URL's host is "[*.]google.<TLD>". if (google_util::IsGoogleHostname(url.host(), google_util::DISALLOW_SUBDOMAIN)) return TemplateURLPrepopulateData::google.type; // Now check the rest of the prepopulate data. for (size_t i = 0; i < TemplateURLPrepopulateData::kAllEnginesLength; ++i) { // First check the main search URL. if (SameDomain( url, GURL(TemplateURLPrepopulateData::kAllEngines[i]->search_url))) return TemplateURLPrepopulateData::kAllEngines[i]->type; // Then check the alternate URLs. for (size_t j = 0; j < TemplateURLPrepopulateData::kAllEngines[i]->alternate_urls_size; ++j) { if (SameDomain(url, GURL(TemplateURLPrepopulateData::kAllEngines[i] ->alternate_urls[j]))) return TemplateURLPrepopulateData::kAllEngines[i]->type; } } return SEARCH_ENGINE_OTHER; } } // namespace SearchEngineUtils
2,214
704
/* Copyright 2013-present Barefoot Networks, Inc. * Copyright 2021 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Antonin Bas * */ #include <PI/proto/util.h> #include <algorithm> #include <map> #include <memory> #include <string> #include <unordered_map> #include <utility> // std::move #include <vector> #include "google/rpc/code.pb.h" #include "action_helpers.h" #include "action_prof_mgr.h" #include "common.h" #include "logger.h" #include "report_error.h" #include "statusor.h" #include "watch_port_enforcer.h" namespace p4v1 = ::p4::v1; namespace p4configv1 = ::p4::config::v1; namespace pi { namespace fe { namespace proto { using Id = ActionProfBiMap::Id; using common::SessionTemp; using common::make_invalid_p4_id_status; using Code = ::google::rpc::Code; using MembershipInfo = ActionProfGroupMembership::MembershipInfo; using OneShotMember = ActionProfAccessOneshot::OneShotMember; namespace { // temporary until we have port translation support int bytestring_to_integer(const std::string &str) { int v = 0; if (str.size() > 4) return -1; for (auto c : str) { v = v << 8; v += static_cast<int>(static_cast<unsigned char>(c)); } return v; } pi_port_t watch_port_p4rt_to_pi(int watch) { return (watch == p4v1::SDN_PORT_UNKNOWN) ? WatchPortEnforcer::INVALID_WATCH : static_cast<pi_port_t>(watch); } pi_port_t watch_port_p4rt_to_pi(const std::string &watch) { if (watch == "") return WatchPortEnforcer::INVALID_WATCH; auto v = bytestring_to_integer(watch); if (v < 0 || v == p4v1::SDN_PORT_UNKNOWN) return WatchPortEnforcer::INVALID_WATCH; return static_cast<pi_port_t>(v); } } // namespace void ActionProfBiMap::add(const Id &id, pi_indirect_handle_t h) { bimap.add_mapping_1_2(id, h); } const pi_indirect_handle_t * ActionProfBiMap::retrieve_handle(const Id &id) const { return bimap.get_from_1(id); } const Id * ActionProfBiMap::retrieve_id(pi_indirect_handle_t h) const { return bimap.get_from_2(h); } void ActionProfBiMap::remove(const Id &id) { auto h_ptr = retrieve_handle(id); if (h_ptr != nullptr) { auto h = *h_ptr; // need to save the value before modifying the map bimap.remove_from_1(id); bimap.remove_from_2(h); } } bool ActionProfBiMap::empty() const { return bimap.empty(); } bool ActionProfMemberMap::add(const Id &id, pi_indirect_handle_t h, // NOLINTNEXTLINE(whitespace/operators) pi::ActionData &&action_data) { auto p = members.emplace(id, MemberState(std::move(action_data))); if (!p.second) return false; p.first->second.handles.push_back(h); p.first->second.weight_counts[1] = 1; return true; } ActionProfMemberMap::MemberState * ActionProfMemberMap::access_member_state(const Id &id) { auto it = members.find(id); return (it == members.end()) ? nullptr : &it->second; } const pi_indirect_handle_t * ActionProfMemberMap::get_first_handle(const Id &id) const { auto it = members.find(id); if (it == members.end()) return nullptr; return &it->second.handles.front(); } const Id * ActionProfMemberMap::retrieve_id(pi_indirect_handle_t h) const { auto it = handle_to_id.find(h); return (it == handle_to_id.end()) ? nullptr : &it->second; } bool ActionProfMemberMap::remove(const Id &id) { return (members.erase(id) > 0); } bool ActionProfMemberMap::add_handle(pi_indirect_handle_t h, const Id &id) { auto p = handle_to_id.emplace(h, id); return p.second; } bool ActionProfMemberMap::remove_handle(pi_indirect_handle_t h) { return (handle_to_id.erase(h) > 0); } bool ActionProfMemberMap::empty() const { return members.empty(); } ActionProfGroupMembership::ActionProfGroupMembership(size_t max_size_user) : max_size_user(max_size_user) { } bool operator==(const MembershipInfo &lhs, const MembershipInfo &rhs) { return (lhs.weight == rhs.weight) && (lhs.watch == rhs.watch); } namespace { template <typename T> WatchPort make_watch_port_helper(const T &msg) { WatchPort::WatchKindCase watch_kind_case = WatchPort::WatchKindCase::kNotSet; int watch = p4v1::SDN_PORT_UNKNOWN; std::string watch_port = ""; pi_port_t pi_port = WatchPortEnforcer::INVALID_WATCH; switch (msg.watch_kind_case()) { case T::kWatch: watch_kind_case = WatchPort::WatchKindCase::kWatch; watch = msg.watch(); pi_port = watch_port_p4rt_to_pi(msg.watch()); break; case T::kWatchPort: watch_kind_case = WatchPort::WatchKindCase::kWatchPort; watch_port = msg.watch_port(); pi_port = watch_port_p4rt_to_pi(msg.watch_port()); break; default: break; } return WatchPort{watch_kind_case, watch, watch_port, pi_port}; } } // namespace /* static */ const WatchPort WatchPort::invalid_watch() { return WatchPort{ WatchKindCase::kNotSet, 0, "", WatchPortEnforcer::INVALID_WATCH}; } /* static */ WatchPort WatchPort::make(const p4v1::ActionProfileGroup::Member &member) { return make_watch_port_helper(member); } /* static */ WatchPort WatchPort::make(const p4v1::ActionProfileAction &action) { return make_watch_port_helper(action); } template <typename T> void WatchPort::to_p4rt_helper(T *msg) const { switch (watch_kind_case) { case WatchKindCase::kWatch: msg->set_watch(watch); break; case WatchKindCase::kWatchPort: msg->set_watch_port(watch_port); break; default: break; } } void WatchPort::to_p4rt(p4::v1::ActionProfileGroup::Member *member) const { return to_p4rt_helper(member); } void WatchPort::to_p4rt(p4::v1::ActionProfileAction *action) const { return to_p4rt_helper(action); } bool operator==(const WatchPort &lhs, const WatchPort &rhs) { return lhs.pi_port == rhs.pi_port; } bool operator!=(const WatchPort &lhs, const WatchPort &rhs) { return !(lhs == rhs); } // The result is the union of all members (current and new) with current_weight // and new_weight set appropriately. For a new member, current_weight is 0 while // new_weight is > 0. For an old member that needs to be removed, new_weight is // 0 while current_weight is > 0. For an existing member whose weight we are // changing new_weight and current_weight are both > 0. If we are not changing // the weight, new_weight == current_weight. We also store the desired watch // port for the member as new_watch, which is set to -1 if the member needs to // be removed, along with the current watch port as current_watch. std::vector<ActionProfGroupMembership::MembershipUpdate> ActionProfGroupMembership::compute_membership_update( const std::map<Id, MembershipInfo> &desired_membership) const { std::vector<MembershipUpdate> update; auto new_it = desired_membership.begin(); auto current_it = members.begin(); while (new_it != desired_membership.end() || current_it != members.end()) { if (new_it == desired_membership.end()) { for (; current_it != members.end(); current_it++) update.emplace_back(current_it->first, current_it->second.weight, 0, current_it->second.watch, WatchPort::invalid_watch()); break; } if (current_it == members.end()) { for (; new_it != desired_membership.end(); new_it++) update.emplace_back(new_it->first, 0, new_it->second.weight, WatchPort::invalid_watch(), new_it->second.watch); break; } if (current_it->first < new_it->first) { // member no longer exists update.emplace_back(current_it->first, current_it->second.weight, 0, current_it->second.watch, WatchPort::invalid_watch()); current_it++; } else if (current_it->first > new_it->first) { // new member update.emplace_back(new_it->first, 0, new_it->second.weight, WatchPort::invalid_watch(), new_it->second.watch); new_it++; } else { update.emplace_back(current_it->first, current_it->second.weight, new_it->second.weight, current_it->second.watch, new_it->second.watch); current_it++; new_it++; } } return update; } void ActionProfGroupMembership::set_membership( std::map<Id, MembershipInfo> &&new_members) { members = std::move(new_members); } const std::map<Id, MembershipInfo> & ActionProfGroupMembership::get_membership() const { return members; } std::map<Id, MembershipInfo> & ActionProfGroupMembership::get_membership() { return members; } size_t ActionProfGroupMembership::get_max_size_user() const { return max_size_user; } bool ActionProfGroupMembership::get_member_info( const Id &member_id, int *weight, WatchPort *watch) const { auto it = members.find(member_id); if (it == members.end()) return false; *weight = it->second.weight; *watch = it->second.watch; return true; } ActionProfAccessBase::ActionProfAccessBase( pi_dev_tgt_t device_tgt, pi_p4_id_t act_prof_id, pi_p4info_t *p4info, PiApiChoice pi_api_choice, WatchPortEnforcer *watch_port_enforcer) : device_tgt(device_tgt), act_prof_id(act_prof_id), p4info(p4info), pi_api_choice(pi_api_choice), watch_port_enforcer(watch_port_enforcer) { max_group_size = pi_p4info_act_prof_max_grp_size(p4info, act_prof_id); } bool ActionProfAccessBase::check_p4_action_id(pi_p4_id_t p4_id) const { using pi::proto::util::resource_type_from_id; return (resource_type_from_id(p4_id) == p4configv1::P4Ids::ACTION) && pi_p4info_is_valid_id(p4info, p4_id); } Status ActionProfAccessBase::validate_action(const p4v1::Action &action) { auto action_id = action.action_id(); if (!check_p4_action_id(action_id)) return make_invalid_p4_id_status(); if (!pi_p4info_act_prof_is_action_of(p4info, act_prof_id, action_id)) { RETURN_ERROR_STATUS(Code::INVALID_ARGUMENT, "Invalid action for action profile"); } RETURN_OK_STATUS(); } bool ActionProfAccessManual::empty() const { return member_map.empty() && group_bimap.empty(); } Status ActionProfAccessManual::member_create(const p4v1::ActionProfileMember &member, const SessionTemp &session) { RETURN_IF_ERROR(validate_action(member.action())); pi::ActionData action_data(p4info, member.action().action_id()); RETURN_IF_ERROR(construct_action_data(p4info, member.action(), &action_data)); pi::ActProf ap(session.get(), device_tgt, p4info, act_prof_id); // we check if the member id already exists if (member_map.access_member_state(member.member_id()) != nullptr) { RETURN_ERROR_STATUS( Code::ALREADY_EXISTS, "Duplicate member id: {}", member.member_id()); } pi_indirect_handle_t member_h; auto pi_status = ap.member_create(action_data, &member_h); if (pi_status != PI_STATUS_SUCCESS) RETURN_ERROR_STATUS(Code::UNKNOWN, "Error when creating member on target"); if (!member_map.add(member.member_id(), member_h, std::move(action_data))) { RETURN_ERROR_STATUS( Code::INTERNAL, "Error when add new member to member map"); } if (!member_map.add_handle(member_h, member.member_id())) { RETURN_ERROR_STATUS( Code::INTERNAL, "Error when updating handle to member id map"); } RETURN_OK_STATUS(); } StatusOr<size_t> ActionProfAccessManual::validate_max_group_size(int max_size) { /* - If max_group_size is greater than 0, then max_size must be greater than 0, and less than or equal to max_group_size. We assume that the target can support selector groups for which the sum of all member weights is up to max_group_size, or the P4Runtime server would have rejected the Forwarding Pipeline Config. If max_size is greater than max_group_size, the server must return INVALID_ARGUMENT. - Otherwise (i.e. if max_group_size is 0), the P4Runtime client can set max_size to any value greater than or equal to 0. - A max_size of 0 indicates that the client is not able to specify a maximum size at group-creation time, and the target should use the maximum value it can support. If the maximum value supported by the target is exceeded during a write update (INSERT or MODIFY), the target must return a RESOURCE_EXHAUSTED error. - If max_size is greater than 0 and the value is not supported by the target, the server must return a RESOURCE_EXHAUSTED error at group-creation time. */ if (max_size < 0) { RETURN_ERROR_STATUS( Code::INVALID_ARGUMENT, "Group max_size cannot be less than 0"); } auto max_size_ = static_cast<size_t>(max_size); if (max_group_size > 0 && max_size_ > max_group_size) { RETURN_ERROR_STATUS( Code::INVALID_ARGUMENT, "Group max_size cannot exceed static max_group_size (from P4Info)"); } return max_size_; } // TODO(antonin): we could try to do some better cleanup in case of error when // creating a group or modifying it. However, especially now that we have weight // support, it is more complex than for the one-shot case. At least, we try to // ensure that the ActionProfMgr state is consistent with HW. Status ActionProfAccessManual::group_create(const p4v1::ActionProfileGroup &group, const SessionTemp &session) { auto max_size = validate_max_group_size(group.max_size()); RETURN_IF_ERROR(max_size.status()); pi::ActProf ap(session.get(), device_tgt, p4info, act_prof_id); // we check if the group id already exists if (group_bimap.retrieve_handle(group.group_id()) != nullptr) { RETURN_ERROR_STATUS( Code::ALREADY_EXISTS, "Duplicate group id: {}", group.group_id()); } pi_indirect_handle_t group_h; auto pi_status = ap.group_create(max_size.ValueOrDie(), &group_h); if (pi_status != PI_STATUS_SUCCESS) RETURN_ERROR_STATUS(Code::UNKNOWN, "Error when creating group on target"); group_bimap.add(group.group_id(), group_h); group_members.emplace(group.group_id(), ActionProfGroupMembership(group.max_size())); return group_update_members(ap, group); } Status ActionProfAccessManual::member_modify(const p4v1::ActionProfileMember &member, const SessionTemp &session) { RETURN_IF_ERROR(validate_action(member.action())); pi::ActionData action_data(p4info, member.action().action_id()); RETURN_IF_ERROR(construct_action_data(p4info, member.action(), &action_data)); pi::ActProf ap(session.get(), device_tgt, p4info, act_prof_id); auto member_state = member_map.access_member_state(member.member_id()); if (member_state == nullptr) { RETURN_ERROR_STATUS(Code::NOT_FOUND, "Member id does not exist: {}", member.member_id()); } for (auto member_h : member_state->handles) { auto pi_status = ap.member_modify(member_h, action_data); if (pi_status != PI_STATUS_SUCCESS) { RETURN_ERROR_STATUS( Code::UNKNOWN, "Error when modifying member on target"); } } member_state->action_data = std::move(action_data); RETURN_OK_STATUS(); } Status ActionProfAccessManual::group_modify(const p4v1::ActionProfileGroup &group, const SessionTemp &session) { auto group_id = group.group_id(); pi::ActProf ap(session.get(), device_tgt, p4info, act_prof_id); auto group_h = group_bimap.retrieve_handle(group_id); if (group_h == nullptr) { RETURN_ERROR_STATUS(Code::NOT_FOUND, "Group id does not exist: {}", group.group_id()); } auto max_size_user = group_members.at(group_id).get_max_size_user(); // TODO(antonin): I don't want to take the risk to break existing // implementations (for not much benefit) so no check is performed if max_size // is "unset". if (group.max_size() != 0 && static_cast<size_t>(group.max_size()) != max_size_user) { RETURN_ERROR_STATUS( Code::INVALID_ARGUMENT, "Cannot change group max_size after group creation"); } return group_update_members(ap, group); } Status ActionProfAccessManual::member_delete(const p4v1::ActionProfileMember &member, const SessionTemp &session) { pi::ActProf ap(session.get(), device_tgt, p4info, act_prof_id); auto member_state = member_map.access_member_state(member.member_id()); if (member_state == nullptr) { RETURN_ERROR_STATUS(Code::NOT_FOUND, "Member id does not exist: {}", member.member_id()); } // at this point there should probably be a single handle; otherwise the // member is still used by a group and the target should fail to delete it. for (auto member_h : member_state->handles) { auto pi_status = ap.member_delete(member_h); if (pi_status != PI_STATUS_SUCCESS) { RETURN_ERROR_STATUS( Code::UNKNOWN, "Error when deleting member on target"); } if (!member_map.remove_handle(member_h)) { RETURN_ERROR_STATUS( Code::INTERNAL, "Error when removing member handle from map"); } } if (!member_map.remove(member.member_id())) { RETURN_ERROR_STATUS( Code::INTERNAL, "Error when removing member from member map"); } RETURN_OK_STATUS(); } Status ActionProfAccessManual::group_delete(const p4v1::ActionProfileGroup &group, const SessionTemp &session) { pi::ActProf ap(session.get(), device_tgt, p4info, act_prof_id); auto group_h = group_bimap.retrieve_handle(group.group_id()); if (group_h == nullptr) { RETURN_ERROR_STATUS(Code::NOT_FOUND, "Group id does not exist: {}", group.group_id()); } auto pi_status = ap.group_delete(*group_h); if (pi_status != PI_STATUS_SUCCESS) RETURN_ERROR_STATUS(Code::UNKNOWN, "Error when deleting group on target"); auto it = group_members.find(group.group_id()); if (it == group_members.end()) { RETURN_ERROR_STATUS( Code::INTERNAL, "Cannot find membership information for group {}", group.group_id()); } const auto &members = it->second.get_membership(); for (const auto &m : members) { auto member_state = member_map.access_member_state(m.first); if (!member_state) { RETURN_ERROR_STATUS( Code::INTERNAL, "Cannot access state for member {} in group {}", m.first, group.group_id()); } assert(m.second.weight > 0); member_state->weight_counts[m.second.weight]--; for (int i = 0; i < m.second.weight; i++) { // no reason to fail, we are just updating the watch_port_enforcer // internal state RETURN_IF_ERROR(watch_port_enforcer->delete_member( act_prof_id, *group_h, member_state->handles[i], m.second.watch.pi_port)); } RETURN_IF_ERROR(purge_unused_weighted_members_wrapper(ap, member_state)); } group_members.erase(it); // we do this last, after every use of group_h since it will invalidate the // pointer (of course we could also copy *group_h to a stack variable...) group_bimap.remove(group.group_id()); RETURN_OK_STATUS(); } bool ActionProfAccessManual::group_get_max_size_user(const Id &group_id, size_t *max_size_user) const { auto it = group_members.find(group_id); if (it == group_members.end()) return false; *max_size_user = it->second.get_max_size_user(); return true; } bool ActionProfAccessManual::get_member_info(const Id &group_id, const Id &member_id, int *weight, WatchPort *watch_port) const { auto it = group_members.find(group_id); if (it == group_members.end()) return false; return it->second.get_member_info(member_id, weight, watch_port); } Status ActionProfAccessManual::create_missing_weighted_members( pi::ActProf &ap, ActionProfMemberMap::MemberState *member_state, const ActionProfGroupMembership::MembershipUpdate &update) { auto handles_size = static_cast<int>(member_state->handles.size()); assert(handles_size >= update.current_weight); for (int i = handles_size; i < update.new_weight; i++) { pi_indirect_handle_t member_h; auto pi_status = ap.member_create(member_state->action_data, &member_h); if (pi_status != PI_STATUS_SUCCESS) { RETURN_ERROR_STATUS( Code::UNKNOWN, "Error when creating member on target"); } member_state->handles.push_back(member_h); if (!member_map.add_handle(member_h, update.id)) { RETURN_ERROR_STATUS( Code::INTERNAL, "Error when updating handle to member id map"); } } RETURN_OK_STATUS(); } Status ActionProfAccessManual::purge_unused_weighted_members( pi::ActProf &ap, ActionProfMemberMap::MemberState *member_state) { int new_max_weight = -1; for (auto weight_count_rit = member_state->weight_counts.rbegin(); weight_count_rit != member_state->weight_counts.rend(); ++weight_count_rit) { if (weight_count_rit->second == 0) continue; new_max_weight = weight_count_rit->first; // weight_count_rit.base() will return an iterator one element past the one // we get when dereferencing weight_count_rit, which is exactly what we want // for the erase call member_state->weight_counts.erase( weight_count_rit.base(), member_state->weight_counts.end()); break; } assert(new_max_weight > 0); for (int i = static_cast<int>(member_state->handles.size()) - 1; i >= new_max_weight; i--) { auto member_h = member_state->handles.back(); auto pi_status = ap.member_delete(member_h); if (pi_status != PI_STATUS_SUCCESS) { RETURN_ERROR_STATUS( Code::UNKNOWN, "Error when creating member on target"); } if (!member_map.remove_handle(member_h)) { RETURN_ERROR_STATUS( Code::INTERNAL, "Error when removing member handle from map"); } member_state->handles.pop_back(); } RETURN_OK_STATUS(); } Status ActionProfAccessManual::purge_unused_weighted_members_wrapper( pi::ActProf &ap, ActionProfMemberMap::MemberState *member_state) { if (IS_ERROR(purge_unused_weighted_members(ap, member_state))) { RETURN_ERROR_STATUS( Code::INTERNAL, "Error encountered when cleaning up action profile member copies " "created for weighted member programming. This is a serious error and " "there may be dangling action profile members. You may need to do a " "SetForwardingPipelineConfig again or reboot the switch."); } RETURN_OK_STATUS(); } Status ActionProfAccessManual::group_update_members( pi::ActProf &ap, const p4v1::ActionProfileGroup &group) { size_t sum_of_weights = 0; for (const auto& member : group.members()) { if (member.weight() <= 0) { RETURN_ERROR_STATUS(Code::INVALID_ARGUMENT, "Member weight must be a positive integer value"); } sum_of_weights += member.weight(); } auto group_id = group.group_id(); auto group_h = group_bimap.retrieve_handle(group_id); assert(group_h); auto &membership = group_members.at(group_id); auto max_size_user = membership.get_max_size_user(); auto max_size = (max_size_user == 0) ? max_group_size : max_size_user; if (max_size > 0 && sum_of_weights > max_size) { RETURN_ERROR_STATUS(Code::RESOURCE_EXHAUSTED, "Sum of member weights exceeds maximum group size"); } std::map<Id, MembershipInfo> new_membership; for (const auto &m : group.members()) { // check that member id exists if (!member_map.access_member_state(m.member_id())) { RETURN_ERROR_STATUS( Code::NOT_FOUND, "Member id does not exist: {}", m.member_id()); } // check if duplicate if (new_membership.count(m.member_id()) > 0) { RETURN_ERROR_STATUS( Code::INVALID_ARGUMENT, "Duplicate member id {} for group {}, use weights instead", m.member_id(), group_id); } new_membership.emplace(m.member_id(), MembershipInfo{m.weight(), WatchPort::make(m)}); } auto membership_update = membership.compute_membership_update( new_membership); auto cleanup_members = [&membership_update, &ap, this]() { for (const auto &m : membership_update) { auto member_state = member_map.access_member_state(m.id); assert(member_state); // TODO(antonin): try to purge subsequent members even if one fails RETURN_IF_ERROR(purge_unused_weighted_members_wrapper(ap, member_state)); } RETURN_OK_STATUS(); }; auto &current_membership = membership.get_membership(); if (pi_api_choice == PiApiChoice::INDIVIDUAL_ADDS_AND_REMOVES) { // TODO(antonin): make this code smarter so that the group is never empty // and never too big at any given time. for (auto &m : membership_update) { auto member_state = member_map.access_member_state(m.id); assert(member_state); // checked previously RETURN_IF_ERROR(create_missing_weighted_members(ap, member_state, m)); if (m.current_weight > 0) member_state->weight_counts[m.current_weight]--; auto add_member = [&ap, group_h](pi_indirect_handle_t h) -> Status { auto pi_status = ap.group_add_member(*group_h, h); if (pi_status != PI_STATUS_SUCCESS) { RETURN_ERROR_STATUS( Code::UNKNOWN, "Error when adding member to group on target"); } RETURN_OK_STATUS(); }; auto remove_member = [&ap, group_h](pi_indirect_handle_t h) -> Status { auto pi_status = ap.group_remove_member(*group_h, h); if (pi_status != PI_STATUS_SUCCESS) { RETURN_ERROR_STATUS( Code::UNKNOWN, "Error when removing member from group on target"); } RETURN_OK_STATUS(); }; int end_weight = m.current_weight; Status status = OK_STATUS(); // remove members as needed for (int i = m.current_weight - 1; i >= m.new_weight; i--) { auto h = member_state->handles.at(i); // no reason to fail, we are just updating the watch_port_enforcer // internal state status = watch_port_enforcer->delete_member( act_prof_id, *group_h, h, m.current_watch.pi_port); if (IS_ERROR(status)) break; status = remove_member(h); if (IS_ERROR(status)) break; end_weight--; auto it = current_membership.find(m.id); assert(it != current_membership.end()); if (it->second.weight == 1) current_membership.erase(it); else it->second.weight--; } // add members as needed for (int i = m.current_weight; i < m.new_weight; i++) { auto h = member_state->handles.at(i); status = add_member(h); if (IS_ERROR(status)) break; end_weight++; // may construct and value-initialize MembershipInfo instance auto &minfo = current_membership[m.id]; minfo.weight++; minfo.watch = m.new_watch; status = watch_port_enforcer->add_member_and_update_hw( &ap, *group_h, h, m.new_watch.pi_port); if (IS_ERROR(status)) break; } // modify watch ports if needed if (m.new_watch != m.current_watch && IS_OK(status)) { for (int i = 0; i < std::min(m.current_weight, m.new_weight); i++) { auto h = member_state->handles.at(i); status = watch_port_enforcer->modify_member_and_update_hw( &ap, *group_h, h, m.current_watch.pi_port, m.new_watch.pi_port); if (IS_ERROR(status)) break; } current_membership.at(m.id).watch = m.new_watch; } if (end_weight > 0) member_state->weight_counts[end_weight]++; if (IS_ERROR(status)) { RETURN_IF_ERROR(cleanup_members()); return status; } RETURN_IF_ERROR(status); assert(end_weight == m.new_weight); } assert(current_membership == new_membership); } else if (pi_api_choice == PiApiChoice::SET_MEMBERSHIP) { std::vector<pi_indirect_handle_t> members_to_set; std::unique_ptr<bool[]> activate(new bool[sum_of_weights]); int activate_idx = 0; for (const auto &m : membership_update) { auto member_state = member_map.access_member_state(m.id); if (!member_state) { RETURN_ERROR_STATUS( Code::NOT_FOUND, "Member id does not exist: {}", m.id); } RETURN_IF_ERROR(create_missing_weighted_members(ap, member_state, m)); if (m.new_weight > 0) { members_to_set.insert(members_to_set.end(), member_state->handles.begin(), member_state->handles.begin() + m.new_weight); auto port_status = watch_port_enforcer->get_port_status( act_prof_id, m.new_watch.pi_port); for (int i = 0; i < m.new_weight; i++) { activate[activate_idx++] = (port_status == PI_PORT_STATUS_UP); } } } auto pi_status = ap.group_set_members( *group_h, members_to_set.size(), members_to_set.data(), activate.get()); if (pi_status != PI_STATUS_SUCCESS) { RETURN_IF_ERROR(cleanup_members()); RETURN_ERROR_STATUS( Code::UNKNOWN, "Error when setting group membership on target"); } size_t watch_port_errors = 0; for (const auto &m : membership_update) { auto member_state = member_map.access_member_state(m.id); assert(member_state); if (m.current_weight > 0) member_state->weight_counts[m.current_weight]--; if (m.new_weight > 0) member_state->weight_counts[m.new_weight]++; // no reasons for any of these to fail, we are not touching the HW for (int i = m.current_weight - 1; i >= m.new_weight; i--) { auto h = member_state->handles.at(i); auto status = watch_port_enforcer->delete_member( act_prof_id, *group_h, h, m.current_watch.pi_port); if (IS_ERROR(status)) watch_port_errors++; } for (int i = m.current_weight; i < m.new_weight; i++) { auto h = member_state->handles.at(i); auto status = watch_port_enforcer->add_member( act_prof_id, *group_h, h, m.new_watch.pi_port); if (IS_ERROR(status)) watch_port_errors++; } if (m.new_watch != m.current_watch) { for (int i = 0; i < std::min(m.current_weight, m.new_weight); i++) { auto h = member_state->handles.at(i); auto status = watch_port_enforcer->modify_member( act_prof_id, *group_h, h, m.current_watch.pi_port, m.new_watch.pi_port); if (IS_ERROR(status)) watch_port_errors++; } } } membership.set_membership(std::move(new_membership)); if (watch_port_errors > 0) { RETURN_ERROR_STATUS( Code::INTERNAL, "Error when storing watch port information for group {}, watch ports " "may not be enforced correctly", group_id); } } else { RETURN_ERROR_STATUS(Code::INTERNAL, "Unknown PiApiChoice"); } // cleanup members which are not used anymore RETURN_IF_ERROR(cleanup_members()); RETURN_OK_STATUS(); } bool ActionProfAccessManual::retrieve_member_handle( const Id &member_id, pi_indirect_handle_t *member_h) const { auto *h_ptr = member_map.get_first_handle(member_id); if (!h_ptr) return false; *member_h = *h_ptr; return true; } bool ActionProfAccessManual::retrieve_group_handle( const Id &group_id, pi_indirect_handle_t *group_h) const { auto *h_ptr = group_bimap.retrieve_handle(group_id); if (!h_ptr) return false; *group_h = *h_ptr; return true; } bool ActionProfAccessManual::retrieve_member_id( pi_indirect_handle_t member_h, Id *member_id) const { auto *id_ptr = member_map.retrieve_id(member_h); if (!id_ptr) return false; *member_id = *id_ptr; return true; } bool ActionProfAccessManual::retrieve_group_id( pi_indirect_handle_t group_h, Id *group_id) const { auto *id_ptr = group_bimap.retrieve_id(group_h); if (!id_ptr) return false; *group_id = *id_ptr; return true; } struct ActionProfAccessOneshot::OneShotGroupCleanupTask : common::LocalCleanupIface { OneShotGroupCleanupTask(ActionProfAccessOneshot *action_prof_access_oneshot, pi_indirect_handle_t group_h) : access(action_prof_access_oneshot), group_h(group_h) { } Status cleanup(const SessionTemp &session) override { if (!access) RETURN_OK_STATUS(); pi::ActProf ap( session.get(), access->device_tgt, access->p4info, access->act_prof_id); auto pi_status = ap.group_delete(group_h); if (pi_status != PI_STATUS_SUCCESS) { RETURN_ERROR_STATUS( Code::INTERNAL, "Error encountered when cleaning up action profile group created " "by one-shot indirect table programming. This is a serious error and " "there is now a dangling action profile group. You may need to " "reboot the system"); } RETURN_OK_STATUS(); } void cancel() override { access = nullptr; } ActionProfAccessOneshot *access; pi_indirect_handle_t group_h; }; struct ActionProfAccessOneshot::OneShotMemberCleanupTask : common::LocalCleanupIface { OneShotMemberCleanupTask(ActionProfAccessOneshot *action_prof_access_oneshot, pi_indirect_handle_t member_h) : access(action_prof_access_oneshot), member_h(member_h) { } Status cleanup(const SessionTemp &session) override { if (!access) RETURN_OK_STATUS(); pi::ActProf ap( session.get(), access->device_tgt, access->p4info, access->act_prof_id); auto pi_status = ap.member_delete(member_h); if (pi_status != PI_STATUS_SUCCESS) { RETURN_ERROR_STATUS( Code::INTERNAL, "Error encountered when cleaning up action profile member created " "by one-shot indirect table programming. This is a serious error and " "you may need to reboot the system"); } RETURN_OK_STATUS(); } void cancel() override { access = nullptr; } ActionProfAccessOneshot *access; pi_indirect_handle_t member_h; }; struct ActionProfAccessOneshot::OneShotWatchPortCleanupTask : common::LocalCleanupIface { OneShotWatchPortCleanupTask( ActionProfAccessOneshot *action_prof_access_oneshot, pi_indirect_handle_t group_h, pi_indirect_handle_t member_h, pi_port_t watch) : access(action_prof_access_oneshot), group_h(group_h), member_h(member_h), watch(watch) { } Status cleanup(const SessionTemp &session) override { (void)session; if (!access) RETURN_OK_STATUS(); // no reason to fail, we are just updating the watch_port_enforcer internal // state auto status = access->watch_port_enforcer->delete_member( access->act_prof_id, group_h, member_h, watch); if (IS_ERROR(status)) { RETURN_ERROR_STATUS( Code::INTERNAL, "Error encountered when undoing changes to action profile group " "member watch port status committed during one-shot indirect table " "programming. This is a serious error and you may need to reboot " "the system"); } RETURN_OK_STATUS(); } void cancel() override { access = nullptr; } ActionProfAccessOneshot *access; pi_indirect_handle_t group_h; pi_indirect_handle_t member_h; pi_port_t watch; }; bool ActionProfAccessOneshot::empty() const { return group_members.empty(); } Status ActionProfAccessOneshot::group_create_helper( pi::ActProf &ap, pi_indirect_handle_t group_h, std::vector<pi_indirect_handle_t> members_h, std::vector<pi_port_t> members_watch_port, SessionTemp *session) { if (pi_api_choice == PiApiChoice::INDIVIDUAL_ADDS_AND_REMOVES) { for (size_t i = 0; i < members_h.size(); i++) { auto pi_status = ap.group_add_member(group_h, members_h[i]); if (pi_status != PI_STATUS_SUCCESS) { RETURN_ERROR_STATUS( Code::UNKNOWN, "Error when adding member to group on target"); } RETURN_IF_ERROR(watch_port_enforcer->add_member_and_update_hw( &ap, group_h, members_h[i], members_watch_port[i])); session->cleanup_task_push(std::unique_ptr<OneShotWatchPortCleanupTask>( new OneShotWatchPortCleanupTask( this, group_h, members_h[i], members_watch_port[i]))); } } else if (pi_api_choice == PiApiChoice::SET_MEMBERSHIP) { std::unique_ptr<bool[]> activate(new bool[members_h.size()]); for (size_t i = 0; i < members_h.size(); i++) { auto port_status = watch_port_enforcer->get_port_status( act_prof_id, members_watch_port[i]); activate[i] = (port_status == PI_PORT_STATUS_UP); } auto pi_status = ap.group_set_members( group_h, members_h.size(), members_h.data(), activate.get()); if (pi_status != PI_STATUS_SUCCESS) { RETURN_ERROR_STATUS( Code::UNKNOWN, "Error when setting group membership on target"); } for (size_t i = 0; i < members_h.size(); i++) { RETURN_IF_ERROR(watch_port_enforcer->add_member( act_prof_id, group_h, members_h[i], members_watch_port[i])); session->cleanup_task_push(std::unique_ptr<OneShotWatchPortCleanupTask>( new OneShotWatchPortCleanupTask( this, group_h, members_h[i], members_watch_port[i]))); } } else { RETURN_ERROR_STATUS(Code::INTERNAL, "Unknown PiApiChoice"); } RETURN_OK_STATUS(); } Status ActionProfAccessOneshot::group_create( const p4::v1::ActionProfileActionSet &action_set, pi_indirect_handle_t *group_h, SessionTemp *session) { if (action_set.action_profile_actions().empty()) { RETURN_ERROR_STATUS( Code::UNIMPLEMENTED, "No support for empty action profile groups"); } for (const auto &action : action_set.action_profile_actions()) RETURN_IF_ERROR(validate_action(action.action())); size_t sum_of_weights = 0; for (const auto &action : action_set.action_profile_actions()) { if (action.weight() <= 0) { RETURN_ERROR_STATUS(Code::INVALID_ARGUMENT, "Member weight must be a positive integer value"); } sum_of_weights += action.weight(); } if (max_group_size > 0 && sum_of_weights > max_group_size) { RETURN_ERROR_STATUS( Code::RESOURCE_EXHAUSTED, "Sum of weights exceeds static max_group_size (from P4Info)"); } session->cleanup_scope_push(); pi::ActProf ap(session->get(), device_tgt, p4info, act_prof_id); std::vector<OneShotMember> members; std::vector<pi_indirect_handle_t> members_h; std::vector<pi_port_t> members_watch_port; for (const auto &action : action_set.action_profile_actions()) { for (int i = 0; i < action.weight(); i++) { pi_indirect_handle_t member_h; pi::ActionData action_data(p4info, action.action().action_id()); RETURN_IF_ERROR( construct_action_data(p4info, action.action(), &action_data)); auto pi_status = ap.member_create(action_data, &member_h); if (pi_status != PI_STATUS_SUCCESS) { RETURN_ERROR_STATUS( Code::UNKNOWN, "Error when creating member on target"); } auto watch = WatchPort::make(action); members.push_back({member_h, (i == 0) ? action.weight() : 0, watch}); members_h.push_back(member_h); members_watch_port.push_back(watch.pi_port); session->cleanup_task_push(std::unique_ptr<OneShotMemberCleanupTask>( new OneShotMemberCleanupTask(this, member_h))); } } { auto pi_status = ap.group_create( action_set.action_profile_actions_size(), group_h); if (pi_status != PI_STATUS_SUCCESS) RETURN_ERROR_STATUS(Code::UNKNOWN, "Error when creating group on target"); session->cleanup_task_push(std::unique_ptr<OneShotGroupCleanupTask>( new OneShotGroupCleanupTask(this, *group_h))); } assert(members_h.size() == members_watch_port.size()); RETURN_IF_ERROR(group_create_helper( ap, *group_h, members_h, members_watch_port, session)); session->cleanup_scope_pop(); auto p = group_members.emplace(*group_h, members); assert(p.second); (void)p; RETURN_OK_STATUS(); } Status ActionProfAccessOneshot::group_delete(pi_indirect_handle_t group_h, const SessionTemp &session) { auto members_it = group_members.find(group_h); assert(members_it != group_members.end()); pi::ActProf ap(session.get(), device_tgt, p4info, act_prof_id); // Group needs to be deleted first, otherwise target may complain about group // referencing members which no longer exist. { auto pi_status = ap.group_delete(group_h); if (pi_status != PI_STATUS_SUCCESS) RETURN_ERROR_STATUS(Code::UNKNOWN, "Error when deleting group on target"); } for (const auto &member : members_it->second) { auto pi_status = ap.member_delete(member.member_h); if (pi_status != PI_STATUS_SUCCESS) { RETURN_ERROR_STATUS( Code::UNKNOWN, "Error when deleting member on target"); } // no reason to fail, we are just updating the watch_port_enforcer internal // state RETURN_IF_ERROR(watch_port_enforcer->delete_member( act_prof_id, group_h, member.member_h, member.watch.pi_port)); } group_members.erase(members_it); RETURN_OK_STATUS(); } bool ActionProfAccessOneshot::group_get_members( pi_indirect_handle_t group_h, std::vector<OneShotMember> *members) const { auto it = group_members.find(group_h); if (it == group_members.end()) return false; *members = it->second; return true; } ActionProfMgr::ActionProfMgr(pi_dev_tgt_t device_tgt, pi_p4_id_t act_prof_id, pi_p4info_t *p4info, PiApiChoice pi_api_choice, WatchPortEnforcer *watch_port_enforcer) : device_tgt(device_tgt), act_prof_id(act_prof_id), p4info(p4info), pi_api_choice(pi_api_choice), watch_port_enforcer(watch_port_enforcer), pimp(nullptr) { } namespace { template <typename T> struct AccessType; template <> struct AccessType<ActionProfAccessManual> { static constexpr ActionProfMgr::SelectorUsage usage = ActionProfMgr::SelectorUsage::MANUAL; }; template <> struct AccessType<ActionProfAccessOneshot> { static constexpr ActionProfMgr::SelectorUsage usage = ActionProfMgr::SelectorUsage::ONESHOT; }; } // namespace template <typename T> Status ActionProfMgr::check_selector_usage() { if (selector_usage == AccessType<T>::usage) RETURN_OK_STATUS(); if (selector_usage == SelectorUsage::UNSPECIFIED || pimp->empty()) { selector_usage = AccessType<T>::usage; pimp.reset(new T( device_tgt, act_prof_id, p4info, pi_api_choice, watch_port_enforcer)); RETURN_OK_STATUS(); } RETURN_ERROR_STATUS( Code::INVALID_ARGUMENT, "Invalid attempt to mix action selector programming modes"); } StatusOr<ActionProfAccessOneshot *> ActionProfMgr::oneshot() { RETURN_IF_ERROR(check_selector_usage<ActionProfAccessOneshot>()); return static_cast<ActionProfAccessOneshot *>(pimp.get()); } StatusOr<ActionProfAccessManual *> ActionProfMgr::manual() { RETURN_IF_ERROR(check_selector_usage<ActionProfAccessManual>()); return static_cast<ActionProfAccessManual *>(pimp.get()); } /* static */ StatusOr<ActionProfMgr::PiApiChoice> ActionProfMgr::choose_pi_api(pi_dev_id_t device_id) { int pi_api_support = pi_act_prof_api_support(device_id); if (pi_api_support & PI_ACT_PROF_API_SUPPORT_GRP_SET_MBRS) { return PiApiChoice::SET_MEMBERSHIP; } else if (pi_api_support & PI_ACT_PROF_API_SUPPORT_GRP_ADD_AND_REMOVE_MBR) { return PiApiChoice::INDIVIDUAL_ADDS_AND_REMOVES; } RETURN_ERROR_STATUS(Code::INTERNAL, "Invalid return value from pi_act_prof_api_support"); } } // namespace proto } // namespace fe } // namespace pi
44,559
15,118
#if !defined MOUSE #define MOUSE #include "Entity.hpp" #include "Utils.hpp" #include "Text.hpp" #include "Shape.hpp" struct Mouse : public Entity{ bool must_draw = true; int must_draw_cooldown = 500; glm::vec3 color_on_left_click = {0.2f, 1.0f, 0.2f}; glm::vec3 color_on_right_click = {1.0f, 0.0f, 0.5f}; glm::vec3 normal_color = {1.0f, 1.0f, 1.0f}; Mouse(){ this->setNome("Mouse"); this->setColor(this->normal_color); this->transform.eulerRotation.z = 45.0f; this->is_movable = true; } virtual void draw(){ if (must_draw) Entity::draw(); } // Desenha se puder ser desenhado virtual void update_position_on_world(int x, int y){ glm::vec4 position_on_world = glm::inverse(parent->transform.modelMatrix)*glm::vec4(x, y, 0.0f, 1.0f); this->transform.position.x = position_on_world.x; this->transform.position.y = position_on_world.y; } virtual void act(int* keyStatus, GLdouble deltaTime){ must_draw_cooldown -= deltaTime; if(keyStatus[(int) ('m')] && must_draw_cooldown <= 0){ must_draw_cooldown = 500; must_draw = !must_draw; std::string message = must_draw ? "Mouse is showing" : "Mouse is not showing"; #if defined TEST //std::cout << message << std::endl; #endif Left_Corner_Timed_Minitext::change_left_corner_text(message); } if(keyStatus[MOUSE_LEFT_CLICK]) this->setColor(color_on_left_click); else if(keyStatus[MOUSE_RIGHT_CLICK]) this->setColor(color_on_right_click); else this->setColor(normal_color); } }; #endif
1,700
615
// // Created by Aman LaChapelle on 2019-02-13. // // tyr // Copyright (c) 2019 Aman LaChapelle // Full license at tyr/LICENSE.txt // /* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef TYR_PASSMANAGER_HPP #define TYR_PASSMANAGER_HPP #include "Pass.hpp" #include <llvm/ADT/SmallVector.h> namespace tyr { class Module; class PassManager { public: void registerPass(ir::Pass::Ptr pass); bool runOnModule(Module &m); private: llvm::SmallVector<ir::Pass::Ptr, 0> m_passes_; }; } // namespace tyr #endif // TYR_PASSMANAGER_HPP
1,059
372
/* Copyright (c) 2020 Hirokazu Ishida This software is released under the MIT License, see LICENSE. tinyfk: https://github.com/HiroIshida/tinyfk */ // inefficient methods which will be used only in test #include "tinyfk.hpp" namespace tinyfk { void RobotModel::get_link_point( unsigned int link_id, urdf::Pose& out_tf_rlink_to_elink, bool basealso) const { // h : here , e: endeffector , r: root, p: parent // e.g. hlink means here_link and rlink means root_link urdf::LinkSharedPtr hlink = _links[link_id]; urdf::Pose tf_hlink_to_elink; // unit transform by default while(true){ // transform from parent to child links are computed by combining // three transforms: tf_here_to_joint, tf_joint_to_joint, tf_joint_to_parent, in order. const urdf::JointSharedPtr& pjoint = hlink->parent_joint; if(pjoint == nullptr){ if(basealso){tf_hlink_to_elink = pose_transform(_base_pose._pose, tf_hlink_to_elink);} break; } urdf::Pose tf_plink_to_hlink; const urdf::Pose& tf_plink_to_pjoint = pjoint->parent_to_joint_origin_transform; if(pjoint->type==urdf::Joint::FIXED){ tf_plink_to_hlink = tf_plink_to_pjoint; }else{ double angle = _joint_angles[pjoint->id]; urdf::Pose tf_pjoint_to_hlink = pjoint->transform(angle); tf_plink_to_hlink = pose_transform(tf_plink_to_pjoint, tf_pjoint_to_hlink); } urdf::Pose tf_plink_to_elink = pose_transform(tf_plink_to_hlink, tf_hlink_to_elink); // update here node tf_hlink_to_elink = std::move(tf_plink_to_elink); hlink = hlink->getParent(); } out_tf_rlink_to_elink = tf_hlink_to_elink; } Eigen::MatrixXd RobotModel::get_jacobian_naive( unsigned int elink_id, const std::vector<unsigned int>& joint_ids, bool rotalso, bool basealso) { unsigned int n_pose_dim = (rotalso ? 6 : 3); unsigned int n_joints = joint_ids.size(); unsigned int n_dof = (basealso ? n_joints + 3 : n_joints); Eigen::MatrixXd J = Eigen::MatrixXd::Zero(n_pose_dim, n_dof); double dx = 1e-7; std::vector<double> q0 = this->get_joint_angles(joint_ids); urdf::Pose pose0, pose1; this->get_link_point(elink_id, pose0, basealso); for(unsigned int i=0; i<n_joints; i++){ int jid = joint_ids[i]; this->set_joint_angle(jid, q0[i] + dx); this->get_link_point(elink_id, pose1, basealso); this->set_joint_angle(jid, q0[i]); // must to set to the original urdf::Vector3& pos0 = pose0.position; urdf::Vector3& pos1 = pose1.position; J(0, i) = (pos1.x - pos0.x)/dx; J(1, i) = (pos1.y - pos0.y)/dx; J(2, i) = (pos1.z - pos0.z)/dx; if(rotalso){ urdf::Vector3&& rpy0 = pose0.rotation.getRPY(); urdf::Vector3&& rpy1 = pose1.rotation.getRPY(); urdf::Vector3 rpy_diff = rpy1 - rpy0; J(3, i) = rpy_diff.x/dx; J(4, i) = rpy_diff.y/dx; J(5, i) = rpy_diff.z/dx; } } if(basealso){ for(unsigned int i=0; i<3; i++){ std::array<double, 3>& tmp = _base_pose._pose3d; tmp[i] += dx; this->set_base_pose(tmp[0], tmp[1], tmp[2]); this->get_link_point(elink_id, pose1, true); tmp[i] -= dx; this->set_base_pose(tmp[0], tmp[1], tmp[2]); urdf::Vector3& pos0 = pose0.position; urdf::Vector3& pos1 = pose1.position; J(0, n_joints+i) = (pos1.x - pos0.x)/dx; J(1, n_joints+i) = (pos1.y - pos0.y)/dx; J(2, n_joints+i) = (pos1.z - pos0.z)/dx; if(rotalso){ urdf::Vector3&& rpy0 = pose0.rotation.getRPY(); urdf::Vector3&& rpy1 = pose1.rotation.getRPY(); urdf::Vector3 rpy_diff = rpy1 - rpy0; J(3, n_joints+i) = rpy_diff.x/dx; J(4, n_joints+i) = rpy_diff.y/dx; J(5, n_joints+i) = rpy_diff.z/dx; } } } return J; } }
3,920
1,594
#include <ConfigManager.hpp> void ConfigManager::ReplaceInString( const std::string& replacement, std::string& textStr, std::int64_t start, std::int64_t end ) noexcept { textStr.replace(start, end - start, replacement); } std::string ConfigManager::GetLineFromString( const std::string& textString, std::int64_t start, std::int64_t end ) noexcept { std::string foundLine; foundLine = std::string(textString.begin() + start, textString.begin() + end); return foundLine; } std::pair<std::int64_t, std::int64_t> ConfigManager::FindInString( const std::string& textStr, const std::string& searchItem ) noexcept { auto start = std::search( textStr.begin(), textStr.end(), searchItem.begin(), searchItem.end() ); std::string::const_iterator end; if (start != textStr.end()) end = std::find(start, textStr.end(), '\n'); std::int64_t startPos = -1; std::int64_t endPos = -1; if (start != textStr.end() && end != textStr.end()) { startPos = std::distance(textStr.begin(), start); endPos = std::distance(textStr.begin(), end) + 1; } return { startPos, endPos }; } std::string ConfigManager::FileToString(const char* fileName) noexcept { std::ifstream input(fileName, std::ios_base::in); std::string buffer; std::string str; while (std::getline(input, buffer)) str.append(buffer + "\n"s); return str; }
1,488
506
#pragma once // Generated by map_print/map_print2/lane_graph_to_cpp.m // Do not edit #include <vector> /** * \defgroup lane_graph_one_lane Lane Graph With One Lane * \ingroup central_routing * TODO */ /** * \struct LaneGraph * \brief TODO * \ingroup lane_graph_one_lane */ struct LaneGraph { //! TODO const size_t n_nodes = 44; //! TODO const std::vector<double> nodes_x = std::vector<double>{2.2500e+00,3.1500e+00,3.8074e+00,4.2103e+00,4.2450e+00,4.0623e+00,3.8242e+00,3.0500e+00,2.4750e+00,2.6065e+00,3.1425e+00,2.2500e+00,2.4750e+00,2.0250e+00,3.0500e+00,1.3500e+00,6.9264e-01,2.8966e-01,2.5500e-01,6.7576e-01,4.3775e-01,1.4500e+00,1.8935e+00,1.3575e+00,2.0250e+00,1.4500e+00,3.1500e+00,2.2500e+00,3.8074e+00,4.2103e+00,3.8242e+00,4.0623e+00,2.6065e+00,2.4750e+00,3.1425e+00,2.2500e+00,2.0250e+00,1.3500e+00,6.9264e-01,2.8966e-01,4.3775e-01,6.7576e-01,1.8935e+00,1.3575e+00,}; //! TODO const std::vector<double> nodes_y = std::vector<double>{3.7450e+00,3.7390e+00,3.5902e+00,2.9310e+00,2.0000e+00,2.9071e+00,2.3258e+00,2.2250e+00,2.8000e+00,3.4081e+00,3.5892e+00,2.2250e+00,2.0000e+00,2.8000e+00,1.7750e+00,3.7390e+00,3.5902e+00,2.9310e+00,2.0000e+00,2.3258e+00,2.9071e+00,2.2250e+00,3.4081e+00,3.5892e+00,2.0000e+00,1.7750e+00,2.6100e-01,2.5500e-01,4.0979e-01,1.0690e+00,1.6742e+00,1.0929e+00,5.9189e-01,1.2000e+00,4.1081e-01,1.7750e+00,1.2000e+00,2.6100e-01,4.0979e-01,1.0690e+00,1.0929e+00,1.6742e+00,5.9189e-01,4.1081e-01,}; //! TODO const std::vector<double> nodes_cos = std::vector<double>{1.0000e+00,9.9875e-01,8.7677e-01,1.5918e-01,0.0000e+00,1.5925e-01,-8.7962e-01,-1.0000e+00,-4.0327e-05,6.1691e-01,9.9874e-01,-1.0000e+00,0.0000e+00,-4.0327e-05,1.0000e+00,9.9875e-01,8.7677e-01,1.5918e-01,0.0000e+00,-8.7962e-01,1.5925e-01,-1.0000e+00,6.1691e-01,9.9874e-01,0.0000e+00,1.0000e+00,-9.9875e-01,-1.0000e+00,-8.7677e-01,-1.5918e-01,8.7962e-01,-1.5925e-01,-6.1691e-01,4.0327e-05,-9.9874e-01,1.0000e+00,4.0327e-05,-9.9875e-01,-8.7677e-01,-1.5918e-01,-1.5925e-01,8.7962e-01,-6.1691e-01,-9.9874e-01,}; //! TODO const std::vector<double> nodes_sin = std::vector<double>{0.0000e+00,-5.0058e-02,-4.8090e-01,-9.8725e-01,-1.0000e+00,-9.8724e-01,-4.7568e-01,3.4305e-05,1.0000e+00,7.8703e-01,-5.0169e-02,0.0000e+00,1.0000e+00,-1.0000e+00,3.4305e-05,5.0058e-02,4.8090e-01,9.8725e-01,1.0000e+00,4.7568e-01,9.8724e-01,-3.4305e-05,-7.8703e-01,5.0169e-02,-1.0000e+00,-3.4305e-05,-5.0058e-02,0.0000e+00,-4.8090e-01,-9.8725e-01,-4.7568e-01,-9.8724e-01,7.8703e-01,1.0000e+00,-5.0169e-02,0.0000e+00,-1.0000e+00,5.0058e-02,4.8090e-01,9.8725e-01,9.8724e-01,4.7568e-01,-7.8703e-01,5.0169e-02,}; //! TODO const size_t n_edges = 56; //! TODO const size_t n_edge_path_nodes = 25; //! TODO const std::vector<size_t> edges_start_index = std::vector<size_t>{0,1,2,3,5,6,8,9,7,7,12,13,10,2,15,16,17,18,19,21,22,23,11,13,13,25,16,20,26,28,29,4,30,14,32,34,35,33,33,7,28,31,27,37,38,39,40,41,36,42,25,25,24,33,43,38,}; //! TODO const std::vector<size_t> edges_end_index = std::vector<size_t>{1,2,3,4,6,7,9,10,11,8,8,14,2,5,0,15,16,17,20,19,13,22,21,21,24,8,23,16,27,26,28,29,31,30,33,32,14,14,12,36,34,28,37,38,39,18,41,25,42,43,35,36,36,21,38,40,}; //! TODO const std::vector<std::vector<double>> edges_x = std::vector<std::vector<double>> { std::vector<double>{2.2500e+00,2.2874e+00,2.3249e+00,2.3627e+00,2.4001e+00,2.4376e+00,2.4750e+00,2.5125e+00,2.5499e+00,2.5877e+00,2.6252e+00,2.6626e+00,2.7001e+00,2.7375e+00,2.7749e+00,2.8127e+00,2.8502e+00,2.8876e+00,2.9251e+00,2.9625e+00,3.0000e+00,3.0378e+00,3.0752e+00,3.1126e+00,3.1500e+00,}, std::vector<double>{3.1500e+00,3.1781e+00,3.2066e+00,3.2347e+00,3.2632e+00,3.2912e+00,3.3196e+00,3.3476e+00,3.3755e+00,3.4038e+00,3.4316e+00,3.4597e+00,3.4874e+00,3.5150e+00,3.5428e+00,3.5701e+00,3.5977e+00,3.6247e+00,3.6518e+00,3.6784e+00,3.7047e+00,3.7311e+00,3.7568e+00,3.7824e+00,3.8074e+00,}, std::vector<double>{3.8074e+00,3.8398e+00,3.8716e+00,3.9020e+00,3.9312e+00,3.9590e+00,3.9834e+00,4.0049e+00,4.0252e+00,4.0443e+00,4.0624e+00,4.0792e+00,4.0948e+00,4.1094e+00,4.1231e+00,4.1356e+00,4.1472e+00,4.1578e+00,4.1677e+00,4.1766e+00,4.1847e+00,4.1921e+00,4.1989e+00,4.2049e+00,4.2103e+00,}, std::vector<double>{4.2103e+00,4.2161e+00,4.2212e+00,4.2255e+00,4.2292e+00,4.2324e+00,4.2350e+00,4.2372e+00,4.2391e+00,4.2405e+00,4.2417e+00,4.2426e+00,4.2434e+00,4.2439e+00,4.2443e+00,4.2446e+00,4.2448e+00,4.2449e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,}, std::vector<double>{4.0623e+00,4.0671e+00,4.0710e+00,4.0738e+00,4.0755e+00,4.0760e+00,4.0752e+00,4.0730e+00,4.0695e+00,4.0646e+00,4.0582e+00,4.0503e+00,4.0410e+00,4.0302e+00,4.0180e+00,4.0044e+00,3.9895e+00,3.9731e+00,3.9555e+00,3.9365e+00,3.9162e+00,3.8948e+00,3.8724e+00,3.8488e+00,3.8242e+00,}, std::vector<double>{3.8242e+00,3.7987e+00,3.7723e+00,3.7448e+00,3.7167e+00,3.6879e+00,3.6584e+00,3.6282e+00,3.5975e+00,3.5658e+00,3.5340e+00,3.5017e+00,3.4689e+00,3.4357e+00,3.4020e+00,3.3677e+00,3.3334e+00,3.2988e+00,3.2639e+00,3.2287e+00,3.1933e+00,3.1574e+00,3.1217e+00,3.0859e+00,3.0500e+00,}, std::vector<double>{2.4750e+00,2.4750e+00,2.4751e+00,2.4753e+00,2.4758e+00,2.4765e+00,2.4776e+00,2.4790e+00,2.4809e+00,2.4834e+00,2.4864e+00,2.4900e+00,2.4943e+00,2.4993e+00,2.5050e+00,2.5114e+00,2.5187e+00,2.5267e+00,2.5356e+00,2.5453e+00,2.5559e+00,2.5673e+00,2.5795e+00,2.5926e+00,2.6065e+00,}, std::vector<double>{2.6065e+00,2.6212e+00,2.6367e+00,2.6532e+00,2.6702e+00,2.6880e+00,2.7066e+00,2.7258e+00,2.7457e+00,2.7664e+00,2.7876e+00,2.8094e+00,2.8317e+00,2.8546e+00,2.8781e+00,2.9023e+00,2.9268e+00,2.9518e+00,2.9773e+00,3.0034e+00,3.0300e+00,3.0574e+00,3.0851e+00,3.1135e+00,3.1425e+00,}, std::vector<double>{3.0500e+00,3.0167e+00,2.9833e+00,2.9500e+00,2.9167e+00,2.8834e+00,2.8500e+00,2.8167e+00,2.7834e+00,2.7499e+00,2.7167e+00,2.6834e+00,2.6499e+00,2.6166e+00,2.5833e+00,2.5501e+00,2.5166e+00,2.4833e+00,2.4500e+00,2.4166e+00,2.3833e+00,2.3500e+00,2.3167e+00,2.2833e+00,2.2500e+00,}, std::vector<double>{3.0500e+00,3.0012e+00,2.9543e+00,2.9097e+00,2.8670e+00,2.8263e+00,2.7873e+00,2.7504e+00,2.7155e+00,2.6826e+00,2.6520e+00,2.6237e+00,2.5976e+00,2.5741e+00,2.5532e+00,2.5349e+00,2.5191e+00,2.5060e+00,2.4955e+00,2.4875e+00,2.4817e+00,2.4780e+00,2.4759e+00,2.4751e+00,2.4750e+00,}, std::vector<double>{2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,}, std::vector<double>{2.0250e+00,2.0251e+00,2.0261e+00,2.0289e+00,2.0345e+00,2.0440e+00,2.0584e+00,2.0784e+00,2.1049e+00,2.1383e+00,2.1787e+00,2.2258e+00,2.2796e+00,2.3388e+00,2.4025e+00,2.4698e+00,2.5397e+00,2.6102e+00,2.6805e+00,2.7498e+00,2.8167e+00,2.8806e+00,2.9411e+00,2.9978e+00,3.0500e+00,}, std::vector<double>{3.1425e+00,3.1708e+00,3.1992e+00,3.2275e+00,3.2558e+00,3.2840e+00,3.3123e+00,3.3402e+00,3.3681e+00,3.3959e+00,3.4234e+00,3.4509e+00,3.4786e+00,3.5063e+00,3.5341e+00,3.5622e+00,3.5905e+00,3.6188e+00,3.6471e+00,3.6752e+00,3.7029e+00,3.7300e+00,3.7564e+00,3.7823e+00,3.8074e+00,}, std::vector<double>{3.8074e+00,3.8350e+00,3.8618e+00,3.8871e+00,3.9107e+00,3.9323e+00,3.9516e+00,3.9684e+00,3.9827e+00,3.9945e+00,4.0040e+00,4.0115e+00,4.0172e+00,4.0215e+00,4.0249e+00,4.0275e+00,4.0299e+00,4.0323e+00,4.0351e+00,4.0383e+00,4.0421e+00,4.0466e+00,4.0516e+00,4.0570e+00,4.0623e+00,}, std::vector<double>{1.3500e+00,1.3874e+00,1.4248e+00,1.4626e+00,1.5000e+00,1.5375e+00,1.5749e+00,1.6124e+00,1.6498e+00,1.6876e+00,1.7251e+00,1.7625e+00,1.7999e+00,1.8374e+00,1.8748e+00,1.9126e+00,1.9501e+00,1.9875e+00,2.0250e+00,2.0624e+00,2.0999e+00,2.1377e+00,2.1751e+00,2.2126e+00,2.2500e+00,}, std::vector<double>{6.9264e-01,7.1756e-01,7.4321e-01,7.6891e-01,7.9527e-01,8.2160e-01,8.4851e-01,8.7532e-01,9.0233e-01,9.2985e-01,9.5719e-01,9.8500e-01,1.0126e+00,1.0403e+00,1.0684e+00,1.0962e+00,1.1245e+00,1.1524e+00,1.1808e+00,1.2088e+00,1.2368e+00,1.2653e+00,1.2934e+00,1.3219e+00,1.3500e+00,}, std::vector<double>{2.8966e-01,2.9508e-01,3.0117e-01,3.0786e-01,3.1525e-01,3.2339e-01,3.3240e-01,3.4216e-01,3.5281e-01,3.6437e-01,3.7703e-01,3.9057e-01,4.0517e-01,4.2084e-01,4.3779e-01,4.5573e-01,4.7482e-01,4.9510e-01,5.1677e-01,5.4098e-01,5.6883e-01,5.9804e-01,6.2874e-01,6.6023e-01,6.9264e-01,}, std::vector<double>{2.5500e-01,2.5500e-01,2.5500e-01,2.5500e-01,2.5500e-01,2.5501e-01,2.5505e-01,2.5511e-01,2.5523e-01,2.5542e-01,2.5570e-01,2.5609e-01,2.5663e-01,2.5735e-01,2.5829e-01,2.5947e-01,2.6095e-01,2.6277e-01,2.6499e-01,2.6763e-01,2.7080e-01,2.7452e-01,2.7887e-01,2.8387e-01,2.8966e-01,}, std::vector<double>{6.7576e-01,6.5119e-01,6.2764e-01,6.0517e-01,5.8362e-01,5.6346e-01,5.4453e-01,5.2687e-01,5.1054e-01,4.9556e-01,4.8197e-01,4.6979e-01,4.5895e-01,4.4967e-01,4.4183e-01,4.3545e-01,4.3049e-01,4.2696e-01,4.2480e-01,4.2399e-01,4.2448e-01,4.2618e-01,4.2903e-01,4.3293e-01,4.3775e-01,}, std::vector<double>{1.4500e+00,1.4141e+00,1.3783e+00,1.3422e+00,1.3067e+00,1.2713e+00,1.2361e+00,1.2012e+00,1.1666e+00,1.1319e+00,1.0980e+00,1.0643e+00,1.0311e+00,9.9834e-01,9.6600e-01,9.3385e-01,9.0254e-01,8.7178e-01,8.4163e-01,8.1213e-01,7.8331e-01,7.5497e-01,7.2770e-01,7.0128e-01,6.7576e-01,}, std::vector<double>{1.8935e+00,1.9074e+00,1.9205e+00,1.9327e+00,1.9442e+00,1.9547e+00,1.9644e+00,1.9733e+00,1.9813e+00,1.9886e+00,1.9950e+00,2.0007e+00,2.0057e+00,2.0100e+00,2.0136e+00,2.0166e+00,2.0191e+00,2.0210e+00,2.0224e+00,2.0235e+00,2.0242e+00,2.0247e+00,2.0249e+00,2.0250e+00,2.0250e+00,}, std::vector<double>{1.3575e+00,1.3865e+00,1.4149e+00,1.4429e+00,1.4700e+00,1.4966e+00,1.5227e+00,1.5482e+00,1.5732e+00,1.5980e+00,1.6219e+00,1.6454e+00,1.6683e+00,1.6906e+00,1.7124e+00,1.7338e+00,1.7543e+00,1.7742e+00,1.7934e+00,1.8120e+00,1.8298e+00,1.8470e+00,1.8633e+00,1.8788e+00,1.8935e+00,}, std::vector<double>{2.2500e+00,2.2167e+00,2.1833e+00,2.1500e+00,2.1167e+00,2.0834e+00,2.0500e+00,2.0167e+00,1.9834e+00,1.9499e+00,1.9167e+00,1.8834e+00,1.8499e+00,1.8166e+00,1.7833e+00,1.7501e+00,1.7166e+00,1.6833e+00,1.6500e+00,1.6166e+00,1.5833e+00,1.5500e+00,1.5167e+00,1.4833e+00,1.4500e+00,}, std::vector<double>{2.0250e+00,2.0249e+00,2.0241e+00,2.0220e+00,2.0183e+00,2.0125e+00,2.0045e+00,1.9940e+00,1.9809e+00,1.9651e+00,1.9468e+00,1.9259e+00,1.9023e+00,1.8763e+00,1.8480e+00,1.8174e+00,1.7845e+00,1.7496e+00,1.7127e+00,1.6737e+00,1.6330e+00,1.5903e+00,1.5457e+00,1.4988e+00,1.4500e+00,}, std::vector<double>{2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,}, std::vector<double>{1.4500e+00,1.5022e+00,1.5589e+00,1.6194e+00,1.6833e+00,1.7502e+00,1.8195e+00,1.8898e+00,1.9603e+00,2.0302e+00,2.0975e+00,2.1612e+00,2.2207e+00,2.2742e+00,2.3213e+00,2.3617e+00,2.3951e+00,2.4216e+00,2.4416e+00,2.4560e+00,2.4655e+00,2.4711e+00,2.4739e+00,2.4749e+00,2.4750e+00,}, std::vector<double>{6.9264e-01,7.1772e-01,7.4356e-01,7.7000e-01,7.9711e-01,8.2477e-01,8.5295e-01,8.8120e-01,9.0949e-01,9.3783e-01,9.6586e-01,9.9370e-01,1.0215e+00,1.0491e+00,1.0766e+00,1.1041e+00,1.1319e+00,1.1598e+00,1.1877e+00,1.2160e+00,1.2442e+00,1.2725e+00,1.3008e+00,1.3292e+00,1.3575e+00,}, std::vector<double>{4.3775e-01,4.4302e-01,4.4837e-01,4.5338e-01,4.5785e-01,4.6170e-01,4.6494e-01,4.6766e-01,4.7008e-01,4.7247e-01,4.7514e-01,4.7845e-01,4.8280e-01,4.8851e-01,4.9596e-01,5.0547e-01,5.1733e-01,5.3160e-01,5.4838e-01,5.6772e-01,5.8928e-01,6.1287e-01,6.3819e-01,6.6499e-01,6.9264e-01,}, std::vector<double>{3.1500e+00,3.1126e+00,3.0752e+00,3.0374e+00,3.0000e+00,2.9625e+00,2.9251e+00,2.8876e+00,2.8502e+00,2.8124e+00,2.7749e+00,2.7375e+00,2.7001e+00,2.6626e+00,2.6252e+00,2.5874e+00,2.5499e+00,2.5125e+00,2.4750e+00,2.4376e+00,2.4001e+00,2.3623e+00,2.3249e+00,2.2874e+00,2.2500e+00,}, std::vector<double>{3.8074e+00,3.7824e+00,3.7568e+00,3.7311e+00,3.7047e+00,3.6784e+00,3.6515e+00,3.6247e+00,3.5977e+00,3.5701e+00,3.5428e+00,3.5150e+00,3.4874e+00,3.4597e+00,3.4316e+00,3.4038e+00,3.3755e+00,3.3476e+00,3.3192e+00,3.2912e+00,3.2632e+00,3.2347e+00,3.2066e+00,3.1781e+00,3.1500e+00,}, std::vector<double>{4.2103e+00,4.2049e+00,4.1988e+00,4.1921e+00,4.1847e+00,4.1766e+00,4.1676e+00,4.1578e+00,4.1472e+00,4.1356e+00,4.1230e+00,4.1094e+00,4.0948e+00,4.0792e+00,4.0622e+00,4.0443e+00,4.0252e+00,4.0049e+00,3.9832e+00,3.9590e+00,3.9312e+00,3.9020e+00,3.8713e+00,3.8398e+00,3.8074e+00,}, std::vector<double>{4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2450e+00,4.2449e+00,4.2448e+00,4.2446e+00,4.2443e+00,4.2439e+00,4.2434e+00,4.2426e+00,4.2417e+00,4.2405e+00,4.2391e+00,4.2372e+00,4.2350e+00,4.2324e+00,4.2292e+00,4.2255e+00,4.2211e+00,4.2161e+00,4.2103e+00,}, std::vector<double>{3.8242e+00,3.8488e+00,3.8724e+00,3.8948e+00,3.9164e+00,3.9365e+00,3.9555e+00,3.9731e+00,3.9895e+00,4.0044e+00,4.0180e+00,4.0302e+00,4.0411e+00,4.0503e+00,4.0582e+00,4.0646e+00,4.0695e+00,4.0730e+00,4.0752e+00,4.0760e+00,4.0755e+00,4.0738e+00,4.0710e+00,4.0671e+00,4.0623e+00,}, std::vector<double>{3.0500e+00,3.0859e+00,3.1217e+00,3.1578e+00,3.1933e+00,3.2287e+00,3.2639e+00,3.2988e+00,3.3334e+00,3.3681e+00,3.4020e+00,3.4357e+00,3.4689e+00,3.5017e+00,3.5340e+00,3.5661e+00,3.5975e+00,3.6282e+00,3.6584e+00,3.6879e+00,3.7167e+00,3.7450e+00,3.7723e+00,3.7987e+00,3.8242e+00,}, std::vector<double>{2.6065e+00,2.5926e+00,2.5795e+00,2.5673e+00,2.5558e+00,2.5453e+00,2.5356e+00,2.5267e+00,2.5187e+00,2.5114e+00,2.5050e+00,2.4993e+00,2.4943e+00,2.4900e+00,2.4864e+00,2.4834e+00,2.4809e+00,2.4790e+00,2.4776e+00,2.4765e+00,2.4758e+00,2.4753e+00,2.4751e+00,2.4750e+00,2.4750e+00,}, std::vector<double>{3.1425e+00,3.1135e+00,3.0851e+00,3.0571e+00,3.0300e+00,3.0034e+00,2.9773e+00,2.9518e+00,2.9268e+00,2.9020e+00,2.8781e+00,2.8546e+00,2.8317e+00,2.8094e+00,2.7876e+00,2.7662e+00,2.7457e+00,2.7258e+00,2.7066e+00,2.6880e+00,2.6702e+00,2.6530e+00,2.6367e+00,2.6212e+00,2.6065e+00,}, std::vector<double>{2.2500e+00,2.2833e+00,2.3167e+00,2.3500e+00,2.3833e+00,2.4166e+00,2.4500e+00,2.4833e+00,2.5166e+00,2.5501e+00,2.5833e+00,2.6166e+00,2.6501e+00,2.6834e+00,2.7167e+00,2.7499e+00,2.7834e+00,2.8167e+00,2.8500e+00,2.8834e+00,2.9167e+00,2.9500e+00,2.9833e+00,3.0167e+00,3.0500e+00,}, std::vector<double>{2.4750e+00,2.4751e+00,2.4759e+00,2.4780e+00,2.4817e+00,2.4875e+00,2.4955e+00,2.5060e+00,2.5191e+00,2.5349e+00,2.5532e+00,2.5741e+00,2.5977e+00,2.6237e+00,2.6520e+00,2.6826e+00,2.7155e+00,2.7504e+00,2.7873e+00,2.8263e+00,2.8670e+00,2.9097e+00,2.9543e+00,3.0012e+00,3.0500e+00,}, std::vector<double>{2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,2.4750e+00,}, std::vector<double>{3.0500e+00,2.9978e+00,2.9411e+00,2.8806e+00,2.8167e+00,2.7498e+00,2.6805e+00,2.6102e+00,2.5397e+00,2.4698e+00,2.4025e+00,2.3388e+00,2.2793e+00,2.2258e+00,2.1787e+00,2.1383e+00,2.1049e+00,2.0784e+00,2.0584e+00,2.0440e+00,2.0345e+00,2.0289e+00,2.0261e+00,2.0251e+00,2.0250e+00,}, std::vector<double>{3.8074e+00,3.7823e+00,3.7564e+00,3.7300e+00,3.7029e+00,3.6752e+00,3.6471e+00,3.6188e+00,3.5905e+00,3.5622e+00,3.5341e+00,3.5063e+00,3.4785e+00,3.4509e+00,3.4234e+00,3.3959e+00,3.3681e+00,3.3402e+00,3.3123e+00,3.2840e+00,3.2558e+00,3.2275e+00,3.1992e+00,3.1708e+00,3.1425e+00,}, std::vector<double>{4.0623e+00,4.0570e+00,4.0516e+00,4.0466e+00,4.0421e+00,4.0383e+00,4.0351e+00,4.0323e+00,4.0299e+00,4.0275e+00,4.0249e+00,4.0215e+00,4.0172e+00,4.0115e+00,4.0040e+00,3.9945e+00,3.9827e+00,3.9684e+00,3.9516e+00,3.9323e+00,3.9107e+00,3.8871e+00,3.8618e+00,3.8350e+00,3.8074e+00,}, std::vector<double>{2.2500e+00,2.2126e+00,2.1751e+00,2.1373e+00,2.0999e+00,2.0624e+00,2.0250e+00,1.9875e+00,1.9501e+00,1.9123e+00,1.8748e+00,1.8374e+00,1.7999e+00,1.7625e+00,1.7251e+00,1.6873e+00,1.6498e+00,1.6124e+00,1.5749e+00,1.5375e+00,1.5000e+00,1.4622e+00,1.4248e+00,1.3874e+00,1.3500e+00,}, std::vector<double>{1.3500e+00,1.3219e+00,1.2934e+00,1.2653e+00,1.2368e+00,1.2088e+00,1.1804e+00,1.1524e+00,1.1245e+00,1.0962e+00,1.0684e+00,1.0403e+00,1.0126e+00,9.8500e-01,9.5719e-01,9.2985e-01,9.0233e-01,8.7532e-01,8.4818e-01,8.2160e-01,7.9527e-01,7.6891e-01,7.4321e-01,7.1756e-01,6.9264e-01,}, std::vector<double>{6.9264e-01,6.6023e-01,6.2845e-01,5.9804e-01,5.6883e-01,5.4098e-01,5.1656e-01,4.9510e-01,4.7482e-01,4.5573e-01,4.3763e-01,4.2084e-01,4.0517e-01,3.9057e-01,3.7690e-01,3.6437e-01,3.5281e-01,3.4216e-01,3.3231e-01,3.2339e-01,3.1525e-01,3.0786e-01,3.0111e-01,2.9508e-01,2.8966e-01,}, std::vector<double>{2.8966e-01,2.8387e-01,2.7883e-01,2.7452e-01,2.7080e-01,2.6763e-01,2.6497e-01,2.6277e-01,2.6095e-01,2.5947e-01,2.5828e-01,2.5735e-01,2.5663e-01,2.5609e-01,2.5569e-01,2.5542e-01,2.5523e-01,2.5511e-01,2.5504e-01,2.5501e-01,2.5500e-01,2.5500e-01,2.5500e-01,2.5500e-01,2.5500e-01,}, std::vector<double>{4.3775e-01,4.3293e-01,4.2903e-01,4.2618e-01,4.2447e-01,4.2399e-01,4.2480e-01,4.2696e-01,4.3049e-01,4.3545e-01,4.4183e-01,4.4967e-01,4.5905e-01,4.6979e-01,4.8197e-01,4.9556e-01,5.1054e-01,5.2687e-01,5.4453e-01,5.6346e-01,5.8382e-01,6.0517e-01,6.2764e-01,6.5119e-01,6.7576e-01,}, std::vector<double>{6.7576e-01,7.0128e-01,7.2770e-01,7.5524e-01,7.8331e-01,8.1213e-01,8.4163e-01,8.7178e-01,9.0254e-01,9.3416e-01,9.6600e-01,9.9834e-01,1.0311e+00,1.0643e+00,1.0980e+00,1.1323e+00,1.1666e+00,1.2012e+00,1.2361e+00,1.2713e+00,1.3067e+00,1.3426e+00,1.3783e+00,1.4141e+00,1.4500e+00,}, std::vector<double>{2.0250e+00,2.0250e+00,2.0249e+00,2.0247e+00,2.0242e+00,2.0235e+00,2.0224e+00,2.0210e+00,2.0191e+00,2.0166e+00,2.0136e+00,2.0100e+00,2.0057e+00,2.0007e+00,1.9950e+00,1.9886e+00,1.9813e+00,1.9733e+00,1.9644e+00,1.9547e+00,1.9441e+00,1.9327e+00,1.9205e+00,1.9074e+00,1.8935e+00,}, std::vector<double>{1.8935e+00,1.8788e+00,1.8633e+00,1.8468e+00,1.8298e+00,1.8120e+00,1.7934e+00,1.7742e+00,1.7543e+00,1.7336e+00,1.7124e+00,1.6906e+00,1.6683e+00,1.6454e+00,1.6219e+00,1.5977e+00,1.5732e+00,1.5482e+00,1.5227e+00,1.4966e+00,1.4700e+00,1.4426e+00,1.4149e+00,1.3865e+00,1.3575e+00,}, std::vector<double>{1.4500e+00,1.4833e+00,1.5167e+00,1.5500e+00,1.5833e+00,1.6166e+00,1.6500e+00,1.6833e+00,1.7166e+00,1.7501e+00,1.7833e+00,1.8166e+00,1.8501e+00,1.8834e+00,1.9167e+00,1.9499e+00,1.9834e+00,2.0167e+00,2.0500e+00,2.0834e+00,2.1167e+00,2.1500e+00,2.1833e+00,2.2167e+00,2.2500e+00,}, std::vector<double>{1.4500e+00,1.4988e+00,1.5457e+00,1.5903e+00,1.6330e+00,1.6737e+00,1.7127e+00,1.7496e+00,1.7845e+00,1.8174e+00,1.8480e+00,1.8763e+00,1.9024e+00,1.9259e+00,1.9468e+00,1.9651e+00,1.9809e+00,1.9940e+00,2.0045e+00,2.0125e+00,2.0183e+00,2.0220e+00,2.0241e+00,2.0249e+00,2.0250e+00,}, std::vector<double>{2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,2.0250e+00,}, std::vector<double>{2.4750e+00,2.4749e+00,2.4739e+00,2.4711e+00,2.4655e+00,2.4560e+00,2.4416e+00,2.4216e+00,2.3951e+00,2.3617e+00,2.3213e+00,2.2742e+00,2.2204e+00,2.1612e+00,2.0975e+00,2.0302e+00,1.9603e+00,1.8898e+00,1.8195e+00,1.7502e+00,1.6833e+00,1.6194e+00,1.5589e+00,1.5022e+00,1.4500e+00,}, std::vector<double>{1.3575e+00,1.3292e+00,1.3008e+00,1.2725e+00,1.2442e+00,1.2160e+00,1.1877e+00,1.1598e+00,1.1319e+00,1.1041e+00,1.0766e+00,1.0491e+00,1.0214e+00,9.9370e-01,9.6586e-01,9.3783e-01,9.0949e-01,8.8120e-01,8.5295e-01,8.2477e-01,7.9711e-01,7.7000e-01,7.4356e-01,7.1772e-01,6.9264e-01,}, std::vector<double>{6.9264e-01,6.6499e-01,6.3819e-01,6.1287e-01,5.8928e-01,5.6772e-01,5.4838e-01,5.3160e-01,5.1733e-01,5.0547e-01,4.9596e-01,4.8851e-01,4.8277e-01,4.7845e-01,4.7514e-01,4.7247e-01,4.7008e-01,4.6766e-01,4.6494e-01,4.6170e-01,4.5785e-01,4.5338e-01,4.4837e-01,4.4302e-01,4.3775e-01,}, }; //! TODO const std::vector<std::vector<double>> edges_y = std::vector<std::vector<double>> { std::vector<double>{3.7450e+00,3.7450e+00,3.7450e+00,3.7450e+00,3.7451e+00,3.7451e+00,3.7452e+00,3.7453e+00,3.7454e+00,3.7455e+00,3.7456e+00,3.7457e+00,3.7458e+00,3.7459e+00,3.7459e+00,3.7459e+00,3.7457e+00,3.7455e+00,3.7452e+00,3.7447e+00,3.7441e+00,3.7432e+00,3.7421e+00,3.7407e+00,3.7390e+00,}, std::vector<double>{3.7390e+00,3.7375e+00,3.7357e+00,3.7337e+00,3.7315e+00,3.7289e+00,3.7260e+00,3.7228e+00,3.7193e+00,3.7153e+00,3.7110e+00,3.7061e+00,3.7009e+00,3.6951e+00,3.6888e+00,3.6819e+00,3.6744e+00,3.6664e+00,3.6576e+00,3.6483e+00,3.6383e+00,3.6274e+00,3.6158e+00,3.6033e+00,3.5902e+00,}, std::vector<double>{3.5902e+00,3.5715e+00,3.5510e+00,3.5292e+00,3.5057e+00,3.4807e+00,3.4561e+00,3.4321e+00,3.4072e+00,3.3812e+00,3.3543e+00,3.3268e+00,3.2987e+00,3.2700e+00,3.2405e+00,3.2109e+00,3.1808e+00,3.1505e+00,3.1195e+00,3.0886e+00,3.0574e+00,3.0261e+00,2.9943e+00,2.9627e+00,2.9310e+00,}, std::vector<double>{2.9310e+00,2.8925e+00,2.8539e+00,2.8155e+00,2.7767e+00,2.7379e+00,2.6991e+00,2.6605e+00,2.6216e+00,2.5827e+00,2.5438e+00,2.5052e+00,2.4663e+00,2.4273e+00,2.3884e+00,2.3498e+00,2.3108e+00,2.2719e+00,2.2330e+00,2.1944e+00,2.1554e+00,2.1165e+00,2.0776e+00,2.0389e+00,2.0000e+00,}, std::vector<double>{2.9071e+00,2.8750e+00,2.8436e+00,2.8128e+00,2.7824e+00,2.7528e+00,2.7238e+00,2.6954e+00,2.6675e+00,2.6402e+00,2.6135e+00,2.5875e+00,2.5619e+00,2.5373e+00,2.5134e+00,2.4904e+00,2.4682e+00,2.4469e+00,2.4265e+00,2.4072e+00,2.3886e+00,2.3713e+00,2.3551e+00,2.3399e+00,2.3258e+00,}, std::vector<double>{2.3258e+00,2.3128e+00,2.3009e+00,2.2899e+00,2.2801e+00,2.2713e+00,2.2635e+00,2.2566e+00,2.2505e+00,2.2453e+00,2.2409e+00,2.2372e+00,2.2342e+00,2.2317e+00,2.2297e+00,2.2282e+00,2.2271e+00,2.2263e+00,2.2257e+00,2.2254e+00,2.2252e+00,2.2251e+00,2.2250e+00,2.2250e+00,2.2250e+00,}, std::vector<double>{2.8000e+00,2.8304e+00,2.8604e+00,2.8900e+00,2.9196e+00,2.9485e+00,2.9770e+00,3.0051e+00,3.0328e+00,3.0601e+00,3.0870e+00,3.1134e+00,3.1397e+00,3.1652e+00,3.1902e+00,3.2148e+00,3.2388e+00,3.2622e+00,3.2850e+00,3.3072e+00,3.3290e+00,3.3499e+00,3.3700e+00,3.3895e+00,3.4081e+00,}, std::vector<double>{3.4081e+00,3.4260e+00,3.4430e+00,3.4593e+00,3.4745e+00,3.4889e+00,3.5023e+00,3.5148e+00,3.5263e+00,3.5370e+00,3.5466e+00,3.5552e+00,3.5629e+00,3.5696e+00,3.5753e+00,3.5802e+00,3.5842e+00,3.5873e+00,3.5895e+00,3.5910e+00,3.5918e+00,3.5919e+00,3.5914e+00,3.5905e+00,3.5892e+00,}, std::vector<double>{2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,}, std::vector<double>{2.2250e+00,2.2251e+00,2.2259e+00,2.2280e+00,2.2317e+00,2.2375e+00,2.2455e+00,2.2560e+00,2.2691e+00,2.2849e+00,2.3032e+00,2.3241e+00,2.3477e+00,2.3737e+00,2.4020e+00,2.4326e+00,2.4655e+00,2.5004e+00,2.5373e+00,2.5763e+00,2.6170e+00,2.6597e+00,2.7043e+00,2.7512e+00,2.8000e+00,}, std::vector<double>{2.0000e+00,2.0333e+00,2.0667e+00,2.1000e+00,2.1333e+00,2.1666e+00,2.2000e+00,2.2333e+00,2.2666e+00,2.3001e+00,2.3333e+00,2.3666e+00,2.4001e+00,2.4334e+00,2.4667e+00,2.4999e+00,2.5334e+00,2.5667e+00,2.6000e+00,2.6334e+00,2.6667e+00,2.7000e+00,2.7333e+00,2.7667e+00,2.8000e+00,}, std::vector<double>{2.8000e+00,2.7478e+00,2.6911e+00,2.6306e+00,2.5667e+00,2.4998e+00,2.4305e+00,2.3602e+00,2.2897e+00,2.2198e+00,2.1525e+00,2.0888e+00,2.0293e+00,1.9758e+00,1.9287e+00,1.8883e+00,1.8549e+00,1.8284e+00,1.8084e+00,1.7940e+00,1.7845e+00,1.7789e+00,1.7761e+00,1.7751e+00,1.7750e+00,}, std::vector<double>{3.5892e+00,3.5878e+00,3.5867e+00,3.5864e+00,3.5871e+00,3.5889e+00,3.5920e+00,3.5962e+00,3.6014e+00,3.6074e+00,3.6138e+00,3.6204e+00,3.6269e+00,3.6328e+00,3.6379e+00,3.6417e+00,3.6441e+00,3.6446e+00,3.6430e+00,3.6393e+00,3.6333e+00,3.6252e+00,3.6152e+00,3.6033e+00,3.5902e+00,}, std::vector<double>{3.5902e+00,3.5742e+00,3.5566e+00,3.5371e+00,3.5156e+00,3.4921e+00,3.4665e+00,3.4393e+00,3.4108e+00,3.3810e+00,3.3505e+00,3.3194e+00,3.2879e+00,3.2562e+00,3.2245e+00,3.1927e+00,3.1607e+00,3.1288e+00,3.0970e+00,3.0651e+00,3.0334e+00,3.0018e+00,2.9702e+00,2.9386e+00,2.9071e+00,}, std::vector<double>{3.7390e+00,3.7407e+00,3.7421e+00,3.7432e+00,3.7441e+00,3.7447e+00,3.7452e+00,3.7455e+00,3.7457e+00,3.7459e+00,3.7459e+00,3.7459e+00,3.7458e+00,3.7457e+00,3.7456e+00,3.7455e+00,3.7454e+00,3.7453e+00,3.7452e+00,3.7451e+00,3.7451e+00,3.7450e+00,3.7450e+00,3.7450e+00,3.7450e+00,}, std::vector<double>{3.5902e+00,3.6033e+00,3.6158e+00,3.6274e+00,3.6383e+00,3.6483e+00,3.6578e+00,3.6664e+00,3.6744e+00,3.6819e+00,3.6888e+00,3.6951e+00,3.7009e+00,3.7061e+00,3.7110e+00,3.7153e+00,3.7193e+00,3.7228e+00,3.7261e+00,3.7289e+00,3.7315e+00,3.7337e+00,3.7357e+00,3.7375e+00,3.7390e+00,}, std::vector<double>{2.9310e+00,2.9627e+00,2.9946e+00,3.0261e+00,3.0574e+00,3.0886e+00,3.1198e+00,3.1505e+00,3.1808e+00,3.2109e+00,3.2408e+00,3.2700e+00,3.2987e+00,3.3268e+00,3.3545e+00,3.3812e+00,3.4072e+00,3.4321e+00,3.4564e+00,3.4807e+00,3.5057e+00,3.5292e+00,3.5512e+00,3.5715e+00,3.5902e+00,}, std::vector<double>{2.0000e+00,2.0389e+00,2.0779e+00,2.1165e+00,2.1554e+00,2.1944e+00,2.2333e+00,2.2719e+00,2.3108e+00,2.3498e+00,2.3887e+00,2.4273e+00,2.4663e+00,2.5052e+00,2.5441e+00,2.5827e+00,2.6216e+00,2.6605e+00,2.6994e+00,2.7379e+00,2.7767e+00,2.8155e+00,2.8542e+00,2.8925e+00,2.9310e+00,}, std::vector<double>{2.3258e+00,2.3399e+00,2.3551e+00,2.3713e+00,2.3888e+00,2.4072e+00,2.4265e+00,2.4469e+00,2.4682e+00,2.4904e+00,2.5134e+00,2.5373e+00,2.5621e+00,2.5875e+00,2.6135e+00,2.6402e+00,2.6675e+00,2.6954e+00,2.7238e+00,2.7528e+00,2.7827e+00,2.8128e+00,2.8436e+00,2.8750e+00,2.9071e+00,}, std::vector<double>{2.2250e+00,2.2250e+00,2.2250e+00,2.2251e+00,2.2252e+00,2.2254e+00,2.2257e+00,2.2263e+00,2.2271e+00,2.2282e+00,2.2297e+00,2.2317e+00,2.2342e+00,2.2372e+00,2.2409e+00,2.2454e+00,2.2505e+00,2.2566e+00,2.2635e+00,2.2713e+00,2.2801e+00,2.2900e+00,2.3009e+00,2.3128e+00,2.3258e+00,}, std::vector<double>{3.4081e+00,3.3895e+00,3.3700e+00,3.3499e+00,3.3288e+00,3.3072e+00,3.2850e+00,3.2622e+00,3.2388e+00,3.2148e+00,3.1902e+00,3.1652e+00,3.1394e+00,3.1134e+00,3.0870e+00,3.0601e+00,3.0328e+00,3.0051e+00,2.9770e+00,2.9485e+00,2.9193e+00,2.8900e+00,2.8604e+00,2.8304e+00,2.8000e+00,}, std::vector<double>{3.5892e+00,3.5905e+00,3.5914e+00,3.5919e+00,3.5918e+00,3.5910e+00,3.5895e+00,3.5873e+00,3.5842e+00,3.5802e+00,3.5753e+00,3.5696e+00,3.5629e+00,3.5552e+00,3.5466e+00,3.5369e+00,3.5263e+00,3.5148e+00,3.5023e+00,3.4889e+00,3.4745e+00,3.4591e+00,3.4430e+00,3.4260e+00,3.4081e+00,}, std::vector<double>{2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,2.2250e+00,}, std::vector<double>{2.8000e+00,2.7512e+00,2.7043e+00,2.6597e+00,2.6170e+00,2.5763e+00,2.5373e+00,2.5004e+00,2.4655e+00,2.4326e+00,2.4020e+00,2.3737e+00,2.3476e+00,2.3241e+00,2.3032e+00,2.2849e+00,2.2691e+00,2.2560e+00,2.2455e+00,2.2375e+00,2.2317e+00,2.2280e+00,2.2259e+00,2.2251e+00,2.2250e+00,}, std::vector<double>{2.8000e+00,2.7667e+00,2.7333e+00,2.7000e+00,2.6667e+00,2.6334e+00,2.6000e+00,2.5667e+00,2.5334e+00,2.4999e+00,2.4667e+00,2.4334e+00,2.3999e+00,2.3666e+00,2.3333e+00,2.3001e+00,2.2666e+00,2.2333e+00,2.2000e+00,2.1666e+00,2.1333e+00,2.1000e+00,2.0667e+00,2.0333e+00,2.0000e+00,}, std::vector<double>{1.7750e+00,1.7751e+00,1.7761e+00,1.7789e+00,1.7845e+00,1.7940e+00,1.8084e+00,1.8284e+00,1.8549e+00,1.8883e+00,1.9287e+00,1.9758e+00,2.0296e+00,2.0888e+00,2.1525e+00,2.2198e+00,2.2897e+00,2.3602e+00,2.4305e+00,2.4998e+00,2.5667e+00,2.6306e+00,2.6911e+00,2.7478e+00,2.8000e+00,}, std::vector<double>{3.5902e+00,3.6033e+00,3.6152e+00,3.6252e+00,3.6333e+00,3.6393e+00,3.6430e+00,3.6446e+00,3.6441e+00,3.6417e+00,3.6379e+00,3.6328e+00,3.6268e+00,3.6204e+00,3.6138e+00,3.6074e+00,3.6014e+00,3.5962e+00,3.5920e+00,3.5889e+00,3.5871e+00,3.5864e+00,3.5867e+00,3.5878e+00,3.5892e+00,}, std::vector<double>{2.9071e+00,2.9386e+00,2.9702e+00,3.0018e+00,3.0334e+00,3.0651e+00,3.0970e+00,3.1288e+00,3.1607e+00,3.1927e+00,3.2245e+00,3.2562e+00,3.2880e+00,3.3194e+00,3.3505e+00,3.3810e+00,3.4108e+00,3.4393e+00,3.4665e+00,3.4921e+00,3.5156e+00,3.5371e+00,3.5566e+00,3.5742e+00,3.5902e+00,}, std::vector<double>{2.6100e-01,2.5929e-01,2.5791e-01,2.5679e-01,2.5593e-01,2.5527e-01,2.5480e-01,2.5447e-01,2.5426e-01,2.5415e-01,2.5412e-01,2.5414e-01,2.5421e-01,2.5430e-01,2.5441e-01,2.5452e-01,2.5463e-01,2.5473e-01,2.5482e-01,2.5489e-01,2.5494e-01,2.5497e-01,2.5499e-01,2.5500e-01,2.5500e-01,}, std::vector<double>{4.0979e-01,3.9666e-01,3.8418e-01,3.7264e-01,3.6173e-01,3.5169e-01,3.4224e-01,3.3357e-01,3.2555e-01,3.1805e-01,3.1123e-01,3.0488e-01,2.9914e-01,2.9388e-01,2.8904e-01,2.8470e-01,2.8071e-01,2.7717e-01,2.7394e-01,2.7109e-01,2.6855e-01,2.6627e-01,2.6428e-01,2.6251e-01,2.6100e-01,}, std::vector<double>{1.0690e+00,1.0373e+00,1.0054e+00,9.7390e-01,9.4258e-01,9.1143e-01,8.8021e-01,8.4954e-01,8.1917e-01,7.8913e-01,7.5920e-01,7.3000e-01,7.0132e-01,6.7320e-01,6.4548e-01,6.1876e-01,5.9285e-01,5.6785e-01,5.4364e-01,5.1929e-01,4.9427e-01,4.7085e-01,4.4881e-01,4.2854e-01,4.0979e-01,}, std::vector<double>{2.0000e+00,1.9611e+00,1.9221e+00,1.8835e+00,1.8446e+00,1.8056e+00,1.7667e+00,1.7281e+00,1.6892e+00,1.6502e+00,1.6113e+00,1.5727e+00,1.5337e+00,1.4948e+00,1.4559e+00,1.4173e+00,1.3784e+00,1.3395e+00,1.3006e+00,1.2621e+00,1.2233e+00,1.1845e+00,1.1458e+00,1.1075e+00,1.0690e+00,}, std::vector<double>{1.6742e+00,1.6601e+00,1.6449e+00,1.6287e+00,1.6112e+00,1.5928e+00,1.5735e+00,1.5531e+00,1.5318e+00,1.5096e+00,1.4866e+00,1.4627e+00,1.4379e+00,1.4125e+00,1.3865e+00,1.3598e+00,1.3325e+00,1.3046e+00,1.2762e+00,1.2472e+00,1.2173e+00,1.1872e+00,1.1564e+00,1.1250e+00,1.0929e+00,}, std::vector<double>{1.7750e+00,1.7750e+00,1.7750e+00,1.7749e+00,1.7748e+00,1.7746e+00,1.7743e+00,1.7737e+00,1.7729e+00,1.7718e+00,1.7703e+00,1.7683e+00,1.7658e+00,1.7628e+00,1.7591e+00,1.7546e+00,1.7495e+00,1.7434e+00,1.7365e+00,1.7287e+00,1.7199e+00,1.7100e+00,1.6991e+00,1.6872e+00,1.6742e+00,}, std::vector<double>{5.9189e-01,6.1053e-01,6.2995e-01,6.5012e-01,6.7120e-01,6.9276e-01,7.1498e-01,7.3782e-01,7.6125e-01,7.8524e-01,8.0976e-01,8.3480e-01,8.6058e-01,8.8657e-01,9.1302e-01,9.3991e-01,9.6721e-01,9.9492e-01,1.0230e+00,1.0515e+00,1.0807e+00,1.1100e+00,1.1396e+00,1.1696e+00,1.2000e+00,}, std::vector<double>{4.1081e-01,4.0949e-01,4.0855e-01,4.0809e-01,4.0822e-01,4.0899e-01,4.1048e-01,4.1274e-01,4.1583e-01,4.1981e-01,4.2466e-01,4.3043e-01,4.3714e-01,4.4480e-01,4.5342e-01,4.6312e-01,4.7369e-01,4.8522e-01,4.9770e-01,5.1113e-01,5.2548e-01,5.4089e-01,5.5704e-01,5.7405e-01,5.9189e-01,}, std::vector<double>{1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,}, std::vector<double>{1.2000e+00,1.2488e+00,1.2957e+00,1.3403e+00,1.3830e+00,1.4237e+00,1.4627e+00,1.4996e+00,1.5345e+00,1.5674e+00,1.5980e+00,1.6263e+00,1.6524e+00,1.6759e+00,1.6968e+00,1.7151e+00,1.7309e+00,1.7440e+00,1.7545e+00,1.7625e+00,1.7683e+00,1.7720e+00,1.7741e+00,1.7749e+00,1.7750e+00,}, std::vector<double>{1.2000e+00,1.2333e+00,1.2667e+00,1.3000e+00,1.3333e+00,1.3666e+00,1.4000e+00,1.4333e+00,1.4666e+00,1.5001e+00,1.5333e+00,1.5666e+00,1.6001e+00,1.6334e+00,1.6667e+00,1.6999e+00,1.7334e+00,1.7667e+00,1.8000e+00,1.8334e+00,1.8667e+00,1.9000e+00,1.9333e+00,1.9667e+00,2.0000e+00,}, std::vector<double>{2.2250e+00,2.2249e+00,2.2239e+00,2.2211e+00,2.2155e+00,2.2060e+00,2.1916e+00,2.1716e+00,2.1451e+00,2.1117e+00,2.0713e+00,2.0242e+00,1.9704e+00,1.9112e+00,1.8475e+00,1.7802e+00,1.7103e+00,1.6398e+00,1.5695e+00,1.5002e+00,1.4333e+00,1.3694e+00,1.3089e+00,1.2522e+00,1.2000e+00,}, std::vector<double>{4.0979e-01,3.9669e-01,3.8484e-01,3.7476e-01,3.6666e-01,3.6071e-01,3.5697e-01,3.5544e-01,3.5593e-01,3.5826e-01,3.6212e-01,3.6719e-01,3.7315e-01,3.7960e-01,3.8621e-01,3.9264e-01,3.9861e-01,4.0379e-01,4.0799e-01,4.1108e-01,4.1294e-01,4.1364e-01,4.1331e-01,4.1223e-01,4.1081e-01,}, std::vector<double>{1.0929e+00,1.0614e+00,1.0298e+00,9.9825e-01,9.6663e-01,9.3493e-01,9.0300e-01,8.7118e-01,8.3934e-01,8.0734e-01,7.7552e-01,7.4376e-01,7.1197e-01,6.8055e-01,6.4950e-01,6.1902e-01,5.8922e-01,5.6066e-01,5.3350e-01,5.0791e-01,4.8436e-01,4.6286e-01,4.4341e-01,4.2578e-01,4.0979e-01,}, std::vector<double>{2.5500e-01,2.5500e-01,2.5499e-01,2.5497e-01,2.5494e-01,2.5489e-01,2.5482e-01,2.5473e-01,2.5463e-01,2.5452e-01,2.5441e-01,2.5430e-01,2.5421e-01,2.5414e-01,2.5412e-01,2.5415e-01,2.5426e-01,2.5447e-01,2.5480e-01,2.5527e-01,2.5593e-01,2.5680e-01,2.5791e-01,2.5929e-01,2.6100e-01,}, std::vector<double>{2.6100e-01,2.6251e-01,2.6428e-01,2.6627e-01,2.6855e-01,2.7109e-01,2.7398e-01,2.7717e-01,2.8071e-01,2.8470e-01,2.8904e-01,2.9388e-01,2.9914e-01,3.0488e-01,3.1123e-01,3.1805e-01,3.2555e-01,3.3357e-01,3.4235e-01,3.5169e-01,3.6173e-01,3.7264e-01,3.8418e-01,3.9666e-01,4.0979e-01,}, std::vector<double>{4.0979e-01,4.2854e-01,4.4901e-01,4.7085e-01,4.9427e-01,5.1929e-01,5.4386e-01,5.6785e-01,5.9285e-01,6.1876e-01,6.4574e-01,6.7320e-01,7.0132e-01,7.3000e-01,7.5948e-01,7.8913e-01,8.1917e-01,8.4954e-01,8.8051e-01,9.1143e-01,9.4258e-01,9.7390e-01,1.0057e+00,1.0373e+00,1.0690e+00,}, std::vector<double>{1.0690e+00,1.1075e+00,1.1461e+00,1.1845e+00,1.2233e+00,1.2621e+00,1.3009e+00,1.3395e+00,1.3784e+00,1.4173e+00,1.4562e+00,1.4948e+00,1.5337e+00,1.5727e+00,1.6116e+00,1.6502e+00,1.6892e+00,1.7281e+00,1.7670e+00,1.8056e+00,1.8446e+00,1.8835e+00,1.9224e+00,1.9611e+00,2.0000e+00,}, std::vector<double>{1.0929e+00,1.1250e+00,1.1564e+00,1.1872e+00,1.2176e+00,1.2472e+00,1.2762e+00,1.3046e+00,1.3325e+00,1.3598e+00,1.3865e+00,1.4125e+00,1.4381e+00,1.4627e+00,1.4866e+00,1.5096e+00,1.5318e+00,1.5531e+00,1.5735e+00,1.5928e+00,1.6114e+00,1.6287e+00,1.6449e+00,1.6601e+00,1.6742e+00,}, std::vector<double>{1.6742e+00,1.6872e+00,1.6991e+00,1.7101e+00,1.7199e+00,1.7287e+00,1.7365e+00,1.7434e+00,1.7495e+00,1.7547e+00,1.7591e+00,1.7628e+00,1.7658e+00,1.7683e+00,1.7703e+00,1.7718e+00,1.7729e+00,1.7737e+00,1.7743e+00,1.7746e+00,1.7748e+00,1.7749e+00,1.7750e+00,1.7750e+00,1.7750e+00,}, std::vector<double>{1.2000e+00,1.1696e+00,1.1396e+00,1.1100e+00,1.0804e+00,1.0515e+00,1.0230e+00,9.9492e-01,9.6721e-01,9.3991e-01,9.1302e-01,8.8657e-01,8.6033e-01,8.3480e-01,8.0976e-01,7.8524e-01,7.6125e-01,7.3782e-01,7.1498e-01,6.9276e-01,6.7099e-01,6.5012e-01,6.2995e-01,6.1053e-01,5.9189e-01,}, std::vector<double>{5.9189e-01,5.7405e-01,5.5704e-01,5.4074e-01,5.2548e-01,5.1113e-01,4.9770e-01,4.8522e-01,4.7369e-01,4.6302e-01,4.5342e-01,4.4480e-01,4.3714e-01,4.3043e-01,4.2466e-01,4.1977e-01,4.1583e-01,4.1274e-01,4.1048e-01,4.0899e-01,4.0822e-01,4.0810e-01,4.0855e-01,4.0949e-01,4.1081e-01,}, std::vector<double>{1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,1.7750e+00,}, std::vector<double>{1.7750e+00,1.7749e+00,1.7741e+00,1.7720e+00,1.7683e+00,1.7625e+00,1.7545e+00,1.7440e+00,1.7309e+00,1.7151e+00,1.6968e+00,1.6759e+00,1.6523e+00,1.6263e+00,1.5980e+00,1.5674e+00,1.5345e+00,1.4996e+00,1.4627e+00,1.4237e+00,1.3830e+00,1.3403e+00,1.2957e+00,1.2488e+00,1.2000e+00,}, std::vector<double>{2.0000e+00,1.9667e+00,1.9333e+00,1.9000e+00,1.8667e+00,1.8334e+00,1.8000e+00,1.7667e+00,1.7334e+00,1.6999e+00,1.6667e+00,1.6334e+00,1.5999e+00,1.5666e+00,1.5333e+00,1.5001e+00,1.4666e+00,1.4333e+00,1.4000e+00,1.3666e+00,1.3333e+00,1.3000e+00,1.2667e+00,1.2333e+00,1.2000e+00,}, std::vector<double>{1.2000e+00,1.2522e+00,1.3089e+00,1.3694e+00,1.4333e+00,1.5002e+00,1.5695e+00,1.6398e+00,1.7103e+00,1.7802e+00,1.8475e+00,1.9112e+00,1.9707e+00,2.0242e+00,2.0713e+00,2.1117e+00,2.1451e+00,2.1716e+00,2.1916e+00,2.2060e+00,2.2155e+00,2.2211e+00,2.2239e+00,2.2249e+00,2.2250e+00,}, std::vector<double>{4.1081e-01,4.1223e-01,4.1331e-01,4.1364e-01,4.1294e-01,4.1108e-01,4.0799e-01,4.0379e-01,3.9861e-01,3.9264e-01,3.8621e-01,3.7960e-01,3.7312e-01,3.6719e-01,3.6212e-01,3.5826e-01,3.5593e-01,3.5544e-01,3.5697e-01,3.6071e-01,3.6666e-01,3.7476e-01,3.8484e-01,3.9669e-01,4.0979e-01,}, std::vector<double>{4.0979e-01,4.2578e-01,4.4341e-01,4.6286e-01,4.8436e-01,5.0791e-01,5.3350e-01,5.6066e-01,5.8922e-01,6.1902e-01,6.4950e-01,6.8055e-01,7.1212e-01,7.4376e-01,7.7552e-01,8.0734e-01,8.3934e-01,8.7118e-01,9.0300e-01,9.3493e-01,9.6663e-01,9.9825e-01,1.0298e+00,1.0614e+00,1.0929e+00,}, }; //! TODO const std::vector<std::vector<double>> edges_cos = std::vector<std::vector<double>> { std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,9.9999e-01,9.9998e-01,9.9994e-01,9.9989e-01,9.9980e-01,9.9966e-01,9.9945e-01,9.9916e-01,9.9875e-01,}, std::vector<double>{9.9874e-01,9.9834e-01,9.9782e-01,9.9718e-01,9.9639e-01,9.9543e-01,9.9425e-01,9.9286e-01,9.9119e-01,9.8918e-01,9.8684e-01,9.8405e-01,9.8083e-01,9.7709e-01,9.7269e-01,9.6768e-01,9.6184e-01,9.5525e-01,9.4764e-01,9.3909e-01,9.2943e-01,9.1839e-01,9.0613e-01,8.9223e-01,8.7689e-01,}, std::vector<double>{8.7668e-01,8.5381e-01,8.2711e-01,7.9696e-01,7.6281e-01,7.2437e-01,6.8524e-01,6.4841e-01,6.1169e-01,5.7533e-01,5.3922e-01,5.0421e-01,4.7011e-01,4.3707e-01,4.0489e-01,3.7425e-01,3.4491e-01,3.1691e-01,2.9005e-01,2.6484e-01,2.4102e-01,2.1860e-01,1.9736e-01,1.7769e-01,1.5934e-01,}, std::vector<double>{1.5917e-01,1.3887e-01,1.2022e-01,1.0346e-01,8.8219e-02,7.4569e-02,6.2418e-02,5.1759e-02,4.2332e-02,3.4137e-02,2.7085e-02,2.1129e-02,1.6086e-02,1.1920e-02,8.5433e-03,5.8890e-03,3.8309e-03,2.3096e-03,1.2433e-03,5.5588e-04,1.5791e-04,-2.1301e-05,-5.7829e-05,-2.6650e-05,-7.9530e-10,}, std::vector<double>{1.5916e-01,1.3673e-01,1.0857e-01,7.5298e-02,3.6965e-02,-5.2149e-03,-5.1077e-02,-1.0008e-01,-1.5165e-01,-2.0519e-01,-2.6008e-01,-3.1569e-01,-3.7194e-01,-4.2714e-01,-4.8128e-01,-5.3381e-01,-5.8426e-01,-6.3223e-01,-6.7737e-01,-7.1943e-01,-7.5856e-01,-7.9391e-01,-8.2582e-01,-8.5433e-01,-8.7951e-01,}, std::vector<double>{-8.7973e-01,-9.0149e-01,-9.2047e-01,-9.3679e-01,-9.5038e-01,-9.6165e-01,-9.7086e-01,-9.7827e-01,-9.8413e-01,-9.8871e-01,-9.9215e-01,-9.9471e-01,-9.9655e-01,-9.9784e-01,-9.9870e-01,-9.9927e-01,-9.9962e-01,-9.9981e-01,-9.9992e-01,-9.9997e-01,-9.9999e-01,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,}, std::vector<double>{3.6946e-08,1.1936e-03,4.8199e-03,1.0906e-02,1.9566e-02,3.0641e-02,4.4201e-02,6.0232e-02,7.8707e-02,9.9586e-02,1.2281e-01,1.4831e-01,1.7627e-01,2.0604e-01,2.3775e-01,2.7123e-01,3.0632e-01,3.4280e-01,3.8046e-01,4.1906e-01,4.5870e-01,4.9836e-01,5.3812e-01,5.7768e-01,6.1673e-01,}, std::vector<double>{6.1710e-01,6.5496e-01,6.9208e-01,7.2815e-01,7.6220e-01,7.9434e-01,8.2436e-01,8.5208e-01,8.7737e-01,9.0033e-01,9.2048e-01,9.3804e-01,9.5306e-01,9.6561e-01,9.7585e-01,9.8399e-01,9.9009e-01,9.9447e-01,9.9738e-01,9.9909e-01,9.9987e-01,9.9998e-01,9.9968e-01,9.9920e-01,9.9874e-01,}, std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,}, std::vector<double>{-1.0000e+00,-9.9997e-01,-9.9957e-01,-9.9792e-01,-9.9374e-01,-9.8549e-01,-9.7147e-01,-9.5026e-01,-9.2055e-01,-8.8126e-01,-8.3243e-01,-7.7419e-01,-7.0711e-01,-6.3332e-01,-5.5452e-01,-4.7303e-01,-3.9102e-01,-3.1183e-01,-2.3752e-01,-1.7002e-01,-1.1196e-01,-6.4637e-02,-2.9452e-02,-7.4995e-03,-5.8615e-08,}, std::vector<double>{-1.7344e-13,-2.2733e-08,-9.2211e-08,-1.7243e-07,-2.8353e-07,-3.9645e-07,-4.5504e-07,-4.7637e-07,-4.9573e-07,-4.7817e-07,-3.6141e-07,-1.5529e-07,5.4920e-08,2.0080e-07,3.0102e-07,4.0445e-07,5.0182e-07,5.2826e-07,4.6262e-07,3.6293e-07,2.7853e-07,1.8535e-07,8.4890e-08,2.5600e-08,-3.4688e-13,}, std::vector<double>{5.8625e-08,7.4285e-03,2.9314e-02,6.4437e-02,1.1170e-01,1.6972e-01,2.3717e-01,3.1145e-01,3.9063e-01,4.7264e-01,5.5413e-01,6.3295e-01,7.0711e-01,7.7389e-01,8.3217e-01,8.8104e-01,9.2038e-01,9.5014e-01,9.7138e-01,9.8544e-01,9.9371e-01,9.9791e-01,9.9957e-01,9.9997e-01,1.0000e+00,}, std::vector<double>{9.9874e-01,9.9889e-01,9.9964e-01,9.9999e-01,9.9900e-01,9.9619e-01,9.9162e-01,9.8597e-01,9.8021e-01,9.7542e-01,9.7265e-01,9.7255e-01,9.7531e-01,9.8050e-01,9.8717e-01,9.9382e-01,9.9869e-01,9.9985e-01,9.9574e-01,9.8528e-01,9.6853e-01,9.4651e-01,9.2151e-01,8.9681e-01,8.7678e-01,}, std::vector<double>{8.7678e-01,8.5245e-01,8.1593e-01,7.6771e-01,7.0852e-01,6.4008e-01,5.6463e-01,4.8614e-01,4.0774e-01,3.3245e-01,2.6400e-01,2.0438e-01,1.5506e-01,1.1748e-01,9.1685e-02,7.7371e-02,7.3685e-02,7.9282e-02,9.2241e-02,1.1029e-01,1.3039e-01,1.4931e-01,1.6332e-01,1.6821e-01,1.5925e-01,}, std::vector<double>{9.9875e-01,9.9916e-01,9.9945e-01,9.9966e-01,9.9980e-01,9.9989e-01,9.9994e-01,9.9998e-01,9.9999e-01,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,}, std::vector<double>{8.7689e-01,8.9223e-01,9.0613e-01,9.1839e-01,9.2943e-01,9.3909e-01,9.4774e-01,9.5525e-01,9.6184e-01,9.6768e-01,9.7269e-01,9.7709e-01,9.8083e-01,9.8405e-01,9.8684e-01,9.8918e-01,9.9119e-01,9.9286e-01,9.9427e-01,9.9543e-01,9.9639e-01,9.9718e-01,9.9782e-01,9.9834e-01,9.9874e-01,}, std::vector<double>{1.5934e-01,1.7769e-01,1.9756e-01,2.1860e-01,2.4102e-01,2.6484e-01,2.9030e-01,3.1691e-01,3.4491e-01,3.7425e-01,4.0518e-01,4.3707e-01,4.7011e-01,5.0421e-01,5.3955e-01,5.7533e-01,6.1169e-01,6.4841e-01,6.8559e-01,7.2437e-01,7.6281e-01,7.9696e-01,8.2737e-01,8.5381e-01,8.7668e-01,}, std::vector<double>{-7.9530e-10,-2.6650e-05,-5.7905e-05,-2.1301e-05,1.5791e-04,5.5588e-04,1.2502e-03,2.3096e-03,3.8309e-03,5.8890e-03,8.5670e-03,1.1920e-02,1.6086e-02,2.1129e-02,2.7136e-02,3.4137e-02,4.2332e-02,5.1759e-02,6.2508e-02,7.4569e-02,8.8219e-02,1.0346e-01,1.2036e-01,1.3887e-01,1.5917e-01,}, std::vector<double>{-8.7951e-01,-8.5433e-01,-8.2582e-01,-7.9391e-01,-7.5820e-01,-7.1943e-01,-6.7737e-01,-6.3223e-01,-5.8426e-01,-5.3381e-01,-4.8128e-01,-4.2714e-01,-3.7140e-01,-3.1569e-01,-2.6008e-01,-2.0519e-01,-1.5165e-01,-1.0008e-01,-5.1077e-02,-5.2149e-03,3.7351e-02,7.5298e-02,1.0857e-01,1.3673e-01,1.5916e-01,}, std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-9.9999e-01,-9.9997e-01,-9.9992e-01,-9.9981e-01,-9.9962e-01,-9.9927e-01,-9.9870e-01,-9.9784e-01,-9.9655e-01,-9.9471e-01,-9.9215e-01,-9.8867e-01,-9.8413e-01,-9.7827e-01,-9.7086e-01,-9.6165e-01,-9.5038e-01,-9.3665e-01,-9.2047e-01,-9.0149e-01,-8.7973e-01,}, std::vector<double>{6.1673e-01,5.7768e-01,5.3812e-01,4.9836e-01,4.5832e-01,4.1906e-01,3.8046e-01,3.4280e-01,3.0632e-01,2.7123e-01,2.3775e-01,2.0604e-01,1.7599e-01,1.4831e-01,1.2281e-01,9.9586e-02,7.8707e-02,6.0232e-02,4.4201e-02,3.0641e-02,1.9471e-02,1.0906e-02,4.8199e-03,1.1936e-03,3.6946e-08,}, std::vector<double>{9.9874e-01,9.9920e-01,9.9968e-01,9.9998e-01,9.9987e-01,9.9909e-01,9.9738e-01,9.9447e-01,9.9009e-01,9.8392e-01,9.7585e-01,9.6561e-01,9.5306e-01,9.3804e-01,9.2048e-01,9.0013e-01,8.7737e-01,8.5208e-01,8.2436e-01,7.9434e-01,7.6220e-01,7.2781e-01,6.9208e-01,6.5496e-01,6.1710e-01,}, std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,}, std::vector<double>{-5.8615e-08,-7.4995e-03,-2.9452e-02,-6.4637e-02,-1.1196e-01,-1.7002e-01,-2.3752e-01,-3.1183e-01,-3.9102e-01,-4.7303e-01,-5.5452e-01,-6.3332e-01,-7.0745e-01,-7.7419e-01,-8.3243e-01,-8.8126e-01,-9.2055e-01,-9.5026e-01,-9.7147e-01,-9.8549e-01,-9.9374e-01,-9.9792e-01,-9.9957e-01,-9.9997e-01,-1.0000e+00,}, std::vector<double>{-3.4688e-13,2.5600e-08,8.4890e-08,1.8535e-07,2.7853e-07,3.6293e-07,4.6262e-07,5.2826e-07,5.0182e-07,4.0445e-07,3.0102e-07,2.0080e-07,5.4045e-08,-1.5529e-07,-3.6141e-07,-4.7817e-07,-4.9573e-07,-4.7637e-07,-4.5504e-07,-3.9645e-07,-2.8353e-07,-1.7243e-07,-9.2211e-08,-2.2733e-08,-1.7344e-13,}, std::vector<double>{1.0000e+00,9.9997e-01,9.9957e-01,9.9791e-01,9.9371e-01,9.8544e-01,9.7138e-01,9.5014e-01,9.2038e-01,8.8104e-01,8.3217e-01,7.7389e-01,7.0677e-01,6.3295e-01,5.5413e-01,4.7264e-01,3.9063e-01,3.1145e-01,2.3717e-01,1.6972e-01,1.1170e-01,6.4437e-02,2.9314e-02,7.4285e-03,5.8625e-08,}, std::vector<double>{8.7678e-01,8.9681e-01,9.2151e-01,9.4651e-01,9.6853e-01,9.8528e-01,9.9574e-01,9.9985e-01,9.9869e-01,9.9382e-01,9.8717e-01,9.8050e-01,9.7529e-01,9.7255e-01,9.7265e-01,9.7542e-01,9.8021e-01,9.8597e-01,9.9162e-01,9.9619e-01,9.9900e-01,9.9999e-01,9.9964e-01,9.9889e-01,9.9874e-01,}, std::vector<double>{1.5925e-01,1.6821e-01,1.6332e-01,1.4931e-01,1.3039e-01,1.1029e-01,9.2241e-02,7.9282e-02,7.3685e-02,7.7371e-02,9.1685e-02,1.1748e-01,1.5527e-01,2.0438e-01,2.6400e-01,3.3245e-01,4.0774e-01,4.8614e-01,5.6463e-01,6.4008e-01,7.0852e-01,7.6771e-01,8.1593e-01,8.5245e-01,8.7678e-01,}, std::vector<double>{-9.9875e-01,-9.9916e-01,-9.9945e-01,-9.9966e-01,-9.9980e-01,-9.9989e-01,-9.9994e-01,-9.9998e-01,-9.9999e-01,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,}, std::vector<double>{-8.7689e-01,-8.9223e-01,-9.0613e-01,-9.1839e-01,-9.2943e-01,-9.3909e-01,-9.4774e-01,-9.5525e-01,-9.6184e-01,-9.6768e-01,-9.7269e-01,-9.7709e-01,-9.8083e-01,-9.8405e-01,-9.8684e-01,-9.8918e-01,-9.9119e-01,-9.9286e-01,-9.9427e-01,-9.9543e-01,-9.9639e-01,-9.9718e-01,-9.9782e-01,-9.9834e-01,-9.9874e-01,}, std::vector<double>{-1.5934e-01,-1.7769e-01,-1.9756e-01,-2.1860e-01,-2.4102e-01,-2.6484e-01,-2.9030e-01,-3.1691e-01,-3.4491e-01,-3.7425e-01,-4.0518e-01,-4.3707e-01,-4.7011e-01,-5.0421e-01,-5.3955e-01,-5.7533e-01,-6.1169e-01,-6.4841e-01,-6.8559e-01,-7.2437e-01,-7.6281e-01,-7.9696e-01,-8.2737e-01,-8.5381e-01,-8.7668e-01,}, std::vector<double>{7.9530e-10,2.6650e-05,5.7905e-05,2.1301e-05,-1.5791e-04,-5.5588e-04,-1.2502e-03,-2.3096e-03,-3.8309e-03,-5.8890e-03,-8.5670e-03,-1.1920e-02,-1.6086e-02,-2.1129e-02,-2.7136e-02,-3.4137e-02,-4.2332e-02,-5.1759e-02,-6.2508e-02,-7.4569e-02,-8.8219e-02,-1.0346e-01,-1.2036e-01,-1.3887e-01,-1.5917e-01,}, std::vector<double>{8.7951e-01,8.5433e-01,8.2582e-01,7.9391e-01,7.5820e-01,7.1943e-01,6.7737e-01,6.3223e-01,5.8426e-01,5.3381e-01,4.8128e-01,4.2714e-01,3.7140e-01,3.1569e-01,2.6008e-01,2.0519e-01,1.5165e-01,1.0008e-01,5.1077e-02,5.2149e-03,-3.7351e-02,-7.5298e-02,-1.0857e-01,-1.3673e-01,-1.5916e-01,}, std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,9.9999e-01,9.9997e-01,9.9992e-01,9.9981e-01,9.9962e-01,9.9927e-01,9.9870e-01,9.9784e-01,9.9655e-01,9.9471e-01,9.9215e-01,9.8867e-01,9.8413e-01,9.7827e-01,9.7086e-01,9.6165e-01,9.5038e-01,9.3665e-01,9.2047e-01,9.0149e-01,8.7973e-01,}, std::vector<double>{-6.1673e-01,-5.7768e-01,-5.3812e-01,-4.9836e-01,-4.5832e-01,-4.1906e-01,-3.8046e-01,-3.4280e-01,-3.0632e-01,-2.7123e-01,-2.3775e-01,-2.0604e-01,-1.7599e-01,-1.4831e-01,-1.2281e-01,-9.9586e-02,-7.8707e-02,-6.0232e-02,-4.4201e-02,-3.0641e-02,-1.9471e-02,-1.0906e-02,-4.8199e-03,-1.1936e-03,-3.6946e-08,}, std::vector<double>{-9.9874e-01,-9.9920e-01,-9.9968e-01,-9.9998e-01,-9.9987e-01,-9.9909e-01,-9.9738e-01,-9.9447e-01,-9.9009e-01,-9.8392e-01,-9.7585e-01,-9.6561e-01,-9.5306e-01,-9.3804e-01,-9.2048e-01,-9.0013e-01,-8.7737e-01,-8.5208e-01,-8.2436e-01,-7.9434e-01,-7.6220e-01,-7.2781e-01,-6.9208e-01,-6.5496e-01,-6.1710e-01,}, std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,}, std::vector<double>{5.8615e-08,7.4995e-03,2.9452e-02,6.4637e-02,1.1196e-01,1.7002e-01,2.3752e-01,3.1183e-01,3.9102e-01,4.7303e-01,5.5452e-01,6.3332e-01,7.0745e-01,7.7419e-01,8.3243e-01,8.8126e-01,9.2055e-01,9.5026e-01,9.7147e-01,9.8549e-01,9.9374e-01,9.9792e-01,9.9957e-01,9.9997e-01,1.0000e+00,}, std::vector<double>{3.4688e-13,-2.5600e-08,-8.4890e-08,-1.8535e-07,-2.7853e-07,-3.6293e-07,-4.6262e-07,-5.2826e-07,-5.0182e-07,-4.0445e-07,-3.0102e-07,-2.0080e-07,-5.4045e-08,1.5529e-07,3.6141e-07,4.7817e-07,4.9573e-07,4.7637e-07,4.5504e-07,3.9645e-07,2.8353e-07,1.7243e-07,9.2211e-08,2.2733e-08,1.7344e-13,}, std::vector<double>{-1.0000e+00,-9.9997e-01,-9.9957e-01,-9.9791e-01,-9.9371e-01,-9.8544e-01,-9.7138e-01,-9.5014e-01,-9.2038e-01,-8.8104e-01,-8.3217e-01,-7.7389e-01,-7.0677e-01,-6.3295e-01,-5.5413e-01,-4.7264e-01,-3.9063e-01,-3.1145e-01,-2.3717e-01,-1.6972e-01,-1.1170e-01,-6.4437e-02,-2.9314e-02,-7.4285e-03,-5.8625e-08,}, std::vector<double>{-8.7678e-01,-8.9681e-01,-9.2151e-01,-9.4651e-01,-9.6853e-01,-9.8528e-01,-9.9574e-01,-9.9985e-01,-9.9869e-01,-9.9382e-01,-9.8717e-01,-9.8050e-01,-9.7529e-01,-9.7255e-01,-9.7265e-01,-9.7542e-01,-9.8021e-01,-9.8597e-01,-9.9162e-01,-9.9619e-01,-9.9900e-01,-9.9999e-01,-9.9964e-01,-9.9889e-01,-9.9874e-01,}, std::vector<double>{-1.5925e-01,-1.6821e-01,-1.6332e-01,-1.4931e-01,-1.3039e-01,-1.1029e-01,-9.2241e-02,-7.9282e-02,-7.3685e-02,-7.7371e-02,-9.1685e-02,-1.1748e-01,-1.5527e-01,-2.0438e-01,-2.6400e-01,-3.3245e-01,-4.0774e-01,-4.8614e-01,-5.6463e-01,-6.4008e-01,-7.0852e-01,-7.6771e-01,-8.1593e-01,-8.5245e-01,-8.7678e-01,}, std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-9.9999e-01,-9.9998e-01,-9.9994e-01,-9.9989e-01,-9.9980e-01,-9.9966e-01,-9.9945e-01,-9.9916e-01,-9.9875e-01,}, std::vector<double>{-9.9874e-01,-9.9834e-01,-9.9782e-01,-9.9718e-01,-9.9639e-01,-9.9543e-01,-9.9425e-01,-9.9286e-01,-9.9119e-01,-9.8918e-01,-9.8684e-01,-9.8405e-01,-9.8083e-01,-9.7709e-01,-9.7269e-01,-9.6768e-01,-9.6184e-01,-9.5525e-01,-9.4764e-01,-9.3909e-01,-9.2943e-01,-9.1839e-01,-9.0613e-01,-8.9223e-01,-8.7689e-01,}, std::vector<double>{-8.7668e-01,-8.5381e-01,-8.2711e-01,-7.9696e-01,-7.6281e-01,-7.2437e-01,-6.8524e-01,-6.4841e-01,-6.1169e-01,-5.7533e-01,-5.3922e-01,-5.0421e-01,-4.7011e-01,-4.3707e-01,-4.0489e-01,-3.7425e-01,-3.4491e-01,-3.1691e-01,-2.9005e-01,-2.6484e-01,-2.4102e-01,-2.1860e-01,-1.9736e-01,-1.7769e-01,-1.5934e-01,}, std::vector<double>{-1.5917e-01,-1.3887e-01,-1.2022e-01,-1.0346e-01,-8.8219e-02,-7.4569e-02,-6.2418e-02,-5.1759e-02,-4.2332e-02,-3.4137e-02,-2.7085e-02,-2.1129e-02,-1.6086e-02,-1.1920e-02,-8.5433e-03,-5.8890e-03,-3.8309e-03,-2.3096e-03,-1.2433e-03,-5.5588e-04,-1.5791e-04,2.1301e-05,5.7829e-05,2.6650e-05,7.9530e-10,}, std::vector<double>{-1.5916e-01,-1.3673e-01,-1.0857e-01,-7.5298e-02,-3.6965e-02,5.2149e-03,5.1077e-02,1.0008e-01,1.5165e-01,2.0519e-01,2.6008e-01,3.1569e-01,3.7194e-01,4.2714e-01,4.8128e-01,5.3381e-01,5.8426e-01,6.3223e-01,6.7737e-01,7.1943e-01,7.5856e-01,7.9391e-01,8.2582e-01,8.5433e-01,8.7951e-01,}, std::vector<double>{8.7973e-01,9.0149e-01,9.2047e-01,9.3679e-01,9.5038e-01,9.6165e-01,9.7086e-01,9.7827e-01,9.8413e-01,9.8871e-01,9.9215e-01,9.9471e-01,9.9655e-01,9.9784e-01,9.9870e-01,9.9927e-01,9.9962e-01,9.9981e-01,9.9992e-01,9.9997e-01,9.9999e-01,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,}, std::vector<double>{-3.6946e-08,-1.1936e-03,-4.8199e-03,-1.0906e-02,-1.9566e-02,-3.0641e-02,-4.4201e-02,-6.0232e-02,-7.8707e-02,-9.9586e-02,-1.2281e-01,-1.4831e-01,-1.7627e-01,-2.0604e-01,-2.3775e-01,-2.7123e-01,-3.0632e-01,-3.4280e-01,-3.8046e-01,-4.1906e-01,-4.5870e-01,-4.9836e-01,-5.3812e-01,-5.7768e-01,-6.1673e-01,}, std::vector<double>{-6.1710e-01,-6.5496e-01,-6.9208e-01,-7.2815e-01,-7.6220e-01,-7.9434e-01,-8.2436e-01,-8.5208e-01,-8.7737e-01,-9.0033e-01,-9.2048e-01,-9.3804e-01,-9.5306e-01,-9.6561e-01,-9.7585e-01,-9.8399e-01,-9.9009e-01,-9.9447e-01,-9.9738e-01,-9.9909e-01,-9.9987e-01,-9.9998e-01,-9.9968e-01,-9.9920e-01,-9.9874e-01,}, std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,}, std::vector<double>{1.0000e+00,9.9997e-01,9.9957e-01,9.9792e-01,9.9374e-01,9.8549e-01,9.7147e-01,9.5026e-01,9.2055e-01,8.8126e-01,8.3243e-01,7.7419e-01,7.0711e-01,6.3332e-01,5.5452e-01,4.7303e-01,3.9102e-01,3.1183e-01,2.3752e-01,1.7002e-01,1.1196e-01,6.4637e-02,2.9452e-02,7.4995e-03,5.8615e-08,}, std::vector<double>{1.7344e-13,2.2733e-08,9.2211e-08,1.7243e-07,2.8353e-07,3.9645e-07,4.5504e-07,4.7637e-07,4.9573e-07,4.7817e-07,3.6141e-07,1.5529e-07,-5.4920e-08,-2.0080e-07,-3.0102e-07,-4.0445e-07,-5.0182e-07,-5.2826e-07,-4.6262e-07,-3.6293e-07,-2.7853e-07,-1.8535e-07,-8.4890e-08,-2.5600e-08,3.4688e-13,}, std::vector<double>{-5.8625e-08,-7.4285e-03,-2.9314e-02,-6.4437e-02,-1.1170e-01,-1.6972e-01,-2.3717e-01,-3.1145e-01,-3.9063e-01,-4.7264e-01,-5.5413e-01,-6.3295e-01,-7.0711e-01,-7.7389e-01,-8.3217e-01,-8.8104e-01,-9.2038e-01,-9.5014e-01,-9.7138e-01,-9.8544e-01,-9.9371e-01,-9.9791e-01,-9.9957e-01,-9.9997e-01,-1.0000e+00,}, std::vector<double>{-9.9874e-01,-9.9889e-01,-9.9964e-01,-9.9999e-01,-9.9900e-01,-9.9619e-01,-9.9162e-01,-9.8597e-01,-9.8021e-01,-9.7542e-01,-9.7265e-01,-9.7255e-01,-9.7531e-01,-9.8050e-01,-9.8717e-01,-9.9382e-01,-9.9869e-01,-9.9985e-01,-9.9574e-01,-9.8528e-01,-9.6853e-01,-9.4651e-01,-9.2151e-01,-8.9681e-01,-8.7678e-01,}, std::vector<double>{-8.7678e-01,-8.5245e-01,-8.1593e-01,-7.6771e-01,-7.0852e-01,-6.4008e-01,-5.6463e-01,-4.8614e-01,-4.0774e-01,-3.3245e-01,-2.6400e-01,-2.0438e-01,-1.5506e-01,-1.1748e-01,-9.1685e-02,-7.7371e-02,-7.3685e-02,-7.9282e-02,-9.2241e-02,-1.1029e-01,-1.3039e-01,-1.4931e-01,-1.6332e-01,-1.6821e-01,-1.5925e-01,}, }; //! TODO const std::vector<std::vector<double>> edges_sin = std::vector<std::vector<double>> { std::vector<double>{2.8280e-09,8.7033e-05,3.2684e-04,6.8721e-04,1.1230e-03,1.5971e-03,2.0674e-03,2.4902e-03,2.8192e-03,3.0077e-03,3.0017e-03,2.7517e-03,2.2038e-03,1.3022e-03,-1.1162e-05,-1.8156e-03,-4.1394e-03,-7.0609e-03,-1.0646e-02,-1.4962e-02,-2.0079e-02,-2.6128e-02,-3.3068e-02,-4.1027e-02,-5.0078e-02,}, std::vector<double>{-5.0170e-02,-5.7655e-02,-6.6035e-02,-7.5042e-02,-8.4936e-02,-9.5504e-02,-1.0704e-01,-1.1930e-01,-1.3244e-01,-1.4668e-01,-1.6169e-01,-1.7788e-01,-1.9486e-01,-2.1285e-01,-2.3212e-01,-2.5220e-01,-2.7360e-01,-2.9580e-01,-3.1935e-01,-3.4366e-01,-3.6900e-01,-3.9568e-01,-4.2299e-01,-4.5159e-01,-4.8070e-01,}, std::vector<double>{-4.8107e-01,-5.2058e-01,-5.6205e-01,-6.0403e-01,-6.4662e-01,-6.8942e-01,-7.2831e-01,-7.6129e-01,-7.9110e-01,-8.1792e-01,-8.4217e-01,-8.6358e-01,-8.8261e-01,-8.9943e-01,-9.1437e-01,-9.2733e-01,-9.3864e-01,-9.4845e-01,-9.5701e-01,-9.6429e-01,-9.7052e-01,-9.7581e-01,-9.8033e-01,-9.8409e-01,-9.8722e-01,}, std::vector<double>{-9.8725e-01,-9.9031e-01,-9.9275e-01,-9.9463e-01,-9.9610e-01,-9.9722e-01,-9.9805e-01,-9.9866e-01,-9.9910e-01,-9.9942e-01,-9.9963e-01,-9.9978e-01,-9.9987e-01,-9.9993e-01,-9.9996e-01,-9.9998e-01,-9.9999e-01,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,}, std::vector<double>{-9.8725e-01,-9.9061e-01,-9.9409e-01,-9.9716e-01,-9.9932e-01,-9.9999e-01,-9.9869e-01,-9.9498e-01,-9.8843e-01,-9.7872e-01,-9.6559e-01,-9.4886e-01,-9.2826e-01,-9.0418e-01,-8.7657e-01,-8.4561e-01,-8.1157e-01,-7.7478e-01,-7.3564e-01,-6.9457e-01,-6.5161e-01,-6.0804e-01,-5.6393e-01,-5.1974e-01,-4.7589e-01,}, std::vector<double>{-4.7547e-01,-4.3279e-01,-3.9081e-01,-3.4989e-01,-3.1110e-01,-2.7429e-01,-2.3965e-01,-2.0733e-01,-1.7745e-01,-1.4982e-01,-1.2502e-01,-1.0277e-01,-8.3032e-02,-6.5764e-02,-5.0880e-02,-3.8165e-02,-2.7734e-02,-1.9306e-02,-1.2714e-02,-7.7711e-03,-4.2732e-03,-1.9803e-03,-6.9309e-04,-1.2527e-04,-2.2879e-09,}, std::vector<double>{1.0000e+00,1.0000e+00,9.9999e-01,9.9994e-01,9.9981e-01,9.9953e-01,9.9902e-01,9.9818e-01,9.9690e-01,9.9503e-01,9.9243e-01,9.8894e-01,9.8434e-01,9.7854e-01,9.7133e-01,9.6251e-01,9.5193e-01,9.3941e-01,9.2480e-01,9.0796e-01,8.8859e-01,8.6697e-01,8.4287e-01,8.1626e-01,7.8718e-01,}, std::vector<double>{7.8689e-01,7.5566e-01,7.2182e-01,6.8542e-01,6.4734e-01,6.0748e-01,5.6607e-01,5.2341e-01,4.7981e-01,4.3520e-01,3.9079e-01,3.4653e-01,3.0280e-01,2.5998e-01,2.1846e-01,1.7824e-01,1.4045e-01,1.0504e-01,7.2350e-02,4.2693e-02,1.6370e-02,-6.5324e-03,-2.5301e-02,-3.9907e-02,-5.0086e-02,}, std::vector<double>{1.7344e-13,-8.1628e-09,-3.3111e-08,-6.1918e-08,-1.0181e-07,-1.4236e-07,-1.6340e-07,-1.7106e-07,-1.7801e-07,-1.7170e-07,-1.2978e-07,-5.5762e-08,1.9721e-08,7.2103e-08,1.0809e-07,1.4523e-07,1.8019e-07,1.8969e-07,1.6612e-07,1.3032e-07,1.0001e-07,6.6555e-08,3.0482e-08,9.1925e-09,-3.4688e-13,}, std::vector<double>{5.8615e-08,7.4285e-03,2.9314e-02,6.4437e-02,1.1170e-01,1.6972e-01,2.3717e-01,3.1145e-01,3.9063e-01,4.7264e-01,5.5413e-01,6.3295e-01,7.0711e-01,7.7389e-01,8.3217e-01,8.8104e-01,9.2038e-01,9.5014e-01,9.7138e-01,9.8544e-01,9.9371e-01,9.9791e-01,9.9957e-01,9.9997e-01,1.0000e+00,}, std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,}, std::vector<double>{-1.0000e+00,-9.9997e-01,-9.9957e-01,-9.9792e-01,-9.9374e-01,-9.8549e-01,-9.7147e-01,-9.5026e-01,-9.2055e-01,-8.8126e-01,-8.3243e-01,-7.7419e-01,-7.0711e-01,-6.3332e-01,-5.5452e-01,-4.7303e-01,-3.9102e-01,-3.1183e-01,-2.3752e-01,-1.7002e-01,-1.1196e-01,-6.4637e-02,-2.9452e-02,-7.4995e-03,-5.8625e-08,}, std::vector<double>{-5.0124e-02,-4.7058e-02,-2.6797e-02,5.3534e-03,4.4786e-02,8.7252e-02,1.2917e-01,1.6689e-01,1.9796e-01,2.2035e-01,2.3225e-01,2.3269e-01,2.2085e-01,1.9650e-01,1.5970e-01,1.1099e-01,5.1198e-02,-1.7293e-02,-9.2253e-02,-1.7092e-01,-2.4891e-01,-3.2268e-01,-3.8835e-01,-4.4242e-01,-4.8088e-01,}, std::vector<double>{-4.8088e-01,-5.2280e-01,-5.7815e-01,-6.4079e-01,-7.0570e-01,-7.6831e-01,-8.2534e-01,-8.7388e-01,-9.1310e-01,-9.4312e-01,-9.6452e-01,-9.7889e-01,-9.8791e-01,-9.9308e-01,-9.9579e-01,-9.9700e-01,-9.9728e-01,-9.9685e-01,-9.9574e-01,-9.9390e-01,-9.9146e-01,-9.8879e-01,-9.8657e-01,-9.8575e-01,-9.8724e-01,}, std::vector<double>{5.0078e-02,4.1027e-02,3.3068e-02,2.6066e-02,2.0079e-02,1.4962e-02,1.0646e-02,7.0609e-03,4.1394e-03,1.7961e-03,1.1162e-05,-1.3022e-03,-2.2038e-03,-2.7517e-03,-3.0017e-03,-3.0068e-03,-2.8192e-03,-2.4902e-03,-2.0674e-03,-1.5971e-03,-1.1230e-03,-6.8337e-04,-3.2684e-04,-8.7033e-05,-2.8280e-09,}, std::vector<double>{4.8070e-01,4.5159e-01,4.2299e-01,3.9568e-01,3.6900e-01,3.4366e-01,3.1905e-01,2.9580e-01,2.7360e-01,2.5220e-01,2.3212e-01,2.1285e-01,1.9486e-01,1.7788e-01,1.6169e-01,1.4668e-01,1.3244e-01,1.1930e-01,1.0689e-01,9.5504e-02,8.4936e-02,7.5042e-02,6.6035e-02,5.7655e-02,5.0170e-02,}, std::vector<double>{9.8722e-01,9.8409e-01,9.8029e-01,9.7581e-01,9.7052e-01,9.6429e-01,9.5694e-01,9.4845e-01,9.3864e-01,9.2733e-01,9.1424e-01,8.9943e-01,8.8261e-01,8.6358e-01,8.4195e-01,8.1792e-01,7.9110e-01,7.6129e-01,7.2798e-01,6.8942e-01,6.4662e-01,6.0403e-01,5.6165e-01,5.2058e-01,4.8107e-01,}, std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,9.9999e-01,9.9998e-01,9.9996e-01,9.9993e-01,9.9987e-01,9.9978e-01,9.9963e-01,9.9942e-01,9.9910e-01,9.9866e-01,9.9804e-01,9.9722e-01,9.9610e-01,9.9463e-01,9.9273e-01,9.9031e-01,9.8725e-01,}, std::vector<double>{4.7589e-01,5.1974e-01,5.6393e-01,6.0804e-01,6.5202e-01,6.9457e-01,7.3564e-01,7.7478e-01,8.1157e-01,8.4561e-01,8.7657e-01,9.0418e-01,9.2847e-01,9.4886e-01,9.6559e-01,9.7872e-01,9.8843e-01,9.9498e-01,9.9869e-01,9.9999e-01,9.9930e-01,9.9716e-01,9.9409e-01,9.9061e-01,9.8725e-01,}, std::vector<double>{2.2879e-09,1.2527e-04,6.9309e-04,1.9970e-03,4.2732e-03,7.7711e-03,1.2714e-02,1.9306e-02,2.7734e-02,3.8276e-02,5.0880e-02,6.5764e-02,8.3032e-02,1.0277e-01,1.2502e-01,1.5007e-01,1.7745e-01,2.0733e-01,2.3965e-01,2.7429e-01,3.1110e-01,3.5027e-01,3.9081e-01,4.3279e-01,4.7547e-01,}, std::vector<double>{-7.8718e-01,-8.1626e-01,-8.4287e-01,-8.6697e-01,-8.8879e-01,-9.0796e-01,-9.2480e-01,-9.3941e-01,-9.5193e-01,-9.6251e-01,-9.7133e-01,-9.7854e-01,-9.8439e-01,-9.8894e-01,-9.9243e-01,-9.9503e-01,-9.9690e-01,-9.9818e-01,-9.9902e-01,-9.9953e-01,-9.9981e-01,-9.9994e-01,-9.9999e-01,-1.0000e+00,-1.0000e+00,}, std::vector<double>{5.0086e-02,3.9907e-02,2.5301e-02,6.3326e-03,-1.6370e-02,-4.2693e-02,-7.2350e-02,-1.0504e-01,-1.4045e-01,-1.7862e-01,-2.1846e-01,-2.5998e-01,-3.0280e-01,-3.4653e-01,-3.9079e-01,-4.3563e-01,-4.7981e-01,-5.2341e-01,-5.6607e-01,-6.0748e-01,-6.4734e-01,-6.8578e-01,-7.2182e-01,-7.5566e-01,-7.8689e-01,}, std::vector<double>{3.4688e-13,-9.1925e-09,-3.0482e-08,-6.6555e-08,-1.0001e-07,-1.3032e-07,-1.6612e-07,-1.8969e-07,-1.8019e-07,-1.4523e-07,-1.0809e-07,-7.2103e-08,-1.9406e-08,5.5762e-08,1.2978e-07,1.7170e-07,1.7801e-07,1.7106e-07,1.6340e-07,1.4236e-07,1.0181e-07,6.1918e-08,3.3111e-08,8.1628e-09,-1.7344e-13,}, std::vector<double>{-1.0000e+00,-9.9997e-01,-9.9957e-01,-9.9791e-01,-9.9371e-01,-9.8544e-01,-9.7138e-01,-9.5014e-01,-9.2038e-01,-8.8104e-01,-8.3217e-01,-7.7389e-01,-7.0677e-01,-6.3295e-01,-5.5413e-01,-4.7264e-01,-3.9063e-01,-3.1145e-01,-2.3717e-01,-1.6972e-01,-1.1170e-01,-6.4437e-02,-2.9314e-02,-7.4285e-03,-5.8615e-08,}, std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,}, std::vector<double>{5.8625e-08,7.4995e-03,2.9452e-02,6.4637e-02,1.1196e-01,1.7002e-01,2.3752e-01,3.1183e-01,3.9102e-01,4.7303e-01,5.5452e-01,6.3332e-01,7.0745e-01,7.7419e-01,8.3243e-01,8.8126e-01,9.2055e-01,9.5026e-01,9.7147e-01,9.8549e-01,9.9374e-01,9.9792e-01,9.9957e-01,9.9997e-01,1.0000e+00,}, std::vector<double>{4.8088e-01,4.4242e-01,3.8835e-01,3.2268e-01,2.4891e-01,1.7092e-01,9.2253e-02,1.7293e-02,-5.1198e-02,-1.1099e-01,-1.5970e-01,-1.9650e-01,-2.2094e-01,-2.3269e-01,-2.3225e-01,-2.2035e-01,-1.9796e-01,-1.6689e-01,-1.2917e-01,-8.7252e-02,-4.4786e-02,-5.3534e-03,2.6797e-02,4.7058e-02,5.0124e-02,}, std::vector<double>{9.8724e-01,9.8575e-01,9.8657e-01,9.8879e-01,9.9146e-01,9.9390e-01,9.9574e-01,9.9685e-01,9.9728e-01,9.9700e-01,9.9579e-01,9.9308e-01,9.8787e-01,9.7889e-01,9.6452e-01,9.4312e-01,9.1310e-01,8.7388e-01,8.2534e-01,7.6831e-01,7.0570e-01,6.4079e-01,5.7815e-01,5.2280e-01,4.8088e-01,}, std::vector<double>{-5.0078e-02,-4.1027e-02,-3.3068e-02,-2.6066e-02,-2.0079e-02,-1.4962e-02,-1.0646e-02,-7.0609e-03,-4.1394e-03,-1.7961e-03,-1.1162e-05,1.3022e-03,2.2038e-03,2.7517e-03,3.0017e-03,3.0068e-03,2.8192e-03,2.4902e-03,2.0674e-03,1.5971e-03,1.1230e-03,6.8337e-04,3.2684e-04,8.7033e-05,2.8280e-09,}, std::vector<double>{-4.8070e-01,-4.5159e-01,-4.2299e-01,-3.9568e-01,-3.6900e-01,-3.4366e-01,-3.1905e-01,-2.9580e-01,-2.7360e-01,-2.5220e-01,-2.3212e-01,-2.1285e-01,-1.9486e-01,-1.7788e-01,-1.6169e-01,-1.4668e-01,-1.3244e-01,-1.1930e-01,-1.0689e-01,-9.5504e-02,-8.4936e-02,-7.5042e-02,-6.6035e-02,-5.7655e-02,-5.0170e-02,}, std::vector<double>{-9.8722e-01,-9.8409e-01,-9.8029e-01,-9.7581e-01,-9.7052e-01,-9.6429e-01,-9.5694e-01,-9.4845e-01,-9.3864e-01,-9.2733e-01,-9.1424e-01,-8.9943e-01,-8.8261e-01,-8.6358e-01,-8.4195e-01,-8.1792e-01,-7.9110e-01,-7.6129e-01,-7.2798e-01,-6.8942e-01,-6.4662e-01,-6.0403e-01,-5.6165e-01,-5.2058e-01,-4.8107e-01,}, std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-9.9999e-01,-9.9998e-01,-9.9996e-01,-9.9993e-01,-9.9987e-01,-9.9978e-01,-9.9963e-01,-9.9942e-01,-9.9910e-01,-9.9866e-01,-9.9804e-01,-9.9722e-01,-9.9610e-01,-9.9463e-01,-9.9273e-01,-9.9031e-01,-9.8725e-01,}, std::vector<double>{-4.7589e-01,-5.1974e-01,-5.6393e-01,-6.0804e-01,-6.5202e-01,-6.9457e-01,-7.3564e-01,-7.7478e-01,-8.1157e-01,-8.4561e-01,-8.7657e-01,-9.0418e-01,-9.2847e-01,-9.4886e-01,-9.6559e-01,-9.7872e-01,-9.8843e-01,-9.9498e-01,-9.9869e-01,-9.9999e-01,-9.9930e-01,-9.9716e-01,-9.9409e-01,-9.9061e-01,-9.8725e-01,}, std::vector<double>{-2.2879e-09,-1.2527e-04,-6.9309e-04,-1.9970e-03,-4.2732e-03,-7.7711e-03,-1.2714e-02,-1.9306e-02,-2.7734e-02,-3.8276e-02,-5.0880e-02,-6.5764e-02,-8.3032e-02,-1.0277e-01,-1.2502e-01,-1.5007e-01,-1.7745e-01,-2.0733e-01,-2.3965e-01,-2.7429e-01,-3.1110e-01,-3.5027e-01,-3.9081e-01,-4.3279e-01,-4.7547e-01,}, std::vector<double>{7.8718e-01,8.1626e-01,8.4287e-01,8.6697e-01,8.8879e-01,9.0796e-01,9.2480e-01,9.3941e-01,9.5193e-01,9.6251e-01,9.7133e-01,9.7854e-01,9.8439e-01,9.8894e-01,9.9243e-01,9.9503e-01,9.9690e-01,9.9818e-01,9.9902e-01,9.9953e-01,9.9981e-01,9.9994e-01,9.9999e-01,1.0000e+00,1.0000e+00,}, std::vector<double>{-5.0086e-02,-3.9907e-02,-2.5301e-02,-6.3326e-03,1.6370e-02,4.2693e-02,7.2350e-02,1.0504e-01,1.4045e-01,1.7862e-01,2.1846e-01,2.5998e-01,3.0280e-01,3.4653e-01,3.9079e-01,4.3563e-01,4.7981e-01,5.2341e-01,5.6607e-01,6.0748e-01,6.4734e-01,6.8578e-01,7.2182e-01,7.5566e-01,7.8689e-01,}, std::vector<double>{-3.4688e-13,9.1925e-09,3.0482e-08,6.6555e-08,1.0001e-07,1.3032e-07,1.6612e-07,1.8969e-07,1.8019e-07,1.4523e-07,1.0809e-07,7.2103e-08,1.9406e-08,-5.5762e-08,-1.2978e-07,-1.7170e-07,-1.7801e-07,-1.7106e-07,-1.6340e-07,-1.4236e-07,-1.0181e-07,-6.1918e-08,-3.3111e-08,-8.1628e-09,1.7344e-13,}, std::vector<double>{1.0000e+00,9.9997e-01,9.9957e-01,9.9791e-01,9.9371e-01,9.8544e-01,9.7138e-01,9.5014e-01,9.2038e-01,8.8104e-01,8.3217e-01,7.7389e-01,7.0677e-01,6.3295e-01,5.5413e-01,4.7264e-01,3.9063e-01,3.1145e-01,2.3717e-01,1.6972e-01,1.1170e-01,6.4437e-02,2.9314e-02,7.4285e-03,5.8615e-08,}, std::vector<double>{1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,}, std::vector<double>{-5.8625e-08,-7.4995e-03,-2.9452e-02,-6.4637e-02,-1.1196e-01,-1.7002e-01,-2.3752e-01,-3.1183e-01,-3.9102e-01,-4.7303e-01,-5.5452e-01,-6.3332e-01,-7.0745e-01,-7.7419e-01,-8.3243e-01,-8.8126e-01,-9.2055e-01,-9.5026e-01,-9.7147e-01,-9.8549e-01,-9.9374e-01,-9.9792e-01,-9.9957e-01,-9.9997e-01,-1.0000e+00,}, std::vector<double>{-4.8088e-01,-4.4242e-01,-3.8835e-01,-3.2268e-01,-2.4891e-01,-1.7092e-01,-9.2253e-02,-1.7293e-02,5.1198e-02,1.1099e-01,1.5970e-01,1.9650e-01,2.2094e-01,2.3269e-01,2.3225e-01,2.2035e-01,1.9796e-01,1.6689e-01,1.2917e-01,8.7252e-02,4.4786e-02,5.3534e-03,-2.6797e-02,-4.7058e-02,-5.0124e-02,}, std::vector<double>{-9.8724e-01,-9.8575e-01,-9.8657e-01,-9.8879e-01,-9.9146e-01,-9.9390e-01,-9.9574e-01,-9.9685e-01,-9.9728e-01,-9.9700e-01,-9.9579e-01,-9.9308e-01,-9.8787e-01,-9.7889e-01,-9.6452e-01,-9.4312e-01,-9.1310e-01,-8.7388e-01,-8.2534e-01,-7.6831e-01,-7.0570e-01,-6.4079e-01,-5.7815e-01,-5.2280e-01,-4.8088e-01,}, std::vector<double>{-2.8280e-09,-8.7033e-05,-3.2684e-04,-6.8721e-04,-1.1230e-03,-1.5971e-03,-2.0674e-03,-2.4902e-03,-2.8192e-03,-3.0077e-03,-3.0017e-03,-2.7517e-03,-2.2038e-03,-1.3022e-03,1.1162e-05,1.8156e-03,4.1394e-03,7.0609e-03,1.0646e-02,1.4962e-02,2.0079e-02,2.6128e-02,3.3068e-02,4.1027e-02,5.0078e-02,}, std::vector<double>{5.0170e-02,5.7655e-02,6.6035e-02,7.5042e-02,8.4936e-02,9.5504e-02,1.0704e-01,1.1930e-01,1.3244e-01,1.4668e-01,1.6169e-01,1.7788e-01,1.9486e-01,2.1285e-01,2.3212e-01,2.5220e-01,2.7360e-01,2.9580e-01,3.1935e-01,3.4366e-01,3.6900e-01,3.9568e-01,4.2299e-01,4.5159e-01,4.8070e-01,}, std::vector<double>{4.8107e-01,5.2058e-01,5.6205e-01,6.0403e-01,6.4662e-01,6.8942e-01,7.2831e-01,7.6129e-01,7.9110e-01,8.1792e-01,8.4217e-01,8.6358e-01,8.8261e-01,8.9943e-01,9.1437e-01,9.2733e-01,9.3864e-01,9.4845e-01,9.5701e-01,9.6429e-01,9.7052e-01,9.7581e-01,9.8033e-01,9.8409e-01,9.8722e-01,}, std::vector<double>{9.8725e-01,9.9031e-01,9.9275e-01,9.9463e-01,9.9610e-01,9.9722e-01,9.9805e-01,9.9866e-01,9.9910e-01,9.9942e-01,9.9963e-01,9.9978e-01,9.9987e-01,9.9993e-01,9.9996e-01,9.9998e-01,9.9999e-01,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,1.0000e+00,}, std::vector<double>{9.8725e-01,9.9061e-01,9.9409e-01,9.9716e-01,9.9932e-01,9.9999e-01,9.9869e-01,9.9498e-01,9.8843e-01,9.7872e-01,9.6559e-01,9.4886e-01,9.2826e-01,9.0418e-01,8.7657e-01,8.4561e-01,8.1157e-01,7.7478e-01,7.3564e-01,6.9457e-01,6.5161e-01,6.0804e-01,5.6393e-01,5.1974e-01,4.7589e-01,}, std::vector<double>{4.7547e-01,4.3279e-01,3.9081e-01,3.4989e-01,3.1110e-01,2.7429e-01,2.3965e-01,2.0733e-01,1.7745e-01,1.4982e-01,1.2502e-01,1.0277e-01,8.3032e-02,6.5764e-02,5.0880e-02,3.8165e-02,2.7734e-02,1.9306e-02,1.2714e-02,7.7711e-03,4.2732e-03,1.9803e-03,6.9309e-04,1.2527e-04,2.2879e-09,}, std::vector<double>{-1.0000e+00,-1.0000e+00,-9.9999e-01,-9.9994e-01,-9.9981e-01,-9.9953e-01,-9.9902e-01,-9.9818e-01,-9.9690e-01,-9.9503e-01,-9.9243e-01,-9.8894e-01,-9.8434e-01,-9.7854e-01,-9.7133e-01,-9.6251e-01,-9.5193e-01,-9.3941e-01,-9.2480e-01,-9.0796e-01,-8.8859e-01,-8.6697e-01,-8.4287e-01,-8.1626e-01,-7.8718e-01,}, std::vector<double>{-7.8689e-01,-7.5566e-01,-7.2182e-01,-6.8542e-01,-6.4734e-01,-6.0748e-01,-5.6607e-01,-5.2341e-01,-4.7981e-01,-4.3520e-01,-3.9079e-01,-3.4653e-01,-3.0280e-01,-2.5998e-01,-2.1846e-01,-1.7824e-01,-1.4045e-01,-1.0504e-01,-7.2350e-02,-4.2693e-02,-1.6370e-02,6.5324e-03,2.5301e-02,3.9907e-02,5.0086e-02,}, std::vector<double>{-1.7344e-13,8.1628e-09,3.3111e-08,6.1918e-08,1.0181e-07,1.4236e-07,1.6340e-07,1.7106e-07,1.7801e-07,1.7170e-07,1.2978e-07,5.5762e-08,-1.9721e-08,-7.2103e-08,-1.0809e-07,-1.4523e-07,-1.8019e-07,-1.8969e-07,-1.6612e-07,-1.3032e-07,-1.0001e-07,-6.6555e-08,-3.0482e-08,-9.1925e-09,3.4688e-13,}, std::vector<double>{-5.8615e-08,-7.4285e-03,-2.9314e-02,-6.4437e-02,-1.1170e-01,-1.6972e-01,-2.3717e-01,-3.1145e-01,-3.9063e-01,-4.7264e-01,-5.5413e-01,-6.3295e-01,-7.0711e-01,-7.7389e-01,-8.3217e-01,-8.8104e-01,-9.2038e-01,-9.5014e-01,-9.7138e-01,-9.8544e-01,-9.9371e-01,-9.9791e-01,-9.9957e-01,-9.9997e-01,-1.0000e+00,}, std::vector<double>{-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,-1.0000e+00,}, std::vector<double>{1.0000e+00,9.9997e-01,9.9957e-01,9.9792e-01,9.9374e-01,9.8549e-01,9.7147e-01,9.5026e-01,9.2055e-01,8.8126e-01,8.3243e-01,7.7419e-01,7.0711e-01,6.3332e-01,5.5452e-01,4.7303e-01,3.9102e-01,3.1183e-01,2.3752e-01,1.7002e-01,1.1196e-01,6.4637e-02,2.9452e-02,7.4995e-03,5.8625e-08,}, std::vector<double>{5.0124e-02,4.7058e-02,2.6797e-02,-5.3534e-03,-4.4786e-02,-8.7252e-02,-1.2917e-01,-1.6689e-01,-1.9796e-01,-2.2035e-01,-2.3225e-01,-2.3269e-01,-2.2085e-01,-1.9650e-01,-1.5970e-01,-1.1099e-01,-5.1198e-02,1.7293e-02,9.2253e-02,1.7092e-01,2.4891e-01,3.2268e-01,3.8835e-01,4.4242e-01,4.8088e-01,}, std::vector<double>{4.8088e-01,5.2280e-01,5.7815e-01,6.4079e-01,7.0570e-01,7.6831e-01,8.2534e-01,8.7388e-01,9.1310e-01,9.4312e-01,9.6452e-01,9.7889e-01,9.8791e-01,9.9308e-01,9.9579e-01,9.9700e-01,9.9728e-01,9.9685e-01,9.9574e-01,9.9390e-01,9.9146e-01,9.8879e-01,9.8657e-01,9.8575e-01,9.8724e-01,}, }; };
73,612
66,412
#include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <fstream> #include <string> #include <iostream> using namespace std; // char buf1[1000047], buf2[1000047]; string buf1,buf2; char l1[20],l2[20]; // char _replace[300]; string _replace[300]; char bb[10]; #define HTML void fix(string &buf) { string res; int eol=0; if (buf[ buf.size()-1 ] == 10) { buf = buf.substr(0,buf.size()-1); eol=1; } unsigned int kde=0; while (1) { if (kde >= buf.size()) break; if (res.size() >= 40) break; int idx = buf[kde++]; if (idx < 0) idx += 256; res += _replace[idx]; } if (kde < buf.size()) res+="..."; if (!eol) res += " (missing end-of-line character)"; buf = res; } ifstream &mygetline(ifstream &sin, string &res) { int ch; res.clear(); while (1) { ch = sin.get(); if (ch == EOF) break; res += ch; if (ch == 10) break; } return sin; } int main(int argc, char **argv){ if (argc<3) { printf("Usage: %s file1 file2 [label1 [label2]]\n",argv[0]); return 1; } ifstream f1(argv[1]); ifstream f2(argv[2]); if (!f1) { printf("Cannot open file %s.\n",argv[1]); return 1; } if (!f2) { printf("Cannot open file %s.\n",argv[2]); return 1; } memset(l1,0,sizeof(l1)); memset(l2,0,sizeof(l2)); strncpy(l1,(argc>=4)?argv[3]:argv[1],8); strncpy(l2,(argc>=5)?argv[4]:argv[2],8); if (!strcmp(l1,l2)) { strcpy(l1,"first"); strcpy(l2,"second"); } for (int i=0;i<=255;i++) { sprintf(bb,"\\%02x",i); _replace[i]=string(bb); } for (unsigned char ch=33; ch<=127; ch++) _replace[ch]=ch; _replace[32] = "_"; _replace[92] = "\\\\"; _replace[95] = "\\_"; #ifdef HTML _replace['<'] = "&lt;"; _replace['>'] = "&gt;"; _replace['&'] = "&amp;"; #endif // _replace[0]='_'; // for (int i=1;i<=32;i++) _replace[i]='_'; // for (int i=33;i<=127;i++) _replace[i]=char(i); // for (int i=128;i<=255;i++) _replace[i]='_'; int row = 0; int errors = 0; while (1) { mygetline(f1,buf1); mygetline(f2,buf2); if (buf1=="") break; if (buf2=="") break; row++; if (buf1 == buf2) { // fix(buf1); // printf(" %04d: %s\n",row,buf1); } else { errors++; if (errors<=10) { fix(buf1); fix(buf2); printf("%8s %04d: %s\n",l1,row,buf1.c_str()); printf("%8s %04d: %s\n",l2,row,buf2.c_str()); } } } if (errors>10) printf("(skipping the next %d errors)\n",errors-10); if ((!f1) && (f2)) printf("%s terminated, %s continues:\n",l1,l2); if ((f1) && (!f2)) printf("%s terminated, %s continues:\n",l2,l1); int nrows=0; if (!buf1.empty()) { fix(buf1); printf("%8s %04d: %s\n",l1,++row,buf1.c_str()); } if (!buf2.empty()) { fix(buf2); printf("%8s %04d: %s\n",l2,++row,buf2.c_str()); } while (f1) { row++; mygetline(f1,buf1); if (buf1=="") break; nrows++; if (nrows <= 10) { fix(buf1); printf("%8s %04d: %s\n",l1,row,buf1.c_str()); } } while (f2) { row++; mygetline(f2,buf2); if (buf2=="") break; nrows++; if (nrows <= 10) { fix(buf2); printf("%8s %04d: %s\n",l2,row,buf2.c_str()); } } if (nrows > 10) printf("(skipping next %d lines)\n",nrows-10); return 0; }
3,251
1,518
/* Copyright (c) 2009-2016, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #include <El.hpp> #include "../../../QP/affine/IPM/util.hpp" namespace El { namespace lp { namespace affine { // Initialize // ========== template<typename Real> void Initialize ( const AffineLPProblem<Matrix<Real>,Matrix<Real>>& problem, AffineLPSolution<Matrix<Real>>& solution, bool primalInit, bool dualInit, bool standardShift ); template<typename Real> void Initialize ( const AffineLPProblem<DistMatrix<Real>,DistMatrix<Real>>& problem, AffineLPSolution<DistMatrix<Real>>& solution, bool primalInit, bool dualInit, bool standardShift ); template<typename Real> void Initialize ( const AffineLPProblem<SparseMatrix<Real>,Matrix<Real>>& problem, AffineLPSolution<Matrix<Real>>& solution, const SparseMatrix<Real>& JStatic, const Matrix<Real>& regTmp, SparseLDLFactorization<Real>& sparseLDLFact, bool primalInit, bool dualInit, bool standardShift, const RegSolveCtrl<Real>& solveCtrl ); template<typename Real> void Initialize ( const AffineLPProblem<DistSparseMatrix<Real>,DistMultiVec<Real>>& problem, AffineLPSolution<DistMultiVec<Real>>& solution, const DistSparseMatrix<Real>& JStatic, const DistMultiVec<Real>& regTmp, DistSparseLDLFactorization<Real>& sparseLDLFact, bool primalInit, bool dualInit, bool standardShift, const RegSolveCtrl<Real>& solveCtrl ); // Full system // =========== // We explicitly accept s and z rather than AffineLPSolution because it is // common to initialize IPM's by solving the KKT system with s = z = ones(k,1). template<typename Real> void KKT ( const Matrix<Real>& A, const Matrix<Real>& G, const Matrix<Real>& s, const Matrix<Real>& z, Matrix<Real>& J, bool onlyLower=true ); template<typename Real> void KKT ( const DistMatrix<Real>& A, const DistMatrix<Real>& G, const DistMatrix<Real>& s, const DistMatrix<Real>& z, DistMatrix<Real>& J, bool onlyLower=true ); template<typename Real> void KKT ( const SparseMatrix<Real>& A, const SparseMatrix<Real>& G, const Matrix<Real>& s, const Matrix<Real>& z, SparseMatrix<Real>& J, bool onlyLower=true ); template<typename Real> void StaticKKT ( const SparseMatrix<Real>& A, const SparseMatrix<Real>& G, Real gamma, Real delta, Real beta, SparseMatrix<Real>& J, bool onlyLower=true ); template<typename Real> void KKT ( const DistSparseMatrix<Real>& A, const DistSparseMatrix<Real>& G, const DistMultiVec<Real>& s, const DistMultiVec<Real>& z, DistSparseMatrix<Real>& J, bool onlyLower=true ); template<typename Real> void StaticKKT ( const DistSparseMatrix<Real>& A, const DistSparseMatrix<Real>& G, Real gamma, Real delta, Real beta, DistSparseMatrix<Real>& J, bool onlyLower=true ); using qp::affine::FinishKKT; using qp::affine::KKTRHS; using qp::affine::ExpandCoreSolution; using qp::affine::ExpandSolution; } // namespace affine } // namespace lp } // namespace El
3,233
1,048
/* Copyright (C) 1997,1998,1999 Kenji Hiranabe, Eiwa System Management, Inc. This program is free software. Implemented by Kenji Hiranabe(hiranabe@esm.co.jp), conforming to the Java(TM) 3D API specification by Sun Microsystems. Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. Kenji Hiranabe and Eiwa System Management,Inc. makes no representations about the suitability of this software for any purpose. It is provided "AS IS" with NO WARRANTY. */ #include "Matrix4.h" template<class T, class S> bool equals(T a, S b) { return fabs(a - b) < 1.0e-5; } #ifdef VM_INCLUDE_NAMESPACE using namespace kh_vecmath; #endif template<class T> void f(T) { /* * constructors */ Matrix4<T> m1(1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16); T array[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; Matrix4<T> m2(array); #ifdef VM_INCLUDE_CONVERSION_FROM_2DARRAY T array2[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; Matrix4<T> m3(array2); #else Matrix4<T> m3(m2); #endif int k = 0; for (unsigned i = 0; i < Matrix4<T>::DIMENSION; i++) { for (unsigned j = 0; j < Matrix4<T>::DIMENSION; j++) { k++; #ifdef VM_INCLUDE_SUBSCRIPTION_OPERATOR assert(m1(i,j) == k); assert(m2(i,j) == k); assert(m3(i,j) == k); #endif assert(m1.getElement(i,j) == k); assert(m2.getElement(i,j) == k); assert(m3.getElement(i,j) == k); } } assert(m1 == m2); assert(m1 == m3); /* * set/get row/column */ m1.setIdentity(); m1.setScale(2); assert(m1 == Matrix4<T>(2,0,0,0, 0,2,0,0, 0,0,2,0, 0,0,0,1)); #ifdef VM_INCLUDE_SUBSCRIPTION_OPERATOR for (unsigned i = 0; i < 4; i++) for (unsigned j = 0; j < 4; j++) m1(i,j) = 10*i + j; for (unsigned ii = 0; ii < 4; ii++) for (unsigned j = 0; j < 4; j++) assert(10*ii + j == m1(ii,j)); #endif for (unsigned i2 = 0; i2 < 4; i2++) for (unsigned j = 0; j < 4; j++) m1.setElement(i2,j,10*i2 + j); for (unsigned i3 = 0; i3 < 4; i3++) for (unsigned j = 0; j < 4; j++) assert(10*i3 + j == m1.getElement(i3,j)); for (unsigned i4 = 0; i4 < 4; i4++) { Vector4<T> v1(10*i4,6*i4,i4,17*i4); Vector4<T> v2; m1.setRow(i4, v1); m1.getRow(i4, &v2); assert(v1 == v2); } for (unsigned i5 = 0; i5 < 4; i5++) { const T t[] = { 1, 2, 3, 4 }; T s[4]; m1.setRow(i5, t); m1.getRow(i5, s); for (unsigned j = 0; j < 4; j ++) assert(t[j] == s[j]); } for (unsigned i6 = 0; i6 < 4; i6++) { Vector4<T> v1(7*i6,5*i6,i6,13*(-i6)); Vector4<T> v2; m1.setColumn(i6, v1); m1.getColumn(i6, &v2); assert(v1 == v2); } for (unsigned i7 = 0; i7 < 4; i7++) { const T t[] = { 1, 2, 3, 4}; T s[4]; m1.setColumn(i7, t); m1.getColumn(i7, s); for (unsigned j = 0; j < 4; j ++) assert(t[j] == s[j]); } /* * scales */ m1.setIdentity(); for (unsigned i8 = 1; i8 < 10; i8++) { m1.setScale(i8); T s = m1.getScale(); assert(equals(s, i8)); } /* * add/sub */ m1.set(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12, 13,14,15,16); m2.add(10, m1); m2.sub(10); assert(m1 == m2); /** * negate */ m1.set(1, 2, 3, 10, 4, 5, 6, 11, 2, 5, 1, 100, 9, 3, 4, 12); m2.negate(m1); m3.add(m1, m2); assert(m3 == Matrix4<T>(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)); /* * transpose */ m2.transpose(m1); m2.transpose(); assert(m1 == m2); /* * invert */ m2.invert(m1); m2 *= m1; #ifdef VM_INCLUDE_SUBSCRIPTION_OPERATOR assert(equals(m2(0,0),1)); assert(equals(m2(0,1),0)); assert(equals(m2(0,2),0)); assert(equals(m2(0,3),0)); assert(equals(m2(1,0),0)); assert(equals(m2(1,1),1)); assert(equals(m2(1,2),0)); assert(equals(m2(1,3),0)); assert(equals(m2(2,0),0)); assert(equals(m2(2,1),0)); assert(equals(m2(2,2),1)); assert(equals(m2(2,3),0)); assert(equals(m2(3,0),0)); assert(equals(m2(3,1),0)); assert(equals(m2(3,2),0)); assert(equals(m2(3,3),1)); #endif assert(equals(m2.getElement(0,0),1)); assert(equals(m2.getElement(0,1),0)); assert(equals(m2.getElement(0,2),0)); assert(equals(m2.getElement(0,3),0)); assert(equals(m2.getElement(1,0),0)); assert(equals(m2.getElement(1,1),1)); assert(equals(m2.getElement(1,2),0)); assert(equals(m2.getElement(1,3),0)); assert(equals(m2.getElement(2,0),0)); assert(equals(m2.getElement(2,1),0)); assert(equals(m2.getElement(2,2),1)); assert(equals(m2.getElement(2,3),0)); assert(equals(m2.getElement(3,0),0)); assert(equals(m2.getElement(3,1),0)); assert(equals(m2.getElement(3,2),0)); assert(equals(m2.getElement(3,3),1)); } /** * test for Matrix3 */ #ifdef TESTALL int test_9() { #else int main(int, char**) { #endif f(1.0); f(1.0f); return 0; }
5,627
2,501
#include <cstdio> #include <vector> #include <algorithm> int main(){ const int N = 10; const int S = 6; std::vector<int> counts(N,0); for(int p = 0; p < S; p++){int temp; scanf("%d", &temp); ++counts[temp];} std::sort(counts.begin(), counts.end()); if(counts[N - 1] < 4){puts("Alien");} else if(counts[N - 2] == 2 || counts[N - 1] == 6){puts("Elephant");} else if(counts[N - 2] == 1 || counts[N - 1] == 5){puts("Bear");} else{puts("Error");} return 0; }
500
226
// https://leetcode.com/problems/valid-perfect-square class Solution { public: bool isPerfectSquare(int num) { if (num <= 1) return true; int lo = 0, hi = num, mid; while (lo <= hi) { mid = lo + (hi - lo) / 2; if (mid == num / mid) { return num % mid == 0; } if (mid < (num / mid) && (mid + 1) > num / (mid + 1)) return false; if (num / mid < mid) { hi = mid; } else { lo = mid + 1; } } return false; } }; // Newton's method for sqrt public boolean isPerfectSquare(int num) { long x = num; while (x * x > num) { x = (x + num / x) >> 1; } return x * x == num; }
796
269
/* Copyright 2001, 2019 IBM Corporation * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // *********************************************************************** // File: rmsd.cpp // Author: RSG // Date: April 17, 2002 // Class: Rmsd // Description: Function object that computes rmsd from a vector of // doubles. // *********************************************************************** #include <BlueMatter/rmsd.hpp> #include <numeric> #include <cmath> double Rmsd::operator()(const std::vector<double>& data) const { double avg = std::accumulate(data.begin(), data.end(), 0.0); avg = avg/data.size(); double sum = 0.0; for (std::vector<double>::const_iterator iter = data.begin(); iter != data.end(); ++iter) { sum = sum + (*iter - avg)*(*iter - avg); } sum = std::sqrt(sum/data.size()); return(sum); }
2,113
731
// // Copyright (c) 2012-2020 Kris Jusiak (kris at jusiak dot net) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "boost/di/core/dependency.hpp" #include <type_traits> #include "boost/di/concepts/boundable.hpp" #include "common/fakes/fake_injector.hpp" #include "common/fakes/fake_scope.hpp" namespace core { test is_dependency_types = [] { expect(!std::is_base_of<dependency_base, void>::value); expect(!std::is_base_of<dependency_base, int>::value); expect(std::is_base_of<dependency_base, dependency<scopes::deduce, int>>::value); expect(std::is_base_of<dependency_base, dependency<scopes::deduce, double, double>>::value); }; struct name {}; test types = [] { using dep = dependency<fake_scope<>, int, double, name>; expect(std::is_same<fake_scope<>, typename dep::scope>::value); expect(std::is_same<int, typename dep::expected>::value); expect(std::is_same<double, typename dep::given>::value); expect(std::is_same<name, typename dep::name>::value); }; test def_ctor = [] { dependency<scopes::deduce, int> dep; (void)dep; }; test ctor = [] { fake_scope<>::ctor_calls() = 0; dependency<fake_scope<>, int> dep{0}; expect(1 == fake_scope<>::ctor_calls()); }; test named = [] { using dep1 = dependency<scopes::deduce, int>; expect(std::is_same<no_name, typename dep1::name>::value); using dep2 = decltype(dep1{}.named(name{})); expect(std::is_same<name, typename dep2::name>::value); }; test in = [] { using dep1 = dependency<fake_scope<>, int>; expect(std::is_same<fake_scope<>, typename dep1::scope>::value); using dep2 = decltype(dep1{}.in(scopes::deduce{})); expect(std::is_same<scopes::deduce, typename dep2::scope>::value); }; test to = [] { using dep1 = dependency<scopes::deduce, int>; expect(std::is_same<scopes::deduce, typename dep1::scope>::value); using dep2 = decltype(dep1{}.to(42)); expect(std::is_same<scopes::instance, typename dep2::scope>::value); expect(std::is_same<int, typename dep2::expected>::value); expect(std::is_same<int, typename dep2::given>::value); }; } // namespace core
2,199
833
#include "retro_collider_component.h" #include "retro_transform_component.h" #include "../retro_entity.h" namespace retro3d { retro_register_component(ColliderComponent) } void retro3d::ColliderComponent::OnSpawn( void ) { m_collider->AttachTransform(GetObject()->AddComponent<retro3d::TransformComponent>()->GetTransform()); m_reinsert = false; } retro3d::ColliderComponent::ColliderComponent( void ) : mtlInherit(this), m_filter_flags(uint64_t(~0)), m_is_static(false), m_reinsert(false) { CreateCollider<retro3d::AABBCollider>(); } retro3d::Collider &retro3d::ColliderComponent::GetCollider( void ) { return *m_collider.GetShared(); } const retro3d::Collider &retro3d::ColliderComponent::GetCollider( void ) const { return *m_collider.GetShared(); } uint64_t retro3d::ColliderComponent::GetFilterFlags( void ) const { return m_filter_flags; } bool retro3d::ColliderComponent::GetFilterFlag(uint32_t flag_index) const { return (m_filter_flags & (uint64_t(1) << flag_index)) != 0; } void retro3d::ColliderComponent::SetFilterFlags(uint64_t filter_flags) { m_filter_flags = filter_flags; m_reinsert = true; } void retro3d::ColliderComponent::SetFilterFlag(uint32_t flag_index, bool state) { if (state == true) { m_filter_flags |= (uint64_t(1) << flag_index); } else { m_filter_flags &= ~(uint64_t(1) << flag_index); } } bool retro3d::ColliderComponent::IsStatic( void ) const { return m_is_static; } void retro3d::ColliderComponent::ToggleStatic( void ) { m_is_static = !m_is_static; m_reinsert = true; } bool retro3d::ColliderComponent::ShouldReinsert( void ) const { return m_reinsert; } void retro3d::ColliderComponent::ToggleReinsert( void ) { m_reinsert = !m_reinsert; }
1,710
652
#include <iostream> class TCPServerThread { };
48
16
// Bugs.cpp: implementation of the CBugs class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "verifiee.h" #include "Bugs.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif typedef void (*PBUG_STOP_ROUTINE)( LPVOID lpParameter ); void BugAccessViolation(LPVOID lpParameter) { *(int *)0=1; } void BugDestroyProcHeap(LPVOID lpParameter) { HeapDestroy(GetProcessHeap()); } void BugDoubleFree(LPVOID lpParameter) { LPVOID lpvBase; // base address of the test memory SYSTEM_INFO sSysInfo; // useful information about the system DWORD dwPageSize; GetSystemInfo(&sSysInfo); // initialize the structure dwPageSize = sSysInfo.dwPageSize; lpvBase = VirtualAlloc( NULL, // system selects address 2*dwPageSize, // size of allocation MEM_RESERVE, // allocate reserved pages PAGE_NOACCESS); // protection = no access if (lpvBase == NULL ) { MessageBox(NULL, _T("VirtualAlloc failed"),_T("verifiee"), MB_OK); return; } VirtualFree(lpvBase, 0, MEM_RELEASE); // try freeing the freed mempry. VirtualFree(lpvBase, 0, MEM_RELEASE); } ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// typedef struct _BugStop{ TCHAR * StopName; // title of column DWORD StopCode; // width of column in pixels PBUG_STOP_ROUTINE BugRoutine; } BugStop; static BugStop g_BugStops[] = { { "Access Violation Exception", 2, BugAccessViolation }, { "Attempt to destroy process heap", 9, BugDestroyProcHeap}, { "Trying to free freed memory." , 0x0610, BugDoubleFree}, }; CBugs::CBugs() { } CBugs::~CBugs() { } void CBugs::FillListBox(CListBox &lb) { for (int i=0;i< sizeof(g_BugStops)/sizeof (BugStop);i++) { lb.AddString(g_BugStops[i].StopName); } } void CBugs::FireBug(int i) { g_BugStops[i].BugRoutine(this); }
2,031
766
#include <Eigen/Eigen> #include <iostream> #ifndef M_PI #define M_PI 3.1415926535897932384626433832795 #endif using namespace Eigen; using namespace std; int main(int, char**) { cout.precision(3); MatrixXf matA(2, 2); matA << 1, 2, 3, 4; MatrixXf matB(4, 4); matB << matA, matA/10, matA/10, matA; std::cout << matB << std::endl; return 0; }
352
187
#ifndef VIENNASHE_SIMULATOR_QUANTITY_HPP #define VIENNASHE_SIMULATOR_QUANTITY_HPP /* ============================================================================ Copyright (c) 2011-2014, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaSHE - The Vienna Spherical Harmonics Expansion Boltzmann Solver ----------------- http://viennashe.sourceforge.net/ License: MIT (X11), see file LICENSE in the base directory =============================================================================== */ /** @file viennashe/simulator_quantity.hpp @brief Defines a generic simulator quantity for use within the solvers of ViennaSHE */ #include <vector> #include <string> #include "viennagrid/mesh/mesh.hpp" #include "viennashe/forwards.h" namespace viennashe { /** @brief Holds a function per quantity, which returns the name of the respective quantity as std::string. */ namespace quantity { inline std::string potential() { return "Electrostatic potential"; } inline std::string electron_density() { return "Electron density"; } inline std::string hole_density() { return "Hole density"; } inline std::string density_gradient_electron_correction() { return "DG electron correction potential"; } inline std::string density_gradient_hole_correction() { return "DG hole correction potential"; } inline std::string lattice_temperature() { return "Lattice temperature"; } inline std::string electron_distribution_function() { return "Electron distribution function"; } inline std::string hole_distribution_function() { return "Hole distribution function"; } } /** @brief Common representation of any quantity associated with objects of a certain type. * * This is the minimum requirement one can have: Return value for a vertex/cell. */ template<typename AssociatedT, typename ValueT = double> class const_quantity { public: typedef const_quantity<AssociatedT, ValueT> self_type; typedef ValueT value_type; typedef AssociatedT associated_type; typedef associated_type access_type; const_quantity(std::string quan_name, std::size_t num_values, value_type default_value = value_type()) : name_(quan_name), values_(num_values, default_value) {} const_quantity(std::string quan_name, std::vector<ValueT> const & values_array) : name_(quan_name), values_(values_array) {} const_quantity(self_type const & o) : name_(o.name_), values_(o.values_) { } void operator=(self_type const & o) { name_(o.name_); values_(o.values_); } ValueT get_value (associated_type const & elem) const { return values_.at(static_cast<std::size_t>(elem.id().get())); } ValueT at (associated_type const & elem) const { return this->get_value(elem); } ValueT operator()(associated_type const & elem) const { return this->get_value(elem); } std::string name() const { return name_; } private: std::string name_; std::vector<ValueT> values_; }; template<typename AssociatedT, typename ValueT = double> class non_const_quantity { public: typedef non_const_quantity<AssociatedT, ValueT> self_type; typedef ValueT value_type; typedef AssociatedT associated_type; non_const_quantity(std::string quan_name, std::size_t num_values, value_type default_value = value_type()) : name_(quan_name), values_(num_values, default_value) {} non_const_quantity(std::string quan_name, std::vector<ValueT> const & values_array) : name_(quan_name), values_(values_array) {} non_const_quantity(self_type const & o) : name_(o.name_), values_(o.values_) { } void operator=(self_type const & o) { name_(o.name_); values_(o.values_); } ValueT get_value(associated_type const & elem) const { return values_.at(static_cast<std::size_t>(elem.id().get())); } ValueT at (associated_type const & elem) const { return this->get_value(elem); } ValueT operator()(associated_type const & elem) const { return this->get_value(elem); } void set_value(associated_type const & elem, ValueT value) { values_.at(static_cast<std::size_t>(elem.id().get())) = value; } std::string name() const { return name_; } private: std::string name_; std::vector<ValueT> values_; }; template <typename ValueT = double> struct robin_boundary_coefficients { ValueT alpha; ValueT beta; }; template<typename AssociatedT, typename ValueT = double> class unknown_quantity { std::size_t get_id(AssociatedT const & elem) const { return static_cast<std::size_t>(elem.id().get()); } public: typedef unknown_quantity<AssociatedT, ValueT> self_type; typedef ValueT value_type; typedef AssociatedT associated_type; typedef robin_boundary_coefficients<ValueT> robin_boundary_type; unknown_quantity() {} // to fulfill default constructible concept! unknown_quantity(std::string const & quan_name, equation_id quan_equation, std::size_t num_values, value_type default_value = value_type()) : name_(quan_name), equation_(quan_equation), values_ (num_values, default_value), boundary_types_ (num_values, BOUNDARY_NONE), boundary_values_ (num_values, default_value), boundary_values_alpha_ (num_values, 0), defined_but_unknown_mask_(num_values, false), unknowns_indices_ (num_values, -1), log_damping_(false) {} unknown_quantity(self_type const & o) : name_(o.name_), equation_(o.equation_), values_ (o.values_), boundary_types_ (o.boundary_types_), boundary_values_ (o.boundary_values_), boundary_values_alpha_ (o.boundary_values_alpha_), defined_but_unknown_mask_(o.defined_but_unknown_mask_), unknowns_indices_ (o.unknowns_indices_), log_damping_ (o.log_damping_) { } void operator=(self_type const & o) { name_ = o.name_; equation_ = o.equation_; values_ = o.values_; boundary_types_ = o.boundary_types_; boundary_values_ = o.boundary_values_; boundary_values_alpha_ = o.boundary_values_alpha_; defined_but_unknown_mask_= o.defined_but_unknown_mask_; unknowns_indices_ = o.unknowns_indices_; log_damping_ = o.log_damping_; } std::string get_name() const { return name_; } equation_id get_equation() const { return equation_; } ValueT get_value(associated_type const & elem) const { return values_.at(get_id(elem)); } ValueT at (associated_type const & elem) const { return this->get_value(elem); } ValueT operator()(associated_type const & elem) const { return this->get_value(elem); } void set_value(associated_type const & elem, ValueT value) { values_.at(get_id(elem)) = value; } void set_value(associated_type const & elem, robin_boundary_type value) { (void)elem; (void)value; } //TODO: Fix this rather ugly hack which stems from set_boundary_for_material() // Dirichlet and Neumann ValueT get_boundary_value(associated_type const & elem) const { return boundary_values_.at(get_id(elem)); } void set_boundary_value(associated_type const & elem, ValueT value) { boundary_values_.at(get_id(elem)) = value; } // Robin boundary conditions /** @brief Returns the coefficients alpha and beta for the Robin boundary condition du/dn = beta - alpha u * * * @return A pair holding (beta, alpha). .first returns beta, .second returns alpha */ robin_boundary_type get_boundary_values(associated_type const & elem) const { robin_boundary_type ret; ret.alpha = boundary_values_alpha_.at(get_id(elem)); ret.beta = boundary_values_.at(get_id(elem)); return ret; } /** @brief Setter function for Robin boundary conditions. * * Note that this is an overload rather than a new function 'set_boundary_values' in order to have a uniform setter interface. */ void set_boundary_value(associated_type const & elem, robin_boundary_type const & values) { boundary_values_.at(get_id(elem)) = values.beta; boundary_values_alpha_.at(get_id(elem)) = values.alpha; } boundary_type_id get_boundary_type(associated_type const & elem) const { return boundary_types_.at(get_id(elem)); } void set_boundary_type(associated_type const & elem, boundary_type_id value) { boundary_types_.at(get_id(elem)) = value; } bool get_unknown_mask(associated_type const & elem) const { return defined_but_unknown_mask_.at(get_id(elem)); } void set_unknown_mask(associated_type const & elem, bool value) { defined_but_unknown_mask_.at(get_id(elem)) = value; } long get_unknown_index(associated_type const & elem) const { return unknowns_indices_.at(get_id(elem)); } void set_unknown_index(associated_type const & elem, long value) { unknowns_indices_.at(get_id(elem)) = value; } std::size_t get_unknown_num() const { std::size_t num = 0; for (std::size_t i=0; i<unknowns_indices_.size(); ++i) { if (unknowns_indices_[i] >= 0) ++num; } return num; } // possible design flaws: std::vector<ValueT> const & values() const { return values_; } std::vector<boundary_type_id> const & boundary_types() const { return boundary_types_; } std::vector<ValueT> const & boundary_values() const { return boundary_values_; } std::vector<bool> const & defined_but_unknown_mask() const { return defined_but_unknown_mask_; } std::vector<long> const & unknowns_indices() const { return unknowns_indices_; } bool get_logarithmic_damping() const { return log_damping_; } void set_logarithmic_damping(bool b) { log_damping_ = b; } private: std::string name_; equation_id equation_; std::vector<ValueT> values_; std::vector<boundary_type_id> boundary_types_; std::vector<ValueT> boundary_values_; std::vector<ValueT> boundary_values_alpha_; std::vector<bool> defined_but_unknown_mask_; std::vector<long> unknowns_indices_; bool log_damping_; }; } //namespace viennashe #endif
11,565
3,324
#include <Arduino.h> #include "soc/efuse_reg.h" #include <esp_spi_flash.h> #include <esp_system.h> #include <rom/rtc.h> class ChipInfo { public: ChipInfo(); uint8_t reason; const char *sdkVersion; uint8_t chipVersion; uint8_t coreCount; uint8_t featureBT; uint8_t featureBLE; uint8_t featureWiFi; bool internalFlash; uint8_t flashSize; };
359
157
// Copyright 2017 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "garnet/drivers/bluetooth/lib/hci/low_energy_connector.h" #include <vector> #include <lib/async/cpp/task.h> #include "garnet/drivers/bluetooth/lib/hci/defaults.h" #include "garnet/drivers/bluetooth/lib/testing/fake_controller.h" #include "garnet/drivers/bluetooth/lib/testing/fake_controller_test.h" #include "garnet/drivers/bluetooth/lib/testing/fake_device.h" #include "lib/fxl/macros.h" namespace btlib { namespace hci { namespace { using common::HostError; using testing::FakeController; using testing::FakeDevice; using TestingBase = testing::FakeControllerTest<FakeController>; const common::DeviceAddress kLocalAddress( common::DeviceAddress::Type::kLEPublic, "00:00:00:00:00:FF"); const common::DeviceAddress kTestAddress(common::DeviceAddress::Type::kLEPublic, "00:00:00:00:00:01"); const LEPreferredConnectionParameters kTestParams(1, 1, 1, 1); constexpr int64_t kConnectTimeoutMs = 10000; class LowEnergyConnectorTest : public TestingBase { public: LowEnergyConnectorTest() = default; ~LowEnergyConnectorTest() override = default; protected: // TestingBase overrides: void SetUp() override { TestingBase::SetUp(); InitializeACLDataChannel(); FakeController::Settings settings; settings.ApplyLegacyLEConfig(); test_device()->set_settings(settings); connector_ = std::make_unique<LowEnergyConnector>( transport(), kLocalAddress, dispatcher(), std::bind(&LowEnergyConnectorTest::OnIncomingConnectionCreated, this, std::placeholders::_1)); test_device()->SetConnectionStateCallback( std::bind(&LowEnergyConnectorTest::OnConnectionStateChanged, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), dispatcher()); StartTestDevice(); } void TearDown() override { connector_ = nullptr; test_device()->Stop(); TestingBase::TearDown(); } void DeleteConnector() { connector_ = nullptr; } bool request_canceled = false; const std::vector<std::unique_ptr<Connection>>& in_connections() const { return in_connections_; } LowEnergyConnector* connector() const { return connector_.get(); } private: void OnIncomingConnectionCreated(std::unique_ptr<Connection> connection) { in_connections_.push_back(std::move(connection)); } void OnConnectionStateChanged(const common::DeviceAddress& address, bool connected, bool canceled) { request_canceled = canceled; } std::unique_ptr<LowEnergyConnector> connector_; // Incoming connections. std::vector<std::unique_ptr<Connection>> in_connections_; FXL_DISALLOW_COPY_AND_ASSIGN(LowEnergyConnectorTest); }; using HCI_LowEnergyConnectorTest = LowEnergyConnectorTest; TEST_F(HCI_LowEnergyConnectorTest, CreateConnection) { auto fake_device = std::make_unique<FakeDevice>(kTestAddress, true, true); test_device()->AddDevice(std::move(fake_device)); EXPECT_FALSE(connector()->request_pending()); hci::Status status; ConnectionPtr conn; bool callback_called = false; auto callback = [&, this](auto cb_status, auto cb_conn) { status = cb_status; conn = std::move(cb_conn); callback_called = true; }; bool ret = connector()->CreateConnection( LEOwnAddressType::kPublic, false, kTestAddress, defaults::kLEScanInterval, defaults::kLEScanWindow, kTestParams, callback, kConnectTimeoutMs); EXPECT_TRUE(ret); EXPECT_TRUE(connector()->request_pending()); ret = connector()->CreateConnection( LEOwnAddressType::kPublic, false, kTestAddress, defaults::kLEScanInterval, defaults::kLEScanWindow, kTestParams, callback, kConnectTimeoutMs); EXPECT_FALSE(ret); RunLoopUntilIdle(); EXPECT_FALSE(connector()->request_pending()); EXPECT_TRUE(callback_called); EXPECT_TRUE(status); EXPECT_TRUE(in_connections().empty()); ASSERT_TRUE(conn); EXPECT_EQ(1u, conn->handle()); EXPECT_EQ(kLocalAddress, conn->local_address()); EXPECT_EQ(kTestAddress, conn->peer_address()); EXPECT_TRUE(conn->is_open()); conn->set_closed(); } // Controller reports error from HCI Command Status event. TEST_F(HCI_LowEnergyConnectorTest, CreateConnectionStatusError) { auto fake_device = std::make_unique<FakeDevice>(kTestAddress, true, true); fake_device->set_connect_status(StatusCode::kCommandDisallowed); test_device()->AddDevice(std::move(fake_device)); EXPECT_FALSE(connector()->request_pending()); hci::Status status; ConnectionPtr conn; bool callback_called = false; auto callback = [&, this](auto cb_status, auto cb_conn) { status = cb_status; conn = std::move(cb_conn); callback_called = true; }; bool ret = connector()->CreateConnection( LEOwnAddressType::kPublic, false, kTestAddress, defaults::kLEScanInterval, defaults::kLEScanWindow, kTestParams, callback, kConnectTimeoutMs); EXPECT_TRUE(ret); EXPECT_TRUE(connector()->request_pending()); RunLoopUntilIdle(); EXPECT_FALSE(connector()->request_pending()); EXPECT_TRUE(callback_called); EXPECT_FALSE(status); EXPECT_TRUE(status.is_protocol_error()); EXPECT_EQ(StatusCode::kCommandDisallowed, status.protocol_error()); EXPECT_FALSE(conn); EXPECT_TRUE(in_connections().empty()); } // Controller reports error from HCI LE Connection Complete event TEST_F(HCI_LowEnergyConnectorTest, CreateConnectionEventError) { auto fake_device = std::make_unique<FakeDevice>(kTestAddress, true, true); fake_device->set_connect_response(StatusCode::kConnectionRejectedSecurity); test_device()->AddDevice(std::move(fake_device)); EXPECT_FALSE(connector()->request_pending()); hci::Status status; ConnectionPtr conn; bool callback_called = false; auto callback = [&, this](auto cb_status, auto cb_conn) { status = cb_status; callback_called = true; conn = std::move(cb_conn); }; bool ret = connector()->CreateConnection( LEOwnAddressType::kPublic, false, kTestAddress, defaults::kLEScanInterval, defaults::kLEScanWindow, kTestParams, callback, kConnectTimeoutMs); EXPECT_TRUE(ret); EXPECT_TRUE(connector()->request_pending()); RunLoopUntilIdle(); EXPECT_FALSE(connector()->request_pending()); EXPECT_TRUE(callback_called); EXPECT_FALSE(status); EXPECT_TRUE(status.is_protocol_error()); EXPECT_EQ(StatusCode::kConnectionRejectedSecurity, status.protocol_error()); EXPECT_TRUE(in_connections().empty()); EXPECT_FALSE(conn); } // Controller reports error from HCI LE Connection Complete event TEST_F(HCI_LowEnergyConnectorTest, Cancel) { auto fake_device = std::make_unique<FakeDevice>(kTestAddress, true, true); // Make sure the pending connect remains pending. fake_device->set_force_pending_connect(true); test_device()->AddDevice(std::move(fake_device)); hci::Status status; ConnectionPtr conn; bool callback_called = false; auto callback = [&, this](auto cb_status, auto cb_conn) { status = cb_status; callback_called = true; conn = std::move(cb_conn); }; bool ret = connector()->CreateConnection( LEOwnAddressType::kPublic, false, kTestAddress, defaults::kLEScanInterval, defaults::kLEScanWindow, kTestParams, callback, kConnectTimeoutMs); EXPECT_TRUE(ret); EXPECT_TRUE(connector()->request_pending()); ASSERT_FALSE(request_canceled); connector()->Cancel(); EXPECT_TRUE(connector()->request_pending()); // The request timeout should be canceled regardless of whether it was posted // before. EXPECT_FALSE(connector()->timeout_posted()); RunLoopUntilIdle(); EXPECT_FALSE(connector()->timeout_posted()); EXPECT_FALSE(connector()->request_pending()); EXPECT_TRUE(callback_called); EXPECT_TRUE(request_canceled); EXPECT_EQ(HostError::kCanceled, status.error()); EXPECT_TRUE(in_connections().empty()); EXPECT_FALSE(conn); } TEST_F(HCI_LowEnergyConnectorTest, IncomingConnect) { EXPECT_TRUE(in_connections().empty()); EXPECT_FALSE(connector()->request_pending()); LEConnectionCompleteSubeventParams event; std::memset(&event, 0, sizeof(event)); event.status = StatusCode::kSuccess; event.peer_address = kTestAddress.value(); event.peer_address_type = LEPeerAddressType::kPublic; event.conn_interval = defaults::kLEConnectionIntervalMin; event.connection_handle = 1; test_device()->SendLEMetaEvent(kLEConnectionCompleteSubeventCode, common::BufferView(&event, sizeof(event))); RunLoopUntilIdle(); ASSERT_EQ(1u, in_connections().size()); auto conn = in_connections()[0].get(); EXPECT_EQ(1u, conn->handle()); EXPECT_EQ(kLocalAddress, conn->local_address()); EXPECT_EQ(kTestAddress, conn->peer_address()); EXPECT_TRUE(conn->is_open()); conn->set_closed(); } TEST_F(HCI_LowEnergyConnectorTest, IncomingConnectDuringConnectionRequest) { const common::DeviceAddress kIncomingAddress( common::DeviceAddress::Type::kLEPublic, "00:00:00:00:00:02"); EXPECT_TRUE(in_connections().empty()); EXPECT_FALSE(connector()->request_pending()); auto fake_device = std::make_unique<FakeDevice>(kTestAddress, true, true); test_device()->AddDevice(std::move(fake_device)); hci::Status status; ConnectionPtr conn; unsigned int callback_count = 0; auto callback = [&, this](auto cb_status, auto cb_conn) { status = cb_status; callback_count++; conn = std::move(cb_conn); }; connector()->CreateConnection( LEOwnAddressType::kPublic, false, kTestAddress, defaults::kLEScanInterval, defaults::kLEScanWindow, kTestParams, callback, kConnectTimeoutMs); async::PostTask(dispatcher(), [kIncomingAddress, this] { LEConnectionCompleteSubeventParams event; std::memset(&event, 0, sizeof(event)); event.status = StatusCode::kSuccess; event.peer_address = kIncomingAddress.value(); event.peer_address_type = LEPeerAddressType::kPublic; event.conn_interval = defaults::kLEConnectionIntervalMin; event.connection_handle = 2; test_device()->SendLEMetaEvent(kLEConnectionCompleteSubeventCode, common::BufferView(&event, sizeof(event))); }); RunLoopUntilIdle(); EXPECT_TRUE(status); EXPECT_EQ(1u, callback_count); ASSERT_EQ(1u, in_connections().size()); const auto& in_conn = in_connections().front(); EXPECT_EQ(1u, conn->handle()); EXPECT_EQ(2u, in_conn->handle()); EXPECT_EQ(kTestAddress, conn->peer_address()); EXPECT_EQ(kIncomingAddress, in_conn->peer_address()); EXPECT_TRUE(conn->is_open()); EXPECT_TRUE(in_conn->is_open()); conn->set_closed(); in_conn->set_closed(); } TEST_F(HCI_LowEnergyConnectorTest, CreateConnectionTimeout) { // We do not set up any fake devices. This will cause the request to time out. EXPECT_FALSE(connector()->request_pending()); hci::Status status; ConnectionPtr conn; bool callback_called = false; auto callback = [&, this](auto cb_status, auto cb_conn) { status = cb_status; callback_called = true; conn = std::move(cb_conn); }; connector()->CreateConnection( LEOwnAddressType::kPublic, false, kTestAddress, defaults::kLEScanInterval, defaults::kLEScanWindow, kTestParams, callback, kConnectTimeoutMs); EXPECT_TRUE(connector()->request_pending()); EXPECT_FALSE(request_canceled); // Make the connection attempt time out. RunLoopFor(zx::msec(kConnectTimeoutMs)); EXPECT_FALSE(connector()->request_pending()); EXPECT_TRUE(callback_called); EXPECT_TRUE(request_canceled); EXPECT_EQ(HostError::kTimedOut, status.error()) << status.ToString(); EXPECT_TRUE(in_connections().empty()); EXPECT_FALSE(conn); } TEST_F(HCI_LowEnergyConnectorTest, SendRequestAndDelete) { auto fake_device = std::make_unique<FakeDevice>(kTestAddress, true, true); // Make sure the pending connect remains pending. fake_device->set_force_pending_connect(true); test_device()->AddDevice(std::move(fake_device)); bool ret = connector()->CreateConnection( LEOwnAddressType::kPublic, false, kTestAddress, defaults::kLEScanInterval, defaults::kLEScanWindow, kTestParams, [](auto, auto) {}, kConnectTimeoutMs); EXPECT_TRUE(ret); EXPECT_TRUE(connector()->request_pending()); DeleteConnector(); RunLoopUntilIdle(); EXPECT_TRUE(request_canceled); EXPECT_TRUE(in_connections().empty()); } } // namespace } // namespace hci } // namespace btlib
12,610
4,231
/* ** Copyright 2009-2017 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #include <cstdlib> #include <ctime> #include <memory> #include <QDomDocument> #include <QDomElement> #include <QString> #include <QStringList> #include <set> #include <unistd.h> #include "com/centreon/broker/config/applier/state.hh" #include "com/centreon/broker/config/parser.hh" #include "com/centreon/broker/config/state.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/neb/callback.hh" #include "com/centreon/broker/neb/callbacks.hh" #include "com/centreon/broker/neb/events.hh" #include "com/centreon/broker/neb/initial.hh" #include "com/centreon/broker/neb/internal.hh" #include "com/centreon/broker/neb/set_log_data.hh" #include "com/centreon/broker/neb/statistics/generator.hh" #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/nebcallbacks.hh" #include "com/centreon/engine/nebstructs.hh" #include "com/centreon/engine/hostdependency.hh" #include "com/centreon/engine/servicedependency.hh" #include "com/centreon/engine/comment.hh" #include "com/centreon/engine/hostgroup.hh" #include "com/centreon/engine/servicegroup.hh" #include "com/centreon/engine/events/timed_event.hh" #include "com/centreon/engine/events/defines.hh" using namespace com::centreon::broker; // List of Nagios modules. extern nebmodule* neb_module_list; // Acknowledgement list. std::map<std::pair<unsigned int, unsigned int>, neb::acknowledgement> neb::gl_acknowledgements; // Downtime list. struct private_downtime_params { bool cancelled; time_t deletion_time; time_t end_time; bool started; time_t start_time; }; // Unstarted downtimes. static umap<unsigned int, private_downtime_params> downtimes; // Load flags. int neb::gl_mod_flags(0); // Module handle. void* neb::gl_mod_handle(nullptr); // List of common callbacks. static struct { unsigned int macro; int (* callback)(int, void*); } const gl_callbacks[] = { { NEBCALLBACK_ACKNOWLEDGEMENT_DATA, &neb::callback_acknowledgement }, { NEBCALLBACK_COMMENT_DATA, &neb::callback_comment }, { NEBCALLBACK_DOWNTIME_DATA, &neb::callback_downtime }, { NEBCALLBACK_EVENT_HANDLER_DATA, &neb::callback_event_handler }, { NEBCALLBACK_EXTERNAL_COMMAND_DATA, &neb::callback_external_command }, { NEBCALLBACK_FLAPPING_DATA, &neb::callback_flapping_status }, { NEBCALLBACK_HOST_CHECK_DATA, &neb::callback_host_check }, { NEBCALLBACK_HOST_STATUS_DATA, &neb::callback_host_status }, { NEBCALLBACK_PROGRAM_STATUS_DATA, &neb::callback_program_status }, { NEBCALLBACK_SERVICE_CHECK_DATA, &neb::callback_service_check }, { NEBCALLBACK_SERVICE_STATUS_DATA, &neb::callback_service_status } }; // List of Engine-specific callbacks. static struct { unsigned int macro; int (* callback)(int, void*); } const gl_engine_callbacks[] = { { NEBCALLBACK_ADAPTIVE_DEPENDENCY_DATA, &neb::callback_dependency }, { NEBCALLBACK_ADAPTIVE_HOST_DATA, &neb::callback_host }, { NEBCALLBACK_ADAPTIVE_SERVICE_DATA, &neb::callback_service }, { NEBCALLBACK_CUSTOM_VARIABLE_DATA, &neb::callback_custom_variable }, { NEBCALLBACK_GROUP_DATA, &neb::callback_group }, { NEBCALLBACK_GROUP_MEMBER_DATA, &neb::callback_group_member }, { NEBCALLBACK_MODULE_DATA, &neb::callback_module }, { NEBCALLBACK_RELATION_DATA, &neb::callback_relation } }; // Registered callbacks. std::list<std::shared_ptr<neb::callback> > neb::gl_registered_callbacks; // External function to get program version. extern "C" { char const* get_program_version(); } // Statistics generator. static neb::statistics::generator gl_generator; extern "C" void event_statistics(void* args) { (void)args; try { gl_generator.run(); } catch (std::exception const& e) { logging::error(logging::medium) << "stats: error occurred while generating statistics event: " << e.what(); } // Avoid exception propagation in C code. catch (...) {} return ; } /** * @brief Function that process acknowledgement data. * * This function is called by Nagios when some acknowledgement data are * available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_ACKNOWLEDGEMENT_DATA). * @param[in] data A pointer to a nebstruct_acknowledgement_data * containing the acknowledgement data. * * @return 0 on success. */ int neb::callback_acknowledgement(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating acknowledgement event"; (void)callback_type; try { // In/Out variables. nebstruct_acknowledgement_data const* ack_data; std::shared_ptr<neb::acknowledgement> ack(new neb::acknowledgement); // Fill output var. ack_data = static_cast<nebstruct_acknowledgement_data*>(data); ack->acknowledgement_type = ack_data->acknowledgement_type; if (ack_data->author_name) ack->author = ack_data->author_name; if (ack_data->comment_data) ack->comment = ack_data->comment_data; ack->entry_time = time(nullptr); if (!ack_data->host_name) throw (exceptions::msg() << "unnamed host"); if (ack_data->service_description) { std::pair<unsigned int, unsigned int> p; p = engine::get_host_and_service_id( ack_data->host_name, ack_data->service_description); ack->host_id = p.first; ack->service_id = p.second; if (!ack->host_id || !ack->service_id) throw (exceptions::msg() << "could not find ID of service ('" << ack_data->host_name << "', '" << ack_data->service_description << "')"); } else { ack->host_id = engine::get_host_id(ack_data->host_name); if (ack->host_id == 0) throw (exceptions::msg() << "could not find ID of host '" << ack_data->host_name << "'"); } ack->poller_id = config::applier::state::instance().poller_id(); ack->is_sticky = ack_data->is_sticky; ack->notify_contacts = ack_data->notify_contacts; ack->persistent_comment = ack_data->persistent_comment; ack->state = ack_data->state; gl_acknowledgements[std::make_pair(ack->host_id, ack->service_id)] = *ack; // Send event. gl_publisher.write(ack); } catch (std::exception const& e) { logging::error(logging::medium) << "callbacks: error occurred while" " generating acknowledgement event: " << e.what(); } // Avoid exception propagation in C code. catch (...) {} return 0; } /** * @brief Function that process comment data. * * This function is called by Nagios when some comment data are available. * * @param[in] callback_type Type of the callback (NEBCALLBACK_COMMENT_DATA). * @param[in] data A pointer to a nebstruct_comment_data containing * the comment data. * * @return 0 on success. */ int neb::callback_comment(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating comment event"; (void)callback_type; try { // In/Out variables. nebstruct_comment_data const* comment_data; std::shared_ptr<neb::comment> comment(new neb::comment); // Fill output var. comment_data = static_cast<nebstruct_comment_data*>(data); if (comment_data->author_name) comment->author = comment_data->author_name; if (comment_data->comment_data) comment->data = comment_data->comment_data; comment->comment_type = comment_data->comment_type; if (NEBTYPE_COMMENT_DELETE == comment_data->type) comment->deletion_time = time(nullptr); comment->entry_time = comment_data->entry_time; comment->entry_type = comment_data->entry_type; comment->expire_time = comment_data->expire_time; comment->expires = comment_data->expires; if (!comment_data->host_name) throw (exceptions::msg() << "unnamed host"); if (comment_data->service_description) { std::pair<unsigned int, unsigned int> p; p = engine::get_host_and_service_id( comment_data->host_name, comment_data->service_description); comment->host_id = p.first; comment->service_id = p.second; if (!comment->host_id || !comment->service_id) throw (exceptions::msg() << "could not find ID of service ('" << comment_data->host_name << "', '" << comment_data->service_description << "')"); } else { comment->host_id = engine::get_host_id(comment_data->host_name); if (comment->host_id == 0) throw (exceptions::msg() << "could not find ID of host '" << comment_data->host_name << "'"); } comment->poller_id = config::applier::state::instance().poller_id(); comment->internal_id = comment_data->comment_id; comment->persistent = comment_data->persistent; comment->source = comment_data->source; // Send event. gl_publisher.write(comment); } catch (std::exception const& e) { logging::error(logging::medium) << "callbacks: error occurred while" " generating comment event: " << e.what(); } // Avoid exception propagation in C code. catch (...) {} return 0; } /** * @brief Function that process custom variable data. * * This function is called by Engine when some custom variable data is * available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_CUSTOMVARIABLE_DATA). * @param[in] data Pointer to a nebstruct_custom_variable_data * containing the custom variable data. * * @return 0 on success. */ int neb::callback_custom_variable(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating custom variable event"; (void)callback_type; try { // Input variable. nebstruct_custom_variable_data const* cvar(static_cast<nebstruct_custom_variable_data*>(data)); if (cvar && cvar->var_name && cvar->var_value) { // Host custom variable. if (NEBTYPE_HOSTCUSTOMVARIABLE_ADD == cvar->type) { engine::host* hst(static_cast<engine::host*>(cvar->object_ptr)); if (hst && !hst->get_name().empty()) { // Fill custom variable event. uint64_t host_id = engine::get_host_id(hst->get_name()); if (host_id != 0) { std::shared_ptr<custom_variable> new_cvar(new custom_variable); new_cvar->enabled = true; new_cvar->host_id = host_id; new_cvar->modified = false; new_cvar->name = cvar->var_name; new_cvar->var_type = 0; new_cvar->update_time = cvar->timestamp.tv_sec; new_cvar->value = cvar->var_value; new_cvar->default_value = cvar->var_value; // Send custom variable event. logging::info(logging::low) << "callbacks: new custom variable '" << new_cvar->name << "' on host " << new_cvar->host_id; neb::gl_publisher.write(new_cvar); } } } else if (NEBTYPE_HOSTCUSTOMVARIABLE_DELETE == cvar->type) { engine::host* hst(static_cast<engine::host*>(cvar->object_ptr)); if (hst && !hst->get_name().empty()) { unsigned int host_id = engine::get_host_id(hst->get_name()); if (host_id != 0) { std::shared_ptr<custom_variable> old_cvar(new custom_variable); old_cvar->enabled = false; old_cvar->host_id = host_id; old_cvar->name = cvar->var_name; old_cvar->var_type = 0; old_cvar->update_time = cvar->timestamp.tv_sec; // Send custom variable event. logging::info(logging::low) << "callbacks: deleted custom variable '" << old_cvar->name << "' on host '" << old_cvar->host_id; neb::gl_publisher.write(old_cvar); } } } // Service custom variable. else if (NEBTYPE_SERVICECUSTOMVARIABLE_ADD == cvar->type) { engine::service* svc{static_cast<engine::service*>(cvar->object_ptr)}; if (svc && !svc->get_description().empty() && !svc->get_hostname().empty()) { // Fill custom variable event. std::pair<unsigned int, unsigned int> p; p = engine::get_host_and_service_id( svc->get_hostname(), svc->get_description()); if (p.first && p.second) { std::shared_ptr<custom_variable> new_cvar(new custom_variable); new_cvar->enabled = true; new_cvar->host_id = p.first; new_cvar->modified = false; new_cvar->name = cvar->var_name; new_cvar->service_id = p.second; new_cvar->var_type = 1; new_cvar->update_time = cvar->timestamp.tv_sec; new_cvar->value = cvar->var_value; new_cvar->default_value = cvar->var_value; // Send custom variable event. logging::info(logging::low) << "callbacks: new custom variable '" << new_cvar->name << "' on service (" << new_cvar->host_id << ", " << new_cvar->service_id << ")"; neb::gl_publisher.write(new_cvar); } } } else if (NEBTYPE_SERVICECUSTOMVARIABLE_DELETE == cvar->type) { engine::service* svc{static_cast<engine::service*>(cvar->object_ptr)}; if (svc && !svc->get_description().empty() && !svc->get_hostname().empty()) { std::pair<uint64_t, uint64_t> p{engine::get_host_and_service_id( svc->get_hostname(), svc->get_description())}; if (p.first && p.second) { std::shared_ptr<custom_variable> old_cvar(new custom_variable); old_cvar->enabled = false; old_cvar->host_id = p.first; old_cvar->modified = true; old_cvar->name = cvar->var_name; old_cvar->service_id = p.second; old_cvar->var_type = 1; old_cvar->update_time = cvar->timestamp.tv_sec; // Send custom variable event. logging::info(logging::low) << "callbacks: deleted custom variable '" << old_cvar->name << "' on service (" << old_cvar->host_id << ", " << old_cvar->service_id << ")"; neb::gl_publisher.write(old_cvar); } } } } } // Avoid exception propagation to C code. catch (...) {} return 0; } /** * @brief Function that process dependency data. * * This function is called by Centreon Engine when some dependency data * is available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_ADAPTIVE_DEPENDENCY_DATA). * @param[in] data A pointer to a * nebstruct_adaptive_dependency_data * containing the dependency data. * * @return 0 on success. */ int neb::callback_dependency(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating dependency event"; (void)callback_type; try { // Input variables. nebstruct_adaptive_dependency_data* nsadd(static_cast<nebstruct_adaptive_dependency_data*>(data)); // Host dependency. if ((NEBTYPE_HOSTDEPENDENCY_ADD == nsadd->type) || (NEBTYPE_HOSTDEPENDENCY_UPDATE == nsadd->type) || (NEBTYPE_HOSTDEPENDENCY_DELETE == nsadd->type)) { // Find IDs. uint64_t host_id; uint64_t dep_host_id; engine::hostdependency* dep(static_cast<engine::hostdependency*>(nsadd->object_ptr)); if (!dep->get_hostname().empty()) { host_id = engine::get_host_id(dep->get_hostname()); } else { logging::error(logging::medium) << "callbacks: dependency callback called without " << "valid host"; host_id = 0; } if (!dep->get_dependent_hostname().empty()) { dep_host_id = engine::get_host_id(dep->get_dependent_hostname()); } else { logging::error(logging::medium) << "callbacks: dependency callback called without " << "valid dependent host"; dep_host_id = 0; } // Generate service dependency event. std::shared_ptr<host_dependency> hst_dep(new host_dependency); hst_dep->host_id = host_id; hst_dep->dependent_host_id = dep_host_id; hst_dep->enabled = (nsadd->type != NEBTYPE_HOSTDEPENDENCY_DELETE); if (!dep->get_dependency_period().empty()) hst_dep->dependency_period = QString(dep->get_dependency_period().c_str()); { QString options; if (dep->get_fail_on_down()) options.append("d"); if (dep->get_fail_on_up()) options.append("o"); if (dep->get_fail_on_pending()) options.append("p"); if (dep->get_fail_on_unreachable()) options.append("u"); if (dep->get_dependency_type() == engine::dependency::notification) hst_dep->notification_failure_options = options; else if (dep->get_dependency_type() == engine::dependency::execution) hst_dep->execution_failure_options = options; } hst_dep->inherits_parent = dep->get_inherits_parent(); logging::info(logging::low) << "callbacks: host " << dep_host_id << " depends on host " << host_id; // Publish dependency event. neb::gl_publisher.write(hst_dep); } // Service dependency. else if ((NEBTYPE_SERVICEDEPENDENCY_ADD == nsadd->type) || (NEBTYPE_SERVICEDEPENDENCY_UPDATE == nsadd->type) || (NEBTYPE_SERVICEDEPENDENCY_DELETE == nsadd->type)) { // Find IDs. std::pair<uint64_t, uint64_t> ids; std::pair<uint64_t, uint64_t> dep_ids; engine::servicedependency* dep(static_cast<engine::servicedependency*>(nsadd->object_ptr)); if (!dep->get_hostname().empty() && !dep->get_service_description().empty()) { ids = engine::get_host_and_service_id( dep->get_hostname(), dep->get_service_description()); } else { logging::error(logging::medium) << "callbacks: dependency callback called without " << "valid service"; ids.first = 0; ids.second = 0; } if (!dep->get_dependent_hostname().empty() && !dep->get_dependent_service_description().empty()) { dep_ids = engine::get_host_and_service_id( dep->get_hostname(), dep->get_service_description()); } else { logging::error(logging::medium) << "callbacks: dependency callback called without " << "valid dependent service"; dep_ids.first = 0; dep_ids.second = 0; } // Generate service dependency event. std::shared_ptr<service_dependency> svc_dep(new service_dependency); svc_dep->host_id = ids.first; svc_dep->service_id = ids.second; svc_dep->dependent_host_id = dep_ids.first; svc_dep->dependent_service_id = dep_ids.second; svc_dep->enabled = (nsadd->type != NEBTYPE_SERVICEDEPENDENCY_DELETE); if (!dep->get_dependency_period().empty()) svc_dep->dependency_period = QString(dep->get_dependency_period().c_str()); { QString options; if (dep->get_fail_on_critical()) options.append("c"); if (dep->get_fail_on_ok()) options.append("o"); if (dep->get_fail_on_pending()) options.append("p"); if (dep->get_fail_on_unknown()) options.append("u"); if (dep->get_fail_on_warning()) options.append("w"); if (dep->get_dependency_type() == engine::dependency::notification) svc_dep->notification_failure_options = options; else if (dep->get_dependency_type() == engine::dependency::execution) svc_dep->execution_failure_options = options; } svc_dep->inherits_parent = dep->get_inherits_parent(); logging::info(logging::low) << "callbacks: service (" << dep_ids.first << ", " << dep_ids.second << ") depends on service (" << ids.first << ", " << ids.second << ")"; // Publish dependency event. neb::gl_publisher.write(svc_dep); } } // Avoid exception propagation to C code. catch (...) {} return 0; } /** * @brief Function that process downtime data. * * This function is called by Nagios when some downtime data are available. * * @param[in] callback_type Type of the callback (NEBCALLBACK_DOWNTIME_DATA). * @param[in] data A pointer to a nebstruct_downtime_data containing * the downtime data. * * @return 0 on success. */ int neb::callback_downtime(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating downtime event"; (void)callback_type; try { // In/Out variables. nebstruct_downtime_data const* downtime_data; std::shared_ptr<neb::downtime> downtime(new neb::downtime); // Fill output var. downtime_data = static_cast<nebstruct_downtime_data*>(data); if (downtime_data->author_name) downtime->author = downtime_data->author_name; if (downtime_data->comment_data) downtime->comment = downtime_data->comment_data; downtime->downtime_type = downtime_data->downtime_type; downtime->duration = downtime_data->duration; downtime->end_time = downtime_data->end_time; downtime->entry_time = downtime_data->entry_time; downtime->fixed = downtime_data->fixed; if (!downtime_data->host_name) throw (exceptions::msg() << "unnamed host"); if (downtime_data->service_description) { std::pair<unsigned int, unsigned int> p; p = engine::get_host_and_service_id( downtime_data->host_name, downtime_data->service_description); downtime->host_id = p.first; downtime->service_id = p.second; if (!downtime->host_id || !downtime->service_id) throw (exceptions::msg() << "could not find ID of service ('" << downtime_data->host_name << "', '" << downtime_data->service_description << "')"); } else { downtime->host_id = engine::get_host_id(downtime_data->host_name); if (downtime->host_id == 0) throw (exceptions::msg() << "could not find ID of host '" << downtime_data->host_name << "'"); } downtime->poller_id = config::applier::state::instance().poller_id(); downtime->internal_id = downtime_data->downtime_id; downtime->start_time = downtime_data->start_time; downtime->triggered_by = downtime_data->triggered_by; private_downtime_params& params(downtimes[downtime->internal_id]); if ((NEBTYPE_DOWNTIME_ADD == downtime_data->type) || (NEBTYPE_DOWNTIME_LOAD == downtime_data->type)) { params.cancelled = false; params.deletion_time = -1; params.end_time = -1; params.started = false; params.start_time = -1; } else if (NEBTYPE_DOWNTIME_START == downtime_data->type) { params.started = true; params.start_time = downtime_data->timestamp.tv_sec; } else if (NEBTYPE_DOWNTIME_STOP == downtime_data->type) { if (NEBATTR_DOWNTIME_STOP_CANCELLED == downtime_data->attr) params.cancelled = true; params.end_time = downtime_data->timestamp.tv_sec; } else if (NEBTYPE_DOWNTIME_DELETE == downtime_data->type) { if (!params.started) params.cancelled = true; params.deletion_time = downtime_data->timestamp.tv_sec; } downtime->actual_start_time = params.start_time; downtime->actual_end_time = params.end_time; downtime->deletion_time = params.deletion_time; downtime->was_cancelled = params.cancelled; downtime->was_started = params.started; if (NEBTYPE_DOWNTIME_DELETE == downtime_data->type) downtimes.erase(downtime->internal_id); // Send event. gl_publisher.write(downtime); } catch (std::exception const& e) { logging::error(logging::medium) << "callbacks: error occurred while" "generating downtime event: " << e.what(); } // Avoid exception propagation in C code. catch (...) {} return 0; } /** * @brief Function that process event handler data. * * This function is called by Nagios when some event handler data are * available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_EVENT_HANDLER_DATA). * @param[in] data A pointer to a nebstruct_event_handler_data * containing the event handler data. * * @return 0 on success. */ int neb::callback_event_handler(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating event handler event"; (void)callback_type; try { // In/Out variables. nebstruct_event_handler_data const* event_handler_data; std::shared_ptr<neb::event_handler> event_handler(new neb::event_handler); // Fill output var. event_handler_data = static_cast<nebstruct_event_handler_data*>(data); if (event_handler_data->command_args) event_handler->command_args = event_handler_data->command_args; if (event_handler_data->command_line) event_handler->command_line = event_handler_data->command_line; event_handler->early_timeout = event_handler_data->early_timeout; event_handler->end_time = event_handler_data->end_time.tv_sec; event_handler->execution_time = event_handler_data->execution_time; if (!event_handler_data->host_name) throw (exceptions::msg() << "unnamed host"); if (event_handler_data->service_description) { std::pair<unsigned int, unsigned int> p; p = engine::get_host_and_service_id( event_handler_data->host_name, event_handler_data->service_description); event_handler->host_id = p.first; event_handler->service_id = p.second; if (!event_handler->host_id || !event_handler->service_id) throw (exceptions::msg() << "could not find ID of service ('" << event_handler_data->host_name << "', '" << event_handler_data->service_description << "')"); } else { event_handler->host_id = engine::get_host_id( event_handler_data->host_name); if (event_handler->host_id == 0) throw (exceptions::msg() << "could not find ID of host '" << event_handler_data->host_name << "'"); } if (event_handler_data->output) event_handler->output = event_handler_data->output; event_handler->return_code = event_handler_data->return_code; event_handler->start_time = event_handler_data->start_time.tv_sec; event_handler->state = event_handler_data->state; event_handler->state_type = event_handler_data->state_type; event_handler->timeout = event_handler_data->timeout; event_handler->handler_type = event_handler_data->eventhandler_type; // Send event. gl_publisher.write(event_handler); } catch (std::exception const& e) { logging::error(logging::medium) << "callbacks: error occurred while" " generating event handler event: " << e.what(); } // Avoid exception propagation in C code. catch (...) {} return 0; } /** * @brief Function that process external commands. * * This function is called by the monitoring engine when some external * command is received. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_EXTERNALCOMMAND_DATA). * @param[in] data A pointer to a nebstruct_externalcommand_data * containing the external command data. * * @return 0 on success. */ int neb::callback_external_command(int callback_type, void* data) { // Log message. logging::debug(logging::low) << "callbacks: external command data"; (void)callback_type; nebstruct_external_command_data* necd( static_cast<nebstruct_external_command_data*>(data)); if (necd && (necd->type == NEBTYPE_EXTERNALCOMMAND_START)) { try { if (necd->command_type == CMD_CHANGE_CUSTOM_HOST_VAR) { logging::info(logging::medium) << "callbacks: generating host custom variable update event"; // Split argument string. if (necd->command_args) { QStringList l(QString(necd->command_args).split(';')); if (l.size() != 3) logging::error(logging::medium) << "callbacks: invalid host custom variable command"; else { QStringList::iterator it(l.begin()); QString host(*it++); QString var_name(*it++); QString var_value(*it); // Find host ID. unsigned int host_id = engine::get_host_id( host.toStdString().c_str()); if (host_id != 0) { // Fill custom variable. std::shared_ptr<neb::custom_variable_status> cvs(new neb::custom_variable_status); cvs->host_id = host_id; cvs->modified = true; cvs->name = var_name; cvs->service_id = 0; cvs->update_time = necd->timestamp.tv_sec; cvs->value = var_value; // Send event. gl_publisher.write(cvs); } } } } else if (necd->command_type == CMD_CHANGE_CUSTOM_SVC_VAR) { logging::info(logging::medium) << "callbacks: generating service custom variable update event"; // Split argument string. if (necd->command_args) { QStringList l(QString(necd->command_args).split(';')); if (l.size() != 4) logging::error(logging::medium) << "callbacks: invalid service custom variable command"; else { QStringList::iterator it(l.begin()); QString host(*it++); QString service(*it++); QString var_name(*it++); QString var_value(*it); // Find host/service IDs. std::pair<unsigned int, unsigned int> p; p = engine::get_host_and_service_id( host.toStdString().c_str(), service.toStdString().c_str()); if (p.first && p.second) { // Fill custom variable. std::shared_ptr<neb::custom_variable_status> cvs( new neb::custom_variable_status); cvs->host_id = p.first; cvs->modified = true; cvs->name = var_name; cvs->service_id = p.second; cvs->update_time = necd->timestamp.tv_sec; cvs->value = var_value; // Send event. gl_publisher.write(cvs); } } } } } // Avoid exception propagation in C code. catch (...) {} } return 0; } /** * @brief Function that process flapping status data. * * This function is called by Nagios when some flapping status data is * available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_FLAPPING_DATA). * @param[in] data A pointer to a nebstruct_flapping_data * containing the flapping status data. * * @return 0 on success. */ int neb::callback_flapping_status(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating flapping event"; (void)callback_type; try { // In/Out variables. nebstruct_flapping_data const* flapping_data; std::shared_ptr<neb::flapping_status> flapping_status(new neb::flapping_status); // Fill output var. flapping_data = static_cast<nebstruct_flapping_data*>(data); flapping_status->event_time = flapping_data->timestamp.tv_sec; flapping_status->event_type = flapping_data->type; flapping_status->high_threshold = flapping_data->high_threshold; if (!flapping_data->host_name) throw (exceptions::msg() << "unnamed host"); if (flapping_data->service_description) { std::pair<unsigned int, unsigned int> p; p = engine::get_host_and_service_id( flapping_data->host_name, flapping_data->service_description); flapping_status->host_id = p.first; flapping_status->service_id = p.second; if (!flapping_status->host_id || !flapping_status->service_id) throw (exceptions::msg() << "could not find ID of service ('" << flapping_data->host_name << "', '" << flapping_data->service_description << "')"); } else { flapping_status->host_id = engine::get_host_id(flapping_data->host_name); if (flapping_status->host_id == 0) throw (exceptions::msg() << "could not find ID of host '" << flapping_data->host_name << "'"); } flapping_status->low_threshold = flapping_data->low_threshold; flapping_status->percent_state_change = flapping_data->percent_change; // flapping_status->reason_type = XXX; flapping_status->flapping_type = flapping_data->flapping_type; // Send event. gl_publisher.write(flapping_status); } catch (std::exception const& e) { logging::error(logging::medium) << "callbacks: error occurred while" "generating flapping event: " << e.what(); } // Avoid exception propagation to C code. catch (...) {} return 0; } /** * @brief Function that process group data. * * This function is called by Engine when some group data is available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_GROUP_DATA). * @param[in] data Pointer to a nebstruct_group_data * containing the group data. * * @return 0 on success. */ int neb::callback_group(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating group event"; (void)callback_type; try { // Input variable. nebstruct_group_data const* group_data(static_cast<nebstruct_group_data*>(data)); // Host group. if ((NEBTYPE_HOSTGROUP_ADD == group_data->type) || (NEBTYPE_HOSTGROUP_UPDATE == group_data->type) || (NEBTYPE_HOSTGROUP_DELETE == group_data->type)) { engine::hostgroup const* host_group(static_cast<engine::hostgroup*>(group_data->object_ptr)); if (!host_group->get_group_name().empty()) { std::shared_ptr<neb::host_group> new_hg(new neb::host_group); new_hg->poller_id = config::applier::state::instance().poller_id(); new_hg->id = host_group->get_id(); new_hg->enabled = (group_data->type != NEBTYPE_HOSTGROUP_DELETE && !host_group->members.empty()); new_hg->name = host_group->get_group_name().c_str(); // Send host group event. if (new_hg->id) { logging::info(logging::low) << "callbacks: new host group " << new_hg->id << " ('" << new_hg->name << "') on instance " << new_hg->poller_id; neb::gl_publisher.write(new_hg); } } } // Service group. else if ((NEBTYPE_SERVICEGROUP_ADD == group_data->type) || (NEBTYPE_SERVICEGROUP_UPDATE == group_data->type) || (NEBTYPE_SERVICEGROUP_DELETE == group_data->type)) { engine::servicegroup const* service_group(static_cast<engine::servicegroup*>(group_data->object_ptr)); if (!service_group->get_group_name().empty()) { std::shared_ptr<neb::service_group> new_sg(new neb::service_group); new_sg->poller_id = config::applier::state::instance().poller_id(); new_sg->id = service_group->get_id(); new_sg->enabled = (group_data->type != NEBTYPE_SERVICEGROUP_DELETE && !service_group->members.empty()); new_sg->name = QString(service_group->get_group_name().c_str()); // Send service group event. if (new_sg->id) { logging::info(logging::low) << "callbacks:: new service group " << new_sg->id << " ('" << new_sg->name << "') on instance " << new_sg->poller_id; neb::gl_publisher.write(new_sg); } } } } // Avoid exception propagation to C code. catch (...) {} return 0; } /** * @brief Function that process group membership. * * This function is called by Engine when some group membership data is * available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_GROUPMEMBER_DATA). * @param[in] data Pointer to a nebstruct_group_member_data * containing membership data. * * @return 0 on success. */ int neb::callback_group_member(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating group member event"; (void)callback_type; try { // Input variable. nebstruct_group_member_data const* member_data(static_cast<nebstruct_group_member_data*>(data)); // Host group member. if ((member_data->type == NEBTYPE_HOSTGROUPMEMBER_ADD) || (member_data->type == NEBTYPE_HOSTGROUPMEMBER_DELETE)) { engine::host const* hst(static_cast<engine::host*>(member_data->object_ptr)); engine::hostgroup const* hg(static_cast<engine::hostgroup*>(member_data->group_ptr)); if (!hst->get_name().empty() && !hg->get_group_name().empty()) { // Output variable. std::shared_ptr<neb::host_group_member> hgm(new neb::host_group_member); hgm->group_id = hg->get_id(); hgm->group_name = QString(hg->get_group_name().c_str()); hgm->poller_id = config::applier::state::instance().poller_id(); unsigned int host_id = engine::get_host_id(hst->get_name()); if (host_id != 0 && hgm->group_id != 0) { hgm->host_id = host_id; if (member_data->type == NEBTYPE_HOSTGROUPMEMBER_DELETE) { logging::info(logging::low) << "callbacks: host " << hgm->host_id << " is not a member of group " << hgm->group_id << " on instance " << hgm->poller_id << " anymore"; hgm->enabled = false; } else { logging::info(logging::low) << "callbacks: host " << hgm->host_id << " is a member of group " << hgm->group_id << " on instance " << hgm->poller_id; hgm->enabled = true; } // Send host group member event. if (hgm->host_id && hgm->group_id) neb::gl_publisher.write(hgm); } } } // Service group member. else if ((member_data->type == NEBTYPE_SERVICEGROUPMEMBER_ADD) || (member_data->type == NEBTYPE_SERVICEGROUPMEMBER_DELETE)) { engine::service const* svc(static_cast<engine::service*>(member_data->object_ptr)); engine::servicegroup const* sg(static_cast<engine::servicegroup*>(member_data->group_ptr)); if (!svc->get_description().empty() && !sg->get_group_name().empty() && !svc->get_hostname().empty()) { // Output variable. std::shared_ptr<neb::service_group_member> sgm(new neb::service_group_member); sgm->group_id = sg->get_id(); sgm->group_name = QString(sg->get_group_name().c_str()); sgm->poller_id = config::applier::state::instance().poller_id(); std::pair<unsigned int, unsigned int> p; p = engine::get_host_and_service_id( svc->get_hostname(), svc->get_description()); sgm->host_id = p.first; sgm->service_id = p.second; if (sgm->host_id && sgm->service_id && sgm->group_id) { if (member_data->type == NEBTYPE_SERVICEGROUPMEMBER_DELETE) { logging::info(logging::low) << "callbacks: service (" << sgm->host_id << ", " << sgm->service_id << ") is not a member of group " << sgm->group_id << " on instance " << sgm->poller_id << " anymore"; sgm->enabled = false; } else { logging::info(logging::low) << "callbacks: service (" << sgm->host_id << ", " << sgm->service_id << ") is a member of group " << sgm->group_id << " on instance " << sgm->poller_id; sgm->enabled = true; } // Send service group member event. if (sgm->host_id && sgm->service_id && sgm->group_id) neb::gl_publisher.write(sgm); } } } } // Avoid exception propagation to C code. catch (...) {} return 0; } /** * @brief Function that process host data. * * This function is called by Engine when some host data is available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_HOST_DATA). * @param[in] data A pointer to a nebstruct_host_data * containing a host data. * * @return 0 on success. */ int neb::callback_host(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating host event"; (void)callback_type; try { // In/Out variables. nebstruct_adaptive_host_data const* host_data(static_cast<nebstruct_adaptive_host_data*>(data)); engine::host const* h(static_cast<engine::host*>(host_data->object_ptr)); std::shared_ptr<neb::host> my_host(new neb::host); // Set host parameters. my_host->acknowledged = h->get_problem_has_been_acknowledged(); my_host->acknowledgement_type = h->get_acknowledgement_type(); if (!h->get_action_url().empty()) my_host->action_url = QString(h->get_action_url().c_str()); my_host->active_checks_enabled = h->get_checks_enabled(); if (!h->get_address().empty()) my_host->address = QString(h->get_address().c_str()); if (!h->get_alias().empty()) my_host->alias = QString(h->get_alias().c_str()); my_host->check_freshness = h->get_check_freshness(); if (!h->get_check_command().empty()) my_host->check_command = QString(h->get_check_command().c_str()); my_host->check_interval = h->get_check_interval(); if (!h->get_check_period().empty()) my_host->check_period = QString(h->get_check_period().c_str()); my_host->check_type = h->get_check_type(); my_host->current_check_attempt = h->get_current_attempt(); my_host->current_state = (h->get_has_been_checked() ? h->get_current_state() : 4); // Pending state. my_host->default_active_checks_enabled = h->get_checks_enabled(); my_host->default_event_handler_enabled = h->get_event_handler_enabled(); my_host->default_flap_detection_enabled = h->get_flap_detection_enabled(); my_host->default_notifications_enabled = h->get_notifications_enabled(); my_host->default_passive_checks_enabled = h->get_accept_passive_checks(); my_host->downtime_depth = h->get_scheduled_downtime_depth(); if (!h->get_display_name().empty()) my_host->display_name = QString(h->get_display_name().c_str()); my_host->enabled = (host_data->type != NEBTYPE_HOST_DELETE); if (!h->get_event_handler().empty()) my_host->event_handler = QString(h->get_event_handler().c_str()); my_host->event_handler_enabled = h->get_event_handler_enabled(); my_host->execution_time = h->get_execution_time(); my_host->first_notification_delay = h->get_first_notification_delay(); my_host->notification_number = h->get_notification_number(); my_host->flap_detection_enabled = h->get_flap_detection_enabled(); my_host->flap_detection_on_down = h->get_flap_detection_on(engine::notifier::down); my_host->flap_detection_on_unreachable = h->get_flap_detection_on(engine::notifier::unreachable); my_host->flap_detection_on_up = h->get_flap_detection_on(engine::notifier::up); my_host->freshness_threshold = h->get_freshness_threshold(); my_host->has_been_checked = h->get_has_been_checked(); my_host->high_flap_threshold = h->get_high_flap_threshold(); if (!h->get_name().empty()) my_host->host_name = QString(h->get_name().c_str()); if (!h->get_icon_image().empty()) my_host->icon_image = QString(h->get_icon_image().c_str()); if (!h->get_icon_image_alt().empty()) my_host->icon_image_alt = QString(h->get_icon_image_alt().c_str()); my_host->is_flapping = h->get_is_flapping(); my_host->last_check = h->get_last_check(); my_host->last_hard_state = h->get_last_hard_state(); my_host->last_hard_state_change = h->get_last_hard_state_change(); my_host->last_notification = h->get_last_notification(); my_host->last_state_change = h->get_last_state_change(); my_host->last_time_down = h->get_last_time_down(); my_host->last_time_unreachable = h->get_last_time_unreachable(); my_host->last_time_up = h->get_last_time_up(); my_host->last_update = time(nullptr); my_host->latency = h->get_latency(); my_host->low_flap_threshold = h->get_low_flap_threshold(); my_host->max_check_attempts = h->get_max_attempts(); my_host->next_check = h->get_next_check(); my_host->next_notification = h->get_next_notification(); my_host->no_more_notifications = h->get_no_more_notifications(); if (!h->get_notes().empty()) my_host->notes = QString(h->get_notes().c_str()); if (!h->get_notes_url().empty()) my_host->notes_url = QString(h->get_notes_url().c_str()); my_host->notifications_enabled = h->get_notifications_enabled(); my_host->notification_interval = h->get_notification_interval(); if (!h->get_notification_period().empty()) my_host->notification_period = QString(h->get_notification_period().c_str()); my_host->notify_on_down = h->get_notify_on(engine::notifier::down); my_host->notify_on_downtime = h->get_notify_on(engine::notifier::downtime); my_host->notify_on_flapping = h->get_notify_on(engine::notifier::flappingstart); my_host->notify_on_recovery = h->get_notify_on(engine::notifier::up); my_host->notify_on_unreachable = h->get_notify_on(engine::notifier::unreachable); my_host->obsess_over = h->get_obsess_over(); if (!h->get_plugin_output().empty()) { my_host->output = QString(h->get_plugin_output().c_str()); my_host->output.append("\n"); } if (!h->get_long_plugin_output().empty()) my_host->output.append(QString(h->get_long_plugin_output().c_str())); my_host->passive_checks_enabled = h->get_accept_passive_checks(); my_host->percent_state_change = h->get_percent_state_change(); if (!h->get_perf_data().empty()) my_host->perf_data = QString(h->get_perf_data().c_str()); my_host->poller_id = config::applier::state::instance().poller_id(); my_host->retain_nonstatus_information = h->get_retain_nonstatus_information(); my_host->retain_status_information = h->get_retain_status_information(); my_host->retry_interval = h->get_retry_interval(); my_host->should_be_scheduled = h->get_should_be_scheduled(); my_host->stalk_on_down = h->get_stalk_on(engine::notifier::down); my_host->stalk_on_unreachable = h->get_stalk_on(engine::notifier::unreachable); my_host->stalk_on_up = h->get_stalk_on(engine::notifier::up); my_host->state_type = (h->get_has_been_checked() ? h->get_state_type() : engine::notifier::hard); if (!h->get_statusmap_image().empty()) my_host->statusmap_image = QString(h->get_statusmap_image().c_str()); my_host->timezone = QString(h->get_timezone().c_str()); // Find host ID. uint64_t host_id = engine::get_host_id( my_host->host_name.toStdString().c_str()); if (host_id != 0) { my_host->host_id = host_id; // Send host event. logging::info(logging::low) << "callbacks: new host " << my_host->host_id << " ('" << my_host->host_name << "') on instance " << my_host->poller_id; neb::gl_publisher.write(my_host); // Generate existing custom variables. for (com::centreon::engine::map_customvar::const_iterator it{h->custom_variables.begin()}, end{h->custom_variables.end()}; it != end; ++it) { std::string const& name{it->first}; if (it->second.is_sent() && name != "HOST_ID") { nebstruct_custom_variable_data data; memset(&data, 0, sizeof(data)); data.type = NEBTYPE_HOSTCUSTOMVARIABLE_ADD; data.timestamp.tv_sec = host_data->timestamp.tv_sec; data.var_name = const_cast<char*>(name.c_str()); data.var_value = const_cast<char*>(it->second.get_value().c_str()); data.object_ptr = host_data->object_ptr; callback_custom_variable( NEBCALLBACK_CUSTOM_VARIABLE_DATA, &data); } } } else logging::error(logging::medium) << "callbacks: host '" << (!h->get_name().empty() ? h->get_name() : "(unknown)") << "' has no ID (yet) defined"; } // Avoid exception propagation to C code. catch (...) {} return 0; } /** * @brief Function that process host check data. * * This function is called by Nagios when some host check data are available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_HOST_CHECK_DATA). * @param[in] data A pointer to a nebstruct_host_check_data * containing the host check data. * * @return 0 on success. */ int neb::callback_host_check(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating host check event"; (void)callback_type; try { // In/Out variables. nebstruct_host_check_data const* hcdata; std::shared_ptr<neb::host_check> host_check(new neb::host_check); // Fill output var. hcdata = static_cast<nebstruct_host_check_data*>(data); engine::host* h(static_cast<engine::host*>(hcdata->object_ptr)); if (hcdata->command_line) { host_check->active_checks_enabled = h->get_checks_enabled(); host_check->check_type = hcdata->check_type; host_check->command_line = hcdata->command_line; if (!hcdata->host_name) throw (exceptions::msg() << "unnamed host"); host_check->host_id = engine::get_host_id(hcdata->host_name); if (host_check->host_id == 0) throw (exceptions::msg() << "could not find ID of host '" << hcdata->host_name << "'"); host_check->next_check = h->get_next_check(); // Send event. gl_publisher.write(host_check); } } catch (std::exception const& e) { logging::error(logging::medium) << "callbacks: error occurred while" " generating host check event: " << e.what(); } // Avoid exception propagation in C code. catch (...) {} return 0; } /** * @brief Function that process host status data. * * This function is called by Nagios when some host status data are available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_HOST_STATUS_DATA). * @param[in] data A pointer to a nebstruct_host_status_data * containing the host status data. * * @return 0 on success. */ int neb::callback_host_status(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating host status event"; (void)callback_type; try { // In/Out variables. engine::host const* h; std::shared_ptr<neb::host_status> host_status(new neb::host_status); // Fill output var. h = static_cast<engine::host*>( static_cast<nebstruct_host_status_data*>(data)->object_ptr); host_status->acknowledged = h->get_problem_has_been_acknowledged(); host_status->acknowledgement_type = h->get_acknowledgement_type(); host_status->active_checks_enabled = h->get_checks_enabled(); if (!h->get_check_command().empty()) host_status->check_command = QString(h->get_check_command().c_str()); host_status->check_interval = h->get_check_interval(); if (!h->get_check_period().empty()) host_status->check_period = QString(h->get_check_period().c_str()); host_status->check_type = h->get_check_type(); host_status->current_check_attempt = h->get_current_attempt(); host_status->current_state = (h->get_has_been_checked() ? h->get_current_state() : 4); // Pending state. host_status->downtime_depth = h->get_scheduled_downtime_depth(); if (!h->get_event_handler().empty()) host_status->event_handler = QString(h->get_event_handler().c_str()); host_status->event_handler_enabled = h->get_event_handler_enabled(); host_status->execution_time = h->get_execution_time(); host_status->flap_detection_enabled = h->get_flap_detection_enabled(); host_status->has_been_checked = h->get_has_been_checked(); if (h->get_name().empty()) throw (exceptions::msg() << "unnamed host"); { host_status->host_id = engine::get_host_id(h->get_name()); if (host_status->host_id == 0) throw (exceptions::msg() << "could not find ID of host '" << h->get_name() << "'"); } host_status->is_flapping = h->get_is_flapping(); host_status->last_check = h->get_last_check(); host_status->last_hard_state = h->get_last_hard_state(); host_status->last_hard_state_change = h->get_last_hard_state_change(); host_status->last_notification = h->get_last_notification(); host_status->notification_number = h->get_notification_number(); host_status->last_state_change = h->get_last_state_change(); host_status->last_time_down = h->get_last_time_down(); host_status->last_time_unreachable = h->get_last_time_unreachable(); host_status->last_time_up = h->get_last_time_up(); host_status->last_update = time(nullptr); host_status->latency = h->get_latency(); host_status->max_check_attempts = h->get_max_attempts(); host_status->next_check = h->get_next_check(); host_status->next_notification = h->get_next_notification(); host_status->no_more_notifications = h->get_no_more_notifications(); host_status->notifications_enabled = h->get_notifications_enabled(); host_status->obsess_over = h->get_obsess_over(); if (!h->get_plugin_output().empty()) { host_status->output = QString(h->get_plugin_output().c_str()); host_status->output.append("\n"); } if (!h->get_long_plugin_output().empty()) host_status->output.append(QString(h->get_long_plugin_output().c_str())); host_status->passive_checks_enabled = h->get_accept_passive_checks(); host_status->percent_state_change = h->get_percent_state_change(); if (!h->get_perf_data().empty()) host_status->perf_data = QString(h->get_perf_data().c_str()); host_status->retry_interval = h->get_retry_interval(); host_status->should_be_scheduled = h->get_should_be_scheduled(); host_status->state_type = (h->get_has_been_checked() ? h->get_state_type() : engine::notifier::hard); // Send event(s). gl_publisher.write(host_status); // Acknowledgement event. std::map< std::pair<unsigned int, unsigned int>, neb::acknowledgement>::iterator it(gl_acknowledgements.find( std::make_pair(host_status->host_id, 0u))); if ((it != gl_acknowledgements.end()) && !host_status->acknowledged) { if (!(!host_status->current_state // !(OK or (normal ack and NOK)) || (!it->second.is_sticky && (host_status->current_state != it->second.state)))) { std::shared_ptr<neb::acknowledgement> ack(new neb::acknowledgement(it->second)); ack->deletion_time = time(nullptr); gl_publisher.write(ack); } gl_acknowledgements.erase(it); } } catch (std::exception const& e) { logging::error(logging::medium) << "callbacks: error occurred while" " generating host status event: " << e.what(); } // Avoid exception propagation in C code. catch (...) {} return 0; } /** * @brief Function that process log data. * * This function is called by Nagios when some log data are available. * * @param[in] callback_type Type of the callback (NEBCALLBACK_LOG_DATA). * @param[in] data A pointer to a nebstruct_log_data containing the * log data. * * @return 0 on success. */ int neb::callback_log(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating log event"; (void)callback_type; try { // In/Out variables. nebstruct_log_data const* log_data; std::shared_ptr<neb::log_entry> le(new neb::log_entry); // Fill output var. log_data = static_cast<nebstruct_log_data*>(data); le->c_time = log_data->entry_time; le->poller_name = config::applier::state::instance().poller_name().c_str(); if (log_data->data) { if (log_data->data) le->output = log_data->data; set_log_data(*le, log_data->data); } // Send event. gl_publisher.write(le); } // Avoid exception propagation in C code. catch (...) {} return 0; } /** * @brief Function that process module data. * * This function is called by Engine when some module data is * available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_MODULE_DATA). * @param[in] data A pointer to a nebstruct_module_data * containing the module data. * * @return 0 on success. */ int neb::callback_module(int callback_type, void* data) { // Log message. logging::debug(logging::low) << "callbacks: generating module event"; (void)callback_type; try { // In/Out variables. nebstruct_module_data const* module_data; std::shared_ptr<neb::module> me(new neb::module); // Fill output var. module_data = static_cast<nebstruct_module_data*>(data); if (module_data->module) { me->poller_id = config::applier::state::instance().poller_id(); me->filename = module_data->module; if (module_data->args) me->args = module_data->args; me->loaded = !(module_data->type == NEBTYPE_MODULE_DELETE); me->should_be_loaded = true; // Send events. gl_publisher.write(me); } } // Avoid exception propagation in C code. catch (...) {} return 0; } /** * @brief Function that process process data. * * This function is called by Nagios when some process data is available. * * @param[in] callback_type Type of the callback (NEBCALLBACK_PROCESS_DATA). * @param[in] data A pointer to a nebstruct_process_data containing * the process data. * * @return 0 on success. */ int neb::callback_process(int callback_type, void *data) { // Log message. logging::debug(logging::low) << "callbacks: process event callback"; (void)callback_type; try { // Input variables. nebstruct_process_data const* process_data; static time_t start_time; // Check process event type. process_data = static_cast<nebstruct_process_data*>(data); if (NEBTYPE_PROCESS_EVENTLOOPSTART == process_data->type) { logging::info(logging::medium) << "callbacks: generating process start event"; // Register callbacks. logging::debug(logging::high) << "callbacks: registering callbacks"; for (unsigned int i(0); i < sizeof(gl_callbacks) / sizeof(*gl_callbacks); ++i) gl_registered_callbacks.push_back( std::shared_ptr<callback>(new neb::callback( gl_callbacks[i].macro, gl_mod_handle, gl_callbacks[i].callback))); // Register Engine-specific callbacks. if (gl_mod_flags & NEBMODULE_ENGINE) { for (unsigned int i(0); i < sizeof(gl_engine_callbacks) / sizeof(*gl_engine_callbacks); ++i) gl_registered_callbacks.push_back( std::shared_ptr<callback>(new neb::callback( gl_engine_callbacks[i].macro, gl_mod_handle, gl_engine_callbacks[i].callback))); } // Parse configuration file. unsigned int statistics_interval(0); try { config::parser parsr; config::state conf; parsr.parse(gl_configuration_file, conf); // Apply resulting configuration. config::applier::state::instance().apply(conf); gl_generator.set(conf); // Set variables. statistics_interval = gl_generator.interval(); } catch (exceptions::msg const& e) { logging::config(logging::high) << e.what(); return 0; } // Output variable. std::shared_ptr<neb::instance> instance(new neb::instance); instance->poller_id = config::applier::state::instance().poller_id(); instance->engine = "Centreon Engine"; instance->is_running = true; instance->name = config::applier::state::instance().poller_name().c_str(); instance->pid = getpid(); instance->program_start = time(nullptr); instance->version = get_program_version(); start_time = instance->program_start; // Send initial event and then configuration. gl_publisher.write(instance); send_initial_configuration(); // Add statistics event. if (statistics_interval) { logging::info(logging::medium) << "stats: registering statistics generation event in " << "monitoring engine"; union { void (* code)(void*); void* data; } val; val.code = &event_statistics; com::centreon::engine::timed_event* evt = new com::centreon::engine::timed_event( EVENT_USER_FUNCTION, time(nullptr) + statistics_interval, 1, statistics_interval, nullptr, 1, val.data, nullptr, 0); evt->schedule(false); } } else if (NEBTYPE_PROCESS_EVENTLOOPEND == process_data->type) { logging::info(logging::medium) << "callbacks: generating process end event"; // Output variable. std::shared_ptr<neb::instance> instance(new neb::instance); // Fill output var. instance->poller_id = config::applier::state::instance().poller_id(); instance->engine = "Centreon Engine"; instance->is_running = false; instance->name = config::applier::state::instance().poller_name().c_str(); instance->pid = getpid(); instance->program_end = time(nullptr); instance->program_start = start_time; instance->version = get_program_version(); // Send event. gl_publisher.write(instance); } } // Avoid exception propagation in C code. catch (...) { unregister_callbacks(); } return 0; } /** * @brief Function that process instance status data. * * This function is called by Nagios when some instance status data are * available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_PROGRAM_STATUS_DATA). * @param[in] data A pointer to a nebstruct_program_status_data * containing the program status data. * * @return 0 on success. */ int neb::callback_program_status(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating instance status event"; (void)callback_type; try { // In/Out variables. nebstruct_program_status_data const* program_status_data; std::shared_ptr<neb::instance_status> is( new neb::instance_status); // Fill output var. program_status_data = static_cast<nebstruct_program_status_data*>(data); is->poller_id = config::applier::state::instance().poller_id(); is->active_host_checks_enabled = program_status_data->active_host_checks_enabled; is->active_service_checks_enabled = program_status_data->active_service_checks_enabled; is->check_hosts_freshness = check_host_freshness; is->check_services_freshness = check_service_freshness; is->event_handler_enabled = program_status_data->event_handlers_enabled; is->flap_detection_enabled = program_status_data->flap_detection_enabled; if (program_status_data->global_host_event_handler) is->global_host_event_handler = program_status_data->global_host_event_handler; if (program_status_data->global_service_event_handler) is->global_service_event_handler = program_status_data->global_service_event_handler; is->last_alive = time(nullptr); is->last_command_check = program_status_data->last_command_check; is->notifications_enabled = program_status_data->notifications_enabled; is->obsess_over_hosts = program_status_data->obsess_over_hosts; is->obsess_over_services = program_status_data->obsess_over_services; is->passive_host_checks_enabled = program_status_data->passive_host_checks_enabled; is->passive_service_checks_enabled = program_status_data->passive_service_checks_enabled; // Send event. gl_publisher.write(is); } // Avoid exception propagation in C code. catch (...) {} return 0; } /** * @brief Function that process relation data. * * This function is called by Engine when some relation data is * available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_RELATION_DATA). * @param[in] data Pointer to a nebstruct_relation_data * containing the relationship. * * @return 0 on success. */ int neb::callback_relation(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating relation event"; (void)callback_type; try { // Input variable. nebstruct_relation_data const* relation(static_cast<nebstruct_relation_data*>(data)); // Host parent. if ((NEBTYPE_PARENT_ADD == relation->type) || (NEBTYPE_PARENT_DELETE == relation->type)) { if (relation->hst && relation->dep_hst && !relation->svc && !relation->dep_svc) { // Find host IDs. int host_id; int parent_id; { host_id = engine::get_host_id(relation->dep_hst->get_name()); parent_id = engine::get_host_id(relation->hst->get_name()); } if (host_id && parent_id) { // Generate parent event. std::shared_ptr<host_parent> new_host_parent(new host_parent); new_host_parent->enabled = (relation->type != NEBTYPE_PARENT_DELETE); new_host_parent->host_id = host_id; new_host_parent->parent_id = parent_id; // Send event. logging::info(logging::low) << "callbacks: host " << new_host_parent->parent_id << " is parent of host " << new_host_parent->host_id; neb::gl_publisher.write( new_host_parent); } } } } // Avoid exception propagation to C code. catch (...) {} return 0; } /** * @brief Function that process service data. * * This function is called by Engine when some service data is * available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_ADAPTIVE_SERVICE_DATA). * @param[in] data A pointer to a * nebstruct_adaptive_service_data containing * the service data. * * @return 0 on success. */ int neb::callback_service(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating service event"; (void)callback_type; try { // In/Out variables. nebstruct_adaptive_service_data const* service_data(static_cast<nebstruct_adaptive_service_data*>(data)); engine::service const* s(static_cast<engine::service*>(service_data->object_ptr)); std::shared_ptr<neb::service> my_service(new neb::service); // Fill output var. my_service->acknowledged = s->get_problem_has_been_acknowledged(); my_service->acknowledgement_type = s->get_acknowledgement_type(); if (!s->get_action_url().empty()) my_service->action_url = QString(s->get_action_url().c_str()); my_service->active_checks_enabled = s->get_checks_enabled(); if (!s->get_check_command().empty()) my_service->check_command = QString(s->get_check_command().c_str()); my_service->check_freshness = s->get_check_freshness(); my_service->check_interval = s->get_check_interval(); if (!s->get_check_period().empty()) my_service->check_period = QString(s->get_check_period().c_str()); my_service->check_type = s->get_check_type(); my_service->current_check_attempt = s->get_current_attempt(); my_service->current_state = (s->get_has_been_checked() ? s->get_current_state() : 4); // Pending state. my_service->default_active_checks_enabled = s->get_checks_enabled(); my_service->default_event_handler_enabled = s->get_event_handler_enabled(); my_service->default_flap_detection_enabled = s->get_flap_detection_enabled(); my_service->default_notifications_enabled = s->get_notifications_enabled(); my_service->default_passive_checks_enabled = s->get_accept_passive_checks(); my_service->downtime_depth = s->get_scheduled_downtime_depth(); if (!s->get_display_name().empty()) my_service->display_name = QString(s->get_display_name().c_str()); my_service->enabled = (service_data->type != NEBTYPE_SERVICE_DELETE); if (!s->get_event_handler().empty()) my_service->event_handler = QString(s->get_event_handler().c_str()); my_service->event_handler_enabled = s->get_event_handler_enabled(); my_service->execution_time = s->get_execution_time(); my_service->first_notification_delay = s->get_first_notification_delay(); my_service->notification_number = s->get_notification_number(); my_service->flap_detection_enabled = s->get_flap_detection_enabled(); my_service->flap_detection_on_critical = s->get_flap_detection_on(engine::notifier::critical); my_service->flap_detection_on_ok = s->get_flap_detection_on(engine::notifier::ok); my_service->flap_detection_on_unknown = s->get_flap_detection_on(engine::notifier::unknown); my_service->flap_detection_on_warning = s->get_flap_detection_on(engine::notifier::warning); my_service->freshness_threshold = s->get_freshness_threshold(); my_service->has_been_checked = s->get_has_been_checked(); my_service->high_flap_threshold = s->get_high_flap_threshold(); if (!s->get_hostname().empty()) my_service->host_name = QString(s->get_hostname().c_str()); if (!s->get_icon_image().empty()) my_service->icon_image = QString(s->get_icon_image().c_str()); if (!s->get_icon_image_alt().empty()) my_service->icon_image_alt = QString(s->get_icon_image_alt().c_str()); my_service->is_flapping = s->get_is_flapping(); my_service->is_volatile = s->get_is_volatile(); my_service->last_check = s->get_last_check(); my_service->last_hard_state = s->get_last_hard_state(); my_service->last_hard_state_change = s->get_last_hard_state_change(); my_service->last_notification = s->get_last_notification(); my_service->last_state_change = s->get_last_state_change(); my_service->last_time_critical = s->get_last_time_critical(); my_service->last_time_ok = s->get_last_time_ok(); my_service->last_time_unknown = s->get_last_time_unknown(); my_service->last_time_warning = s->get_last_time_warning(); my_service->last_update = time(nullptr); my_service->latency = s->get_latency(); my_service->low_flap_threshold = s->get_low_flap_threshold(); my_service->max_check_attempts = s->get_max_attempts(); my_service->next_check = s->get_next_check(); my_service->next_notification = s->get_next_notification(); my_service->no_more_notifications = s->get_no_more_notifications(); if (!s->get_notes().empty()) my_service->notes = QString(s->get_notes().c_str()); if (!s->get_notes_url().empty()) my_service->notes_url = QString(s->get_notes_url().c_str()); my_service->notifications_enabled = s->get_notifications_enabled(); my_service->notification_interval = s->get_notification_interval(); if (!s->get_notification_period().empty()) my_service->notification_period = QString(s->get_notification_period().c_str()); my_service->notify_on_critical = s->get_notify_on(engine::notifier::critical); my_service->notify_on_downtime = s->get_notify_on(engine::notifier::downtime); my_service->notify_on_flapping = s->get_notify_on(engine::notifier::flappingstart); my_service->notify_on_recovery = s->get_notify_on(engine::notifier::ok); my_service->notify_on_unknown = s->get_notify_on(engine::notifier::unknown); my_service->notify_on_warning = s->get_notify_on(engine::notifier::warning); my_service->obsess_over = s->get_obsess_over(); if (!s->get_plugin_output().empty()) { my_service->output = QString(s->get_plugin_output().c_str()); my_service->output.append("\n"); } if (!s->get_long_plugin_output().empty()) my_service->output.append(s->get_long_plugin_output().c_str()); my_service->passive_checks_enabled = s->get_accept_passive_checks(); my_service->percent_state_change = s->get_percent_state_change(); if (!s->get_perf_data().empty()) my_service->perf_data = QString(s->get_perf_data().c_str()); my_service->retain_nonstatus_information = s->get_retain_nonstatus_information(); my_service->retain_status_information = s->get_retain_status_information(); my_service->retry_interval = s->get_retry_interval(); if (!s->get_description().empty()) my_service->service_description = QString(s->get_description().c_str()); my_service->should_be_scheduled = s->get_should_be_scheduled(); my_service->stalk_on_critical = s->get_stalk_on(engine::notifier::critical); my_service->stalk_on_ok = s->get_stalk_on(engine::notifier::ok); my_service->stalk_on_unknown = s->get_stalk_on(engine::notifier::unknown); my_service->stalk_on_warning = s->get_stalk_on(engine::notifier::warning); my_service->state_type = (s->get_has_been_checked() ? s->get_state_type() : engine::notifier::hard); // Search host ID and service ID. std::pair<uint64_t, uint64_t> p; p = engine::get_host_and_service_id( s->get_hostname(), s->get_description()); my_service->host_id = p.first; my_service->service_id = p.second; if (my_service->host_id && my_service->service_id) { // Send service event. logging::info(logging::low) << "callbacks: new service " << my_service->service_id << " ('" << my_service->service_description << "') on host " << my_service->host_id; neb::gl_publisher.write(my_service); // Generate existing custom variables. for (com::centreon::engine::map_customvar::const_iterator it{s->custom_variables.begin()}, end{s->custom_variables.end()}; it != end; ++it) { if (it->second.is_sent() && !it->first.empty() && it->first != "HOST_ID" && it->first != "SERVICE_ID") { nebstruct_custom_variable_data data; memset(&data, 0, sizeof(data)); data.type = NEBTYPE_SERVICECUSTOMVARIABLE_ADD; data.timestamp.tv_sec = service_data->timestamp.tv_sec; data.var_name = const_cast<char*>(it->first.c_str()); data.var_value = const_cast<char*>(it->second.get_value().c_str()); data.object_ptr = service_data->object_ptr; callback_custom_variable( NEBCALLBACK_CUSTOM_VARIABLE_DATA, &data); } } } else logging::error(logging::medium) << "callbacks: service has no host ID or no service ID (yet) (host '" << (!s->get_hostname().empty() ? s->get_hostname() : "(unknown)") << "', service '" << (!s->get_description().empty() ? s->get_description() : "(unknown)") << "')"; } // Avoid exception propagation in C code. catch (...) {} return 0; } /** * @brief Function that process service check data. * * This function is called by Nagios when some service check data are * available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_SERVICE_CHECK_DATA). * @param[in] data A pointer to a nebstruct_service_check_data * containing the service check data. * * @return 0 on success. */ int neb::callback_service_check(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating service check event"; (void)callback_type; try { // In/Out variables. nebstruct_service_check_data const* scdata; std::shared_ptr<neb::service_check> service_check( new neb::service_check); // Fill output var. scdata = static_cast<nebstruct_service_check_data*>(data); engine::service* s{static_cast<engine::service*>(scdata->object_ptr)}; if (scdata->command_line) { service_check->active_checks_enabled = s->get_checks_enabled(); service_check->check_type = scdata->check_type; service_check->command_line = scdata->command_line; if (!scdata->host_name) throw (exceptions::msg() << "unnamed host"); if (!scdata->service_description) throw (exceptions::msg() << "unnamed service"); std::pair<unsigned int, unsigned int> p; p = engine::get_host_and_service_id( scdata->host_name, scdata->service_description); service_check->host_id = p.first; service_check->service_id = p.second; if (!service_check->host_id || !service_check->service_id) throw (exceptions::msg() << "could not find ID of service ('" << scdata->host_name << "', '" << scdata->service_description << "')"); service_check->next_check = s->get_next_check(); // Send event. gl_publisher.write(service_check); } } catch (std::exception const& e) { logging::error(logging::medium) << "callbacks: error occurred while" " generating service check event: " << e.what(); } // Avoid exception propagation in C code. catch (...) {} return 0; } /** * @brief Function that process service status data. * * This function is called by Nagios when some service status data are * available. * * @param[in] callback_type Type of the callback * (NEBCALLBACK_SERVICE_STATUS_DATA). * @param[in] data A pointer to a nebstruct_service_status_data * containing the service status data. * * @return 0 on success. */ int neb::callback_service_status(int callback_type, void* data) { // Log message. logging::info(logging::medium) << "callbacks: generating service status event"; (void)callback_type; try { // In/Out variables. std::shared_ptr<neb::service_status> service_status( new neb::service_status); // Fill output var. engine::service const* s{ static_cast<engine::service*>( static_cast<nebstruct_service_status_data*>(data)->object_ptr)}; service_status->acknowledged = s->get_problem_has_been_acknowledged(); service_status->acknowledgement_type = s->get_acknowledgement_type(); service_status->active_checks_enabled = s->get_checks_enabled(); if (!s->get_check_command().empty()) service_status->check_command = QString(s->get_check_command().c_str()); service_status->check_interval = s->get_check_interval(); if (!s->get_check_period().empty()) service_status->check_period = QString(s->get_check_period().c_str()); service_status->check_type = s->get_check_type(); service_status->current_check_attempt = s->get_current_attempt(); service_status->current_state = (s->get_has_been_checked() ? s->get_current_state() : 4); // Pending state. service_status->downtime_depth = s->get_scheduled_downtime_depth(); if (!s->get_event_handler().empty()) service_status->event_handler = QString(s->get_event_handler().c_str()); service_status->event_handler_enabled = s->get_event_handler_enabled(); service_status->execution_time = s->get_execution_time(); service_status->flap_detection_enabled = s->get_flap_detection_enabled(); service_status->has_been_checked = s->get_has_been_checked(); service_status->is_flapping = s->get_is_flapping(); service_status->last_check = s->get_last_check(); service_status->last_hard_state = s->get_last_hard_state(); service_status->last_hard_state_change = s->get_last_hard_state_change(); service_status->last_notification = s->get_last_notification(); service_status->notification_number = s->get_notification_number(); service_status->last_state_change = s->get_last_state_change(); service_status->last_time_critical = s->get_last_time_critical(); service_status->last_time_ok = s->get_last_time_ok(); service_status->last_time_unknown = s->get_last_time_unknown(); service_status->last_time_warning = s->get_last_time_warning(); service_status->last_update = time(nullptr); service_status->latency = s->get_latency(); service_status->max_check_attempts = s->get_max_attempts(); service_status->next_check = s->get_next_check(); service_status->next_notification = s->get_next_notification(); service_status->no_more_notifications = s->get_no_more_notifications(); service_status->notifications_enabled = s->get_notifications_enabled(); service_status->obsess_over = s->get_obsess_over(); if (!s->get_plugin_output().empty()) { service_status->output = QString(s->get_plugin_output().c_str()); service_status->output.append("\n"); } if (!s->get_long_plugin_output().empty()) service_status->output.append(s->get_long_plugin_output().c_str()); service_status->passive_checks_enabled = s->get_accept_passive_checks(); service_status->percent_state_change = s->get_percent_state_change(); if (!s->get_perf_data().empty()) service_status->perf_data = QString(s->get_perf_data().c_str()); service_status->retry_interval = s->get_retry_interval(); if (s->get_hostname().empty()) throw exceptions::msg() << "unnamed host"; if (s->get_description().empty()) throw exceptions::msg() << "unnamed service"; service_status->host_name = QString(s->get_hostname().c_str()); service_status->service_description = QString(s->get_description().c_str()); { std::pair<uint64_t, uint64_t> p{ engine::get_host_and_service_id(s->get_hostname(), s->get_description())}; service_status->host_id = p.first; service_status->service_id = p.second; if (!service_status->host_id || !service_status->service_id) throw exceptions::msg() << "could not find ID of service ('" << s->get_hostname() << "', '" << s->get_description() << "')"; } service_status->should_be_scheduled = s->get_should_be_scheduled(); service_status->state_type = (s->get_has_been_checked() ? s->get_state_type() : engine::notifier::hard); // Send event(s). gl_publisher.write(service_status); // Acknowledgement event. std::map< std::pair<unsigned int, unsigned int>, neb::acknowledgement>::iterator it(gl_acknowledgements.find(std::make_pair( service_status->host_id, service_status->service_id))); if ((it != gl_acknowledgements.end()) && !service_status->acknowledged) { if (!(!service_status->current_state // !(OK or (normal ack and NOK)) || (!it->second.is_sticky && (service_status->current_state != it->second.state)))) { std::shared_ptr<neb::acknowledgement> ack(new neb::acknowledgement(it->second)); ack->deletion_time = time(nullptr); gl_publisher.write(ack); } gl_acknowledgements.erase(it); } } catch (std::exception const& e) { logging::error(logging::medium) << "callbacks: error occurred while" " generating service status event: " << e.what(); } // Avoid exception propagation in C code. catch (...) {} return 0; } /** * Unregister callbacks. */ void neb::unregister_callbacks() { gl_registered_callbacks.clear(); }
86,956
28,233
/* $Id: ondiskmergersimple.cc 5149 2010-03-24 23:37:18Z abehm $ Copyright (C) 2010 by The Regents of the University of California Redistribution of this file is permitted under the terms of the BSD license. Date: 09/06/2008 Author: Alexander Behm <abehm (at) ics.uci.edu> */ #include "ondiskmergersimple.h"
328
145
// RUN: %llvmgxx -I../../../include -g -fno-exceptions -emit-llvm -O0 -c -o %t.bc %s // RUN: %klee --libc=klee --no-output --exit-on-error %t.bc > %t.log // RUN: grep -q {powl\(-11\\.0,0\)=1\\.0\\+} %t.log // RUN: grep -q {powl\(-11\\.0,1\)=-11\\.0\\+} %t.log // RUN: grep -q {powl\(-11\\.0,2\)=121\\.0\\+} %t.log // RUN: grep -q {1/0=inf} %t.log // RUN: grep -q {1/-1=-1\\.0\\+} %t.log // RUN: grep -q {1/-2=-0\\.50\\+} %t.log #include <cstdio> #include <cstdlib> #include <cmath> #include <cassert> #include "klee/klee.h" unsigned klee_urange(unsigned start, unsigned end) { unsigned x; klee_make_symbolic(&x, sizeof x, "x"); if (x-start>=end-start) klee_silent_exit(0); return x; } int main(int argc, char ** argv) { int a = klee_urange(0,3); int b; // fork states switch(a) { case 0: b = -0; break; case 1: b = -1; break; case 2: b = -2; break; default: assert(false && "Impossible switch target"); } // test 80-bit external dispatch long double d = powl((long double)-11.0, (long double)a); printf("powl(-11.0,%d)=%Lf\n", a, d); // test 80-bit fdiv long double e = (long double) 1 / (long double) b; printf("1/%d=%Lf\n", b, e); return 0; }
1,224
587
#include "tools/logger.hpp" namespace Tool { namespace Logger { Logger::Logger(const char *name) { this->_level = Level::info; this->_logger = spdlog::stdout_color_mt(name); } Level Logger::GetLevel() { return this->_level; } void Logger::SetLevel(Level level) { switch (level) { case Level::trace: this->_level = Level::trace; this->_logger->set_level(spdlog::level::trace); break; case Level::debug: this->_level = Level::debug; this->_logger->set_level(spdlog::level::debug); break; case Level::info: this->_level = Level::info; this->_logger->set_level(spdlog::level::info); break; case Level::warning: this->_level = Level::warning; this->_logger->set_level(spdlog::level::warn); break; case Level::error: this->_level = Level::error; this->_logger->set_level(spdlog::level::err); break; case Level::critical: this->_level = Level::critical; this->_logger->set_level(spdlog::level::critical); break; } } void Logger::trace(const char *message) { this->_logger->trace(message); } void Logger::debug(const char *message) { this->_logger->debug(message); } void Logger::info(const char *message) { this->_logger->info(message); } void Logger::warning(const char *message) { this->_logger->warn(message); } void Logger::error(const char *message) { this->_logger->error(message); } void Logger::critical(const char *message) { this->_logger->critical(message); } } }
2,126
543
#include "DisplayHandler.hpp" void DisplayHandler::showClock(struct tm timeinfo, int x, int y) { display.setFont(&DejaVuSans_Bold8pt8b); display.setCursor(x, y); display.print("Aktualisierung"); display.setFont(&DejaVuSansMono_Bold24pt8b); display.setCursor(x, y + 45); display.printf("%02d:%02d", timeinfo.tm_hour, timeinfo.tm_min); }
349
146
#include "hybrid_solver.h" #include "omp_solver.h" #include "force_calculation.h" #include <stdio.h> #include <string.h> #include <cmath> #include <mpi.h> #include <omp.h> #include <immintrin.h> #include <algorithm> #include <unistd.h> void hybrid_ring_solver(NBody_system& nb_sys, size_t rank, size_t comm_sz, size_t num_threads, size_t time_steps, double delta_t, Vectorization_type vect_type) { size_t local_N = nb_sys.N / comm_sz; double*** local_force = (double***)malloc(num_threads*sizeof(double**)); double*** local_recv_force = (double***)malloc(num_threads*sizeof(double**)); for(size_t thread = 0; thread < num_threads;thread++) { local_force[thread] = (double**)malloc(DIM*sizeof(double*)); local_recv_force[thread] = (double**)malloc(DIM*sizeof(double*)); for(size_t d = 0;d < DIM;d++) { local_force[thread][d] = (double*)aligned_alloc(64,sizeof(double) * local_N); local_recv_force[thread][d] = (double*)aligned_alloc(64,sizeof(double) * local_N); } } if(rank == 0) { //Conceptually, //Every Process owns all nb_sys.masses, //Every Process owns nb_sys.positions [i * comm_sz + rank], 0 <= i < local_N, //Every Process owns nb_sys.velocities [i * comm_sz + rank], 0 <= i < local_N, //Since the particles have no order the subsets of particles can be distributed blockwise //and from there on each particle is treated as if it was distributed in a round robin fashion MPI_Bcast(nb_sys.mass, nb_sys.N, MPI_DOUBLE, 0, MPI_COMM_WORLD); for(size_t d = 0;d < DIM;d++) { MPI_Scatter(nb_sys.pos[d], local_N, MPI_DOUBLE, MPI_IN_PLACE, local_N, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Scatter(nb_sys.vel[d], local_N, MPI_DOUBLE, MPI_IN_PLACE, local_N, MPI_DOUBLE, 0, MPI_COMM_WORLD); } //Use larger message for MPI communication //Message contains nb_sys.position and nb_sys.force vectors //The each array inside the message has to be 512-bit aligned size_t local_N_aligned = (local_N/8) * 8; if(local_N_aligned != local_N) local_N_aligned += 8; double *msg; msg = (double*)aligned_alloc(64, 2*DIM*local_N_aligned*sizeof(double)); //Unpack message: Message consists of local_N positions and the corresponding implicit forces double* recv_pos[DIM]; double* recv_force[DIM]; for(size_t d = 0;d < DIM;d++) { recv_pos[d] = &msg[d*local_N_aligned]; memcpy(recv_pos[d], nb_sys.pos[d], local_N*sizeof(double)); recv_force[d] = &msg[(DIM+d)*local_N_aligned]; } for(size_t i = 0;i < time_steps;i++) { //Reset all Forces for(size_t k = 0;k < local_N;k++) { recv_force[X][k] = 0.0; recv_force[Y][k] = 0.0; recv_force[Z][k] = 0.0; nb_sys.force[X][k] = 0.0; nb_sys.force[Y][k] = 0.0; nb_sys.force[Z][k] = 0.0; } //Distribute particles in a ring scheme //After comm_sz message passes, the original message returns to the owner for(size_t recv_round = 0;recv_round < comm_sz;recv_round++) { //compute pairwise force interaction for the received subset and the rank-local subset of particles if(vect_type == Vectorization_type::AVX2) { compute_forces_avx2_blocked(nb_sys, recv_pos, recv_force, local_force, local_recv_force, local_N, rank, comm_sz, recv_round, num_threads); } else if(vect_type == Vectorization_type::AVX512RSQRT) { compute_forces_avx512_rsqrt_blocked(nb_sys, recv_pos, recv_force, local_force, local_recv_force, local_N,rank,comm_sz,recv_round,num_threads); } else if(vect_type == Vectorization_type::AVX512RSQRT4I) { compute_forces_avx512_rsqrt_4i_blocked(nb_sys, recv_pos, recv_force, local_force, local_recv_force, local_N,rank,comm_sz,recv_round,num_threads); } //Only the main thread is allowed to communicate over MPI int flag; MPI_Is_thread_main(&flag); if(!flag) { printf("Not main thread trying to call MPI communication function\n"); exit(1); } //Send message to the next lower rank in the ring; Recv the message of the next higher rank MPI_Status stat; MPI_Sendrecv_replace(msg, 2*DIM*local_N_aligned, MPI_DOUBLE, (rank - 1 + comm_sz)%comm_sz, 0, (rank + 1)%comm_sz, 0, MPI_COMM_WORLD, &stat); } //Update the positions and velocities #pragma omp parallel for simd for(size_t k = 0;k < local_N;k++) { nb_sys.force[X][k] += recv_force[X][k]; nb_sys.force[Y][k] += recv_force[Y][k]; nb_sys.force[Z][k] += recv_force[Z][k]; nb_sys.pos[X][k] += nb_sys.vel[X][k] * delta_t; nb_sys.pos[Y][k] += nb_sys.vel[Y][k] * delta_t; nb_sys.pos[Z][k] += nb_sys.vel[Z][k] * delta_t; nb_sys.vel[X][k] += nb_sys.force[X][k] * delta_t / nb_sys.mass[rank * local_N + k]; nb_sys.vel[Y][k] += nb_sys.force[Y][k] * delta_t / nb_sys.mass[rank * local_N + k]; nb_sys.vel[Z][k] += nb_sys.force[Z][k] * delta_t / nb_sys.mass[rank * local_N + k]; } } //Collect all subsets back to the main rank for(size_t d = 0;d < DIM;d++) { MPI_Gather(MPI_IN_PLACE, local_N, MPI_DOUBLE, nb_sys.pos[d], local_N, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Gather(MPI_IN_PLACE, local_N, MPI_DOUBLE, nb_sys.vel[d], local_N, MPI_DOUBLE, 0, MPI_COMM_WORLD); } free(msg); } else { MPI_Bcast(nb_sys.mass, nb_sys.N, MPI_DOUBLE, 0, MPI_COMM_WORLD); for(size_t d = 0; d < DIM;d++) { MPI_Scatter(NULL, 0, MPI_DATATYPE_NULL, nb_sys.pos[d], local_N, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Scatter(NULL, 0, MPI_DATATYPE_NULL, nb_sys.vel[d], local_N, MPI_DOUBLE, 0, MPI_COMM_WORLD); } size_t local_N_aligned = (local_N/8) * 8; if(local_N_aligned != local_N) local_N_aligned += 8; double *msg; msg = (double*)aligned_alloc(64, 2*DIM*local_N_aligned*sizeof(double)); double* recv_pos[DIM]; double* recv_force[DIM]; for(size_t d = 0;d < DIM;d++) { recv_pos[d] = &msg[d*local_N_aligned]; memcpy(recv_pos[d], nb_sys.pos[d], local_N*sizeof(double)); recv_force[d] = &msg[(DIM+d)*local_N_aligned]; } for(size_t i = 0;i < time_steps;i++) { for(size_t k = 0;k < local_N;k++) { recv_force[X][k] = 0.0; recv_force[Y][k] = 0.0; recv_force[Z][k] = 0.0; nb_sys.force[X][k] = 0.0; nb_sys.force[Y][k] = 0.0; nb_sys.force[Z][k] = 0.0; } for(size_t recv_round = 0;recv_round < comm_sz;recv_round++) { if(vect_type == Vectorization_type::AVX2) { compute_forces_avx2_blocked(nb_sys, recv_pos, recv_force, local_force, local_recv_force, local_N, rank, comm_sz, recv_round, num_threads); } else if(vect_type == Vectorization_type::AVX512RSQRT) { compute_forces_avx512_rsqrt_blocked(nb_sys, recv_pos, recv_force, local_force, local_recv_force, local_N,rank,comm_sz,recv_round,num_threads); } else if(vect_type == Vectorization_type::AVX512RSQRT4I) { compute_forces_avx512_rsqrt_4i_blocked(nb_sys, recv_pos, recv_force, local_force, local_recv_force, local_N,rank,comm_sz,recv_round,num_threads); } int flag; MPI_Is_thread_main(&flag); if(!flag) { printf("Not main thread trying to call MPI communication function\n"); exit(1); } MPI_Status stat; MPI_Sendrecv_replace(msg, 2*DIM*local_N_aligned, MPI_DOUBLE, (rank - 1 + comm_sz)%comm_sz, 0, (rank + 1)%comm_sz, 0, MPI_COMM_WORLD, &stat); } #pragma omp parallel for simd for(size_t k = 0;k < local_N;k++) { nb_sys.force[X][k] += recv_force[X][k]; nb_sys.force[Y][k] += recv_force[Y][k]; nb_sys.force[Z][k] += recv_force[Z][k]; nb_sys.pos[X][k] += nb_sys.vel[X][k] * delta_t; nb_sys.pos[Y][k] += nb_sys.vel[Y][k] * delta_t; nb_sys.pos[Z][k] += nb_sys.vel[Z][k] * delta_t; nb_sys.vel[X][k] += nb_sys.force[X][k] * delta_t / nb_sys.mass[rank * local_N + k]; nb_sys.vel[Y][k] += nb_sys.force[Y][k] * delta_t / nb_sys.mass[rank * local_N + k]; nb_sys.vel[Z][k] += nb_sys.force[Z][k] * delta_t / nb_sys.mass[rank * local_N + k]; } } for(size_t d = 0; d < DIM;d++) { MPI_Gather(nb_sys.pos[d], local_N, MPI_DOUBLE, NULL, 0, MPI_DATATYPE_NULL, 0, MPI_COMM_WORLD); MPI_Gather(nb_sys.vel[d], local_N, MPI_DOUBLE, NULL, 0, MPI_DATATYPE_NULL, 0, MPI_COMM_WORLD); } free(msg); } for(size_t thread = 0; thread < num_threads;thread++) { for(size_t d = 0;d < DIM;d++) { free(local_force[thread][d]); free(local_recv_force[thread][d]); } free(local_force[thread]); free(local_recv_force[thread]); } free(local_force); free(local_recv_force); } void hybrid_full_solver(NBody_system& nb_sys, size_t rank, size_t comm_sz, size_t num_threads, size_t time_steps, double delta_t, Vectorization_type vect_type) { size_t local_N = nb_sys.N / comm_sz; double*** local_force = (double***)malloc(num_threads*sizeof(double**)); size_t num_masks = local_N/4; if(num_masks*4 != local_N)num_masks++; __mmask8** sqrt_mask = (__mmask8**)malloc(num_threads*sizeof(__mmask8*)); for(size_t thread = 0; thread < num_threads;thread++) { local_force[thread] = (double**)malloc(DIM*sizeof(double*)); sqrt_mask[thread] = (__mmask8*)malloc(num_masks*sizeof(__mmask8)); for(size_t d = 0;d < DIM;d++) { local_force[thread][d] = (double*)aligned_alloc(64,sizeof(double) * local_N); } for(size_t k = 0;k < num_masks;k++) { sqrt_mask[thread][k] = 0xFF; } } MPI_Bcast(nb_sys.mass, nb_sys.N, MPI_DOUBLE, 0, MPI_COMM_WORLD); for(size_t d = 0;d < DIM;d++) { MPI_Bcast(nb_sys.pos[d], nb_sys.N, MPI_DOUBLE, 0, MPI_COMM_WORLD); } for(size_t d = 0;d < DIM;d++) { if(rank == 0) MPI_Scatter(nb_sys.vel[d], local_N, MPI_DOUBLE, MPI_IN_PLACE, local_N, MPI_DOUBLE, 0, MPI_COMM_WORLD); else MPI_Scatter(NULL, 0, MPI_DATATYPE_NULL, nb_sys.vel[d], local_N, MPI_DOUBLE, 0, MPI_COMM_WORLD); } /* for(size_t k = 0;k < nb_sys.N;k++) printf("%zu:mass[%zu] = %f, pos[%zu] = {%f,%f,%f}\n", rank, k, nb_sys.mass[k], k, nb_sys.pos[X][k], nb_sys.pos[Y][k], nb_sys.pos[Z][k]); for(size_t k = 0;k < local_N;k++) printf("%zu:vel[%zu] = {%f,%f,%f}\n", rank, k, nb_sys.vel[X][k], nb_sys.vel[Y][k], nb_sys.vel[Z][k]); */ //Allocate buffer for local particles as they have to be aligned double* local_mass = (double*)aligned_alloc(64,sizeof(double) * local_N); memcpy(local_mass, &nb_sys.mass[rank*local_N], sizeof(double) * local_N); double* local_pos[DIM]; for(size_t d = 0;d < DIM;d++) { local_pos[d] = (double*)aligned_alloc(64, sizeof(double) * local_N); memcpy(local_pos[d], &nb_sys.pos[d][rank*local_N], sizeof(double)*local_N); } for(size_t i = 0;i < time_steps;i++) { //Reset all Forces for(size_t k = 0;k < local_N;k++) { nb_sys.force[X][k] = 0.0; nb_sys.force[Y][k] = 0.0; nb_sys.force[Z][k] = 0.0; } compute_forces_full_avx2(nb_sys, local_force, local_pos, local_mass, sqrt_mask, local_N, rank, comm_sz, num_threads); //Update the positions and velocities #pragma omp parallel for simd for(size_t k = 0;k < local_N;k++) { local_pos[X][k] += nb_sys.vel[X][k] * delta_t; local_pos[Y][k] += nb_sys.vel[Y][k] * delta_t; local_pos[Z][k] += nb_sys.vel[Z][k] * delta_t; nb_sys.vel[X][k] += nb_sys.force[X][k] * delta_t / local_mass[k]; nb_sys.vel[Y][k] += nb_sys.force[Y][k] * delta_t / local_mass[k]; nb_sys.vel[Z][k] += nb_sys.force[Z][k] * delta_t / local_mass[k]; } //Only the main thread is allowed to communicate over MPI int flag; MPI_Is_thread_main(&flag); if(!flag) { printf("Not main thread trying to call MPI communication function\n"); exit(1); } for(size_t d = 0;d < DIM;d++) MPI_Allgather(local_pos[d], local_N, MPI_DOUBLE, nb_sys.pos[d], local_N, MPI_DOUBLE, MPI_COMM_WORLD); } //Collect all subsets back to the main rank for(size_t d = 0;d < DIM;d++) { if(rank == 0) MPI_Gather(MPI_IN_PLACE, local_N, MPI_DOUBLE, nb_sys.vel[d], local_N, MPI_DOUBLE, 0, MPI_COMM_WORLD); else MPI_Gather(nb_sys.vel[d], local_N, MPI_DOUBLE, NULL, 0, MPI_DATATYPE_NULL, 0, MPI_COMM_WORLD); } for(size_t thread = 0; thread < num_threads;thread++) { for(size_t d = 0;d < DIM;d++) { free(local_force[thread][d]); } free(local_force[thread]); free(sqrt_mask[thread]); } for(size_t d = 0;d < DIM;d++) free(local_pos[d]); free(local_mass); free(local_force); free(sqrt_mask); } int hybrid_main(int argc, char** argv, size_t N, size_t time_steps, double T, double ratio, Vectorization_type vect_type, Solver_type solver_type, bool verbose) { //Initialize MPI for hybrid OpenMP usage int provided, flag, claimed; MPI_Init_thread(NULL, NULL, MPI_THREAD_FUNNELED, &provided); if(provided != MPI_THREAD_FUNNELED) { printf("MPI_THREAD_FUNNELED not available.\n"); exit(1); } MPI_Query_thread(&claimed); if(provided != claimed) { printf("Query thread gave %d but init gave%d\n", claimed, provided); exit(1); } MPI_Is_thread_main(&flag); if(!flag) { printf("This thread called init, but claims not to be main."); exit(1); } size_t comm_sz; size_t rank; int mpi_ret; MPI_Comm_size(MPI_COMM_WORLD, &mpi_ret); comm_sz = static_cast<size_t>(mpi_ret); MPI_Comm_rank(MPI_COMM_WORLD, &mpi_ret); rank = static_cast<size_t>(mpi_ret); size_t num_threads = omp_get_max_threads(); //could be improved using gatherv and scatterv if(N % comm_sz != 0) { if(rank == 0)printf("N not evenly divisible by comm_sz; currently not supported; exiting!\n"); MPI_Finalize(); return 1; } double R = 1.0; //Distance to center particle double omega = (2.0 * M_PI)/T; //Number of orbits per unit time double delta_t = T/time_steps; if(rank == 0) { printf("Number of MPI ranks: %zu\n", comm_sz); printf("Threads per rank: %zu\n", num_threads); //Let the simulation run for one orbit //Compare the result with the original positions //Ideally, there is no deviation NBody_system sys1; NBody_system ref; sys1.init_stable_orbiting_particles(N, R, omega, ratio); ref = sys1; if(solver_type == Solver_type::REDUCED) { double start = MPI_Wtime(); hybrid_ring_solver(sys1, rank, comm_sz, num_threads, time_steps, delta_t, vect_type); double end = MPI_Wtime(); double num_pairs = double(time_steps) * double(N)*double(N-1); double mpairs = num_pairs/(1e6 * (end-start)); printf("Ring Solver took %fs\n", end - start); printf("MPairs/s: %f\n", mpairs); } else if(solver_type == Solver_type::FULL) { double start = MPI_Wtime(); hybrid_full_solver(sys1, rank, comm_sz, num_threads, time_steps, delta_t, vect_type); double end = MPI_Wtime(); double num_pairs = double(time_steps) * double(N)*double(N-1); double mpairs = num_pairs/(1e6 * (end-start)); printf("%zu:Ring Solver took %fs\n", rank, end - start); printf("MPairs/s: %f\n", mpairs); } //Compare solution to reference print_deviation(sys1.pos, ref.pos, "position", N, verbose); print_deviation(sys1.vel, ref.vel, "velocity", N, verbose); printf("\n\n"); MPI_Barrier(MPI_COMM_WORLD); } else { NBody_system sys; //Only allocate the needed buffers //The corresponding data will be send from the main rank if(solver_type == Solver_type::REDUCED) { sys.alloc_particles(N, N/comm_sz); hybrid_ring_solver(sys, rank, comm_sz, num_threads, time_steps, delta_t, vect_type); } else { sys.alloc_particles(N, N); hybrid_full_solver(sys, rank, comm_sz, num_threads, time_steps, delta_t, vect_type); } MPI_Barrier(MPI_COMM_WORLD); } MPI_Finalize(); return 0; } int hybrid_scaling_benchmark(int argc, char** argv, size_t N, size_t time_steps, double T, double ratio, bool weak, std::string output_path, Vectorization_type vect_type, Solver_type solver_type, bool verbose) { //Initialize MPI for hybrid OpenMP usage int provided, flag, claimed; MPI_Init_thread(NULL, NULL, MPI_THREAD_FUNNELED, &provided); if(provided != MPI_THREAD_FUNNELED) { printf("MPI_THREAD_FUNNELED not available.\n"); MPI_Finalize(); return EXIT_FAILURE; } MPI_Query_thread(&claimed); if(provided != claimed) { printf("Query thread gave %d but init gave%d\n", claimed, provided); MPI_Finalize(); return EXIT_FAILURE; } MPI_Is_thread_main(&flag); if(!flag) { printf("This thread called init, but claims not to be main."); MPI_Finalize(); return EXIT_FAILURE; } size_t comm_sz; size_t rank; int mpi_ret; MPI_Comm_size(MPI_COMM_WORLD, &mpi_ret); comm_sz = static_cast<size_t>(mpi_ret); MPI_Comm_rank(MPI_COMM_WORLD, &mpi_ret); rank = static_cast<size_t>(mpi_ret); size_t num_threads = omp_get_max_threads(); double R = 1.0; //Distance to center particle double omega = (2.0 * M_PI)/T; //Number of orbits per unit time double delta_t = T/time_steps; size_t scaled_N = N; //weak scaling scales the number of particles in relation to the number of cores used if(weak) scaled_N = comm_sz*num_threads*N; if(scaled_N % comm_sz != 0) { if(rank == 0)printf("N not evenly divisible by comm_sz; currently not supported; exiting!\n"); MPI_Finalize(); return EXIT_FAILURE; } constexpr size_t avg_steps = 3; if(rank == 0) { printf("\n\n-------- Ring Solver --------\n"); printf("N = %zu, time_steps = %zu\n", scaled_N, time_steps); printf("Number of MPI ranks: %zu\n", comm_sz); printf("Threads per rank: %zu\n", num_threads); double avg_timing[avg_steps]; //Repeat the simulation several times for the given problem size //to average out fluctuations in the performance for(size_t avg = 0; avg < avg_steps;avg++) { NBody_system sys1; sys1.init_stable_orbiting_particles(scaled_N, R, omega, ratio); if(solver_type == Solver_type::REDUCED) { double start = MPI_Wtime(); hybrid_ring_solver(sys1, rank, comm_sz, num_threads, time_steps, delta_t, vect_type); double end = MPI_Wtime(); avg_timing[avg] = end - start; } else if(solver_type == Solver_type::FULL) { double start = MPI_Wtime(); hybrid_full_solver(sys1, rank, comm_sz, num_threads, time_steps, delta_t, vect_type); double end = MPI_Wtime(); avg_timing[avg] = end - start; } MPI_Barrier(MPI_COMM_WORLD); } //take the median execution time as the averaged result std::nth_element(avg_timing, avg_timing+avg_steps/2, avg_timing+avg_steps); double t_total = avg_timing[avg_steps/2]; double num_pairs = double(time_steps) * double(scaled_N)*double(scaled_N-1); double mpairs = num_pairs/(1e6 * t_total); for(size_t i = 0;i < avg_steps;i++) { printf("Ring Solver execution %lu took %fs\n", i, avg_timing[i]); printf("Execution %lu MPairs/s: %f\n", i, num_pairs/(1e6 * avg_timing[i])); } printf("Median Ring Solver Execution took %fs\n", t_total); printf("Median MPairs/s: %f\n", mpairs); //The hybrid solver can not change the number of ranks dynamically from within the program //Therefore, the program is called multiple times from a job script //To only initialize the resulting .csv once, check whether the file exists bool file_exists = (access(output_path.c_str(), F_OK) != -1); if(file_exists) { /*FILE* output_file = fopen(output_path.c_str(), "r"); if(output_file == NULL) { perror("Failed to open output file for reading: "); MPI_Finalize(); return EXIT_FAILURE; } char* header_line = nullptr; size_t header_len; int ret = getline(&header_line, &header_len, output_file); if(ret == -1) { if(ferror(output_file)) { perror("Failed to read in header line: "); MPI_Finalize(); return EXIT_FAILURE; } else if(feof(output_file)) { printf("Reached EOF\n"); } } if(header_line)free(header_line); size_t baseline_cores, baseline_N; double baseline_t_total, baseline_mpairs, baseline_speedup; ret = fscanf(output_file, "%zu, %zu, %lf, %lf ,%lf\n", &baseline_cores, &baseline_N, &baseline_t_total, &baseline_mpairs, &baseline_speedup); if(ret != 5) { printf("ret: %d\n", ret); if(ferror(output_file)) { perror("Failed to read in baseline: "); MPI_Finalize(); return EXIT_FAILURE; } else if(feof(output_file)) { printf("Reached EOF\n"); } } fclose(output_file); //if(baseline_N != N) //{ // printf("N = %zu does not match the baseline N = %zu! Results would not be meaningful.\n", N, baseline_N); // MPI_Finalize(); // return EXIT_FAILURE; //} double speedup = 1.0; if(weak) { printf("Using %fMpairs/s as the baseline performance\n", baseline_mpairs); speedup = mpairs/baseline_mpairs; } else { printf("Using %fs as the baseline execution time\n", baseline_t_total); speedup = baseline_t_total/t_total; } */ FILE* output_file = fopen(output_path.c_str(), "a"); if(output_file == NULL) { perror("Failed to open output file for appending: "); MPI_Finalize(); return EXIT_FAILURE; } fprintf(output_file, "%zu,%zu,%zu,%f,%f,%f,%f\n", comm_sz/2, comm_sz*num_threads, scaled_N, t_total, mpairs, time_steps/t_total, t_total*1000.0/time_steps); fclose(output_file); } else { FILE* output_file = fopen(output_path.c_str(), "w"); if(output_file == NULL) { perror("Failed to open output file for writing: "); MPI_Finalize(); return EXIT_FAILURE; } fprintf(output_file, "#Nodes, Cores, N, t_total[s], performance[Mpairs/s], time_steps/s, ms/time_step\n"); fprintf(output_file, "%zu,%zu,%zu,%f,%f,%f,%f\n", comm_sz/2, comm_sz*num_threads, scaled_N, t_total, mpairs, time_steps/t_total, t_total*1000.0/time_steps); fclose(output_file); } } else { for(size_t avg = 0; avg < avg_steps;avg++) { NBody_system sys; if(solver_type == Solver_type::REDUCED) { sys.alloc_particles(scaled_N, scaled_N/comm_sz); hybrid_ring_solver(sys, rank, comm_sz, num_threads, time_steps, delta_t, vect_type); } else { sys.alloc_particles(scaled_N, scaled_N); hybrid_full_solver(sys, rank, comm_sz, num_threads, time_steps, delta_t, vect_type); } MPI_Barrier(MPI_COMM_WORLD); } } MPI_Finalize(); return 0; }
26,382
9,561
// Copyright 2004-present Facebook. All Rights Reserved. #include "fboss/agent/platforms/sai/SaiBcmWedge40PlatformPort.h" namespace facebook::fboss { void SaiBcmWedge40PlatformPort::linkStatusChanged( bool /*up*/, bool /*adminUp*/) {} } // namespace facebook::fboss
278
99
// Copyright (c) 2012 Plenluno All rights reserved. #include <gtest/gtest.h> #include <libj/array_list.h> #include <libj/typed_value_holder.h> namespace libj { TEST(GTestTypedValueHolder, TestCreate) { TypedValueHolder<Int>::Ptr h = TypedValueHolder<Int>::create(1); ASSERT_TRUE(!!h); TypedValueHolder<String::CPtr>::Ptr h2 = TypedValueHolder<String::CPtr>::create(String::create("123")); ASSERT_TRUE(!!h2); } TEST(GTestTypedValueHolder, TestGet) { TypedValueHolder<Int>::Ptr h = TypedValueHolder<Int>::create(3); ASSERT_EQ(3, h->getTyped()); } TEST(GTestTypedValueHolder, TestGetPtr) { ArrayList::Ptr a = ArrayList::create(); TypedValueHolder<ArrayList::Ptr>::Ptr h = TypedValueHolder<ArrayList::Ptr>::create(a); ASSERT_TRUE(h->getTyped()->equals(a)); ASSERT_TRUE(a->isEmpty()); h->getTyped()->add(5); ASSERT_TRUE(a->get(0).equals(5)); } TEST(GTestTypedValueHolder, TestGetCPtr) { String::CPtr s = String::create("abc"); TypedValueHolder<String::CPtr>::Ptr h = TypedValueHolder<String::CPtr>::create(s); ASSERT_TRUE(h->getTyped()->equals(s)); } TEST(GTestTypedValueHolder, TestSet) { String::CPtr s = String::create("abc"); TypedValueHolder<String::CPtr>::Ptr h = TypedValueHolder<String::CPtr>::create(s); h->setTyped(h->getTyped()->concat(String::create("123"))); ASSERT_TRUE(h->getTyped()->equals(String::create("abc123"))); } class GTestTypedValueHolderIncrement { public: TypedValueHolder<Int>::Ptr holder; void inc() { holder->setTyped(holder->getTyped() + 1); } }; TEST(GTestTypedValueHolder, TestSet2) { GTestTypedValueHolderIncrement i1; GTestTypedValueHolderIncrement i2; TypedValueHolder<Int>::Ptr h = TypedValueHolder<Int>::create(0); i1.holder = h; i2.holder = h; i1.inc(); i2.inc(); ASSERT_EQ(2, h->getTyped()); } } // namespace libj
1,925
722
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * JS Atomics pseudo-module. * * See "Spec: JavaScript Shared Memory, Atomics, and Locks" for the * full specification. * * In addition to what is specified there, we throw an Error object if * the futex API hooks have not been installed on the runtime. * Essentially that is an implementation error at a higher level. * * * Note on the current implementation of atomic operations. * * The Mozilla atomics are not sufficient to implement these APIs * because we need to support 8-bit, 16-bit, and 32-bit data: the * Mozilla atomics only support 32-bit data. * * At the moment we include mozilla/Atomics.h, which will define * MOZ_HAVE_CXX11_ATOMICS and include <atomic> if we have C++11 * atomics. * * If MOZ_HAVE_CXX11_ATOMICS is set we'll use C++11 atomics. * * Otherwise, if the compiler has them we'll fall back on gcc/Clang * intrinsics. * * Otherwise, if we're on VC++2012, we'll use C++11 atomics even if * MOZ_HAVE_CXX11_ATOMICS is not defined. The compiler has the * atomics but they are disabled in Mozilla due to a performance bug. * That performance bug does not affect the Atomics code. See * mozilla/Atomics.h for further comments on that bug. * * Otherwise, if we're on VC++2010 or VC++2008, we'll emulate the * gcc/Clang intrinsics with simple code below using the VC++ * intrinsics, like the VC++2012 solution this is a stopgap since * we're about to start using VC++2013 anyway. * * If none of those options are available then the build must disable * shared memory, or compilation will fail with a predictable error. */ #include "builtin/AtomicsObject.h" #include "mozilla/Atomics.h" #include "mozilla/FloatingPoint.h" #include "jsapi.h" #include "jsfriendapi.h" #include "prmjtime.h" #include "vm/GlobalObject.h" #include "vm/SharedTypedArrayObject.h" #include "vm/TypedArrayObject.h" #include "jsobjinlines.h" using namespace js; #if defined(MOZ_HAVE_CXX11_ATOMICS) # define CXX11_ATOMICS #elif defined(__clang__) || defined(__GNUC__) # define GNU_ATOMICS #elif _MSC_VER >= 1700 && _MSC_VER < 1800 // Visual Studion 2012 # define CXX11_ATOMICS # include <atomic> #elif defined(_MSC_VER) // Visual Studio 2010 # define GNU_ATOMICS static inline void __sync_synchronize() { # if JS_BITS_PER_WORD == 32 // If configured for SSE2+ we can use the MFENCE instruction, available // through the _mm_mfence intrinsic. But for non-SSE2 systems we have // to do something else. Linux uses "lock add [esp], 0", so why not? __asm lock add [esp], 0; # else _mm_mfence(); # endif } # define MSC_CAS(T, U, cmpxchg) \ static inline T \ __sync_val_compare_and_swap(T* addr, T oldval, T newval) { \ return (T)cmpxchg((U volatile*)addr, (U)oldval, (U)newval); \ } MSC_CAS(int8_t, char, _InterlockedCompareExchange8) MSC_CAS(uint8_t, char, _InterlockedCompareExchange8) MSC_CAS(int16_t, short, _InterlockedCompareExchange16) MSC_CAS(uint16_t, short, _InterlockedCompareExchange16) MSC_CAS(int32_t, long, _InterlockedCompareExchange) MSC_CAS(uint32_t, long, _InterlockedCompareExchange) # define MSC_FETCHADDOP(T, U, xadd) \ static inline T \ __sync_fetch_and_add(T* addr, T val) { \ return (T)xadd((U volatile*)addr, (U)val); \ } \ static inline T \ __sync_fetch_and_sub(T* addr, T val) { \ return (T)xadd((U volatile*)addr, (U)-val); \ } MSC_FETCHADDOP(int8_t, char, _InterlockedExchangeAdd8) MSC_FETCHADDOP(uint8_t, char, _InterlockedExchangeAdd8) MSC_FETCHADDOP(int16_t, short, _InterlockedExchangeAdd16) MSC_FETCHADDOP(uint16_t, short, _InterlockedExchangeAdd16) MSC_FETCHADDOP(int32_t, long, _InterlockedExchangeAdd) MSC_FETCHADDOP(uint32_t, long, _InterlockedExchangeAdd) # define MSC_FETCHBITOP(T, U, andop, orop, xorop) \ static inline T \ __sync_fetch_and_and(T* addr, T val) { \ return (T)andop((U volatile*)addr, (U)val); \ } \ static inline T \ __sync_fetch_and_or(T* addr, T val) { \ return (T)orop((U volatile*)addr, (U)val); \ } \ static inline T \ __sync_fetch_and_xor(T* addr, T val) { \ return (T)xorop((U volatile*)addr, (U)val); \ } \ MSC_FETCHBITOP(int8_t, char, _InterlockedAnd8, _InterlockedOr8, _InterlockedXor8) MSC_FETCHBITOP(uint8_t, char, _InterlockedAnd8, _InterlockedOr8, _InterlockedXor8) MSC_FETCHBITOP(int16_t, short, _InterlockedAnd16, _InterlockedOr16, _InterlockedXor16) MSC_FETCHBITOP(uint16_t, short, _InterlockedAnd16, _InterlockedOr16, _InterlockedXor16) MSC_FETCHBITOP(int32_t, long, _InterlockedAnd, _InterlockedOr, _InterlockedXor) MSC_FETCHBITOP(uint32_t, long, _InterlockedAnd, _InterlockedOr, _InterlockedXor) # undef MSC_CAS # undef MSC_FETCHADDOP # undef MSC_FETCHBITOP #elif defined(ENABLE_SHARED_ARRAY_BUFFER) # error "Either disable JS shared memory or use a compiler that supports C++11 atomics or GCC/clang atomics" #endif const Class AtomicsObject::class_ = { "Atomics", JSCLASS_HAS_CACHED_PROTO(JSProto_Atomics) }; static bool ReportBadArrayType(JSContext* cx) { JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_ATOMICS_BAD_ARRAY); return false; } static bool GetSharedTypedArray(JSContext* cx, HandleValue v, MutableHandle<SharedTypedArrayObject*> viewp) { if (!v.isObject()) return ReportBadArrayType(cx); if (!v.toObject().is<SharedTypedArrayObject>()) return ReportBadArrayType(cx); viewp.set(&v.toObject().as<SharedTypedArrayObject>()); return true; } // Returns true so long as the conversion succeeds, and then *inRange // is set to false if the index is not in range. static bool GetSharedTypedArrayIndex(JSContext* cx, HandleValue v, Handle<SharedTypedArrayObject*> view, uint32_t* offset, bool* inRange) { RootedId id(cx); if (!ValueToId<CanGC>(cx, v, &id)) return false; uint64_t index; if (!IsTypedArrayIndex(id, &index) || index >= view->length()) { *inRange = false; } else { *offset = (uint32_t)index; *inRange = true; } return true; } void js::atomics_fullMemoryBarrier() { #if defined(CXX11_ATOMICS) std::atomic_thread_fence(std::memory_order_seq_cst); #elif defined(GNU_ATOMICS) __sync_synchronize(); #endif } static bool atomics_fence_impl(JSContext* cx, MutableHandleValue r) { atomics_fullMemoryBarrier(); r.setUndefined(); return true; } bool js::atomics_fence(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); return atomics_fence_impl(cx, args.rval()); } bool js::atomics_compareExchange(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); HandleValue objv = args.get(0); HandleValue idxv = args.get(1); HandleValue oldv = args.get(2); HandleValue newv = args.get(3); MutableHandleValue r = args.rval(); Rooted<SharedTypedArrayObject*> view(cx, nullptr); if (!GetSharedTypedArray(cx, objv, &view)) return false; uint32_t offset; bool inRange; if (!GetSharedTypedArrayIndex(cx, idxv, view, &offset, &inRange)) return false; int32_t oldCandidate; if (!ToInt32(cx, oldv, &oldCandidate)) return false; int32_t newCandidate; if (!ToInt32(cx, newv, &newCandidate)) return false; if (!inRange) return atomics_fence_impl(cx, r); // CAS always sets oldval to the old value of the cell. // addr must be a T*, and oldval and newval should be variables of type T #if defined(CXX11_ATOMICS) # define CAS(T, addr, oldval, newval) \ do { \ std::atomic_compare_exchange_strong(reinterpret_cast<std::atomic<T>*>(addr), &oldval, newval); \ } while(0) #elif defined(GNU_ATOMICS) # define CAS(T, addr, oldval, newval) \ do { \ oldval = __sync_val_compare_and_swap(addr, (oldval), (newval)); \ } while(0) #else # define CAS(a, b, c, newval) (void)newval #endif switch (view->type()) { case Scalar::Int8: { int8_t oldval = (int8_t)oldCandidate; int8_t newval = (int8_t)newCandidate; CAS(int8_t, (int8_t*)view->viewData() + offset, oldval, newval); r.setInt32(oldval); return true; } case Scalar::Uint8: { uint8_t oldval = (uint8_t)oldCandidate; uint8_t newval = (uint8_t)newCandidate; CAS(uint8_t, (uint8_t*)view->viewData() + offset, oldval, newval); r.setInt32(oldval); return true; } case Scalar::Uint8Clamped: { uint8_t oldval = ClampIntForUint8Array(oldCandidate); uint8_t newval = ClampIntForUint8Array(newCandidate); CAS(uint8_t, (uint8_t*)view->viewData() + offset, oldval, newval); r.setInt32(oldval); return true; } case Scalar::Int16: { int16_t oldval = (int16_t)oldCandidate; int16_t newval = (int16_t)newCandidate; CAS(int16_t, (int16_t*)view->viewData() + offset, oldval, newval); r.setInt32(oldval); return true; } case Scalar::Uint16: { uint16_t oldval = (uint16_t)oldCandidate; uint16_t newval = (uint16_t)newCandidate; CAS(uint16_t, (uint16_t*)view->viewData() + offset, oldval, newval); r.setInt32(oldval); return true; } case Scalar::Int32: { int32_t oldval = oldCandidate; int32_t newval = newCandidate; CAS(int32_t, (int32_t*)view->viewData() + offset, oldval, newval); r.setInt32(oldval); return true; } case Scalar::Uint32: { uint32_t oldval = (uint32_t)oldCandidate; uint32_t newval = (uint32_t)newCandidate; CAS(uint32_t, (uint32_t*)view->viewData() + offset, oldval, newval); r.setNumber((double)oldval); return true; } default: return ReportBadArrayType(cx); } // Do not undef CAS, it is used later } bool js::atomics_load(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); HandleValue objv = args.get(0); HandleValue idxv = args.get(1); MutableHandleValue r = args.rval(); Rooted<SharedTypedArrayObject*> view(cx, nullptr); if (!GetSharedTypedArray(cx, objv, &view)) return false; uint32_t offset; bool inRange; if (!GetSharedTypedArrayIndex(cx, idxv, view, &offset, &inRange)) return false; if (!inRange) return atomics_fence_impl(cx, r); // LOAD sets v to the value of *addr // addr must be a T*, and v must be a variable of type T #if defined(CXX11_ATOMICS) # define LOAD(T, addr, v) \ do { \ v = std::atomic_load(reinterpret_cast<std::atomic<T>*>(addr)); \ } while(0) #elif defined(GNU_ATOMICS) # define LOAD(T, addr, v) \ do { \ __sync_synchronize(); \ v = *(addr); \ __sync_synchronize(); \ } while(0) #else # define LOAD(a, b, v) v = 0 #endif switch (view->type()) { case Scalar::Uint8: case Scalar::Uint8Clamped: { uint8_t v; LOAD(uint8_t, (uint8_t*)view->viewData() + offset, v); r.setInt32(v); return true; } case Scalar::Int8: { int8_t v; LOAD(int8_t, (int8_t*)view->viewData() + offset, v); r.setInt32(v); return true; } case Scalar::Int16: { int16_t v; LOAD(int16_t, (int16_t*)view->viewData() + offset, v); r.setInt32(v); return true; } case Scalar::Uint16: { uint16_t v; LOAD(uint16_t, (uint16_t*)view->viewData() + offset, v); r.setInt32(v); return true; } case Scalar::Int32: { int32_t v; LOAD(int32_t, (int32_t*)view->viewData() + offset, v); r.setInt32(v); return true; } case Scalar::Uint32: { uint32_t v; LOAD(uint32_t, (uint32_t*)view->viewData() + offset, v); r.setNumber(v); return true; } default: return ReportBadArrayType(cx); } #undef LOAD } bool js::atomics_store(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); HandleValue objv = args.get(0); HandleValue idxv = args.get(1); HandleValue valv = args.get(2); MutableHandleValue r = args.rval(); Rooted<SharedTypedArrayObject*> view(cx, nullptr); if (!GetSharedTypedArray(cx, objv, &view)) return false; uint32_t offset; bool inRange; if (!GetSharedTypedArrayIndex(cx, idxv, view, &offset, &inRange)) return false; int32_t numberValue; if (!ToInt32(cx, valv, &numberValue)) return false; if (!inRange) { atomics_fullMemoryBarrier(); r.set(valv); return true; } // STORE stores value in *addr // addr must be a T*, and value should be of type T #if defined(CXX11_ATOMICS) # define STORE(T, addr, value) \ do { \ std::atomic_store(reinterpret_cast<std::atomic<T>*>(addr), (T)value); \ } while(0) #elif defined(GNU_ATOMICS) # define STORE(T, addr, value) \ do { \ __sync_synchronize(); \ *(addr) = value; \ __sync_synchronize(); \ } while(0) #else # define STORE(a, b, c) (void)0 #endif switch (view->type()) { case Scalar::Int8: { int8_t value = (int8_t)numberValue; STORE(int8_t, (int8_t*)view->viewData() + offset, value); r.setInt32(value); return true; } case Scalar::Uint8: { uint8_t value = (uint8_t)numberValue; STORE(uint8_t, (uint8_t*)view->viewData() + offset, value); r.setInt32(value); return true; } case Scalar::Uint8Clamped: { uint8_t value = ClampIntForUint8Array(numberValue); STORE(uint8_t, (uint8_t*)view->viewData() + offset, value); r.setInt32(value); return true; } case Scalar::Int16: { int16_t value = (int16_t)numberValue; STORE(int16_t, (int16_t*)view->viewData() + offset, value); r.setInt32(value); return true; } case Scalar::Uint16: { uint16_t value = (uint16_t)numberValue; STORE(uint16_t, (uint16_t*)view->viewData() + offset, value); r.setInt32(value); return true; } case Scalar::Int32: { int32_t value = numberValue; STORE(int32_t, (int32_t*)view->viewData() + offset, value); r.setInt32(value); return true; } case Scalar::Uint32: { uint32_t value = (uint32_t)numberValue; STORE(uint32_t, (uint32_t*)view->viewData() + offset, value); r.setNumber((double)value); return true; } default: return ReportBadArrayType(cx); } #undef STORE } template<typename T> static bool atomics_binop_impl(JSContext* cx, HandleValue objv, HandleValue idxv, HandleValue valv, MutableHandleValue r) { Rooted<SharedTypedArrayObject*> view(cx, nullptr); if (!GetSharedTypedArray(cx, objv, &view)) return false; uint32_t offset; bool inRange; if (!GetSharedTypedArrayIndex(cx, idxv, view, &offset, &inRange)) return false; int32_t numberValue; if (!ToInt32(cx, valv, &numberValue)) return false; if (!inRange) return atomics_fence_impl(cx, r); switch (view->type()) { case Scalar::Int8: { int8_t v = (int8_t)numberValue; r.setInt32(T::operate((int8_t*)view->viewData() + offset, v)); return true; } case Scalar::Uint8: { uint8_t v = (uint8_t)numberValue; r.setInt32(T::operate((uint8_t*)view->viewData() + offset, v)); return true; } case Scalar::Uint8Clamped: { // Spec says: // - clamp the input value // - perform the operation // - clamp the result // - store the result // This requires a CAS loop. int32_t value = ClampIntForUint8Array(numberValue); uint8_t* loc = (uint8_t*)view->viewData() + offset; for (;;) { uint8_t old = *loc; uint8_t result = (uint8_t)ClampIntForUint8Array(T::perform(old, value)); uint8_t tmp = old; // tmp is overwritten by CAS CAS(uint8_t, loc, tmp, result); if (tmp == old) { r.setInt32(old); break; } } return true; } case Scalar::Int16: { int16_t v = (int16_t)numberValue; r.setInt32(T::operate((int16_t*)view->viewData() + offset, v)); return true; } case Scalar::Uint16: { uint16_t v = (uint16_t)numberValue; r.setInt32(T::operate((uint16_t*)view->viewData() + offset, v)); return true; } case Scalar::Int32: { int32_t v = numberValue; r.setInt32(T::operate((int32_t*)view->viewData() + offset, v)); return true; } case Scalar::Uint32: { uint32_t v = (uint32_t)numberValue; r.setNumber((double)T::operate((uint32_t*)view->viewData() + offset, v)); return true; } default: return ReportBadArrayType(cx); } } #define INTEGRAL_TYPES_FOR_EACH(NAME, TRANSFORM) \ static int8_t operate(int8_t* addr, int8_t v) { return NAME(TRANSFORM(int8_t, addr), v); } \ static uint8_t operate(uint8_t* addr, uint8_t v) { return NAME(TRANSFORM(uint8_t, addr), v); } \ static int16_t operate(int16_t* addr, int16_t v) { return NAME(TRANSFORM(int16_t, addr), v); } \ static uint16_t operate(uint16_t* addr, uint16_t v) { return NAME(TRANSFORM(uint16_t, addr), v); } \ static int32_t operate(int32_t* addr, int32_t v) { return NAME(TRANSFORM(int32_t, addr), v); } \ static uint32_t operate(uint32_t* addr, uint32_t v) { return NAME(TRANSFORM(uint32_t, addr), v); } #define CAST_ATOMIC(t, v) reinterpret_cast<std::atomic<t>*>(v) #define DO_NOTHING(t, v) v #define ZERO(t, v) 0 class do_add { public: #if defined(CXX11_ATOMICS) INTEGRAL_TYPES_FOR_EACH(std::atomic_fetch_add, CAST_ATOMIC) #elif defined(GNU_ATOMICS) INTEGRAL_TYPES_FOR_EACH(__sync_fetch_and_add, DO_NOTHING) #else INTEGRAL_TYPES_FOR_EACH(ZERO, DO_NOTHING) #endif static int32_t perform(int32_t x, int32_t y) { return x + y; } }; bool js::atomics_add(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); return atomics_binop_impl<do_add>(cx, args.get(0), args.get(1), args.get(2), args.rval()); } class do_sub { public: #if defined(CXX11_ATOMICS) INTEGRAL_TYPES_FOR_EACH(std::atomic_fetch_sub, CAST_ATOMIC) #elif defined(GNU_ATOMICS) INTEGRAL_TYPES_FOR_EACH(__sync_fetch_and_sub, DO_NOTHING) #else INTEGRAL_TYPES_FOR_EACH(ZERO, DO_NOTHING) #endif static int32_t perform(int32_t x, int32_t y) { return x - y; } }; bool js::atomics_sub(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); return atomics_binop_impl<do_sub>(cx, args.get(0), args.get(1), args.get(2), args.rval()); } class do_and { public: #if defined(CXX11_ATOMICS) INTEGRAL_TYPES_FOR_EACH(std::atomic_fetch_and, CAST_ATOMIC) #elif defined(GNU_ATOMICS) INTEGRAL_TYPES_FOR_EACH(__sync_fetch_and_and, DO_NOTHING) #else INTEGRAL_TYPES_FOR_EACH(ZERO, DO_NOTHING) #endif static int32_t perform(int32_t x, int32_t y) { return x & y; } }; bool js::atomics_and(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); return atomics_binop_impl<do_and>(cx, args.get(0), args.get(1), args.get(2), args.rval()); } class do_or { public: #if defined(CXX11_ATOMICS) INTEGRAL_TYPES_FOR_EACH(std::atomic_fetch_or, CAST_ATOMIC) #elif defined(GNU_ATOMICS) INTEGRAL_TYPES_FOR_EACH(__sync_fetch_and_or, DO_NOTHING) #else INTEGRAL_TYPES_FOR_EACH(ZERO, DO_NOTHING) #endif static int32_t perform(int32_t x, int32_t y) { return x | y; } }; bool js::atomics_or(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); return atomics_binop_impl<do_or>(cx, args.get(0), args.get(1), args.get(2), args.rval()); } class do_xor { public: #if defined(CXX11_ATOMICS) INTEGRAL_TYPES_FOR_EACH(std::atomic_fetch_xor, CAST_ATOMIC) #elif defined(GNU_ATOMICS) INTEGRAL_TYPES_FOR_EACH(__sync_fetch_and_xor, DO_NOTHING) #else INTEGRAL_TYPES_FOR_EACH(ZERO, DO_NOTHING) #endif static int32_t perform(int32_t x, int32_t y) { return x ^ y; } }; bool js::atomics_xor(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); return atomics_binop_impl<do_xor>(cx, args.get(0), args.get(1), args.get(2), args.rval()); } #undef INTEGRAL_TYPES_FOR_EACH #undef CAST_ATOMIC #undef DO_NOTHING #undef ZERO namespace js { // Represents one waiting worker. // // The type is declared opaque in SharedArrayObject.h. Instances of // js::FutexWaiter are stack-allocated and linked onto a list across a // call to FutexRuntime::wait(). // // The 'waiters' field of the SharedArrayRawBuffer points to the highest // priority waiter in the list, and lower priority nodes are linked through // the 'lower_pri' field. The 'back' field goes the other direction. // The list is circular, so the 'lower_pri' field of the lowest priority // node points to the first node in the list. The list has no dedicated // header node. class FutexWaiter { public: FutexWaiter(uint32_t offset, JSRuntime* rt) : offset(offset), rt(rt), lower_pri(nullptr), back(nullptr) { } uint32_t offset; // int32 element index within the SharedArrayBuffer JSRuntime* rt; // The runtime of the waiter FutexWaiter* lower_pri; // Lower priority nodes in circular doubly-linked list of waiters FutexWaiter* back; // Other direction }; class AutoLockFutexAPI { public: AutoLockFutexAPI() { FutexRuntime::lock(); } ~AutoLockFutexAPI() { FutexRuntime::unlock(); } }; class AutoUnlockFutexAPI { public: AutoUnlockFutexAPI() { FutexRuntime::unlock(); } ~AutoUnlockFutexAPI() { FutexRuntime::lock(); } }; } // namespace js bool js::atomics_futexWait(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); HandleValue objv = args.get(0); HandleValue idxv = args.get(1); HandleValue valv = args.get(2); HandleValue timeoutv = args.get(3); MutableHandleValue r = args.rval(); JSRuntime* rt = cx->runtime(); Rooted<SharedTypedArrayObject*> view(cx, nullptr); if (!GetSharedTypedArray(cx, objv, &view)) return false; if (view->type() != Scalar::Int32) return ReportBadArrayType(cx); uint32_t offset; bool inRange; if (!GetSharedTypedArrayIndex(cx, idxv, view, &offset, &inRange)) return false; int32_t value; if (!ToInt32(cx, valv, &value)) return false; double timeout_ms; if (timeoutv.isUndefined()) { timeout_ms = mozilla::PositiveInfinity<double>(); } else { if (!ToNumber(cx, timeoutv, &timeout_ms)) return false; if (mozilla::IsNaN(timeout_ms)) timeout_ms = mozilla::PositiveInfinity<double>(); else if (timeout_ms < 0) timeout_ms = 0; } if (!inRange) { atomics_fullMemoryBarrier(); r.setUndefined(); return true; } // This lock also protects the "waiters" field on SharedArrayRawBuffer, // and it provides the necessary memory fence. AutoLockFutexAPI lock; int32_t* addr = (int32_t*)view->viewData() + offset; if (*addr != value) { r.setInt32(AtomicsObject::FutexNotequal); return true; } Rooted<SharedArrayBufferObject*> sab(cx, &view->buffer()->as<SharedArrayBufferObject>()); SharedArrayRawBuffer* sarb = sab->rawBufferObject(); FutexWaiter w(offset, rt); if (FutexWaiter* waiters = sarb->waiters()) { w.lower_pri = waiters; w.back = waiters->back; waiters->back->lower_pri = &w; waiters->back = &w; } else { w.lower_pri = w.back = &w; sarb->setWaiters(&w); } AtomicsObject::FutexWaitResult result = AtomicsObject::FutexOK; bool retval = rt->fx.wait(cx, timeout_ms, &result); if (retval) r.setInt32(result); if (w.lower_pri == &w) { sarb->setWaiters(nullptr); } else { w.lower_pri->back = w.back; w.back->lower_pri = w.lower_pri; if (sarb->waiters() == &w) sarb->setWaiters(w.lower_pri); } return retval; } bool js::atomics_futexWake(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); HandleValue objv = args.get(0); HandleValue idxv = args.get(1); HandleValue countv = args.get(2); MutableHandleValue r = args.rval(); Rooted<SharedTypedArrayObject*> view(cx, nullptr); if (!GetSharedTypedArray(cx, objv, &view)) return false; if (view->type() != Scalar::Int32) return ReportBadArrayType(cx); uint32_t offset; bool inRange; if (!GetSharedTypedArrayIndex(cx, idxv, view, &offset, &inRange)) return false; if (!inRange) { atomics_fullMemoryBarrier(); r.setUndefined(); return true; } double count; if (!ToInteger(cx, countv, &count)) return false; if (count < 0) count = 0; AutoLockFutexAPI lock; Rooted<SharedArrayBufferObject*> sab(cx, &view->buffer()->as<SharedArrayBufferObject>()); SharedArrayRawBuffer* sarb = sab->rawBufferObject(); int32_t woken = 0; FutexWaiter* waiters = sarb->waiters(); if (waiters && count > 0) { FutexWaiter* iter = waiters; do { FutexWaiter* c = iter; iter = iter->lower_pri; if (c->offset != offset || !c->rt->fx.isWaiting()) continue; c->rt->fx.wake(FutexRuntime::WakeExplicit); ++woken; --count; } while (count > 0 && iter != waiters); } r.setInt32(woken); return true; } bool js::atomics_futexWakeOrRequeue(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); HandleValue objv = args.get(0); HandleValue idx1v = args.get(1); HandleValue countv = args.get(2); HandleValue valv = args.get(3); HandleValue idx2v = args.get(4); MutableHandleValue r = args.rval(); Rooted<SharedTypedArrayObject*> view(cx, nullptr); if (!GetSharedTypedArray(cx, objv, &view)) return false; if (view->type() != Scalar::Int32) return ReportBadArrayType(cx); uint32_t offset1; bool inRange1; if (!GetSharedTypedArrayIndex(cx, idx1v, view, &offset1, &inRange1)) return false; double count; if (!ToInteger(cx, countv, &count)) return false; if (count < 0) count = 0; int32_t value; if (!ToInt32(cx, valv, &value)) return false; uint32_t offset2; bool inRange2; if (!GetSharedTypedArrayIndex(cx, idx2v, view, &offset2, &inRange2)) return false; if (!(inRange1 && inRange2)) { atomics_fullMemoryBarrier(); r.setUndefined(); return true; } AutoLockFutexAPI lock; int32_t* addr = (int32_t*)view->viewData() + offset1; if (*addr != value) { r.setInt32(AtomicsObject::FutexNotequal); return true; } Rooted<SharedArrayBufferObject*> sab(cx, &view->buffer()->as<SharedArrayBufferObject>()); SharedArrayRawBuffer* sarb = sab->rawBufferObject(); // Walk the list of waiters looking for those waiting on offset1. // Wake some and requeue the others. There may already be other // waiters on offset2, so those that are requeued must be moved to // the back of the list. Offset1 may equal offset2. The list's // first node may change, and the list may be emptied out by the // operation. FutexWaiter* waiters = sarb->waiters(); if (!waiters) { r.setInt32(0); return true; } int32_t woken = 0; FutexWaiter whead((uint32_t)-1, nullptr); // Header node for waiters FutexWaiter* first = waiters; FutexWaiter* last = waiters->back; whead.lower_pri = first; whead.back = last; first->back = &whead; last->lower_pri = &whead; FutexWaiter rhead((uint32_t)-1, nullptr); // Header node for requeued rhead.lower_pri = rhead.back = &rhead; FutexWaiter* iter = whead.lower_pri; while (iter != &whead) { FutexWaiter* c = iter; iter = iter->lower_pri; if (c->offset != offset1 || !c->rt->fx.isWaiting()) continue; if (count > 0) { c->rt->fx.wake(FutexRuntime::WakeExplicit); ++woken; --count; } else { c->offset = offset2; // Remove the node from the waiters list. c->back->lower_pri = c->lower_pri; c->lower_pri->back = c->back; // Insert the node at the back of the requeuers list. c->lower_pri = &rhead; c->back = rhead.back; rhead.back->lower_pri = c; rhead.back = c; } } // If there are any requeuers, append them to the waiters. if (rhead.lower_pri != &rhead) { whead.back->lower_pri = rhead.lower_pri; rhead.lower_pri->back = whead.back; whead.back = rhead.back; rhead.back->lower_pri = &whead; } // Make the final list and install it. waiters = nullptr; if (whead.lower_pri != &whead) { whead.back->lower_pri = whead.lower_pri; whead.lower_pri->back = whead.back; waiters = whead.lower_pri; } sarb->setWaiters(waiters); r.setInt32(woken); return true; } /* static */ bool js::FutexRuntime::initialize() { MOZ_ASSERT(!lock_); lock_ = PR_NewLock(); return lock_ != nullptr; } /* static */ void js::FutexRuntime::destroy() { if (lock_) { PR_DestroyLock(lock_); lock_ = nullptr; } } /* static */ void js::FutexRuntime::lock() { PR_Lock(lock_); #ifdef DEBUG MOZ_ASSERT(!lockHolder_); lockHolder_ = PR_GetCurrentThread(); #endif } /* static */ mozilla::Atomic<PRLock*> FutexRuntime::lock_; #ifdef DEBUG /* static */ mozilla::Atomic<PRThread*> FutexRuntime::lockHolder_; #endif /* static */ void js::FutexRuntime::unlock() { #ifdef DEBUG MOZ_ASSERT(lockHolder_ == PR_GetCurrentThread()); lockHolder_ = nullptr; #endif PR_Unlock(lock_); } js::FutexRuntime::FutexRuntime() : cond_(nullptr), state_(Idle) { } bool js::FutexRuntime::initInstance() { MOZ_ASSERT(lock_); cond_ = PR_NewCondVar(lock_); return cond_ != nullptr; } void js::FutexRuntime::destroyInstance() { if (cond_) PR_DestroyCondVar(cond_); } bool js::FutexRuntime::isWaiting() { return state_ == Waiting || state_ == WaitingInterrupted; } bool js::FutexRuntime::wait(JSContext* cx, double timeout_ms, AtomicsObject::FutexWaitResult* result) { MOZ_ASSERT(&cx->runtime()->fx == this); MOZ_ASSERT(lockHolder_ == PR_GetCurrentThread()); MOZ_ASSERT(state_ == Idle || state_ == WaitingInterrupted); // Disallow waiting when a runtime is processing an interrupt. // See explanation below. if (state_ == WaitingInterrupted) { JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_ATOMICS_WAIT_NOT_ALLOWED); return false; } const bool timed = !mozilla::IsInfinite(timeout_ms); // Reject the timeout if it is not exactly representable. 2e50 ms = 2e53 us = 6e39 years. if (timed && timeout_ms > 2e50) { JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_ATOMICS_TOO_LONG); return false; } // Times and intervals are in microseconds. const uint64_t finalEnd = timed ? PRMJ_Now() + (uint64_t)ceil(timeout_ms * 1000.0) : 0; // 4000s is about the longest timeout slice that is guaranteed to // work cross-platform. const uint64_t maxSlice = 4000000000LLU; bool retval = true; for (;;) { uint64_t sliceStart = 0; uint32_t timeout = PR_INTERVAL_NO_TIMEOUT; if (timed) { sliceStart = PRMJ_Now(); uint64_t timeLeft = finalEnd > sliceStart ? finalEnd - sliceStart : 0; timeout = PR_MicrosecondsToInterval((uint32_t)Min(timeLeft, maxSlice)); } state_ = Waiting; #ifdef DEBUG PRThread* holder = lockHolder_; lockHolder_ = nullptr; #endif JS_ALWAYS_TRUE(PR_WaitCondVar(cond_, timeout) == PR_SUCCESS); #ifdef DEBUG lockHolder_ = holder; #endif switch (state_) { case FutexRuntime::Waiting: // Timeout or spurious wakeup. if (timed) { uint64_t now = PRMJ_Now(); if (now >= finalEnd) { *result = AtomicsObject::FutexTimedout; goto finished; } } break; case FutexRuntime::Woken: *result = AtomicsObject::FutexOK; goto finished; case FutexRuntime::WokenForJSInterrupt: // The interrupt handler may reenter the engine. In that case // there are two complications: // // - The waiting thread is not actually waiting on the // condition variable so we have to record that it // should be woken when the interrupt handler returns. // To that end, we flag the thread as interrupted around // the interrupt and check state_ when the interrupt // handler returns. A futexWake() call that reaches the // runtime during the interrupt sets state_ to woken. // // - It is in principle possible for futexWait() to be // reentered on the same thread/runtime and waiting on the // same location and to yet again be interrupted and enter // the interrupt handler. In this case, it is important // that when another agent wakes waiters, all waiters using // the same runtime on the same location are woken in LIFO // order; FIFO may be the required order, but FIFO would // fail to wake up the innermost call. Interrupts are // outside any spec anyway. Also, several such suspended // waiters may be woken at a time. // // For the time being we disallow waiting from within code // that runs from within an interrupt handler; this may // occasionally (very rarely) be surprising but is // expedient. Other solutions exist, see bug #1131943. The // code that performs the check is above, at the head of // this function. state_ = WaitingInterrupted; { AutoUnlockFutexAPI unlock; retval = cx->runtime()->handleInterrupt(cx); } if (!retval) goto finished; if (state_ == Woken) { *result = AtomicsObject::FutexOK; goto finished; } break; default: MOZ_CRASH(); } } finished: state_ = Idle; return retval; } void js::FutexRuntime::wake(WakeReason reason) { MOZ_ASSERT(lockHolder_ == PR_GetCurrentThread()); MOZ_ASSERT(isWaiting()); if (state_ == WaitingInterrupted && reason == WakeExplicit) { state_ = Woken; return; } switch (reason) { case WakeExplicit: state_ = Woken; break; case WakeForJSInterrupt: state_ = WokenForJSInterrupt; break; default: MOZ_CRASH(); } PR_NotifyCondVar(cond_); } const JSFunctionSpec AtomicsMethods[] = { JS_FN("compareExchange", atomics_compareExchange, 4,0), JS_FN("load", atomics_load, 2,0), JS_FN("store", atomics_store, 3,0), JS_FN("fence", atomics_fence, 0,0), JS_FN("add", atomics_add, 3,0), JS_FN("sub", atomics_sub, 3,0), JS_FN("and", atomics_and, 3,0), JS_FN("or", atomics_or, 3,0), JS_FN("xor", atomics_xor, 3,0), JS_FN("futexWait", atomics_futexWait, 4,0), JS_FN("futexWake", atomics_futexWake, 3,0), JS_FN("futexWakeOrRequeue", atomics_futexWakeOrRequeue, 5,0), JS_FS_END }; static const JSConstDoubleSpec AtomicsConstants[] = { {"OK", AtomicsObject::FutexOK}, {"TIMEDOUT", AtomicsObject::FutexTimedout}, {"NOTEQUAL", AtomicsObject::FutexNotequal}, {0, 0} }; JSObject* AtomicsObject::initClass(JSContext* cx, Handle<GlobalObject*> global) { // Create Atomics Object. RootedObject objProto(cx, global->getOrCreateObjectPrototype(cx)); if (!objProto) return nullptr; RootedObject Atomics(cx, NewObjectWithGivenProto(cx, &AtomicsObject::class_, objProto, global, SingletonObject)); if (!Atomics) return nullptr; if (!JS_DefineFunctions(cx, Atomics, AtomicsMethods)) return nullptr; if (!JS_DefineConstDoubles(cx, Atomics, AtomicsConstants)) return nullptr; RootedValue AtomicsValue(cx, ObjectValue(*Atomics)); // Everything is set up, install Atomics on the global object. if (!DefineProperty(cx, global, cx->names().Atomics, AtomicsValue, nullptr, nullptr, 0)) return nullptr; global->setConstructor(JSProto_Atomics, AtomicsValue); return Atomics; } JSObject* js_InitAtomicsClass(JSContext* cx, HandleObject obj) { MOZ_ASSERT(obj->is<GlobalObject>()); Rooted<GlobalObject*> global(cx, &obj->as<GlobalObject>()); return AtomicsObject::initClass(cx, global); } #undef CXX11_ATOMICS #undef GNU_ATOMICS
39,398
14,205
/* Author: Gudakov Ramil Sergeevich a.k.a. Gauss Гудаков Рамиль Сергеевич Contacts: [ramil2085@mail.ru, ramil2085@gmail.com] See for more information LICENSE.md. */ #include "DialogBuilderSystem.h" #include <ImGuiWidgets/include/Dialog.h> #include "Modules.h" #include "GraphicEngineModule.h" #include "PositionComponent.h" #include "SizeComponent.h" #include "TitleComponent.h" #include "PrefabOriginalGuidComponent.h" #include "SceneOriginalGuidComponent.h" #include "DialogCloseEventHandlerComponent.h" #include "HandlerLinkHelper.h" #include "UnitBuilderHelper.h" #include "FrameMouseClickHandlerComponent.h" using namespace nsGraphicWrapper; using namespace nsGuiWrapper; void TDialogBuilderSystem::Reactive(nsECSFramework::TEntityID eid, const nsGuiWrapper::TDialogComponent* pDialogComponent) { auto dialogStack = nsTornadoEngine::Modules()->G()->GetDialogStack(); dialogStack->Add(pDialogComponent->value); auto entMng = GetEntMng(); TUnitBuilderHelper::SetupWidget(entMng, eid, pDialogComponent->value); TUnitBuilderHelper::SetupGeometry(entMng, eid, pDialogComponent->value); auto handlerCallCollector = nsTornadoEngine::Modules()->HandlerCalls(); pDialogComponent->value->mOnShowCB.Register(pDialogComponent->value, [entMng, handlerCallCollector, eid, pDialogComponent](bool isShown) { if (isShown) { return; } auto handlers = THandlerLinkHelper::FindHandlers<TDialogCloseEventHandlerComponent>(entMng, eid, pDialogComponent); for (auto& pHandler : handlers) { handlerCallCollector->Add([pHandler, eid, pDialogComponent]() { pHandler->handler->Handle(eid, pDialogComponent); }); } }); THandlerLinkHelper::RegisterMouseKey(entMng, eid, pDialogComponent); }
1,895
600
#include "../../TensorShaderAvxBackend.h" using namespace System; void quaternion_purek(unsigned int length, float* srck_ptr, float* dst_ptr) { for (unsigned int i = 0, j = 0; i < length; i += 4, j++) { dst_ptr[i + 3] = srck_ptr[j]; dst_ptr[i + 0] = dst_ptr[i + 1] = dst_ptr[i + 2] = 0; } } void TensorShaderAvxBackend::Quaternion::PureK(unsigned int length, AvxArray<float>^ src_k, AvxArray<float>^ dst) { Util::CheckDuplicateArray(src_k, dst); if (length % 4 != 0) { throw gcnew System::ArgumentException(); } Util::CheckLength(length / 4, src_k); Util::CheckLength(length, dst); float* srck_ptr = (float*)(src_k->Ptr.ToPointer()); float* dst_ptr = (float*)(dst->Ptr.ToPointer()); quaternion_purek(length, srck_ptr, dst_ptr); }
801
322
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include "caf/async/consumer.hpp" #include "caf/async/producer.hpp" #include "caf/async/spsc_buffer.hpp" #include "caf/cow_tuple.hpp" #include "caf/cow_vector.hpp" #include "caf/defaults.hpp" #include "caf/detail/core_export.hpp" #include "caf/detail/unordered_flat_map.hpp" #include "caf/disposable.hpp" #include "caf/flow/coordinated.hpp" #include "caf/flow/coordinator.hpp" #include "caf/flow/fwd.hpp" #include "caf/flow/observable_decl.hpp" #include "caf/flow/observable_state.hpp" #include "caf/flow/observer.hpp" #include "caf/flow/op/base.hpp" #include "caf/flow/op/concat.hpp" #include "caf/flow/op/from_resource.hpp" #include "caf/flow/op/from_steps.hpp" #include "caf/flow/op/merge.hpp" #include "caf/flow/op/prefetch.hpp" #include "caf/flow/op/publish.hpp" #include "caf/flow/step/all.hpp" #include "caf/flow/subscription.hpp" #include "caf/intrusive_ptr.hpp" #include "caf/logger.hpp" #include "caf/make_counted.hpp" #include "caf/ref_counted.hpp" #include "caf/sec.hpp" #include <cstddef> #include <functional> #include <numeric> #include <type_traits> #include <vector> namespace caf::flow { // -- connectable -------------------------------------------------------------- /// Resembles a regular @ref observable, except that it does not begin emitting /// items when it is subscribed to. Only after calling `connect` will the /// `connectable` start to emit items. template <class T> class connectable { public: /// The type of emitted items. using output_type = T; /// The pointer-to-implementation type. using pimpl_type = intrusive_ptr<op::publish<T>>; explicit connectable(pimpl_type pimpl) noexcept : pimpl_(std::move(pimpl)) { // nop } connectable& operator=(std::nullptr_t) noexcept { pimpl_.reset(); return *this; } connectable() noexcept = default; connectable(connectable&&) noexcept = default; connectable(const connectable&) noexcept = default; connectable& operator=(connectable&&) noexcept = default; connectable& operator=(const connectable&) noexcept = default; /// Returns an @ref observable that automatically connects to this /// `connectable` when reaching `subscriber_threshold` subscriptions. observable<T> auto_connect(size_t subscriber_threshold = 1) & { auto ptr = make_counted<op::publish<T>>(ctx(), pimpl_); ptr->auto_connect_threshold(subscriber_threshold); return observable<T>{ptr}; } /// Similar to the `lvalue` overload, but converts this `connectable` directly /// if possible, thus saving one hop on the pipeline. observable<T> auto_connect(size_t subscriber_threshold = 1) && { if (pimpl_->unique() && !pimpl_->connected()) { pimpl_->auto_connect_threshold(subscriber_threshold); return observable<T>{std::move(pimpl_)}; } else { auto ptr = make_counted<op::publish<T>>(ctx(), pimpl_); ptr->auto_connect_threshold(subscriber_threshold); return observable<T>{ptr}; } } /// Returns an @ref observable that automatically connects to this /// `connectable` when reaching `subscriber_threshold` subscriptions and /// disconnects automatically after the last subscriber canceled its /// subscription. /// @note The threshold only applies to the initial connect, not to any /// re-connects. observable<T> ref_count(size_t subscriber_threshold = 1) & { auto ptr = make_counted<op::publish<T>>(ctx(), pimpl_); ptr->auto_connect_threshold(subscriber_threshold); ptr->auto_disconnect(true); return observable<T>{ptr}; } /// Similar to the `lvalue` overload, but converts this `connectable` directly /// if possible, thus saving one hop on the pipeline. observable<T> ref_count(size_t subscriber_threshold = 1) && { if (pimpl_->unique() && !pimpl_->connected()) { pimpl_->auto_connect_threshold(subscriber_threshold); pimpl_->auto_disconnect(true); return observable<T>{std::move(pimpl_)}; } else { auto ptr = make_counted<op::publish<T>>(ctx(), pimpl_); ptr->auto_connect_threshold(subscriber_threshold); ptr->auto_disconnect(true); return observable<T>{ptr}; } } /// Connects to the source @ref observable, thus starting to emit items. disposable connect() { return pimpl_->connect(); } /// @copydoc observable::compose template <class Fn> auto compose(Fn&& fn) && { return fn(std::move(*this)); } template <class... Ts> disposable subscribe(Ts&&... xs) { return as_observable().subscribe(std::forward<Ts>(xs)...); } observable<T> as_observable() const& { return observable<T>{pimpl_}; } observable<T> as_observable() && { return observable<T>{std::move(pimpl_)}; } const pimpl_type& pimpl() const noexcept { return pimpl_; } bool valid() const noexcept { return pimpl_ != nullptr; } explicit operator bool() const noexcept { return valid(); } bool operator!() const noexcept { return !valid(); } void swap(connectable& other) { pimpl_.swap(other.pimpl_); } /// @pre `valid()` coordinator* ctx() const { return pimpl_->ctx(); } private: pimpl_type pimpl_; }; /// Captures the *definition* of an observable that has not materialized yet. template <class Materializer, class... Steps> class observable_def { public: using output_type = output_type_t<Materializer, Steps...>; observable_def() = delete; observable_def(const observable_def&) = delete; observable_def& operator=(const observable_def&) = delete; observable_def(observable_def&&) = default; observable_def& operator=(observable_def&&) = default; template <size_t N = sizeof...(Steps), class = std::enable_if_t<N == 0>> explicit observable_def(Materializer&& materializer) : materializer_(std::move(materializer)) { // nop } observable_def(Materializer&& materializer, std::tuple<Steps...>&& steps) : materializer_(std::move(materializer)), steps_(std::move(steps)) { // nop } /// @copydoc observable::transform template <class NewStep> observable_def<Materializer, Steps..., NewStep> transform(NewStep step) && { return add_step(std::move(step)); } /// @copydoc observable::compose template <class Fn> auto compose(Fn&& fn) && { return fn(std::move(*this)); } /// @copydoc observable::skip auto skip(size_t n) && { return add_step(step::skip<output_type>{n}); } /// @copydoc observable::take auto take(size_t n) && { return add_step(step::take<output_type>{n}); } template <class Predicate> auto filter(Predicate predicate) && { return add_step(step::filter<Predicate>{std::move(predicate)}); } template <class Predicate> auto take_while(Predicate predicate) && { return add_step(step::take_while<Predicate>{std::move(predicate)}); } template <class Init, class Reducer> auto reduce(Init init, Reducer reducer) && { using val_t = output_type; static_assert(std::is_invocable_r_v<Init, Reducer, Init&&, const val_t&>); return add_step(step::reduce<Reducer>{std::move(init), std::move(reducer)}); } auto sum() && { return std::move(*this).reduce(output_type{}, std::plus<output_type>{}); } auto to_vector() && { using vector_type = cow_vector<output_type>; auto append = [](vector_type&& xs, const output_type& x) { xs.unshared().push_back(x); return xs; }; return std::move(*this) .reduce(vector_type{}, append) .filter([](const vector_type& xs) { return !xs.empty(); }); } auto distinct() && { return add_step(step::distinct<output_type>{}); } template <class F> auto map(F f) && { return add_step(step::map<F>{std::move(f)}); } template <class F> auto do_on_next(F f) && { return add_step(step::do_on_next<F>{std::move(f)}); } template <class F> auto do_on_complete(F f) && { return add_step(step::do_on_complete<output_type, F>{std::move(f)}); } template <class F> auto do_on_error(F f) && { return add_step(step::do_on_error<output_type, F>{std::move(f)}); } template <class F> auto do_finally(F f) && { return add_step(step::do_finally<output_type, F>{std::move(f)}); } auto on_error_complete() { return add_step(step::on_error_complete<output_type>{}); } /// Materializes the @ref observable. observable<output_type> as_observable() && { return materialize(); } /// @copydoc observable::for_each template <class OnNext> auto for_each(OnNext on_next) && { return materialize().for_each(std::move(on_next)); } /// @copydoc observable::merge template <class... Inputs> auto merge(Inputs&&... xs) && { return materialize().merge(std::forward<Inputs>(xs)...); } /// @copydoc observable::concat template <class... Inputs> auto concat(Inputs&&... xs) && { return materialize().concat(std::forward<Inputs>(xs)...); } /// @copydoc observable::flat_map template <class F> auto flat_map(F f) && { return materialize().flat_map(std::move(f)); } /// @copydoc observable::concat_map template <class F> auto concat_map(F f) && { return materialize().concat_map(std::move(f)); } /// @copydoc observable::publish auto publish() && { return materialize().publish(); } /// @copydoc observable::share auto share(size_t subscriber_threshold = 1) && { return materialize().share(subscriber_threshold); } /// @copydoc observable::prefix_and_tail observable<cow_tuple<cow_vector<output_type>, observable<output_type>>> prefix_and_tail(size_t prefix_size) && { return materialize().prefix_and_tail(prefix_size); } /// @copydoc observable::head_and_tail observable<cow_tuple<output_type, observable<output_type>>> head_and_tail() && { return materialize().head_and_tail(); } /// @copydoc observable::subscribe template <class Out> disposable subscribe(Out&& out) && { return materialize().subscribe(std::forward<Out>(out)); } /// @copydoc observable::to_resource async::consumer_resource<output_type> to_resource() && { return materialize().to_resource(); } /// @copydoc observable::to_resource async::consumer_resource<output_type> to_resource(size_t buffer_size, size_t min_request_size) && { return materialize().to_resource(buffer_size, min_request_size); } /// @copydoc observable::observe_on observable<output_type> observe_on(coordinator* other) && { return materialize().observe_on(other); } /// @copydoc observable::observe_on observable<output_type> observe_on(coordinator* other, size_t buffer_size, size_t min_request_size) && { return materialize().observe_on(other, buffer_size, min_request_size); } bool valid() const noexcept { return materializer_.valid(); } private: template <class NewStep> observable_def<Materializer, Steps..., NewStep> add_step(NewStep step) { static_assert(std::is_same_v<output_type, typename NewStep::input_type>); return {std::move(materializer_), std::tuple_cat(std::move(steps_), std::make_tuple(std::move(step)))}; } observable<output_type> materialize() { return std::move(materializer_).materialize(std::move(steps_)); } /// Encapsulates logic for allocating a flow operator. Materializer materializer_; /// Stores processing steps that the materializer fuses into a single flow /// operator. std::tuple<Steps...> steps_; }; // -- transformation ----------------------------------------------------------- /// Materializes an @ref observable from a source @ref observable and one or /// more processing steps. template <class Input> class transformation_materializer { public: using output_type = Input; explicit transformation_materializer(observable<Input> source) : source_(std::move(source).pimpl()) { // nop } explicit transformation_materializer(intrusive_ptr<op::base<Input>> source) : source_(std::move(source)) { // nop } transformation_materializer() = delete; transformation_materializer(const transformation_materializer&) = delete; transformation_materializer& operator=(const transformation_materializer&) = delete; transformation_materializer(transformation_materializer&&) = default; transformation_materializer& operator=(transformation_materializer&&) = default; bool valid() const noexcept { return source_ != nullptr; } coordinator* ctx() { return source_->ctx(); } template <class Step, class... Steps> auto materialize(std::tuple<Step, Steps...>&& steps) && { using impl_t = op::from_steps<Input, Step, Steps...>; return make_observable<impl_t>(ctx(), source_, std::move(steps)); } private: intrusive_ptr<op::base<Input>> source_; }; // -- observable: subscribing -------------------------------------------------- template <class T> disposable observable<T>::subscribe(observer<T> what) { if (pimpl_) { return pimpl_->subscribe(std::move(what)); } else { what.on_error(make_error(sec::invalid_observable)); return disposable{}; } } template <class T> disposable observable<T>::subscribe(async::producer_resource<T> resource) { using buffer_type = typename async::consumer_resource<T>::buffer_type; using adapter_type = buffer_writer_impl<buffer_type>; if (auto buf = resource.try_open()) { CAF_LOG_DEBUG("subscribe producer resource to flow"); auto adapter = make_counted<adapter_type>(pimpl_->ctx(), buf); buf->set_producer(adapter); auto obs = adapter->as_observer(); auto sub = subscribe(std::move(obs)); pimpl_->ctx()->watch(sub); return sub; } else { CAF_LOG_DEBUG("failed to open producer resource"); return {}; } } template <class T> template <class OnNext> disposable observable<T>::for_each(OnNext on_next) { return subscribe(make_observer(std::move(on_next))); } // -- observable: transforming ------------------------------------------------- template <class T> template <class Step> transformation<Step> observable<T>::transform(Step step) { static_assert(std::is_same_v<typename Step::input_type, T>, "step object does not match the input type"); return {transformation_materializer<T>{pimpl()}, std::move(step)}; } template <class T> template <class U> transformation<step::distinct<U>> observable<T>::distinct() { static_assert(detail::is_complete<std::hash<U>>, "distinct uses a hash set and thus requires std::hash<T>"); return transform(step::distinct<U>{}); } template <class T> template <class F> transformation<step::do_finally<T, F>> observable<T>::do_finally(F fn) { return transform(step::do_finally<T, F>{std::move(fn)}); } template <class T> template <class F> transformation<step::do_on_complete<T, F>> observable<T>::do_on_complete(F fn) { return transform(step::do_on_complete<T, F>{std::move(fn)}); } template <class T> template <class F> transformation<step::do_on_error<T, F>> observable<T>::do_on_error(F fn) { return transform(step::do_on_error<T, F>{std::move(fn)}); } template <class T> template <class F> transformation<step::do_on_next<F>> observable<T>::do_on_next(F fn) { return transform(step::do_on_next<F>{std::move(fn)}); } template <class T> template <class Predicate> transformation<step::filter<Predicate>> observable<T>::filter(Predicate predicate) { return transform(step::filter{std::move(predicate)}); } template <class T> template <class F> transformation<step::map<F>> observable<T>::map(F f) { return transform(step::map(std::move(f))); } template <class T> transformation<step::on_error_complete<T>> observable<T>::on_error_complete() { return transform(step::on_error_complete<T>{}); } template <class T> template <class Init, class Reducer> transformation<step::reduce<Reducer>> observable<T>::reduce(Init init, Reducer reducer) { static_assert(std::is_invocable_r_v<Init, Reducer, Init&&, const T&>); return transform(step::reduce<Reducer>{std::move(init), std::move(reducer)}); } template <class T> transformation<step::skip<T>> observable<T>::skip(size_t n) { return transform(step::skip<T>{n}); } template <class T> transformation<step::take<T>> observable<T>::take(size_t n) { return transform(step::take<T>{n}); } template <class T> template <class Predicate> transformation<step::take_while<Predicate>> observable<T>::take_while(Predicate predicate) { return transform(step::take_while{std::move(predicate)}); } // -- observable: combining ---------------------------------------------------- template <class T> template <class Out, class... Inputs> auto observable<T>::merge(Inputs&&... xs) { if constexpr (is_observable_v<Out>) { using value_t = output_type_t<Out>; using impl_t = op::merge<value_t>; return make_observable<impl_t>(ctx(), *this, std::forward<Inputs>(xs)...); } else { static_assert( sizeof...(Inputs) > 0, "merge without arguments expects this observable to emit observables"); using impl_t = op::merge<Out>; return make_observable<impl_t>(ctx(), *this, std::forward<Inputs>(xs)...); } } template <class T> template <class Out, class... Inputs> auto observable<T>::concat(Inputs&&... xs) { if constexpr (is_observable_v<Out>) { using value_t = output_type_t<Out>; using impl_t = op::concat<value_t>; return make_observable<impl_t>(ctx(), *this, std::forward<Inputs>(xs)...); } else { static_assert( sizeof...(Inputs) > 0, "merge without arguments expects this observable to emit observables"); using impl_t = op::concat<Out>; return make_observable<impl_t>(ctx(), *this, std::forward<Inputs>(xs)...); } } template <class T> template <class Out, class F> auto observable<T>::flat_map(F f) { using res_t = decltype(f(std::declval<const Out&>())); if constexpr (is_observable_v<res_t>) { return map([fn = std::move(f)](const Out& x) mutable { return fn(x).as_observable(); }) .merge(); } else if constexpr (detail::is_optional_v<res_t>) { return map([fn = std::move(f)](const Out& x) mutable { return fn(x); }) .filter([](const res_t& x) { return x.has_value(); }) .map([](const res_t& x) { return *x; }); } else { // Here, we dispatch to concat() instead of merging the containers. Merged // output is probably not what anyone would expect and since the values are // all available immediately, there is no good reason to mess up the emitted // order of values. static_assert(detail::is_iterable_v<res_t>); return map([cptr = ctx(), fn = std::move(f)](const Out& x) mutable { return cptr->make_observable().from_container(fn(x)); }) .concat(); } } template <class T> template <class Out, class F> auto observable<T>::concat_map(F f) { using res_t = decltype(f(std::declval<const Out&>())); if constexpr (is_observable_v<res_t>) { return map([fn = std::move(f)](const Out& x) mutable { return fn(x).as_observable(); }) .concat(); } else if constexpr (detail::is_optional_v<res_t>) { return map([fn = std::move(f)](const Out& x) mutable { return fn(x); }) .filter([](const res_t& x) { return x.has_value(); }) .map([](const res_t& x) { return *x; }); } else { static_assert(detail::is_iterable_v<res_t>); return map([cptr = ctx(), fn = std::move(f)](const Out& x) mutable { return cptr->make_observable().from_container(fn(x)); }) .concat(); } } // -- observable: splitting ---------------------------------------------------- template <class T> observable<cow_tuple<cow_vector<T>, observable<T>>> observable<T>::prefix_and_tail(size_t n) { using vector_t = cow_vector<T>; CAF_ASSERT(n > 0); auto do_prefetch = [](auto in) { auto ptr = op::prefetch<T>::apply(std::move(in).as_observable().pimpl()); return observable<T>{std::move(ptr)}; }; auto split = share(2); auto tail = split.skip(n).compose(do_prefetch); return split // .take(n) .to_vector() .filter([n](const vector_t& xs) { return xs.size() == n; }) .map([tail](const vector_t& xs) { return make_cow_tuple(xs, tail); }) .as_observable(); } template <class T> observable<cow_tuple<T, observable<T>>> observable<T>::head_and_tail() { auto do_prefetch = [](auto in) { auto ptr = op::prefetch<T>::apply(std::move(in).as_observable().pimpl()); return observable<T>{std::move(ptr)}; }; auto split = share(2); auto tail = split.skip(1).compose(do_prefetch); return split // .take(1) .map([tail](const T& x) { return make_cow_tuple(x, tail); }) .as_observable(); } // -- observable: multicasting ------------------------------------------------- template <class T> connectable<T> observable<T>::publish() { return connectable<T>{make_counted<op::publish<T>>(ctx(), pimpl_)}; } template <class T> observable<T> observable<T>::share(size_t subscriber_threshold) { return publish().ref_count(subscriber_threshold); } // -- observable: observing ---------------------------------------------------- template <class T> observable<T> observable<T>::observe_on(coordinator* other, size_t buffer_size, size_t min_request_size) { auto [pull, push] = async::make_spsc_buffer_resource<T>(buffer_size, min_request_size); subscribe(push); return make_observable<op::from_resource<T>>(other, std::move(pull)); } // -- observable: converting --------------------------------------------------- template <class T> async::consumer_resource<T> observable<T>::to_resource(size_t buffer_size, size_t min_request_size) { using buffer_type = async::spsc_buffer<T>; auto buf = make_counted<buffer_type>(buffer_size, min_request_size); auto up = make_counted<buffer_writer_impl<buffer_type>>(pimpl_->ctx(), buf); buf->set_producer(up); subscribe(up->as_observer()); return async::consumer_resource<T>{std::move(buf)}; } } // namespace caf::flow
22,278
7,398
// Copyright (c) 2019 London Trust Media Incorporated // // This file is part of the Private Internet Access Desktop Client. // // The Private Internet Access Desktop Client is free software: you can // redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. // // The Private Internet Access Desktop Client is distributed in the hope that // it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with the Private Internet Access Desktop Client. If not, see // <https://www.gnu.org/licenses/>. #include "common.h" #line SOURCE_FILE("win/win_main.cpp") #if defined(PIA_CLIENT) || defined(UNIT_TEST) // Entry point shouldn't be included for these projects void dummyWinMain() {} #else #include "win_console.h" #include "win_service.h" #include "path.h" #include "win.h" #include <QTextStream> int main(int argc, char** argv) { setUtf8LocaleCodec(); Logger::initialize(true); FUNCTION_LOGGING_CATEGORY("win.main"); if (HRESULT error = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED)) qFatal("CoInitializeEx failed with error 0x%08x.", error); if (HRESULT error = ::CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL)) qFatal("CoInitializeSecurity failed with error 0x%08x.", error); switch (WinService::tryRun()) { case WinService::SuccessfullyLaunched: return 0; case WinService::AlreadyRunning: qCritical("Service is already running"); return 1; case WinService::RunningAsConsole: try { Path::initializePreApp(); QCoreApplication app(argc, argv); Path::initializePostApp(); return WinConsole().run(); } catch (const Error& error) { qCritical(error); return 1; } } } #endif
2,230
708
#include "Math.h" ////////////////////////////////////////////////// float Distance(point2 a, point2 b) { const float x = b.x - a.x; const float y = b.y - a.y; const float result = sqrtf(x * x + y * y); return result; } void SimpleCompress(float3 &outColor) { outColor.x /= (1.0f + outColor.x); outColor.y /= (1.0f + outColor.y); outColor.z /= (1.0f + outColor.z); } void Clamp(float3 & outColor) { if (outColor.x > 1.0f) outColor.x = 1.0f; if (outColor.y > 1.0f) outColor.y = 1.0f; if (outColor.z > 1.0f) outColor.z = 1.0f; } void ClampMinMax(float & a) { if (a > 1.0f) a = 1.0f; else if (a < 0.0f) a = 0.0f; } inline vec3 rotate_x(vec3 v, float sin_ang, float cos_ang) { return vec3( v.x, (v.y * cos_ang) + (v.z * sin_ang), (v.z * cos_ang) - (v.y * sin_ang) ); } inline vec3 rotate_y(vec3 v, float sin_ang, float cos_ang) { return vec3( (v.x * cos_ang) + (v.z * sin_ang), v.y, (v.z * cos_ang) - (v.x * sin_ang) ); } float dot(const vec2 & u, const vec2 & v) { return { u.x*v.x + u.y*v.y }; } vec2 VectorFromPoint(const point2 & a, const point2 & b) { return { a.x - b.x, a.y - b.y }; } vec2 NormalToVect(const vec2 & a) { return { a.y * (-1.0f), a.x }; }
1,232
592
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qbs. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "tst_api.h" #include "../shared.h" #include <api/runenvironment.h> #include <qbs.h> #include <tools/fileinfo.h> #include <tools/hostosinfo.h> #include <tools/qttools.h> #include <tools/set.h> #include <tools/toolchains.h> #include <QtCore/qcoreapplication.h> #include <QtCore/qdir.h> #include <QtCore/qeventloop.h> #include <QtCore/qfile.h> #include <QtCore/qfileinfo.h> #include <QtCore/qstringlist.h> #include <QtCore/qthread.h> #include <QtCore/qtimer.h> #include <QtTest/qtest.h> #include <algorithm> #include <functional> #include <memory> #include <regex> #include <utility> #include <vector> #define VERIFY_NO_ERROR(errorInfo) \ QVERIFY2(!errorInfo.hasError(), qPrintable(errorInfo.toString())) #define WAIT_FOR_NEW_TIMESTAMP() waitForNewTimestamp(m_workingDataDir) class LogSink: public qbs::ILogSink { public: QString output; void doPrintWarning(const qbs::ErrorInfo &error) { qDebug("%s", qPrintable(error.toString())); warnings.push_back(error); } void doPrintMessage(qbs::LoggerLevel, const QString &message, const QString &) { output += message; } QList<qbs::ErrorInfo> warnings; }; class BuildDescriptionReceiver : public QObject { Q_OBJECT public: QString descriptions; QStringList descriptionLines; void handleDescription(const QString &, const QString &description) { descriptions += description; descriptionLines << description; } }; class ProcessResultReceiver : public QObject { Q_OBJECT public: QString output; std::vector<qbs::ProcessResult> results; void handleProcessResult(const qbs::ProcessResult &result) { results.push_back(result); output += result.stdErr().join(QLatin1Char('\n')); output += result.stdOut().join(QLatin1Char('\n')); } }; class TaskReceiver : public QObject { Q_OBJECT public: QString taskDescriptions; void handleTaskStart(const QString &task) { taskDescriptions += task; } }; static void removeBuildDir(const qbs::SetupProjectParameters &params) { QString message; const QString dir = params.buildRoot() + '/' + params.configurationName(); if (!qbs::Internal::removeDirectoryWithContents(dir, &message)) qFatal("Could not remove build dir: %s", qPrintable(message)); } static bool waitForFinished(qbs::AbstractJob *job, int timeout = 0) { if (job->state() == qbs::AbstractJob::StateFinished) return true; QEventLoop loop; QObject::connect(job, &qbs::AbstractJob::finished, &loop, &QEventLoop::quit); if (timeout > 0) { QTimer timer; QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); timer.setSingleShot(true); timer.start(timeout); loop.exec(); return timer.isActive(); // Timer ended the loop <=> job did not finish. } loop.exec(); return true; } TestApi::TestApi() : m_logSink(new LogSink) , m_sourceDataDir(QDir::cleanPath(SRCDIR "/testdata")) , m_workingDataDir(testWorkDir(QStringLiteral("api"))) { } TestApi::~TestApi() { delete m_logSink; } void TestApi::initTestCase() { QString errorMessage; qbs::Internal::removeDirectoryWithContents(m_workingDataDir, &errorMessage); QVERIFY2(qbs::Internal::copyFileRecursion(m_sourceDataDir, m_workingDataDir, false, true, &errorMessage), qPrintable(errorMessage)); QVERIFY(copyDllExportHeader(m_sourceDataDir, m_workingDataDir)); } void TestApi::init() { m_logSink->warnings.clear(); m_logSink->setLogLevel(qbs::LoggerInfo); } void TestApi::addQObjectMacroToCppFile() { BuildDescriptionReceiver receiver; qbs::ErrorInfo errorInfo = doBuildProject("add-qobject-macro-to-cpp-file", &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY2(!receiver.descriptions.contains("moc"), qPrintable(receiver.descriptions)); receiver.descriptions.clear(); WAIT_FOR_NEW_TIMESTAMP(); QFile cppFile("object.cpp"); QVERIFY2(cppFile.open(QIODevice::ReadWrite), qPrintable(cppFile.errorString())); QByteArray contents = cppFile.readAll(); contents.replace("// ", ""); cppFile.resize(0); cppFile.write(contents); cppFile.close(); errorInfo = doBuildProject("add-qobject-macro-to-cpp-file", &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY2(receiver.descriptions.contains("moc"), qPrintable(receiver.descriptions)); } static bool isAboutUndefinedSymbols(const QString &_message) { const QString message = _message.toLower(); return message.contains("undefined") || message.contains("unresolved"); } void TestApi::addedFilePersistent() { // On the initial run, linking will fail. const QString relProjectFilePath = "added-file-persistent"; ProcessResultReceiver receiver; qbs::ErrorInfo errorInfo = doBuildProject(relProjectFilePath, 0, &receiver); QVERIFY(errorInfo.hasError()); QVERIFY2(isAboutUndefinedSymbols(receiver.output), qPrintable((receiver.output))); receiver.output.clear(); // Add a file. qbs must schedule it for rule application on the next build. WAIT_FOR_NEW_TIMESTAMP(); const qbs::SetupProjectParameters params = defaultSetupParameters(relProjectFilePath); QFile projectFile(params.projectFilePath()); QVERIFY2(projectFile.open(QIODevice::ReadWrite), qPrintable(projectFile.errorString())); const QByteArray originalContent = projectFile.readAll(); QByteArray addedFileContent = originalContent; addedFileContent.replace("/* 'file.cpp' */", "'file.cpp'"); projectFile.resize(0); projectFile.write(addedFileContent); projectFile.flush(); std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(params, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); setupJob.reset(nullptr); // Remove the file again. qbs must unschedule the rule application again. // Consequently, the linking step must fail as in the initial run. WAIT_FOR_NEW_TIMESTAMP(); projectFile.resize(0); projectFile.write(originalContent); projectFile.flush(); errorInfo = doBuildProject(relProjectFilePath, 0, &receiver); QVERIFY(errorInfo.hasError()); QVERIFY2(isAboutUndefinedSymbols(receiver.output), qPrintable((receiver.output))); // Add the file again. qbs must schedule it for rule application on the next build. WAIT_FOR_NEW_TIMESTAMP(); projectFile.resize(0); projectFile.write(addedFileContent); projectFile.close(); setupJob.reset(qbs::Project().setupProject(params, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); setupJob.reset(nullptr); // qbs must remember that a file was scheduled for rule application. The build must then // succeed, as now all necessary symbols are linked in. errorInfo = doBuildProject(relProjectFilePath); VERIFY_NO_ERROR(errorInfo); } void TestApi::baseProperties() { const qbs::ErrorInfo errorInfo = doBuildProject("base-properties/prj.qbs"); VERIFY_NO_ERROR(errorInfo); } void TestApi::buildGraphInfo() { SettingsPtr s = settings(); qbs::Internal::TemporaryProfile p("bgInfoProfile", s.get()); p.p.setValue("qbs.targetPlatform", "xenix"); qbs::SetupProjectParameters setupParams = defaultSetupParameters("buildgraph-info"); setupParams.setTopLevelProfile(p.p.name()); setupParams.setOverriddenValues({std::make_pair("qbs.architecture", "arm")}); std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); const QString bgFilePath = setupParams.buildRoot() + QLatin1Char('/') + relativeBuildGraphFilePath(); QVERIFY2(QFileInfo::exists(bgFilePath), qPrintable(bgFilePath)); qbs::Project::BuildGraphInfo bgInfo = qbs::Project::getBuildGraphInfo(bgFilePath, QStringList()); QVERIFY(bgInfo.error.hasError()); // Build graph is still locked. setupJob.reset(nullptr); const QStringList requestedProperties({"qbs.architecture", "qbs.shellPath", "qbs.targetPlatform"}); bgInfo = qbs::Project::getBuildGraphInfo(bgFilePath, requestedProperties); QVERIFY2(!bgInfo.error.hasError(), qPrintable(bgInfo.error.toString())); QCOMPARE(bgFilePath, bgInfo.bgFilePath); QCOMPARE(bgInfo.profileData.size(), 1); QCOMPARE(bgInfo.profileData.value(p.p.name()).toMap().size(), 1); QCOMPARE(bgInfo.profileData.value(p.p.name()).toMap().value("qbs").toMap().value( "targetPlatform"), p.p.value("qbs.targetPlatform")); QCOMPARE(bgInfo.overriddenProperties, setupParams.overriddenValues()); QCOMPARE(bgInfo.requestedProperties.size(), requestedProperties.size()); QCOMPARE(bgInfo.requestedProperties.value("qbs.architecture").toString(), QString("arm")); QCOMPARE(bgInfo.requestedProperties.value("qbs.shellPath").toString(), QString("/bin/bash")); QCOMPARE(bgInfo.requestedProperties.value("qbs.targetPlatform").toString(), QString("xenix")); } void TestApi::buildErrorCodeLocation() { const qbs::ErrorInfo errorInfo = doBuildProject("build-error-code-location/build-error-code-location.qbs"); QVERIFY(errorInfo.hasError()); const qbs::ErrorItem errorItem = errorInfo.items().front(); QCOMPARE(errorItem.description(), QString("Rule.outputArtifacts must return an array of objects.")); const qbs::CodeLocation errorLoc = errorItem.codeLocation(); QCOMPARE(QFileInfo(errorLoc.filePath()).fileName(), QString("build-error-code-location.qbs")); QCOMPARE(errorLoc.line(), 9); QCOMPARE(errorLoc.column(), 26); } void TestApi::buildGraphLocking() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("buildgraph-locking"); std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); const qbs::Project project = setupJob->project(); Q_UNUSED(project); // Case 1: Setting up a competing project from scratch. setupJob.reset(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY(setupJob->error().hasError()); QVERIFY2(setupJob->error().toString().contains("lock"), qPrintable(setupJob->error().toString())); // Case 2: Setting up a non-competing project and then making it competing. qbs::SetupProjectParameters setupParams2 = setupParams; setupParams2.setBuildRoot(setupParams.buildRoot() + "/2"); setupJob.reset(qbs::Project().setupProject(setupParams2, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); const QString buildDirName = relativeBuildDir(setupParams2.configurationName()); const QString lockFile = setupParams2.buildRoot() + '/' + buildDirName + '/' + buildDirName + ".bg.lock"; QVERIFY2(QFileInfo(lockFile).isFile(), qPrintable(lockFile)); qbs::Project project2 = setupJob->project(); QVERIFY(project2.isValid()); setupJob.reset(project2.setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY(setupJob->error().hasError()); QVERIFY2(setupJob->error().toString().contains("lock"), qPrintable(setupJob->error().toString())); QVERIFY2(QFileInfo(lockFile).isFile(), qPrintable(lockFile)); // Case 3: Changing the build directory of an existing project to something non-competing. qbs::SetupProjectParameters setupParams3 = setupParams2; setupParams3.setBuildRoot(setupParams.buildRoot() + "/3"); setupJob.reset(qbs::Project().setupProject(setupParams3, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); project2 = qbs::Project(); QVERIFY2(!QFileInfo(lockFile).exists(), qPrintable(lockFile)); const QString newLockFile = setupParams3.buildRoot() + '/' + buildDirName + '/' + buildDirName + ".bg.lock"; QVERIFY2(QFileInfo(newLockFile).isFile(), qPrintable(newLockFile)); qbs::Project project3 = setupJob->project(); QVERIFY(project3.isValid()); // Case 4: Changing the build directory again, but cancelling the job. setupJob.reset(project3.setupProject(setupParams2, m_logSink, 0)); QThread::sleep(1); setupJob->cancel(); waitForFinished(setupJob.get()); QVERIFY(setupJob->error().hasError()); QVERIFY2(!QFileInfo(lockFile).exists(), qPrintable(lockFile)); QVERIFY2(QFileInfo(newLockFile).isFile(), qPrintable(newLockFile)); setupJob.reset(nullptr); project3 = qbs::Project(); QVERIFY2(!QFileInfo(newLockFile).exists(), qPrintable(newLockFile)); } void TestApi::buildProject() { QFETCH(QString, projectSubDir); QFETCH(QString, productFileName); const QString projectFilePath = projectSubDir + QLatin1Char('/') + projectSubDir + QLatin1String(".qbs"); qbs::SetupProjectParameters params = defaultSetupParameters(projectFilePath); removeBuildDir(params); qbs::ErrorInfo errorInfo = doBuildProject(projectFilePath); VERIFY_NO_ERROR(errorInfo); QVERIFY(regularFileExists(relativeBuildGraphFilePath())); if (!productFileName.isEmpty()) { QVERIFY2(regularFileExists(productFileName), qPrintable(productFileName)); QVERIFY2(QFile::remove(productFileName), qPrintable(productFileName)); } WAIT_FOR_NEW_TIMESTAMP(); qbs::BuildOptions options; options.setForceTimestampCheck(true); errorInfo = doBuildProject(projectFilePath, 0, 0, 0, options); VERIFY_NO_ERROR(errorInfo); if (!productFileName.isEmpty()) QVERIFY2(regularFileExists(productFileName), qPrintable(productFileName)); QVERIFY(regularFileExists(relativeBuildGraphFilePath())); } void TestApi::buildProject_data() { QTest::addColumn<QString>("projectSubDir"); QTest::addColumn<QString>("productFileName"); QTest::newRow("BPs in Sources") << QString("build-properties-source") << relativeExecutableFilePath("HelloWorld"); QTest::newRow("code generator") << QString("codegen") << relativeExecutableFilePath("codegen"); QTest::newRow("link static libs") << QString("link-static-lib") << relativeExecutableFilePath("HelloWorld"); QTest::newRow("link staticlib dynamiclib") << QString("link-staticlib-dynamiclib") << relativeExecutableFilePath("app"); QTest::newRow("precompiled header new") << QString("precompiled-header-new") << relativeExecutableFilePath("MyApp"); QTest::newRow("precompiled header dynamic") << QString("precompiled-header-dynamic") << relativeExecutableFilePath("MyApp"); QTest::newRow("lots of dots") << QString("lots-of-dots") << relativeExecutableFilePath("lots.of.dots"); QTest::newRow("Qt5 plugin") << QString("qt5-plugin") << relativeProductBuildDir("echoplugin") + '/' + qbs::Internal::HostOsInfo::dynamicLibraryName("echoplugin"); QTest::newRow("Q_OBJECT in source") << QString("moc-cpp") << relativeExecutableFilePath("moc_cpp"); QTest::newRow("Q_OBJECT in header") << QString("moc-hpp") << relativeExecutableFilePath("moc_hpp"); QTest::newRow("Q_OBJECT in header, moc_XXX.cpp included") << QString("moc-hpp-included") << relativeExecutableFilePath("moc_hpp_included"); QTest::newRow("app and lib with same source file") << QString("lib-same-source") << relativeExecutableFilePath("HelloWorldApp"); QTest::newRow("source files with the same base name but different extensions") << QString("same-base-name") << relativeExecutableFilePath("basename"); QTest::newRow("static library dependencies") << QString("static-lib-deps") << relativeExecutableFilePath("staticLibDeps"); QTest::newRow("simple probes") << QString("simple-probe") << relativeExecutableFilePath("MyApp"); QTest::newRow("application without sources") << QString("app-without-sources") << relativeExecutableFilePath("appWithoutSources"); QTest::newRow("productNameWithDots") << QString("productNameWithDots") << relativeExecutableFilePath("myapp"); QTest::newRow("only default properties") << QString("two-default-property-values") << relativeProductBuildDir("two-default-property-values") + "/set"; QTest::newRow("Export item with Group") << QString("export-item-with-group") << relativeExecutableFilePath("app"); QTest::newRow("QBS-728") << QString("QBS-728") << QString(); } void TestApi::buildProjectDryRun() { QFETCH(QString, projectSubDir); QFETCH(QString, productFileName); const QString projectFilePath = projectSubDir + QLatin1Char('/') + projectSubDir + QLatin1String(".qbs"); qbs::SetupProjectParameters params = defaultSetupParameters(projectFilePath); removeBuildDir(params); qbs::BuildOptions options; options.setDryRun(true); const qbs::ErrorInfo errorInfo = doBuildProject(projectFilePath, 0, 0, 0, options); VERIFY_NO_ERROR(errorInfo); QVERIFY2(!QFileInfo::exists(relativeBuildDir()), qPrintable(QDir(relativeBuildDir()) .entryList(QDir::NoDotAndDotDot | QDir::AllEntries | QDir::System).join(", "))); } void TestApi::buildProjectDryRun_data() { return buildProject_data(); } void TestApi::buildSingleFile() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("build-single-file"); std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); qbs::Project project = setupJob->project(); qbs::BuildOptions options; options.setFilesToConsider(QStringList(setupParams.buildRoot() + "/compiled.cpp")); options.setActiveFileTags(QStringList("obj")); m_logSink->setLogLevel(qbs::LoggerMaxLevel); std::unique_ptr<qbs::BuildJob> buildJob(project.buildAllProducts(options)); BuildDescriptionReceiver receiver; connect(buildJob.get(), &qbs::BuildJob::reportCommandDescription, &receiver, &BuildDescriptionReceiver::handleDescription); waitForFinished(buildJob.get()); QVERIFY2(!buildJob->error().hasError(), qPrintable(buildJob->error().toString())); QCOMPARE(receiver.descriptions.count("compiling"), 2); QCOMPARE(receiver.descriptions.count("precompiling"), 1); QVERIFY2(receiver.descriptions.contains("generating generated.h"), qPrintable(receiver.descriptions)); QVERIFY2(receiver.descriptions.contains("compiling compiled.cpp"), qPrintable(receiver.descriptions)); } void TestApi::canonicalToolchainList() { // All the known toolchain lists should be equal QCOMPARE(qbs::canonicalToolchain(QStringList({"xcode", "clang", "llvm", "gcc"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"clang", "llvm", "gcc"})), QStringList({"clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"llvm", "gcc"})), QStringList({"llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"mingw", "gcc"})), QStringList({"mingw", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"gcc"})), QStringList({"gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"msvc"})), QStringList({"msvc"})); // Single names should canonicalize to the known lists QCOMPARE(qbs::canonicalToolchain(QStringList({"xcode"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"clang"})), QStringList({"clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"llvm"})), QStringList({"llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"mingw"})), QStringList({"mingw", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"gcc"})), QStringList({"gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"msvc"})), QStringList({"msvc"})); // Missing some in the middle QCOMPARE(qbs::canonicalToolchain(QStringList({"xcode", "llvm", "gcc"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"xcode", "clang", "gcc"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"xcode", "gcc"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"clang", "llvm"})), QStringList({"clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"clang", "gcc"})), QStringList({"clang", "llvm", "gcc"})); // Sorted wrong, missing some in the middle QCOMPARE(qbs::canonicalToolchain(QStringList({"gcc", "llvm", "clang", "xcode"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"clang", "gcc", "llvm", "xcode"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"llvm", "clang", "xcode", "gcc"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"gcc", "llvm", "clang"})), QStringList({"clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"gcc", "clang", "xcode"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"gcc", "llvm"})), QStringList({"llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"gcc", "mingw"})), QStringList({"mingw", "gcc"})); // Duplicates QCOMPARE(qbs::canonicalToolchain(QStringList({"gcc", "llvm", "clang", "xcode", "xcode", "xcode"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"clang", "gcc", "llvm", "clang", "xcode"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"llvm", "clang", "clang", "xcode", "xcode", "gcc"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"llvm", "clang", "gcc", "llvm", "clang"})), QStringList({"clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"xcode", "gcc", "clang", "gcc", "clang", "xcode"})), QStringList({"xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"llvm", "gcc", "llvm", "llvm"})), QStringList({"llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain(QStringList({"gcc", "gcc", "gcc", "mingw"})), QStringList({"mingw", "gcc"})); // Custom insanity QCOMPARE(qbs::canonicalToolchain( QStringList({"crazy", "gcc", "llvm", "clang", "xcode", "insane"})), QStringList({"crazy", "insane", "xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain( QStringList({"crazy", "gcc", "llvm", "clang", "xcode", "insane", "crazy"})), QStringList({"crazy", "insane", "xcode", "clang", "llvm", "gcc"})); QCOMPARE(qbs::canonicalToolchain( QStringList({"crazy", "insane", "gcc", "trade", "llvm", "clang", "xcode", "insane", "mark", "crazy"})), QStringList({"crazy", "insane", "trade", "mark", "xcode", "clang", "llvm", "gcc"})); } void TestApi::checkOutputs() { QFETCH(bool, check); qbs::SetupProjectParameters params = defaultSetupParameters("/check-outputs"); qbs::BuildOptions options; options.setForceOutputCheck(check); removeBuildDir(params); qbs::ErrorInfo errorInfo = doBuildProject("/check-outputs", 0, 0, 0, options); if (check) QVERIFY(errorInfo.hasError()); else VERIFY_NO_ERROR(errorInfo); } void TestApi::checkOutputs_data() { QTest::addColumn<bool>("check"); QTest::newRow("checked outputs") << true; QTest::newRow("unchecked outputs") << false; } qbs::GroupData findGroup(const qbs::ProductData &product, const QString &name) { const auto groups = product.groups(); for (const qbs::GroupData &g : groups) { if (g.name() == name) return g; } return qbs::GroupData(); } #ifdef QBS_ENABLE_PROJECT_FILE_UPDATES static qbs::Project::ProductSelection defaultProducts() { return qbs::Project::ProductSelectionDefaultOnly; } static void printProjectData(const qbs::ProjectData &project) { const auto products = project.products(); for (const qbs::ProductData &p : products) { qDebug(" Product '%s' at %s", qPrintable(p.name()), qPrintable(p.location().toString())); const auto groups = p.groups(); for (const qbs::GroupData &g : groups) { qDebug(" Group '%s' at %s", qPrintable(g.name()), qPrintable(g.location().toString())); qDebug(" Files: %s", qPrintable(g.allFilePaths().join(QLatin1String(", ")))); } } } void TestApi::changeContent() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("project-editing"); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); qbs::Project project = job->project(); qbs::ProjectData projectData = project.projectData(); QCOMPARE(projectData.allProducts().size(), 1); qbs::ProductData product = projectData.allProducts().front(); QVERIFY(product.groups().size() >= 8); // Error handling: Invalid product. qbs::ErrorInfo errorInfo = project.addGroup(qbs::ProductData(), "blubb"); QVERIFY(errorInfo.hasError()); QVERIFY(errorInfo.toString().contains("invalid")); // Error handling: Empty group name. errorInfo = project.addGroup(product, QString()); QVERIFY(errorInfo.hasError()); QVERIFY(errorInfo.toString().contains("empty")); errorInfo = project.addGroup(product, "New Group 1"); VERIFY_NO_ERROR(errorInfo); errorInfo = project.addGroup(product, "New Group 2"); VERIFY_NO_ERROR(errorInfo); // Error handling: Group already inserted. errorInfo = project.addGroup(product, "New Group 1"); QVERIFY(errorInfo.hasError()); QVERIFY(errorInfo.toString().contains("already")); // Error handling: Add list of files with double entries. errorInfo = project.addFiles(product, qbs::GroupData(), QStringList() << "file.cpp" << "file.cpp"); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("more than once"), qPrintable(errorInfo.toString())); // Add files to empty array literal. projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); QVERIFY(product.groups().size() >= 10); qbs::GroupData group = findGroup(product, "New Group 1"); QVERIFY(group.isValid()); errorInfo = project.addFiles(product, group, QStringList() << "file.h" << "file.cpp"); VERIFY_NO_ERROR(errorInfo); // Error handling: Add the same file again. projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); QVERIFY(product.groups().size() >= 10); group = findGroup(product, "New Group 1"); QVERIFY(group.isValid()); errorInfo = project.addFiles(product, group, QStringList() << "file.cpp"); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("already"), qPrintable(errorInfo.toString())); // Remove one of the newly added files again. errorInfo = project.removeFiles(product, group, QStringList("file.h")); VERIFY_NO_ERROR(errorInfo); // Error handling: Try to remove the same file again. projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); QVERIFY(product.groups().size() >= 10); group = findGroup(product, "New Group 1"); QVERIFY(group.isValid()); errorInfo = project.removeFiles(product, group, QStringList() << "file.h"); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("not known"), qPrintable(errorInfo.toString())); // Error handling: Try to remove a file from a complex list. group = findGroup(product, "Existing Group 2"); QVERIFY(group.isValid()); errorInfo = project.removeFiles(product, group, QStringList() << "existingfile2.txt"); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("complex"), qPrintable(errorInfo.toString())); // Remove file from product's 'files' binding. errorInfo = project.removeFiles(product, qbs::GroupData(), QStringList("main.cpp")); VERIFY_NO_ERROR(errorInfo); // Add file to non-empty array literal. projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); group = findGroup(product, "Existing Group 1"); QVERIFY(group.isValid()); errorInfo = project.addFiles(product, group, QStringList() << "newfile1.txt"); VERIFY_NO_ERROR(errorInfo); // Add files to list represented as a single string. projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); errorInfo = project.addFiles(product, qbs::GroupData(), QStringList() << "newfile2.txt"); VERIFY_NO_ERROR(errorInfo); // Add files to list represented as an identifier. projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); group = findGroup(product, "Existing Group 2"); QVERIFY(group.isValid()); errorInfo = project.addFiles(product, group, QStringList() << "newfile3.txt"); VERIFY_NO_ERROR(errorInfo); // Add files to list represented as a block of code (not yet implemented). projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); group = findGroup(product, "Existing Group 3"); QVERIFY(group.isValid()); errorInfo = project.addFiles(product, group, QStringList() << "newfile4.txt"); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("complex"), qPrintable(errorInfo.toString())); // Add file to group with directory prefix. projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); group = findGroup(product, "Existing Group 4"); QVERIFY(group.isValid()); errorInfo = project.addFiles(product, group, QStringList() << "file.txt"); VERIFY_NO_ERROR(errorInfo); // Error handling: Add file to group with non-directory prefix. projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); group = findGroup(product, "Existing Group 5"); QVERIFY(group.isValid()); errorInfo = project.addFiles(product, group, QStringList() << "newfile1.txt"); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("prefix"), qPrintable(errorInfo.toString())); // Remove group. projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); group = findGroup(product, "Existing Group 5"); QVERIFY(group.isValid()); errorInfo = project.removeGroup(product, group); VERIFY_NO_ERROR(errorInfo); projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); QVERIFY(projectData.products().front().groups().size() >= 9); // Error handling: Try to remove the same group again. errorInfo = project.removeGroup(product, group); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("does not exist"), qPrintable(errorInfo.toString())); // Add a file to a group where the file name is already matched by a wildcard. projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); group = findGroup(product, "Group with wildcards"); QVERIFY(group.isValid()); QFile newFile("koerper.klaus"); QVERIFY2(newFile.open(QIODevice::WriteOnly), qPrintable(newFile.errorString())); newFile.close(); errorInfo = project.addFiles(product, group, QStringList() << newFile.fileName()); VERIFY_NO_ERROR(errorInfo); projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); group = findGroup(product, "Group with wildcards"); QVERIFY(group.isValid()); QCOMPARE(group.sourceArtifactsFromWildcards().size(), 1); QCOMPARE(group.sourceArtifactsFromWildcards().front().filePath(), QFileInfo(newFile).absoluteFilePath()); // Error checking: Try to remove a file that originates from a wildcard pattern. projectData = project.projectData(); QVERIFY(projectData.products().size() == 1); product = projectData.products().front(); group = findGroup(product, "Other group with wildcards"); QVERIFY(group.isValid()); errorInfo = project.removeFiles(product, group, QStringList() << "test.wildcard"); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("pattern"), qPrintable(errorInfo.toString())); // Check whether building will take the added and removed cpp files into account. // This must not be moved below the re-resolving test!!! qbs::BuildOptions buildOptions; buildOptions.setDryRun(true); BuildDescriptionReceiver rcvr; std::unique_ptr<qbs::BuildJob> buildJob(project.buildAllProducts(buildOptions, defaultProducts(), this)); connect(buildJob.get(), &qbs::BuildJob::reportCommandDescription, &rcvr, &BuildDescriptionReceiver::handleDescription); waitForFinished(buildJob.get()); QVERIFY2(!buildJob->error().hasError(), qPrintable(buildJob->error().toString())); QVERIFY(rcvr.descriptions.contains("compiling file.cpp")); QVERIFY(!rcvr.descriptions.contains("compiling main.cpp")); // Now check whether the data updates were done correctly. projectData = project.projectData(); job.reset(project.setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); project = job->project(); qbs::ProjectData newProjectData = project.projectData(); // Can't use Project::operator== here, as the target artifacts will differ due to the build // not having run yet. bool projectDataMatches = newProjectData.products().size() == 1 && projectData.products().size() == 1 && newProjectData.products().front().groups() == projectData.products().front().groups(); if (!projectDataMatches) { qDebug("This is the assumed project:"); printProjectData(projectData); qDebug("This is the actual project:"); printProjectData(newProjectData); } QVERIFY(projectDataMatches); // Will fail if e.g. code locations don't match. // Now try building again and check if the newly resolved product behaves the same way. buildJob.reset(project.buildAllProducts(buildOptions, defaultProducts(), this)); connect(buildJob.get(), &qbs::BuildJob::reportCommandDescription, &rcvr, &BuildDescriptionReceiver::handleDescription); waitForFinished(buildJob.get()); QVERIFY2(!buildJob->error().hasError(), qPrintable(buildJob->error().toString())); QVERIFY(rcvr.descriptions.contains("compiling file.cpp")); QVERIFY(!rcvr.descriptions.contains("compiling main.cpp")); // Now, after the build, the project data must be entirely identical. QVERIFY(projectData == project.projectData()); // Error handling: Try to change the project during a build. buildJob.reset(project.buildAllProducts(buildOptions, defaultProducts(), this)); errorInfo = project.addGroup(newProjectData.products().front(), "blubb"); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("in process"), qPrintable(errorInfo.toString())); waitForFinished(buildJob.get()); errorInfo = project.addGroup(newProjectData.products().front(), "blubb"); VERIFY_NO_ERROR(errorInfo); project = qbs::Project(); job.reset(nullptr); buildJob.reset(nullptr); removeBuildDir(setupParams); // Add a file to the top level of a product that does not have a "files" binding yet. setupParams.setProjectFilePath(QDir::cleanPath(m_workingDataDir + "/project-editing/project-with-no-files.qbs")); job.reset(project.setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); project = job->project(); projectData = project.projectData(); QCOMPARE(projectData.allProducts().size(), 1); product = projectData.allProducts().front(); errorInfo = project.addFiles(product, qbs::GroupData(), QStringList("main.cpp")); VERIFY_NO_ERROR(errorInfo); projectData = project.projectData(); rcvr.descriptions.clear(); buildJob.reset(project.buildAllProducts(buildOptions, defaultProducts(), this)); connect(buildJob.get(), &qbs::BuildJob::reportCommandDescription, &rcvr, &BuildDescriptionReceiver::handleDescription); waitForFinished(buildJob.get()); QVERIFY2(!buildJob->error().hasError(), qPrintable(buildJob->error().toString())); QVERIFY(rcvr.descriptions.contains("compiling main.cpp")); job.reset(project.setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); // Can't use Project::operator== here, as the target artifacts will differ due to the build // not having run yet. newProjectData = job->project().projectData(); projectDataMatches = newProjectData.products().size() == 1 && projectData.products().size() == 1 && newProjectData.products().front().groups() == projectData.products().front().groups(); if (!projectDataMatches) { printProjectData(projectData); qDebug("\n====\n"); printProjectData(newProjectData); } QVERIFY(projectDataMatches); } #endif // QBS_ENABLE_PROJECT_FILE_UPDATES void TestApi::commandExtraction() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("/command-extraction"); std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); qbs::Project project = setupJob->project(); qbs::ProjectData projectData = project.projectData(); QCOMPARE(projectData.allProducts().size(), 1); qbs::ProductData productData = projectData.allProducts().front(); qbs::ErrorInfo errorInfo; const QString projectDirPath = QDir::cleanPath(QFileInfo(setupParams.projectFilePath()).path()); const QString sourceFilePath = projectDirPath + "/main.cpp"; // Before the first build, no rules exist. qbs::RuleCommandList commands = project.ruleCommands(productData, sourceFilePath, "obj", &errorInfo); QCOMPARE(commands.size(), 0); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("No rule"), qPrintable(errorInfo.toString())); qbs::BuildOptions options; options.setDryRun(true); std::unique_ptr<qbs::BuildJob> buildJob(project.buildAllProducts(options)); waitForFinished(buildJob.get()); QVERIFY2(!buildJob->error().hasError(), qPrintable(buildJob->error().toString())); projectData = project.projectData(); QCOMPARE(projectData.allProducts().size(), 1); productData = projectData.allProducts().front(); errorInfo = qbs::ErrorInfo(); // After the build, the compile command must be found. commands = project.ruleCommands(productData, sourceFilePath, "obj", &errorInfo); QCOMPARE(commands.size(), 1); QVERIFY2(!errorInfo.hasError(), qPrintable(errorInfo.toString())); const qbs::RuleCommand command = commands.front(); QCOMPARE(command.type(), qbs::RuleCommand::ProcessCommandType); QVERIFY(!command.executable().isEmpty()); QVERIFY(!command.arguments().empty()); } void TestApi::changeDependentLib() { qbs::ErrorInfo errorInfo = doBuildProject("change-dependent-lib"); VERIFY_NO_ERROR(errorInfo); WAIT_FOR_NEW_TIMESTAMP(); const QString qbsFileName("change-dependent-lib.qbs"); QFile qbsFile(qbsFileName); QVERIFY(qbsFile.open(QIODevice::ReadWrite)); const QByteArray content1 = qbsFile.readAll(); QByteArray content2 = content1; content2.replace("cpp.defines: [\"XXXX\"]", "cpp.defines: [\"ABCD\"]"); QVERIFY(content1 != content2); qbsFile.seek(0); qbsFile.write(content2); qbsFile.close(); errorInfo = doBuildProject("change-dependent-lib"); VERIFY_NO_ERROR(errorInfo); } void TestApi::enableAndDisableProduct() { BuildDescriptionReceiver bdr; qbs::ErrorInfo errorInfo = doBuildProject("enable-and-disable-product", &bdr); VERIFY_NO_ERROR(errorInfo); QVERIFY(!bdr.descriptions.contains("compiling")); WAIT_FOR_NEW_TIMESTAMP(); QFile projectFile("enable-and-disable-product.qbs"); QVERIFY(projectFile.open(QIODevice::ReadWrite)); QByteArray content = projectFile.readAll(); content.replace("undefined", "'hidden'"); projectFile.resize(0); projectFile.write(content); projectFile.close(); bdr.descriptions.clear(); errorInfo = doBuildProject("enable-and-disable-product", &bdr); VERIFY_NO_ERROR(errorInfo); QVERIFY(bdr.descriptions.contains("linking")); WAIT_FOR_NEW_TIMESTAMP(); touch("main.cpp"); QVERIFY(projectFile.open(QIODevice::ReadWrite)); content = projectFile.readAll(); content.replace("'hidden'", "undefined"); projectFile.resize(0); projectFile.write(content); projectFile.close(); bdr.descriptions.clear(); errorInfo = doBuildProject("enable-and-disable-product", &bdr); VERIFY_NO_ERROR(errorInfo); QVERIFY(!bdr.descriptions.contains("compiling")); } void TestApi::errorInSetupRunEnvironment() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("error-in-setup-run-environment"); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); const qbs::Project project = job->project(); QVERIFY(project.isValid()); QCOMPARE(project.projectData().products().size(), 1); const qbs::ProductData product = project.projectData().products().front(); bool exceptionCaught = false; try { const SettingsPtr s = settings(); qbs::RunEnvironment runEnv = project.getRunEnvironment(product, qbs::InstallOptions(), QProcessEnvironment(), QStringList(), s.get()); qbs::ErrorInfo error; const QProcessEnvironment env = runEnv.runEnvironment(&error); QVERIFY(error.hasError()); QVERIFY(error.toString().contains("trallala")); } catch (const qbs::ErrorInfo &) { exceptionCaught = true; } QVERIFY(!exceptionCaught); } static qbs::ErrorInfo forceRuleEvaluation(const qbs::Project project) { qbs::BuildOptions buildOptions; buildOptions.setDryRun(true); std::unique_ptr<qbs::BuildJob> buildJob(project.buildAllProducts(buildOptions)); waitForFinished(buildJob.get()); return buildJob->error(); } void TestApi::disabledInstallGroup() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("disabled_install_group"); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); const qbs::Project project = job->project(); const qbs::ErrorInfo errorInfo = forceRuleEvaluation(project); VERIFY_NO_ERROR(errorInfo); qbs::ProjectData projectData = project.projectData(); QCOMPARE(projectData.allProducts().size(), 1); qbs::ProductData product = projectData.allProducts().front(); const QList<qbs::ArtifactData> targets = product.targetArtifacts(); QCOMPARE(targets.size(), 1); QVERIFY(targets.front().isGenerated()); QVERIFY(targets.front().isExecutable()); QVERIFY(targets.front().isTargetArtifact()); QCOMPARE(projectData.installableArtifacts().size(), 0); QCOMPARE(product.targetExecutable(), targets.front().filePath()); } void TestApi::disabledProduct() { const qbs::ErrorInfo errorInfo = doBuildProject("disabled-product"); VERIFY_NO_ERROR(errorInfo); } void TestApi::disabledProject() { const qbs::ErrorInfo errorInfo = doBuildProject("disabled-project"); VERIFY_NO_ERROR(errorInfo); } void TestApi::duplicateProductNames() { QFETCH(QString, projectFileName); const qbs::ErrorInfo errorInfo = doBuildProject("duplicate-product-names/" + projectFileName); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("Duplicate product name"), qPrintable(errorInfo.toString())); } void TestApi::duplicateProductNames_data() { QTest::addColumn<QString>("projectFileName"); QTest::newRow("Names explicitly set") << QString("explicit.qbs"); QTest::newRow("Unnamed products in same file") << QString("implicit.qbs"); QTest::newRow("Unnamed products in files of the same name") << QString("implicit-indirect.qbs"); } void TestApi::emptyFileTagList() { const qbs::ErrorInfo errorInfo = doBuildProject("empty-filetag-list"); VERIFY_NO_ERROR(errorInfo); } void TestApi::emptySubmodulesList() { const qbs::ErrorInfo errorInfo = doBuildProject("empty-submodules-list"); VERIFY_NO_ERROR(errorInfo); } void TestApi::explicitlyDependsOn() { BuildDescriptionReceiver receiver; qbs::ErrorInfo errorInfo = doBuildProject("explicitly-depends-on", &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY2(receiver.descriptions.contains("compiling compiler.cpp"), qPrintable(receiver.descriptions)); QVERIFY2(receiver.descriptions.contains("compiling a.in"), qPrintable(receiver.descriptions)); QVERIFY2(receiver.descriptions.contains("compiling b.in"), qPrintable(receiver.descriptions)); QVERIFY2(receiver.descriptions.contains("compiling c.in"), qPrintable(receiver.descriptions)); QFile txtFile(relativeProductBuildDir("p") + "/compiler-name.txt"); QVERIFY2(txtFile.open(QIODevice::ReadOnly), qPrintable(txtFile.errorString())); const QByteArray content = txtFile.readAll(); QCOMPARE(content, QByteArray("compiler file name: compiler")); receiver.descriptions.clear(); errorInfo = doBuildProject("explicitly-depends-on", &receiver); QVERIFY2(!receiver.descriptions.contains("compiling compiler.cpp"), qPrintable(receiver.descriptions)); QVERIFY2(!receiver.descriptions.contains("compiling a.in"), qPrintable(receiver.descriptions)); QVERIFY2(!receiver.descriptions.contains("compiling b.in"), qPrintable(receiver.descriptions)); QVERIFY2(!receiver.descriptions.contains("compiling c.in"), qPrintable(receiver.descriptions)); VERIFY_NO_ERROR(errorInfo); WAIT_FOR_NEW_TIMESTAMP(); touch("compiler.cpp"); errorInfo = doBuildProject("explicitly-depends-on", &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY2(receiver.descriptions.contains("compiling compiler.cpp"), qPrintable(receiver.descriptions)); QVERIFY2(receiver.descriptions.contains("compiling a.in"), qPrintable(receiver.descriptions)); QVERIFY2(receiver.descriptions.contains("compiling b.in"), qPrintable(receiver.descriptions)); QVERIFY2(receiver.descriptions.contains("compiling c.in"), qPrintable(receiver.descriptions)); } void TestApi::exportSimple() { const qbs::ErrorInfo errorInfo = doBuildProject("export-simple"); VERIFY_NO_ERROR(errorInfo); } void TestApi::exportWithRecursiveDepends() { const qbs::ErrorInfo errorInfo = doBuildProject("export-with-recursive-depends"); VERIFY_NO_ERROR(errorInfo); } void TestApi::fallbackGcc() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("fallback-gcc/fallback-gcc.qbs"); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, nullptr)); waitForFinished(job.get()); VERIFY_NO_ERROR(job->error()); qbs::ProjectData project = job->project().projectData(); QVERIFY(project.isValid()); QList<qbs::ProductData> products = project.allProducts(); QCOMPARE(products.size(), 2); for (const qbs::ProductData &p : qAsConst(products)) { if (p.profile() == "unixProfile") { qbs::PropertyMap moduleProps = p.moduleProperties(); QCOMPARE(moduleProps.getModuleProperty("qbs", "targetOS").toStringList(), QStringList({"unix"})); QCOMPARE(moduleProps.getModuleProperty("qbs", "toolchain").toStringList(), QStringList({"gcc"})); QCOMPARE(QFileInfo(moduleProps.getModuleProperty("cpp", "cxxCompilerName").toString()) .completeBaseName(), QString("g++")); QCOMPARE(moduleProps.getModuleProperty("cpp", "dynamicLibrarySuffix").toString(), QString(".so")); } else { QCOMPARE(p.profile(), QString("gccProfile")); qbs::PropertyMap moduleProps = p.moduleProperties(); QCOMPARE(moduleProps.getModuleProperty("qbs", "targetOS").toStringList(), QStringList()); QCOMPARE(moduleProps.getModuleProperty("qbs", "toolchain").toStringList(), QStringList({"gcc"})); QCOMPARE(QFileInfo(moduleProps.getModuleProperty("cpp", "cxxCompilerName").toString()) .completeBaseName(), QString("g++")); QCOMPARE(moduleProps.getModuleProperty("cpp", "dynamicLibrarySuffix").toString(), QString()); } } } void TestApi::fileTagger() { BuildDescriptionReceiver receiver; const qbs::ErrorInfo errorInfo = doBuildProject("file-tagger/moc_cpp.qbs", &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY2(receiver.descriptions.contains("moc bla.cpp"), qPrintable(receiver.descriptions)); } void TestApi::fileTagsFilterOverride() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("filetagsfilter_override"); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); qbs::Project project = job->project(); const qbs::ErrorInfo errorInfo = forceRuleEvaluation(project); VERIFY_NO_ERROR(errorInfo); qbs::ProjectData projectData = project.projectData(); QCOMPARE(projectData.allProducts().size(), 1); const qbs::ProductData product = projectData.allProducts().front(); QList<qbs::ArtifactData> installableFiles = product.installableArtifacts(); QCOMPARE(installableFiles.size(), 1); QVERIFY(installableFiles.front().installData().installFilePath().contains("habicht")); } void TestApi::generatedFilesList() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("generated-files-list"); std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(setupParams, m_logSink, 0)); QVERIFY(waitForFinished(setupJob.get())); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); qbs::Project project = setupJob->project(); qbs::BuildOptions options; options.setExecuteRulesOnly(true); const std::unique_ptr<qbs::BuildJob> buildJob(project.buildAllProducts(options)); QVERIFY(waitForFinished(buildJob.get())); VERIFY_NO_ERROR(buildJob->error()); const qbs::ProjectData projectData = project.projectData(); QCOMPARE(projectData.products().size(), 1); const qbs::ProductData product = projectData.products().front(); QString uiFilePath; QVERIFY(product.generatedArtifacts().size() >= 6); const auto artifacts = product.generatedArtifacts(); for (const qbs::ArtifactData &a : artifacts) { QVERIFY(a.isGenerated()); QFileInfo fi(a.filePath()); using qbs::Internal::HostOsInfo; const QStringList possibleFileNames = QStringList() << "main.cpp.o" << "main.cpp.obj" << "mainwindow.cpp.o" << "mainwindow.cpp.obj" << "moc_mainwindow.cpp" << "moc_mainwindow.cpp.o" << "moc_mainwindow.cpp.obj" << "ui_mainwindow.h" << HostOsInfo::appendExecutableSuffix("generated-files-list"); QVERIFY2(possibleFileNames.contains(fi.fileName()) || fi.fileName().endsWith(".plist"), qPrintable(fi.fileName())); } const auto groups = product.groups(); for (const qbs::GroupData &group : groups) { const auto artifacts = group.sourceArtifacts(); for (const qbs::ArtifactData &a : artifacts) { QVERIFY(!a.isGenerated()); QVERIFY(!a.isTargetArtifact()); if (a.fileTags().contains(QLatin1String("ui"))) { uiFilePath = a.filePath(); break; } } if (!uiFilePath.isEmpty()) break; } QVERIFY(!uiFilePath.isEmpty()); const QStringList directParents = project.generatedFiles(product, uiFilePath, false); QCOMPARE(directParents.size(), 1); const QFileInfo uiHeaderFileInfo(directParents.front()); QCOMPARE(uiHeaderFileInfo.fileName(), QLatin1String("ui_mainwindow.h")); QVERIFY(!uiHeaderFileInfo.exists()); const QStringList allParents = project.generatedFiles(product, uiFilePath, true); QCOMPARE(allParents.size(), 3); } void TestApi::infiniteLoopBuilding() { QFETCH(QString, projectDirName); qbs::SetupProjectParameters setupParams = defaultSetupParameters(projectDirName + "/infinite-loop.qbs"); std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); qbs::Project project = setupJob->project(); const std::unique_ptr<qbs::BuildJob> buildJob(project.buildAllProducts(qbs::BuildOptions())); QTimer::singleShot(1000, buildJob.get(), &qbs::AbstractJob::cancel); QVERIFY(waitForFinished(buildJob.get(), testTimeoutInMsecs())); QVERIFY(buildJob->error().hasError()); } void TestApi::infiniteLoopBuilding_data() { QTest::addColumn<QString>("projectDirName"); QTest::newRow("JS Command") << QString("infinite-loop-js"); QTest::newRow("Process Command") << QString("infinite-loop-process"); } void TestApi::infiniteLoopResolving() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("infinite-loop-resolving"); std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(setupParams, m_logSink, 0)); QTimer::singleShot(1000, setupJob.get(), &qbs::AbstractJob::cancel); QVERIFY(waitForFinished(setupJob.get(), testTimeoutInMsecs())); QVERIFY2(setupJob->error().toString().toLower().contains("cancel"), qPrintable(setupJob->error().toString())); } void TestApi::inheritQbsSearchPaths() { const QString projectFilePath = "inherit-qbs-search-paths/prj.qbs"; qbs::ErrorInfo errorInfo = doBuildProject(projectFilePath); VERIFY_NO_ERROR(errorInfo); WAIT_FOR_NEW_TIMESTAMP(); QFile projectFile(m_workingDataDir + '/' + projectFilePath); QVERIFY(projectFile.open(QIODevice::ReadWrite)); QByteArray content = projectFile.readAll(); content.replace("qbsSearchPaths: \"subdir\"", "//qbsSearchPaths: \"subdir\""); projectFile.resize(0); projectFile.write(content); projectFile.close(); errorInfo = doBuildProject(projectFilePath); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("Dependency 'bli' not found"), qPrintable(errorInfo.toString())); QVariantMap overriddenValues; overriddenValues.insert("project.qbsSearchPaths", QStringList() << m_workingDataDir + "/inherit-qbs-search-paths/subdir"); errorInfo = doBuildProject(projectFilePath, 0, 0, 0, qbs::BuildOptions(), overriddenValues); VERIFY_NO_ERROR(errorInfo); } template <typename T, class Pred> typename T::value_type findElem(const T &list, Pred p) { const auto it = std::find_if(list.cbegin(), list.cend(), p); return it == list.cend() ? typename T::value_type() : *it; } void TestApi::installableFiles() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("installed-artifact"); QVariantMap overriddenValues; overriddenValues.insert(QLatin1String("qbs.installRoot"), QLatin1String("/tmp")); setupParams.setOverriddenValues(overriddenValues); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); qbs::Project project = job->project(); const qbs::ErrorInfo errorInfo = forceRuleEvaluation(project); VERIFY_NO_ERROR(errorInfo); qbs::ProjectData projectData = project.projectData(); QCOMPARE(projectData.allProducts().size(), 2); qbs::ProductData product = findElem(projectData.allProducts(), [](const qbs::ProductData &p) { return p.name() == QLatin1String("installedApp"); }); QVERIFY(product.isValid()); const QList<qbs::ArtifactData> beforeInstallableFiles = product.installableArtifacts(); QCOMPARE(beforeInstallableFiles.size(), 3); for (const qbs::ArtifactData &f : beforeInstallableFiles) { if (!QFileInfo(f.filePath()).fileName().startsWith("main")) { QVERIFY(f.isExecutable()); QString expectedTargetFilePath = qbs::Internal::HostOsInfo ::appendExecutableSuffix(QLatin1String("/tmp/usr/bin/installedApp")); QCOMPARE(f.installData().localInstallFilePath(), expectedTargetFilePath); QCOMPARE(product.targetExecutable(), expectedTargetFilePath); break; } } setupParams = defaultSetupParameters("recursive-wildcards"); setupParams.setOverriddenValues(overriddenValues); job.reset(project.setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); project = job->project(); projectData = project.projectData(); QCOMPARE(projectData.allProducts().size(), 1); product = projectData.allProducts().front(); const QList<qbs::ArtifactData> afterInstallableFiles = product.installableArtifacts(); QCOMPARE(afterInstallableFiles.size(), 2); for (const qbs::ArtifactData &f : afterInstallableFiles) QVERIFY(!f.isExecutable()); QCOMPARE(afterInstallableFiles.front().installData().localInstallFilePath(), QLatin1String("/tmp/dir/file1.txt")); QCOMPARE(afterInstallableFiles.last().installData().localInstallFilePath(), QLatin1String("/tmp/dir/file2.txt")); } void TestApi::isRunnable() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("is-runnable"); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); qbs::Project project = job->project(); const QList<qbs::ProductData> products = project.projectData().products(); QCOMPARE(products.size(), 2); for (const qbs::ProductData &p : products) { QVERIFY2(p.name() == "app" || p.name() == "lib", qPrintable(p.name())); if (p.name() == "app") QVERIFY(p.isRunnable()); else QVERIFY(!p.isRunnable()); } } void TestApi::linkDynamicLibs() { const qbs::ErrorInfo errorInfo = doBuildProject("link-dynamiclibs"); VERIFY_NO_ERROR(errorInfo); } void TestApi::linkDynamicAndStaticLibs() { BuildDescriptionReceiver bdr; qbs::BuildOptions options; options.setEchoMode(qbs::CommandEchoModeCommandLine); const qbs::ErrorInfo errorInfo = doBuildProject("link-dynamiclibs-staticlibs", &bdr, nullptr, nullptr, options); VERIFY_NO_ERROR(errorInfo); // The dependent static libs should not appear in the link command for the executable. const SettingsPtr s = settings(); const qbs::Profile buildProfile(profileName(), s.get()); if (buildProfile.value("qbs.toolchain").toStringList().contains("gcc")) { static const std::regex appLinkCmdRex(" -o [^ ]*/HelloWorld" QBS_HOST_EXE_SUFFIX " "); QString appLinkCmd; for (const QString &line : qAsConst(bdr.descriptionLines)) { const auto ln = line.toStdString(); if (std::regex_search(ln, appLinkCmdRex)) { appLinkCmd = line; break; } } QVERIFY(!appLinkCmd.isEmpty()); QVERIFY(!appLinkCmd.contains("static1")); QVERIFY(!appLinkCmd.contains("static2")); } } void TestApi::linkStaticAndDynamicLibs() { BuildDescriptionReceiver bdr; qbs::BuildOptions options; options.setEchoMode(qbs::CommandEchoModeCommandLine); const qbs::ErrorInfo errorInfo = doBuildProject("link-staticlibs-dynamiclibs", &bdr, nullptr, nullptr, options); VERIFY_NO_ERROR(errorInfo); // The dependencies libdynamic1.so and libstatic2.a must not appear in the link command for the // executable. The -rpath-link line for libdynamic1.so must be there. const SettingsPtr s = settings(); const qbs::Profile buildProfile(profileName(), s.get()); if (buildProfile.value("qbs.toolchain").toStringList().contains("gcc")) { static const std::regex appLinkCmdRex(" -o [^ ]*/HelloWorld" QBS_HOST_EXE_SUFFIX " "); QString appLinkCmd; for (const QString &line : qAsConst(bdr.descriptionLines)) { const auto ln = line.toStdString(); if (std::regex_search(ln, appLinkCmdRex)) { appLinkCmd = line; break; } } QVERIFY(!appLinkCmd.isEmpty()); std::string targetPlatform = buildProfile.value("qbs.targetPlatform") .toString().toStdString(); std::vector<std::string> targetOS = qbs::Internal::HostOsInfo::canonicalOSIdentifiers( targetPlatform); if (!qbs::Internal::contains(targetOS, "darwin") && !qbs::Internal::contains(targetOS, "windows")) { const std::regex rpathLinkRex("-rpath-link=\\S*/" + relativeProductBuildDir("dynamic2").toStdString()); const auto ln = appLinkCmd.toStdString(); QVERIFY(std::regex_search(ln, rpathLinkRex)); } QVERIFY(!appLinkCmd.contains("libstatic2.a")); QVERIFY(!appLinkCmd.contains("libdynamic2.so")); } } void TestApi::listBuildSystemFiles() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("subprojects/toplevelproject.qbs"); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); const auto buildSystemFiles = qbs::Internal::Set<QString>::fromStdSet( job->project().buildSystemFiles()); QVERIFY(buildSystemFiles.contains(setupParams.projectFilePath())); QVERIFY(buildSystemFiles.contains(setupParams.buildRoot() + "/subproject2/subproject2.qbs")); QVERIFY(buildSystemFiles.contains(setupParams.buildRoot() + "/subproject2/subproject3/subproject3.qbs")); } void TestApi::localProfiles() { QFETCH(bool, enableProfiles); qbs::SetupProjectParameters setupParams = defaultSetupParameters("local-profiles/local-profiles.qbs"); setupParams.setOverriddenValues( {std::make_pair(QString("project.enableProfiles"), enableProfiles)}); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); QString taskDescriptions; const auto taskDescHandler = [&taskDescriptions](const QString &desc, int, qbs::AbstractJob *) { taskDescriptions += '\n' + desc; }; connect(job.get(), &qbs::AbstractJob::taskStarted, taskDescHandler); waitForFinished(job.get()); const QString error = job->error().toString(); QVERIFY2(job->error().hasError() == !enableProfiles, qPrintable(error)); if (!enableProfiles) { QVERIFY2(error.contains("does not exist"), qPrintable(error)); return; } QVERIFY2(taskDescriptions.contains("Resolving"), qPrintable(taskDescriptions)); qbs::ProjectData project = job->project().projectData(); QList<qbs::ProductData> products = project.allProducts(); QCOMPARE(products.size(), 4); qbs::ProductData libMingw; qbs::ProductData libClang; qbs::ProductData appDebug; qbs::ProductData appRelease; for (const qbs::ProductData &p : qAsConst(products)) { if (p.name() == "lib") { if (p.profile() == "mingwProfile") libMingw = p; else if (p.profile() == "clangProfile") libClang = p; } else if (p.name() == "app") { const QString buildVariant = p.moduleProperties().getModuleProperty("qbs", "buildVariant").toString(); if (buildVariant == "debug") appDebug = p; else if (buildVariant == "release") appRelease = p; } } QVERIFY(libMingw.isValid()); QVERIFY((libClang.isValid())); QVERIFY(appDebug.isValid()); QVERIFY(appRelease.isValid()); QCOMPARE(appDebug.profile(), QLatin1String("mingwProfile")); QCOMPARE(appRelease.profile(), QLatin1String("mingwProfile")); qbs::PropertyMap moduleProps = libMingw.moduleProperties(); QCOMPARE(moduleProps.getModuleProperty("qbs", "targetOS").toStringList(), QStringList({"windows"})); QCOMPARE(moduleProps.getModuleProperty("qbs", "toolchain").toStringList(), QStringList({"mingw", "gcc"})); if (moduleProps.getModuleProperty("cpp", "present").toBool()) { QCOMPARE(moduleProps.getModuleProperty("cpp", "cxxCompilerName").toString(), QString("g++")); } moduleProps = libClang.moduleProperties(); QCOMPARE(moduleProps.getModuleProperty("qbs", "targetOS").toStringList(), QStringList({"linux", "unix"})); QCOMPARE(moduleProps.getModuleProperty("qbs", "toolchain").toStringList(), QStringList({"clang", "llvm", "gcc"})); if (moduleProps.getModuleProperty("cpp", "present").toBool()) { QCOMPARE(moduleProps.getModuleProperty("cpp", "cxxCompilerName").toString(), QString("clang++")); } moduleProps = appDebug.moduleProperties(); if (moduleProps.getModuleProperty("cpp", "present").toBool()) QCOMPARE(moduleProps.getModuleProperty("cpp", "optimization").toString(), QString("none")); moduleProps = appRelease.moduleProperties(); if (moduleProps.getModuleProperty("cpp", "present").toBool()) QCOMPARE(moduleProps.getModuleProperty("cpp", "optimization").toString(), QString("fast")); taskDescriptions.clear(); job.reset(qbs::Project().setupProject(setupParams, m_logSink, 0)); connect(job.get(), &qbs::AbstractJob::taskStarted, taskDescHandler); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); QVERIFY2(!taskDescriptions.contains("Resolving"), qPrintable(taskDescriptions)); WAIT_FOR_NEW_TIMESTAMP(); QFile projectFile(setupParams.projectFilePath()); QVERIFY2(projectFile.open(QIODevice::ReadWrite), qPrintable(projectFile.errorString())); QByteArray content = projectFile.readAll(); content.replace("\"clang\"", "\"gcc\""); projectFile.resize(0); projectFile.write(content); projectFile.close(); job.reset(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); project = job->project().projectData(); products = project.allProducts(); QCOMPARE(products.size(), 4); int clangProfiles = 0; for (const qbs::ProductData &p : qAsConst(products)) { if (p.profile() == "clangProfile") { ++clangProfiles; moduleProps = p.moduleProperties(); if (moduleProps.getModuleProperty("cpp", "present").toBool()) { QCOMPARE(moduleProps.getModuleProperty("cpp", "cxxCompilerName").toString(), QString("g++")); } } } QCOMPARE(clangProfiles, 1); } void TestApi::localProfiles_data() { QTest::addColumn<bool>("enableProfiles"); QTest::newRow("profiles enabled") << true; QTest::newRow("profiles disabled") << false; } void TestApi::missingSourceFile() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("missing-source-file/missing-source-file.qbs"); setupParams.setProductErrorMode(qbs::ErrorHandlingMode::Relaxed); m_logSink->setLogLevel(qbs::LoggerMinLevel); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); qbs::ProjectData project = job->project().projectData(); QCOMPARE(project.allProducts().size(), 1); qbs::ProductData product = project.allProducts().front(); QCOMPARE(product.groups().size(), 1); qbs::GroupData group = product.groups().front(); QCOMPARE(group.allSourceArtifacts().size(), 2); QFile::rename("file2.txt.missing", "file2.txt"); job.reset(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); project = job->project().projectData(); QCOMPARE(project.allProducts().size(), 1); product = project.allProducts().front(); QCOMPARE(product.groups().size(), 1); group = product.groups().front(); QCOMPARE(group.allSourceArtifacts().size(), 3); } void TestApi::mocCppIncluded() { // Initial build. qbs::ErrorInfo errorInfo = doBuildProject("moc-hpp-included"); VERIFY_NO_ERROR(errorInfo); // Touch header and try again. WAIT_FOR_NEW_TIMESTAMP(); QFile headerFile("object.h"); QVERIFY2(headerFile.open(QIODevice::WriteOnly | QIODevice::Append), qPrintable(headerFile.errorString())); headerFile.write("\n"); headerFile.close(); errorInfo = doBuildProject("moc-hpp-included"); VERIFY_NO_ERROR(errorInfo); // Touch cpp file and try again. WAIT_FOR_NEW_TIMESTAMP(); QFile cppFile("object.cpp"); QVERIFY2(cppFile.open(QIODevice::WriteOnly | QIODevice::Append), qPrintable(cppFile.errorString())); cppFile.write("\n"); cppFile.close(); errorInfo = doBuildProject("moc-hpp-included"); VERIFY_NO_ERROR(errorInfo); } void TestApi::multiArch() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("multi-arch"); const SettingsPtr s = settings(); qbs::Internal::TemporaryProfile tph("host", s.get()); qbs::Profile hostProfile = tph.p; hostProfile.setValue("qbs.architecture", "host-arch"); qbs::Internal::TemporaryProfile tpt("target", s.get()); qbs::Profile targetProfile = tpt.p; targetProfile.setValue("qbs.architecture", "target-arch"); QVariantMap overriddenValues; overriddenValues.insert("project.hostProfile", hostProfile.name()); overriddenValues.insert("project.targetProfile", targetProfile.name()); setupParams.setOverriddenValues(overriddenValues); std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); qbs::Project project = setupJob->project(); QCOMPARE(project.profile(), profileName()); const QList<qbs::ProductData> &products = project.projectData().products(); QCOMPARE(products.size(), 3); QList<qbs::ProductData> hostProducts; QList<qbs::ProductData> targetProducts; for (const qbs::ProductData &p : products) { QVERIFY2(p.profile() == hostProfile.name() || p.profile() == targetProfile.name(), qPrintable(p.profile())); if (p.profile() == hostProfile.name()) hostProducts.push_back(p); else targetProducts.push_back(p); } QCOMPARE(hostProducts.size(), 2); QCOMPARE(targetProducts.size(), 1); QCOMPARE(targetProducts.front().name(), QLatin1String("p1")); QStringList hostProductNames = QStringList() << hostProducts.front().name() << hostProducts.last().name(); QCOMPARE(hostProductNames.count("p1"), 1); QCOMPARE(hostProductNames.count("p2"), 1); const QString p1HostMultiplexCfgId = hostProducts.at(0).multiplexConfigurationId(); const QString p2HostMultiplexCfgId = hostProducts.at(1).multiplexConfigurationId(); const QString p1TargetMultiplexCfgId = targetProducts.at(0).multiplexConfigurationId(); std::unique_ptr<qbs::BuildJob> buildJob(project.buildAllProducts(qbs::BuildOptions())); waitForFinished(buildJob.get()); QVERIFY2(!buildJob->error().hasError(), qPrintable(buildJob->error().toString())); const QString outputBaseDir = setupParams.buildRoot() + '/'; QFile p1HostArtifact(outputBaseDir + relativeProductBuildDir("p1", QString(), p1HostMultiplexCfgId) + "/host+target.output"); QVERIFY2(p1HostArtifact.exists(), qPrintable(p1HostArtifact.fileName())); QVERIFY2(p1HostArtifact.open(QIODevice::ReadOnly), qPrintable(p1HostArtifact.errorString())); QCOMPARE(p1HostArtifact.readAll().constData(), "host-arch"); QFile p1TargetArtifact(outputBaseDir + relativeProductBuildDir("p1", QString(), p1TargetMultiplexCfgId) + "/host+target.output"); QVERIFY2(p1TargetArtifact.exists(), qPrintable(p1TargetArtifact.fileName())); QVERIFY2(p1TargetArtifact.open(QIODevice::ReadOnly), qPrintable(p1TargetArtifact.errorString())); QCOMPARE(p1TargetArtifact.readAll().constData(), "target-arch"); QFile p2Artifact(outputBaseDir + relativeProductBuildDir("p2", QString(), p2HostMultiplexCfgId) + "/host-tool.output"); QVERIFY2(p2Artifact.exists(), qPrintable(p2Artifact.fileName())); QVERIFY2(p2Artifact.open(QIODevice::ReadOnly), qPrintable(p2Artifact.errorString())); QCOMPARE(p2Artifact.readAll().constData(), "host-arch"); const QString installRoot = outputBaseDir + relativeBuildDir() + '/' + qbs::InstallOptions::defaultInstallRoot(); std::unique_ptr<qbs::InstallJob> installJob(project.installAllProducts(qbs::InstallOptions())); waitForFinished(installJob.get()); QVERIFY2(!installJob->error().hasError(), qPrintable(installJob->error().toString())); QFile p1HostArtifactInstalled(installRoot + "/host/host+target.output"); QVERIFY2(p1HostArtifactInstalled.exists(), qPrintable(p1HostArtifactInstalled.fileName())); QFile p1TargetArtifactInstalled(installRoot + "/target/host+target.output"); QVERIFY2(p1TargetArtifactInstalled.exists(), qPrintable(p1TargetArtifactInstalled.fileName())); QFile p2ArtifactInstalled(installRoot + "/host/host-tool.output"); QVERIFY2(p2ArtifactInstalled.exists(), qPrintable(p2ArtifactInstalled.fileName())); // Error check: Try to build for the same profile twice. overriddenValues.insert("project.targetProfile", hostProfile.name()); setupParams.setOverriddenValues(overriddenValues); setupJob.reset(project.setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY(setupJob->error().hasError()); QVERIFY2(setupJob->error().toString().contains("Duplicate product name 'p1'"), qPrintable(setupJob->error().toString())); // Error check: Try to build for the same profile twice, this time attaching // the properties via the product name. overriddenValues.remove(QLatin1String("project.targetProfile")); overriddenValues.insert("products.p1.myProfiles", targetProfile.name() + ',' + targetProfile.name()); setupParams.setOverriddenValues(overriddenValues); setupJob.reset(project.setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY(setupJob->error().hasError()); QVERIFY2(setupJob->error().toString().contains("Duplicate product name 'p1'"), qPrintable(setupJob->error().toString())); } struct ProductDataSelector { void clear() { name.clear(); qbsProperties.clear(); } bool matches(const qbs::ProductData &p) const { return name == p.name() && qbsPropertiesMatch(p); } bool qbsPropertiesMatch(const qbs::ProductData &p) const { for (auto it = qbsProperties.begin(); it != qbsProperties.end(); ++it) { if (it.value() != p.moduleProperties().getModuleProperty("qbs", it.key())) return false; } return true; } QString name; QVariantMap qbsProperties; }; static qbs::ProductData takeMatchingProduct(QList<qbs::ProductData> &products, const ProductDataSelector &s) { qbs::ProductData result; auto it = std::find_if(products.begin(), products.end(), [&s] (const qbs::ProductData &pd) { return s.matches(pd); }); if (it != products.end()) { result = *it; products.erase(it); } return result; } void TestApi::multiplexing() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("multiplexing"); std::unique_ptr<qbs::SetupProjectJob> setupJob( qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); qbs::Project project = setupJob->project(); QList<qbs::ProductData> products = project.projectData().allProducts(); qbs::ProductData product; ProductDataSelector selector; selector.name = "no-multiplexing"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(!product.isMultiplexed()); QVERIFY(product.dependencies().empty()); selector.clear(); selector.name = "multiplex-without-aggregator-2"; selector.qbsProperties["architecture"] = "TRS-80"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QVERIFY(product.dependencies().empty()); selector.qbsProperties["architecture"] = "C64"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QVERIFY(product.dependencies().empty()); selector.clear(); selector.name = "multiplex-with-export"; selector.qbsProperties["architecture"] = "TRS-80"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QVERIFY(product.dependencies().empty()); selector.qbsProperties["architecture"] = "C64"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QVERIFY(product.dependencies().empty()); selector.clear(); selector.name = "nonmultiplex-with-export"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(!product.isMultiplexed()); QVERIFY(product.dependencies().empty()); selector.clear(); selector.name = "nonmultiplex-exporting-aggregation"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(!product.isMultiplexed()); QVERIFY(product.dependencies().empty()); selector.clear(); selector.name = "multiplex-using-export"; selector.qbsProperties["architecture"] = "TRS-80"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 2); selector.qbsProperties["architecture"] = "C64"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 2); selector.clear(); selector.name = "multiplex-without-aggregator-2-depend-on-non-multiplexed"; selector.qbsProperties["architecture"] = "TRS-80"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 1); selector.qbsProperties["architecture"] = "C64"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 1); selector.clear(); selector.name = "multiplex-without-aggregator-4"; selector.qbsProperties["architecture"] = "C64"; selector.qbsProperties["buildVariant"] = "debug"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QVERIFY(product.dependencies().empty()); selector.qbsProperties["buildVariant"] = "release"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QVERIFY(product.dependencies().empty()); selector.qbsProperties["architecture"] = "TRS-80"; selector.qbsProperties["buildVariant"] = "debug"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QVERIFY(product.dependencies().empty()); selector.qbsProperties["buildVariant"] = "release"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QVERIFY(product.dependencies().empty()); selector.clear(); selector.name = "multiplex-with-aggregator-2"; selector.qbsProperties["architecture"] = "C64"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 0); selector.qbsProperties["architecture"] = "TRS-80"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 0); selector.qbsProperties["architecture"] = "Atari ST"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 2); selector.clear(); selector.name = "multiplex-with-aggregator-2-dependent"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(!product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 1); selector.clear(); selector.name = "non-multiplexed-with-dependencies-on-multiplexed"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(!product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 2); selector.clear(); selector.name = "non-multiplexed-with-dependencies-on-multiplexed-via-export1"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(!product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 4); selector.clear(); selector.name = "non-multiplexed-with-dependencies-on-multiplexed-via-export2"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(!product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 3); selector.clear(); selector.name = "non-multiplexed-with-dependencies-on-aggregation-via-export"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(!product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 2); selector.clear(); selector.name = "aggregate-with-dependencies-on-aggregation-via-export"; selector.qbsProperties["architecture"] = "C64"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 2); selector.qbsProperties["architecture"] = "TRS-80"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 2); selector.qbsProperties["architecture"] = "Atari ST"; product = takeMatchingProduct(products, selector); QVERIFY(product.isValid()); QVERIFY(product.isMultiplexed()); QCOMPARE(product.dependencies().size(), 4); QVERIFY(products.empty()); } void TestApi::newOutputArtifactInDependency() { BuildDescriptionReceiver receiver; qbs::ErrorInfo errorInfo = doBuildProject("new-output-artifact-in-dependency", &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY(receiver.descriptions.contains("linking app")); const QByteArray linkingLibString = QByteArray("linking ") + qbs::Internal::HostOsInfo::dynamicLibraryName("lib").toLatin1(); QVERIFY(!receiver.descriptions.contains(linkingLibString)); receiver.descriptions.clear(); WAIT_FOR_NEW_TIMESTAMP(); QFile projectFile("new-output-artifact-in-dependency.qbs"); QVERIFY2(projectFile.open(QIODevice::ReadWrite), qPrintable(projectFile.errorString())); QByteArray contents = projectFile.readAll(); contents.replace("//Depends", "Depends"); projectFile.resize(0); projectFile.write(contents); projectFile.close(); errorInfo = doBuildProject("new-output-artifact-in-dependency", &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY(receiver.descriptions.contains("linking app")); QVERIFY(receiver.descriptions.contains(linkingLibString)); } void TestApi::newPatternMatch() { TaskReceiver receiver; qbs::ErrorInfo errorInfo = doBuildProject("new-pattern-match", 0, 0, &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY2(receiver.taskDescriptions.contains("Resolving"), qPrintable(m_logSink->output)); receiver.taskDescriptions.clear(); errorInfo = doBuildProject("new-pattern-match", 0, 0, &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY(!receiver.taskDescriptions.contains("Resolving")); WAIT_FOR_NEW_TIMESTAMP(); QFile f("test.txt"); QVERIFY2(f.open(QIODevice::WriteOnly), qPrintable(f.errorString())); f.close(); errorInfo = doBuildProject("new-pattern-match", 0, 0, &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY(receiver.taskDescriptions.contains("Resolving")); receiver.taskDescriptions.clear(); errorInfo = doBuildProject("new-pattern-match", 0, 0, &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY(!receiver.taskDescriptions.contains("Resolving")); WAIT_FOR_NEW_TIMESTAMP(); f.remove(); errorInfo = doBuildProject("new-pattern-match", 0, 0, &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY(receiver.taskDescriptions.contains("Resolving")); } void TestApi::nonexistingProjectPropertyFromProduct() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("nonexistingprojectproperties"); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QEXPECT_FAIL("", "QBS-432", Abort); QVERIFY(job->error().hasError()); QVERIFY2(job->error().toString().contains(QLatin1String("blubb")), qPrintable(job->error().toString())); } void TestApi::nonexistingProjectPropertyFromCommandLine() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("nonexistingprojectproperties"); removeBuildDir(setupParams); QVariantMap projectProperties; projectProperties.insert(QLatin1String("project.blubb"), QLatin1String("true")); setupParams.setOverriddenValues(projectProperties); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY(job->error().hasError()); QVERIFY2(job->error().toString().contains(QLatin1String("blubb")), qPrintable(job->error().toString())); } void TestApi::objC() { const qbs::ErrorInfo errorInfo = doBuildProject("objc"); VERIFY_NO_ERROR(errorInfo); } void TestApi::projectDataAfterProductInvalidation() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("project-data-after-" "product-invalidation/project-data-after-product-invalidation.qbs"); std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); qbs::Project project = setupJob->project(); QVERIFY(project.isValid()); QCOMPARE(project.projectData().products().size(), 1); QVERIFY(project.projectData().products().front().generatedArtifacts().empty()); std::unique_ptr<qbs::BuildJob> buildJob(project.buildAllProducts(qbs::BuildOptions())); waitForFinished(buildJob.get()); QVERIFY2(!buildJob->error().hasError(), qPrintable(buildJob->error().toString())); QCOMPARE(project.projectData().products().size(), 1); const qbs::ProductData productAfterBulding = project.projectData().products().front(); QVERIFY(!productAfterBulding.generatedArtifacts().empty()); QFile projectFile(setupParams.projectFilePath()); WAIT_FOR_NEW_TIMESTAMP(); QVERIFY2(projectFile.open(QIODevice::ReadWrite), qPrintable(projectFile.errorString())); QByteArray content = projectFile.readAll(); QVERIFY(!content.isEmpty()); content.replace("\"file.cpp", "// \"file.cpp"); projectFile.resize(0); projectFile.write(content); projectFile.flush(); setupJob.reset(project.setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); QVERIFY(!project.isValid()); project = setupJob->project(); QVERIFY(project.isValid()); QCOMPARE(project.projectData().products().size(), 1); QVERIFY(project.projectData().products().front().generatedArtifacts() == productAfterBulding.generatedArtifacts()); buildJob.reset(project.buildAllProducts(qbs::BuildOptions())); waitForFinished(buildJob.get()); QVERIFY2(!buildJob->error().hasError(), qPrintable(buildJob->error().toString())); QCOMPARE(project.projectData().products().size(), 1); QVERIFY(project.projectData().products().front().generatedArtifacts() != productAfterBulding.generatedArtifacts()); } void TestApi::processResult() { // On Windows, even closed files seem to sometimes block the removal of their parent directories // for a while. if (qbs::Internal::HostOsInfo::isWindowsHost()) QTest::qWait(500); removeBuildDir(defaultSetupParameters("process-result")); QFETCH(int, expectedExitCode); QFETCH(bool, redirectStdout); QFETCH(bool, redirectStderr); QVariantMap overridden; overridden.insert("products.app-caller.argument", expectedExitCode); overridden.insert("products.app-caller.redirectStdout", redirectStdout); overridden.insert("products.app-caller.redirectStderr", redirectStderr); ProcessResultReceiver resultReceiver; const qbs::ErrorInfo errorInfo = doBuildProject("process-result", nullptr, &resultReceiver, nullptr, qbs::BuildOptions(), overridden); QCOMPARE(expectedExitCode != 0, errorInfo.hasError()); QVERIFY(resultReceiver.results.size() > 1); const qbs::ProcessResult &result = resultReceiver.results.back(); QVERIFY2(result.executableFilePath().contains("app"), qPrintable(result.executableFilePath())); QCOMPARE(expectedExitCode, result.exitCode()); QCOMPARE(expectedExitCode == 0, result.success()); QCOMPARE(result.error(), QProcess::UnknownError); struct CheckParams { CheckParams(bool r, const QString &f, const QByteArray &c, const QStringList &co) : redirect(r), fileName(f), expectedContent(c), consoleOutput(co) {} bool redirect; QString fileName; QByteArray expectedContent; const QStringList consoleOutput; }; const std::vector<CheckParams> checkParams({ CheckParams(redirectStdout, "stdout.txt", "stdout", result.stdOut()), CheckParams(redirectStderr, "stderr.txt", "stderr", result.stdErr()) }); for (const CheckParams &p : checkParams) { QFile f(relativeProductBuildDir("app-caller") + '/' + p.fileName); QCOMPARE(f.exists(), p.redirect); if (p.redirect) { QVERIFY2(f.open(QIODevice::ReadOnly), qPrintable(f.errorString())); QCOMPARE(f.readAll(), p.expectedContent); QCOMPARE(p.consoleOutput, QStringList()); } else { QCOMPARE(p.consoleOutput.join("").toLocal8Bit(), p.expectedContent); } } } void TestApi::processResult_data() { QTest::addColumn<int>("expectedExitCode"); QTest::addColumn<bool>("redirectStdout"); QTest::addColumn<bool>("redirectStderr"); QTest::newRow("success, no redirection") << 0 << false << false; QTest::newRow("success, stdout redirection") << 0 << true << false; QTest::newRow("failure, stderr redirection") << 1 << false << true; } void TestApi::projectInvalidation() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("project-invalidation"); QVERIFY(QFile::copy("project.no-error.qbs", "project-invalidation.qbs")); std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); qbs::Project project = setupJob->project(); QVERIFY(project.isValid()); WAIT_FOR_NEW_TIMESTAMP(); copyFileAndUpdateTimestamp("project.early-error.qbs", "project-invalidation.qbs"); setupJob.reset(project.setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY(setupJob->error().hasError()); QVERIFY(project.isValid()); // Error in Loader, old project still valid. WAIT_FOR_NEW_TIMESTAMP(); copyFileAndUpdateTimestamp("project.late-error.qbs", "project-invalidation.qbs"); setupJob.reset(project.setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY(setupJob->error().hasError()); QVERIFY(!project.isValid()); // Error in build data re-resolving, old project not valid anymore. } void TestApi::projectLocking() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("project-locking"); std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); qbs::Project project = setupJob->project(); setupJob.reset(project.setupProject(setupParams, m_logSink, 0)); std::unique_ptr<qbs::SetupProjectJob> setupJob2(project.setupProject(setupParams, m_logSink, 0)); waitForFinished(setupJob2.get()); QVERIFY(setupJob2->error().hasError()); QVERIFY2(setupJob2->error().toString() .contains("Cannot start a job while another one is in progress."), qPrintable(setupJob2->error().toString())); waitForFinished(setupJob.get()); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); } void TestApi::projectPropertiesByName() { const QString projectFile = "project-properties-by-name/project-properties-by-name.qbs"; qbs::ErrorInfo errorInfo = doBuildProject(projectFile); QVERIFY(errorInfo.hasError()); QVariantMap overridden; overridden.insert("project.theDefines", QStringList() << "SUB1" << "SUB2"); errorInfo = doBuildProject(projectFile, 0, 0, 0, qbs::BuildOptions(), overridden); QVERIFY(errorInfo.hasError()); overridden.clear(); overridden.insert("projects.subproject1.theDefines", QStringList() << "SUB1"); errorInfo = doBuildProject(projectFile, 0, 0, 0, qbs::BuildOptions(), overridden); QVERIFY(errorInfo.hasError()); overridden.insert("projects.subproject2.theDefines", QStringList() << "SUB2"); errorInfo = doBuildProject(projectFile, 0, 0, 0, qbs::BuildOptions(), overridden); VERIFY_NO_ERROR(errorInfo); } void TestApi::projectWithPropertiesItem() { const qbs::ErrorInfo errorInfo = doBuildProject("project-with-properties-item"); VERIFY_NO_ERROR(errorInfo); } void TestApi::propertiesBlocks() { const qbs::ErrorInfo errorInfo = doBuildProject("properties-blocks"); VERIFY_NO_ERROR(errorInfo); } void TestApi::rc() { BuildDescriptionReceiver bdr; ProcessResultReceiver prr; const qbs::ErrorInfo errorInfo = doBuildProject("rc", &bdr, &prr); if (errorInfo.hasError()) qDebug() << prr.output; VERIFY_NO_ERROR(errorInfo); const bool rcFileWasCompiled = bdr.descriptions.contains("compiling test.rc"); QCOMPARE(rcFileWasCompiled, qbs::Internal::HostOsInfo::isWindowsHost()); } void TestApi::referencedFileErrors() { QFETCH(bool, relaxedMode); qbs::SetupProjectParameters params = defaultSetupParameters("referenced-file-errors"); params.setDryRun(true); params.setProductErrorMode(relaxedMode ? qbs::ErrorHandlingMode::Relaxed : qbs::ErrorHandlingMode::Strict); m_logSink->setLogLevel(qbs::LoggerMinLevel); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(params, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(job->error().hasError() != relaxedMode, qPrintable(job->error().toString())); const qbs::Project project = job->project(); QCOMPARE(project.isValid(), relaxedMode); if (!relaxedMode) return; const QList<qbs::ProductData> products = project.projectData().allProducts(); QCOMPARE(products.size(), 5); for (const qbs::ProductData &p : products) QCOMPARE(p.isEnabled(), p.name() != "p5"); } void TestApi::referencedFileErrors_data() { QTest::addColumn<bool>("relaxedMode"); QTest::newRow("strict mode") << false; QTest::newRow("relaxed mode") << true; } qbs::SetupProjectParameters TestApi::defaultSetupParameters(const QString &projectFileOrDir) const { QFileInfo fi(m_workingDataDir + QLatin1Char('/') + projectFileOrDir); QString projectDirPath; QString projectFilePath; if (fi.isDir()) { projectDirPath = fi.absoluteFilePath(); projectFilePath = projectDirPath + QLatin1Char('/') + projectFileOrDir + QStringLiteral(".qbs"); } else { projectDirPath = fi.absolutePath(); projectFilePath = fi.absoluteFilePath(); } qbs::SetupProjectParameters setupParams; setupParams.setEnvironment(QProcessEnvironment::systemEnvironment()); setupParams.setProjectFilePath(projectFilePath); setupParams.setPropertyCheckingMode(qbs::ErrorHandlingMode::Strict); setupParams.setOverrideBuildGraphData(true); QDir::setCurrent(projectDirPath); setupParams.setBuildRoot(projectDirPath); const SettingsPtr s = settings(); const qbs::Preferences prefs(s.get(), profileName()); setupParams.setSearchPaths(prefs.searchPaths(QDir::cleanPath(QCoreApplication::applicationDirPath() + QLatin1String("/" QBS_RELATIVE_SEARCH_PATH)))); setupParams.setPluginPaths(prefs.pluginPaths(QDir::cleanPath(QCoreApplication::applicationDirPath() + QLatin1String("/" QBS_RELATIVE_PLUGINS_PATH)))); setupParams.setLibexecPath(QDir::cleanPath(QCoreApplication::applicationDirPath() + QLatin1String("/" QBS_RELATIVE_LIBEXEC_PATH))); setupParams.setTopLevelProfile(profileName()); setupParams.setConfigurationName(QStringLiteral("default")); setupParams.setSettingsDirectory(settings()->baseDirectory()); return setupParams; } void TestApi::references() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("references/invalid1.qbs"); const QString projectDir = QDir::cleanPath(m_workingDataDir + "/references"); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY(job->error().hasError()); QString errorString = job->error().toString(); QVERIFY2(errorString.contains("does not contain"), qPrintable(errorString)); setupParams.setProjectFilePath(projectDir + QLatin1String("/invalid2.qbs")); job.reset(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY(job->error().hasError()); errorString = job->error().toString(); QVERIFY2(errorString.contains("contains more than one"), qPrintable(errorString)); setupParams.setProjectFilePath(projectDir + QLatin1String("/valid.qbs")); job.reset(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); const qbs::ProjectData topLevelProject = job->project().projectData(); QCOMPARE(topLevelProject.subProjects().size(), 1); const QString subProjectFileName = QFileInfo(topLevelProject.subProjects().front().location().filePath()).fileName(); QCOMPARE(subProjectFileName, QString("p.qbs")); } void TestApi::relaxedModeRecovery() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("relaxed-mode-recovery"); setupParams.setProductErrorMode(qbs::ErrorHandlingMode::Relaxed); setupParams.setPropertyCheckingMode(qbs::ErrorHandlingMode::Relaxed); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); if (m_logSink->warnings.size() != 4) { const auto errors = m_logSink->warnings; for (const qbs::ErrorInfo &error : errors) qDebug() << error.toString(); } QCOMPARE(m_logSink->warnings.size(), 4); const auto errors = m_logSink->warnings; for (const qbs::ErrorInfo &error : errors) { QVERIFY2(!error.toString().contains("ASSERT") && (error.toString().contains("Dependency 'blubb' not found") || error.toString().contains("Product 'p1' had errors and was disabled") || error.toString().contains("Product 'p2' had errors and was disabled")), qPrintable(error.toString())); } } void TestApi::renameProduct() { // Initial run. qbs::ErrorInfo errorInfo = doBuildProject("rename-product/rename.qbs"); VERIFY_NO_ERROR(errorInfo); // Rename lib and adapt Depends item. WAIT_FOR_NEW_TIMESTAMP(); QFile f("rename.qbs"); QVERIFY(f.open(QIODevice::ReadWrite)); QByteArray contents = f.readAll(); contents.replace("TheLib", "thelib"); f.resize(0); f.write(contents); f.close(); errorInfo = doBuildProject("rename-product/rename.qbs"); VERIFY_NO_ERROR(errorInfo); // Rename lib and don't adapt Depends item. WAIT_FOR_NEW_TIMESTAMP(); QVERIFY(f.open(QIODevice::ReadWrite)); contents = f.readAll(); const int libNameIndex = contents.lastIndexOf("thelib"); QVERIFY(libNameIndex != -1); contents.replace(libNameIndex, 6, "TheLib"); f.resize(0); f.write(contents); f.close(); errorInfo = doBuildProject("rename-product/rename.qbs"); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("Dependency 'thelib' not found"), qPrintable(errorInfo.toString())); } void TestApi::renameTargetArtifact() { // Initial run. BuildDescriptionReceiver receiver; qbs::ErrorInfo errorInfo = doBuildProject("rename-target-artifact/rename.qbs", &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY2(receiver.descriptions.contains("compiling"), qPrintable(receiver.descriptions)); QCOMPARE(receiver.descriptions.count("linking"), 2); receiver.descriptions.clear(); // Rename library file name. WAIT_FOR_NEW_TIMESTAMP(); QFile f("rename.qbs"); QVERIFY(f.open(QIODevice::ReadWrite)); QByteArray contents = f.readAll(); contents.replace("the_lib", "TheLib"); f.resize(0); f.write(contents); f.close(); errorInfo = doBuildProject("rename-target-artifact/rename.qbs", &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY2(!receiver.descriptions.contains("compiling"), qPrintable(receiver.descriptions)); QCOMPARE(receiver.descriptions.count("linking"), 2); } void TestApi::removeFileDependency() { qbs::ErrorInfo errorInfo = doBuildProject("remove-file-dependency/removeFileDependency.qbs"); VERIFY_NO_ERROR(errorInfo); QFile::remove("someheader.h"); ProcessResultReceiver receiver; errorInfo = doBuildProject("remove-file-dependency/removeFileDependency.qbs", 0, &receiver); QVERIFY(errorInfo.hasError()); QVERIFY2(receiver.output.contains("someheader.h"), qPrintable(receiver.output)); } void TestApi::resolveProject() { QFETCH(QString, projectSubDir); QFETCH(QString, productFileName); const qbs::SetupProjectParameters params = defaultSetupParameters(projectSubDir); removeBuildDir(params); const std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(params, m_logSink, 0)); waitForFinished(setupJob.get()); VERIFY_NO_ERROR(setupJob->error()); QVERIFY2(!QFile::exists(productFileName), qPrintable(productFileName)); QVERIFY(regularFileExists(relativeBuildGraphFilePath())); } void TestApi::resolveProject_data() { return buildProject_data(); } void TestApi::resolveProjectDryRun() { QFETCH(QString, projectSubDir); QFETCH(QString, productFileName); qbs::SetupProjectParameters params = defaultSetupParameters(projectSubDir); params.setDryRun(true); removeBuildDir(params); const std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(params, m_logSink, 0)); waitForFinished(setupJob.get()); VERIFY_NO_ERROR(setupJob->error()); QVERIFY2(!QFile::exists(productFileName), qPrintable(productFileName)); QVERIFY(!regularFileExists(relativeBuildGraphFilePath())); } void TestApi::resolveProjectDryRun_data() { return resolveProject_data(); } void TestApi::restoredWarnings() { qbs::SetupProjectParameters setupParams = defaultSetupParameters("restored-warnings"); setupParams.setPropertyCheckingMode(qbs::ErrorHandlingMode::Relaxed); setupParams.setProductErrorMode(qbs::ErrorHandlingMode::Relaxed); // Initial resolving: Errors are new. std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); job.reset(nullptr); QCOMPARE(m_logSink->warnings.toSet().size(), 2); const auto beforeErrors = m_logSink->warnings; for (const qbs::ErrorInfo &e : beforeErrors) { const QString msg = e.toString(); QVERIFY2(msg.contains("Superfluous version") || msg.contains("Property 'blubb' is not declared"), qPrintable(msg)); } m_logSink->warnings.clear(); // Re-resolving with no changes: Errors come from the stored build graph. job.reset(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); job.reset(nullptr); QCOMPARE(m_logSink->warnings.toSet().size(), 2); m_logSink->warnings.clear(); // Re-resolving with changes: Errors come from the re-resolving, stored ones must be suppressed. QVariantMap overridenValues; overridenValues.insert("products.theProduct.moreFiles", true); setupParams.setOverriddenValues(overridenValues); job.reset(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); job.reset(nullptr); QCOMPARE(m_logSink->warnings.toSet().size(), 3); // One more for the additional group const auto afterErrors = m_logSink->warnings; for (const qbs::ErrorInfo &e : afterErrors) { const QString msg = e.toString(); QVERIFY2(msg.contains("Superfluous version") || msg.contains("Property 'blubb' is not declared") || msg.contains("blubb.cpp' does not exist"), qPrintable(msg)); } m_logSink->warnings.clear(); } void TestApi::ruleConflict() { const qbs::ErrorInfo errorInfo = doBuildProject("rule-conflict"); QVERIFY(errorInfo.hasError()); const QString errorString = errorInfo.toString(); QVERIFY2(errorString.contains("conflict") && errorString.contains("pch1.h") && errorString.contains("pch2.h"), qPrintable(errorString)); } void TestApi::runEnvForDisabledProduct() { const qbs::SetupProjectParameters params = defaultSetupParameters("run-disabled-product/run-disabled-product.qbs"); const std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(params, m_logSink, 0)); QVERIFY(waitForFinished(setupJob.get())); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); const qbs::Project project = setupJob->project(); const std::unique_ptr<qbs::BuildJob> buildJob(project.buildAllProducts(qbs::BuildOptions())); QVERIFY(waitForFinished(buildJob.get())); QVERIFY2(!buildJob->error().hasError(), qPrintable(buildJob->error().toString())); const qbs::ProjectData projectData = project.projectData(); const QList<qbs::ProductData> products = projectData.products(); QCOMPARE(products.size(), 1); const qbs::ProductData product = products.front(); qbs::RunEnvironment runEnv = project.getRunEnvironment( product, qbs::InstallOptions(), QProcessEnvironment(), QStringList(), settings().get()); qbs::ErrorInfo runError; const QProcessEnvironment env = runEnv.runEnvironment(&runError); QVERIFY2(runError.toString().contains("Cannot run disabled product 'app'"), qPrintable(runError.toString())); runError.clear(); runEnv.runTarget(QString(), QStringList(), true, &runError); QVERIFY2(runError.toString().contains("Cannot run disabled product 'app'"), qPrintable(runError.toString())); } void TestApi::softDependency() { const qbs::ErrorInfo errorInfo = doBuildProject("soft-dependency"); VERIFY_NO_ERROR(errorInfo); } void TestApi::sourceFileInBuildDir() { VERIFY_NO_ERROR(doBuildProject("source-file-in-build-dir")); qbs::SetupProjectParameters setupParams = defaultSetupParameters("source-file-in-build-dir"); const QString generatedFile = relativeProductBuildDir("theProduct") + "/generated.cpp"; QVERIFY2(regularFileExists(generatedFile), qPrintable(generatedFile)); std::unique_ptr<qbs::SetupProjectJob> job(qbs::Project().setupProject(setupParams, m_logSink, 0)); waitForFinished(job.get()); QVERIFY2(!job->error().hasError(), qPrintable(job->error().toString())); const qbs::ProjectData projectData = job->project().projectData(); QCOMPARE(projectData.allProducts().size(), 1); const qbs::ProductData product = projectData.allProducts().front(); QCOMPARE(product.profile(), profileName()); const qbs::GroupData group = findGroup(product, "the group"); QVERIFY(group.isValid()); QCOMPARE(group.allFilePaths().size(), 1); } void TestApi::subProjects() { const qbs::SetupProjectParameters params = defaultSetupParameters("subprojects/toplevelproject.qbs"); removeBuildDir(params); // Check all three types of subproject creation, plus property overrides. qbs::ErrorInfo errorInfo = doBuildProject("subprojects/toplevelproject.qbs"); VERIFY_NO_ERROR(errorInfo); // Disabling both the project with the dependency and the one with the dependent // should not cause an error. WAIT_FOR_NEW_TIMESTAMP(); QFile f(params.projectFilePath()); QVERIFY(f.open(QIODevice::ReadWrite)); QByteArray contents = f.readAll(); contents.replace("condition: true", "condition: false"); f.resize(0); f.write(contents); f.close(); f.setFileName(params.buildRoot() + "/subproject2/subproject2.qbs"); QVERIFY(f.open(QIODevice::ReadWrite)); contents = f.readAll(); contents.replace("condition: qbs.targetOS.length > 0", "condition: false"); f.resize(0); f.write(contents); f.close(); errorInfo = doBuildProject("subprojects/toplevelproject.qbs"); VERIFY_NO_ERROR(errorInfo); // Disabling the project with the dependency only is an error. // This tests also whether changes in sub-projects are detected. WAIT_FOR_NEW_TIMESTAMP(); f.setFileName(params.projectFilePath()); QVERIFY(f.open(QIODevice::ReadWrite)); contents = f.readAll(); contents.replace("condition: false", "condition: true"); f.resize(0); f.write(contents); f.close(); errorInfo = doBuildProject("subprojects/toplevelproject.qbs"); QVERIFY(errorInfo.hasError()); QVERIFY2(errorInfo.toString().contains("Dependency 'testLib' not found"), qPrintable(errorInfo.toString())); } void TestApi::toolInModule() { QVariantMap overrides({std::make_pair("qbs.installRoot", m_workingDataDir + "/tool-in-module/use-outside-project")}); const qbs::ErrorInfo error = doBuildProject("tool-in-module/use-within-project/use-within-project.qbs", nullptr, nullptr, nullptr, qbs::BuildOptions(), overrides); QVERIFY2(!error.hasError(), qPrintable(error.toString())); const QString toolOutput = relativeProductBuildDir("user-in-project") + "/tool-output.txt"; QVERIFY2(QFile::exists(toolOutput), qPrintable(toolOutput)); const qbs::SetupProjectParameters params = defaultSetupParameters("tool-in-module/use-outside-project/use-outside-project.qbs"); const std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(params, m_logSink, 0)); QVERIFY(waitForFinished(setupJob.get())); QVERIFY2(!setupJob->error().hasError(), qPrintable(setupJob->error().toString())); const qbs::Project project = setupJob->project(); const qbs::ProjectData projectData = project.projectData(); const QList<qbs::ProductData> products = projectData.products(); QCOMPARE(products.size(), 1); const qbs::ProductData product = products.front(); for (const qbs::GroupData &group : product.groups()) QVERIFY(group.name() != "thetool binary"); const std::unique_ptr<qbs::BuildJob> buildJob(setupJob->project() .buildAllProducts(qbs::BuildOptions())); QVERIFY(waitForFinished(buildJob.get())); QVERIFY2(!buildJob->error().hasError(), qPrintable(buildJob->error().toString())); const QString toolOutput2 = relativeProductBuildDir("user-outside-project") + "/tool-output.txt"; QVERIFY2(QFile::exists(toolOutput2), qPrintable(toolOutput2)); } void TestApi::trackAddQObjectHeader() { const qbs::SetupProjectParameters params = defaultSetupParameters("missing-qobject-header/missingheader.qbs"); QFile qbsFile(params.projectFilePath()); QVERIFY(qbsFile.open(QIODevice::WriteOnly | QIODevice::Truncate)); qbsFile.write("import qbs.base 1.0\nCppApplication {\n Depends { name: 'Qt.core' }\n" " files: ['main.cpp', 'myobject.cpp']\n}"); qbsFile.close(); ProcessResultReceiver receiver; qbs::ErrorInfo errorInfo = doBuildProject("missing-qobject-header/missingheader.qbs", 0, &receiver); QVERIFY(errorInfo.hasError()); QVERIFY2(isAboutUndefinedSymbols(receiver.output), qPrintable(receiver.output)); WAIT_FOR_NEW_TIMESTAMP(); QVERIFY(qbsFile.open(QIODevice::WriteOnly | QIODevice::Truncate)); qbsFile.write("import qbs.base 1.0\nCppApplication {\n Depends { name: 'Qt.core' }\n" " files: ['main.cpp', 'myobject.cpp','myobject.h']\n}"); qbsFile.close(); errorInfo = doBuildProject("missing-qobject-header/missingheader.qbs"); VERIFY_NO_ERROR(errorInfo); } void TestApi::trackRemoveQObjectHeader() { const qbs::SetupProjectParameters params = defaultSetupParameters("missing-qobject-header/missingheader.qbs"); removeBuildDir(params); QFile qbsFile(params.projectFilePath()); QVERIFY(qbsFile.open(QIODevice::WriteOnly | QIODevice::Truncate)); qbsFile.write("import qbs.base 1.0\nCppApplication {\n Depends { name: 'Qt.core' }\n" " files: ['main.cpp', 'myobject.cpp','myobject.h']\n}"); qbsFile.close(); qbs::ErrorInfo errorInfo = doBuildProject("missing-qobject-header/missingheader.qbs"); VERIFY_NO_ERROR(errorInfo); WAIT_FOR_NEW_TIMESTAMP(); QVERIFY(qbsFile.open(QIODevice::WriteOnly | QIODevice::Truncate)); qbsFile.write("import qbs.base 1.0\nCppApplication {\n Depends { name: 'Qt.core' }\n" " files: ['main.cpp', 'myobject.cpp']\n}"); qbsFile.close(); ProcessResultReceiver receiver; errorInfo = doBuildProject("missing-qobject-header/missingheader.qbs", 0, &receiver); QVERIFY(errorInfo.hasError()); QVERIFY2(isAboutUndefinedSymbols(receiver.output), qPrintable(receiver.output)); } void TestApi::transformers() { const qbs::ErrorInfo errorInfo = doBuildProject("transformers/transformers.qbs"); VERIFY_NO_ERROR(errorInfo); } void TestApi::typeChange() { BuildDescriptionReceiver receiver; qbs::ErrorInfo errorInfo = doBuildProject("type-change", &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY2(!receiver.descriptions.contains("compiling"), qPrintable(receiver.descriptions)); WAIT_FOR_NEW_TIMESTAMP(); QFile projectFile("type-change.qbs"); QVERIFY2(projectFile.open(QIODevice::ReadWrite), qPrintable(projectFile.errorString())); QByteArray content = projectFile.readAll(); content.replace("//", ""); projectFile.resize(0); projectFile.write(content); projectFile.close(); errorInfo = doBuildProject("type-change", &receiver); VERIFY_NO_ERROR(errorInfo); QVERIFY2(receiver.descriptions.contains("compiling"), qPrintable(receiver.descriptions)); } void TestApi::uic() { const qbs::ErrorInfo errorInfo = doBuildProject("uic"); VERIFY_NO_ERROR(errorInfo); } qbs::ErrorInfo TestApi::doBuildProject( const QString &projectFilePath, BuildDescriptionReceiver *buildDescriptionReceiver, ProcessResultReceiver *procResultReceiver, TaskReceiver *taskReceiver, const qbs::BuildOptions &options, const QVariantMap overriddenValues) { qbs::SetupProjectParameters params = defaultSetupParameters(projectFilePath); params.setOverriddenValues(overriddenValues); params.setDryRun(options.dryRun()); const std::unique_ptr<qbs::SetupProjectJob> setupJob(qbs::Project().setupProject(params, m_logSink, 0)); if (taskReceiver) { connect(setupJob.get(), &qbs::AbstractJob::taskStarted, taskReceiver, &TaskReceiver::handleTaskStart); } waitForFinished(setupJob.get()); if (setupJob->error().hasError()) return setupJob->error(); const std::unique_ptr<qbs::BuildJob> buildJob(setupJob->project().buildAllProducts(options)); if (buildDescriptionReceiver) { connect(buildJob.get(), &qbs::BuildJob::reportCommandDescription, buildDescriptionReceiver, &BuildDescriptionReceiver::handleDescription); } if (procResultReceiver) { connect(buildJob.get(), &qbs::BuildJob::reportProcessResult, procResultReceiver, &ProcessResultReceiver::handleProcessResult); } waitForFinished(buildJob.get()); return buildJob->error(); } QTEST_MAIN(TestApi) #include "tst_api.moc"
126,756
39,199
// Copyright 2010-2018 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START program] // [START import] #include <iterator> #include <numeric> #include <sstream> #include "ortools/algorithms/knapsack_solver.h" // [END import] namespace operations_research { void RunKnapsackExample() { // Instantiate the solver. // [START solver] KnapsackSolver solver( KnapsackSolver::KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, "KnapsackExample"); // [END solver] // [START data] std::vector<int64> values = { 360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, 38, 48, 147, 78, 256, 63, 17, 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, 514, 28, 87, 73, 78, 15, 26, 78, 210, 36, 85, 189, 274, 43, 33, 10, 19, 389, 276, 312}; std::vector<std::vector<int64>> weights = { {7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9, 0, 42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44, 71, 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13}}; std::vector<int64> capacities = {850}; // [END data] // [START solve] solver.Init(values, weights, capacities); int64 computed_value = solver.Solve(); // [END solve] // Print solution // [START print_solution] std::vector<int> packed_items; for (std::size_t i = 0; i < values.size(); ++i) { if (solver.BestSolutionContains(i)) packed_items.push_back(i); } std::ostringstream packed_items_ss; std::copy(packed_items.begin(), packed_items.end() - 1, std::ostream_iterator<int>(packed_items_ss, ", ")); packed_items_ss << packed_items.back(); std::vector<int64> packed_weights; packed_weights.reserve(packed_items.size()); for (const auto& it : packed_items) { packed_weights.push_back(weights[0][it]); } std::ostringstream packed_weights_ss; std::copy(packed_weights.begin(), packed_weights.end() - 1, std::ostream_iterator<int>(packed_weights_ss, ", ")); packed_weights_ss << packed_weights.back(); int64 total_weights = std::accumulate(packed_weights.begin(), packed_weights.end(), int64{0}); LOG(INFO) << "Total value: " << computed_value; LOG(INFO) << "Packed items: {" << packed_items_ss.str() << "}"; LOG(INFO) << "Total weight: " << total_weights; LOG(INFO) << "Packed weights: {" << packed_weights_ss.str() << "}"; // [END print_solution] } } // namespace operations_research int main(int argc, char** argv) { operations_research::RunKnapsackExample(); return EXIT_SUCCESS; } // [END program]
3,091
1,359
#include <windows.h> #include <commctrl.h> #pragma comment(lib, "comctl32.lib") /* Code derived from example at https://msdn.microsoft.com/en-us/library/windows/desktop/hh298382(v=vs.85).aspx */ HIMAGELIST g_hImageList = NULL; HINSTANCE g_hInst; HWND hwnd; HWND CreateVerticalToolbar(HWND hWndParent) { // Define the buttons. // IDM_NEW, IDM_0PEN, and IDM_SAVE are application-defined command IDs. const int numButtons = 3; TBBUTTON tbButtons3[numButtons] = { { STD_FILENEW, 0, TBSTATE_ENABLED | TBSTATE_WRAP, BTNS_BUTTON,{ 0 }, 0L, 0 }, { STD_FILEOPEN, 0, TBSTATE_ENABLED | TBSTATE_WRAP, BTNS_BUTTON,{ 0 }, 0L, 0 }, { STD_FILESAVE, 0, TBSTATE_ENABLED | TBSTATE_WRAP, BTNS_BUTTON,{ 0 }, 0L, 0 } }; // Create the toolbar window. HWND hWndToolbar = CreateWindowEx(0, TOOLBARCLASSNAME, NULL, WS_CHILD | WS_VISIBLE | CCS_VERT | WS_BORDER, 0, 0, 0, 0, hWndParent, NULL, g_hInst, NULL); // Create the image list. g_hImageList = ImageList_Create(24, 24, // Dimensions of individual bitmaps. ILC_COLOR16 | ILC_MASK, // Ensures transparent background. numButtons, 0); // Set the image list. SendMessage(hWndToolbar, TB_SETIMAGELIST, 0, (LPARAM)g_hImageList); // Load the button images. SendMessage(hWndToolbar, TB_LOADIMAGES, (WPARAM)IDB_STD_LARGE_COLOR, (LPARAM)HINST_COMMCTRL); // Add them to the toolbar. SendMessage(hWndToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0); SendMessage(hWndToolbar, TB_ADDBUTTONS, numButtons, (LPARAM)&tbButtons3); return hWndToolbar; }
1,515
702
#include "Standard.h" #include "PromptBox.h" #include "Global.h" #include "Resources.h" #include "ResourceLoader.h" #include "GUIButton.h" #include "GUITextbox.h" #include "GUIButtonParamaterized.h" PromptBox::PromptBox(ANCHOR anchor, Coord disp, Coord dims, GUIContainer* parent, std::string prompt, void(*onOk) (PromptBox* thisObj), void(*onCancel) (PromptBox* thisObj)) : GUIContainer(parent, anchor, disp, dims, _color_bkg_standard) { promptText_ = prompt; okButton_ = new GUIButtonParamaterized<PromptBox*>(this, ANCHOR_SOUTHWEST, { 20, -20 }, "OK", 50, onOk, this); this->addObject(okButton_); cancelButton_ = new GUIButtonParamaterized<PromptBox*>(this, ANCHOR_SOUTHEAST, { -20, -20 }, "CANCEL", 50, onCancel, this); this->addObject(cancelButton_); entryField_ = new GUITextbox(this, ANCHOR_NORTHWEST, { 5, 50 }, { bounds_.w - 10, textSize_ }, 100, false); this->addObject(entryField_); } PromptBox::~PromptBox() { // dtor } void PromptBox::draw() { // draw the box GUIContainer::drawBkg(); // draw the contents (only buttons in this case) GUIContainer::drawContents(); // draw bounds if (_debug >= DEBUG_NORMAL) GUIContainer::drawBounds(); // draw prompt SDL_Rect tempBounds; SDL_Texture* name = loadString(promptText_, FONT_NORMAL, textSize_, { 255, 255, 255, (Uint8)currAlpha_ }); SDL_QueryTexture(name, NULL, NULL, &tempBounds.w, &tempBounds.h); tempBounds.x = bounds_.x + 5; tempBounds.y = bounds_.y + 5; SDL_RenderCopy(_renderer, name, NULL, &tempBounds); SDL_DestroyTexture(name); } std::string PromptBox::getContents() { return entryField_->getContents(); } void PromptBox::clearContents() { entryField_->clearContents(); } void PromptBox::keyPress(char c) { if (c == 13) { // enter/return okButton_->mouseDown(); okButton_->mouseUp(); } else if (c == 27) { // escape cancelButton_->mouseDown(); cancelButton_->mouseUp(); } else entryField_->keyPress(c); } GUITextbox* PromptBox::getTextbox() { return entryField_; }
1,986
786
/* BLOCKING QUEUE IMPLEMENTATION Version B02: General blocking queues Underlying mechanism: Condition variables */ #include <iostream> #include <queue> #include <string> #include <stdexcept> #include <unistd.h> #include <pthread.h> using namespace std; template <typename T> class BlockingQueue { private: /* I use a lot of synchronization primitives to help you to understand. In a practical context, please take a look at the BlockingQueue implementation in "mylib-blockingqueue" */ pthread_cond_t condEmpty = PTHREAD_COND_INITIALIZER; pthread_cond_t condFull = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutEmpty = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutFull = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutQueue = PTHREAD_MUTEX_INITIALIZER; int capacity = 0; std::queue<T> q; public: BlockingQueue(int capacity) { if (capacity <= 0) throw std::invalid_argument("capacity must be a positive integer"); this->capacity = capacity; } ~BlockingQueue() { pthread_cond_destroy(&condEmpty); pthread_cond_destroy(&condFull); pthread_mutex_destroy(&mutEmpty); pthread_mutex_destroy(&mutFull); pthread_mutex_destroy(&mutQueue); } void put(const T& value) { int ret = 0; ret = pthread_mutex_lock(&mutFull); while (capacity == q.size()) { // queue is full, must wait for 'take' ret = pthread_cond_wait(&condFull, &mutFull); } ret = pthread_mutex_unlock(&mutFull); ret = pthread_mutex_lock(&mutQueue); q.push(value); ret = pthread_mutex_unlock(&mutQueue); ret = pthread_cond_signal(&condEmpty); } T take() { T result; int ret = 0; ret = pthread_mutex_lock(&mutEmpty); while (0 == q.size()) { // queue is empty, must wait for 'put' ret = pthread_cond_wait(&condEmpty, &mutEmpty); } ret = pthread_mutex_unlock(&mutEmpty); ret = pthread_mutex_lock(&mutQueue); result = q.front(); q.pop(); ret = pthread_mutex_unlock(&mutQueue); ret = pthread_cond_signal(&condFull); return result; } }; void* producer(void* arg) { auto blkQueue = (BlockingQueue<std::string>*) arg; auto arr = { "nice", "to", "meet", "you" }; for (auto&& value : arr) { cout << "Producer: " << value << endl; blkQueue->put(value); cout << "Producer: " << value << "\t\t\t[done]" << endl; } pthread_exit(nullptr); return nullptr; } void* consumer(void* arg) { auto blkQueue = (BlockingQueue<std::string>*) arg; sleep(5); for (int i = 0; i < 4; ++i) { std::string data = blkQueue->take(); cout << "\tConsumer: " << data << endl; if (0 == i) sleep(5); } pthread_exit(nullptr); return nullptr; } int main() { BlockingQueue<std::string> blkQueue(2); // capacity = 2 pthread_t tidProducer, tidConsumer; int ret = 0; ret = pthread_create(&tidProducer, nullptr, producer, &blkQueue); ret = pthread_create(&tidConsumer, nullptr, consumer, &blkQueue); ret = pthread_join(tidProducer, nullptr); ret = pthread_join(tidConsumer, nullptr); return 0; }
3,367
1,166
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2020 Intel Corporation. All Rights Reserved. //#cmake:add-file ../../../src/algo/thermal-loop/*.cpp #include "../algo-common.h" #include "create-synthetic-l500-thermal-table.h" #include <src/algo/thermal-loop/l500-thermal-loop.h> using namespace librealsense::algo::thermal_loop::l500; TEST_CASE("parse_thermal_table", "[thermal-loop]") { auto original_table = create_synthetic_table(); auto raw_data = original_table.build_raw_data(); thermal_calibration_table table_from_raw( raw_data ); REQUIRE( original_table == table_from_raw ); } TEST_CASE( "invalid thermal table", "[thermal-loop]" ) { auto table = create_synthetic_table(); table._header.valid = 0.f; auto raw_data = table.build_raw_data(); REQUIRE_THROWS( thermal_calibration_table( raw_data )); } TEST_CASE( "data_size_too_small", "[thermal-loop]" ) { auto syntetic_table = create_synthetic_table(); auto raw_data = syntetic_table.build_raw_data(); raw_data.pop_back(); REQUIRE_THROWS( thermal_calibration_table( raw_data ) ); } TEST_CASE( "data_size_too_large", "[thermal-loop]" ) { auto syntetic_table = create_synthetic_table(); auto raw_data = syntetic_table.build_raw_data(); raw_data.push_back( 1 ); REQUIRE_THROWS( thermal_calibration_table( raw_data ) ); } TEST_CASE( "build_raw_data", "[thermal-loop]" ) { auto syntetic_table = create_synthetic_table(1); auto raw_data = syntetic_table.build_raw_data(); std::vector< byte > raw; raw.insert( raw.end(), (byte *)&( syntetic_table._header.min_temp ), (byte *)&( syntetic_table._header.min_temp ) + 4 ); raw.insert( raw.end(), (byte *)&( syntetic_table._header.max_temp ), (byte *)&( syntetic_table._header.max_temp ) + 4 ); raw.insert( raw.end(), (byte *)&( syntetic_table._header.reference_temp ), (byte *)&( syntetic_table._header.reference_temp ) + 4 ); raw.insert( raw.end(), (byte *)&( syntetic_table._header.valid ), (byte *)&( syntetic_table._header.valid ) + 4 ); for (auto v : syntetic_table.bins) { raw.insert( raw.end(), (byte *)&( v.scale ), (byte *)&( v.scale ) + 4 ); raw.insert( raw.end(), (byte *)&( v.sheer ), (byte *)&( v.sheer ) + 4 ); raw.insert( raw.end(), (byte *)&( v.tx ), (byte *)&( v.tx ) + 4 ); raw.insert( raw.end(), (byte *)&( v.ty ), (byte *)&( v.ty ) + 4 ); } CHECK( raw_data == raw ); REQUIRE_THROWS( thermal_calibration_table( raw_data, 2 ) ); } TEST_CASE( "build_raw_data_no_data", "[thermal-loop]" ) { auto syntetic_table = create_synthetic_table( 0 ); auto raw_data = syntetic_table.build_raw_data(); thermal_calibration_table t( raw_data, 0 ); CHECK( t.bins.size() == 0 ); }
2,963
1,102
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/services/assistant/platform/system_provider_impl.h" #include <utility> #include "base/bind.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/system/sys_info.h" #include "chromeos/services/assistant/platform/power_manager_provider_impl.h" namespace chromeos { namespace assistant { SystemProviderImpl::SystemProviderImpl( std::unique_ptr<PowerManagerProviderImpl> power_manager_provider, mojo::PendingRemote<device::mojom::BatteryMonitor> battery_monitor) : power_manager_provider_(std::move(power_manager_provider)), battery_monitor_(std::move(battery_monitor)) { battery_monitor_->QueryNextStatus(base::BindOnce( &SystemProviderImpl::OnBatteryStatus, base::Unretained(this))); } SystemProviderImpl::~SystemProviderImpl() = default; assistant_client::MicMuteState SystemProviderImpl::GetMicMuteState() { // CRAS input is never muted. return assistant_client::MicMuteState::MICROPHONE_ENABLED; } void SystemProviderImpl::RegisterMicMuteChangeCallback( ConfigChangeCallback callback) { // No need to register since it will never change. } assistant_client::PowerManagerProvider* SystemProviderImpl::GetPowerManagerProvider() { return power_manager_provider_.get(); } bool SystemProviderImpl::GetBatteryState(BatteryState* state) { if (!current_battery_status_) return false; state->is_charging = current_battery_status_->charging; state->charge_percentage = static_cast<int>(current_battery_status_->level * 100); return true; } void SystemProviderImpl::UpdateTimezoneAndLocale(const std::string& timezone, const std::string& locale) {} void SystemProviderImpl::OnBatteryStatus( device::mojom::BatteryStatusPtr battery_status) { current_battery_status_ = std::move(battery_status); // Battery monitor is one shot, send another query to get battery status // updates. This query will only return when a status changes. battery_monitor_->QueryNextStatus(base::BindOnce( &SystemProviderImpl::OnBatteryStatus, base::Unretained(this))); } void SystemProviderImpl::FlushForTesting() { battery_monitor_.FlushForTesting(); } } // namespace assistant } // namespace chromeos
2,436
751
#include "ar/ar.hpp" using namespace AsyncRuntime; void async_io(CoroutineHandler* handler, YieldVoid & yield) { //make input stream auto in_stream = MakeStream(); int res = 0; int fd = 0; yield(); //async open file if( (res = Await(AsyncFsOpen("../../examples/io.cpp"), handler)) < 0 ) { std::cerr << "Error open file: " << FSErrorName(res) << ' ' << FSErrorMsg(res) << std::endl; return; } fd = res; //async read file if( (res = Await(AsyncFsRead(fd, in_stream), handler)) != IO_SUCCESS ) { std::cerr << "Error read file: " << FSErrorName(res) << ' ' << FSErrorMsg(res) << std::endl; return; } //async close file Await(AsyncFsClose(fd), handler); //make output stream with data from input stream auto out_stream = MakeStream(in_stream->GetBuffer(), in_stream->GetBufferSize()); //async open file if( (res = Await(AsyncFsOpen("tmp"), handler)) < 0 ) { std::cerr << "Error open file: " << FSErrorName(res) << ' ' << FSErrorMsg(res) << std::endl; return; } fd = res; //async write to file if( (res = Await(AsyncFsWrite(fd, out_stream), handler)) != IO_SUCCESS ) { std::cerr << "Error write to file: " << FSErrorName(res) << ' ' << FSErrorMsg(res) << std::endl; return; } //async close file Await(AsyncFsClose(fd), handler); } int main() { SetupRuntime(); Coroutine coro = MakeCoroutine(&async_io); while (coro.Valid()) { Await(Async(coro)); } Terminate(); return 0; }
1,584
559
#include "../node.cpp" void insertAtHead(Node **head, int data) { Node *newNode = new Node(data); if (*head == NULL) { *head = newNode; return; } newNode->next = *head; *head = newNode; } void insertNode(Node **head, int data) { Node *newNode = new Node(data); if (*head == NULL) { *head = newNode; return; } Node *temp = *head; while (temp->next != NULL) { temp = temp->next; } temp->next = newNode; } void insertAtPosition(Node **head, int data, int pos) { Node *newNode = new Node(data); int count = 1; Node *temp = *head; while (count < pos - 1) { temp = temp->next; count++; } newNode->next = temp->next; temp->next = newNode; } void recursiveTraversal(Node *head) { if (head == NULL) { return; } Node *temp = head; cout << temp->data << "->"; recursiveTraversal(temp->next); } int main() { Node *head = new Node(1); insertNode(&head, 2); insertNode(&head, 3); insertNode(&head, 4); insertNode(&head, 5); insertNode(&head, 6); insertAtPosition(&head, 10, 5); recursiveTraversal(head); return 0; }
1,222
443
class Solution { public: int maximumSwap(int num) { string n = to_string(num); int l = n.length(); vector<pair<int,int>> right_max(l); right_max[l-1] = make_pair(n[l-1]-'0',l-1); for (int i = l-2; i >= 0; i--) { int curr = n[i]-'0'; int next = right_max[i+1].first; right_max[i] = curr > next ? make_pair(curr, i) : make_pair(next, right_max[i+1].second); } int i = 0; while(i < l && right_max[i].first == n[i]-'0') i++; if (i >= l) return num; string cpy = n; cpy[i] = n[right_max[i].second]; cpy[right_max[i].second] = n[i]; return stoi(cpy); } }; int stringToInteger(string input) { return stoi(input); } int main() { string line; while (getline(cin, line)) { int num = stringToInteger(line); int ret = Solution().maximumSwap(num); string out = to_string(ret); cout << out << endl; } return 0; }
1,055
386
// // Example from Item 12, Lock class version // #include <iostream> #include <vector> #include "ESTLUtil.h" #include "Widget.h" int data[] = { -30, 102, 5, -19, 0, 5, -3000, 4000, 5, -2 }; const int numValues = sizeof data / sizeof(int); // Dummy Mutex library: template<typename T> inline void getMutexFor(const T &t) {} template<typename T> inline void releaseMutexFor(const T &t) {} template<typename Container> // skeletal template for classes class Lock { // that acquire and release mutexes public: // for containers; many details // have been omitted Lock(const Container& container) // acquire mutex in the constructor : c(container) { getMutexFor(c); } ~Lock() { releaseMutexFor(c); } // release it in the destructor private: const Container& c; }; int main() { using namespace std; using namespace ESTLUtils; vector<int> v; v.insert(v.begin(), data, data + numValues); // insert the ints in data // into v at the front printContainer("after range insert, v", v); { // create new block Lock<vector<int> > lock(v); // acquire mutex vector<int>::iterator first5(find(v.begin(), v.end(), 5)); if (first5 != v.end()) { *first5 = 0; } } // close block, automatically // release mutex printContainer("after changing first 5 to zero, v", v); return 0; }
1,369
549
// // $Id$ // // // Original author: Darren Kessner <darren@proteowizard.org> // // Copyright 2006 Louis Warschaw Prostate Cancer Center // Cedars Sinai Medical Center, Los Angeles, California 90048 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef _TRUNCATEDLORENTZIANESTIMATOR_HPP_ #define _TRUNCATEDLORENTZIANESTIMATOR_HPP_ #include "pwiz/utility/misc/Export.hpp" #include "TruncatedLorentzianParameters.hpp" #include "pwiz/data/misc/FrequencyData.hpp" #include <memory> #include <iosfwd> namespace pwiz { namespace frequency { class PWIZ_API_DECL TruncatedLorentzianEstimator { public: static std::auto_ptr<TruncatedLorentzianEstimator> create(); virtual TruncatedLorentzianParameters initialEstimate(const pwiz::data::FrequencyData& fd) const = 0; virtual TruncatedLorentzianParameters iteratedEstimate(const pwiz::data::FrequencyData& fd, const TruncatedLorentzianParameters& tlp, int iterationCount) const = 0; virtual double error(const pwiz::data::FrequencyData& fd, const TruncatedLorentzianParameters& tlp) const = 0; virtual double normalizedError(const pwiz::data::FrequencyData& fd, const TruncatedLorentzianParameters& tlp) const = 0; virtual double sumSquaresModel(const pwiz::data::FrequencyData& fd, const TruncatedLorentzianParameters& tlp) const = 0; virtual void log(std::ostream* os) = 0; // set log stream [default == &cout] virtual void outputDirectory(const std::string& name) = 0; // set intermediate output [default=="" (none)] virtual ~TruncatedLorentzianEstimator(){} }; } // namespace frequency } // namespace pwiz #endif // _TRUNCATEDLORENTZIANESTIMATOR_HPP_
2,297
767
/** @file Image1.cpp @maintainer Morgan McGuire, http://graphics.cs.williams.edu @created 2007-01-31 @edited 2007-01-31 */ #include "G3D/Image1.h" #include "G3D/Image1uint8.h" #include "G3D/GImage.h" #include "G3D/Color4.h" #include "G3D/Color4uint8.h" #include "G3D/Color1.h" #include "G3D/Color1uint8.h" #include "G3D/ImageFormat.h" namespace G3D { Image1::Image1(int w, int h, WrapMode wrap) : Map2D<Color1, Color1>(w, h, wrap) { setAll(Color1(0.0f)); } Image1::Ref Image1::fromGImage(const GImage& im, WrapMode wrap) { switch (im.channels()) { case 1: return fromArray(im.pixel1(), im.width(), im.height(), wrap); case 3: return fromArray(im.pixel3(), im.width(), im.height(), wrap); case 4: return fromArray(im.pixel4(), im.width(), im.height(), wrap); default: debugAssertM(false, "Input GImage must have 1, 3, or 4 channels."); return NULL; } } Image1::Ref Image1::fromImage1uint8(const ReferenceCountedPointer<Image1uint8>& im) { Ref out = createEmpty(static_cast<WrapMode>(im->wrapMode())); out->resize(im->width(), im->height()); int N = im->width() * im->height(); const Color1uint8* src = reinterpret_cast<Color1uint8*>(im->getCArray()); for (int i = 0; i < N; ++i) { out->data[i] = Color1(src[i]); } return out; } Image1::Ref Image1::createEmpty(int width, int height, WrapMode wrap) { return new Type(width, height, wrap); } Image1::Ref Image1::createEmpty(WrapMode wrap) { return createEmpty(0, 0, wrap); } Image1::Ref Image1::fromFile(const std::string& filename, WrapMode wrap, GImage::Format fmt) { Ref out = createEmpty(wrap); out->load(filename, fmt); return out; } void Image1::load(const std::string& filename, GImage::Format fmt) { copyGImage(GImage(filename, fmt)); setChanged(true); } Image1::Ref Image1::fromArray(const class Color3uint8* ptr, int w, int h, WrapMode wrap) { Ref out = createEmpty(wrap); out->copyArray(ptr, w, h); return out; } Image1::Ref Image1::fromArray(const class Color1* ptr, int w, int h, WrapMode wrap) { Ref out = createEmpty(wrap); out->copyArray(ptr, w, h); return out; } Image1::Ref Image1::fromArray(const class Color1uint8* ptr, int w, int h, WrapMode wrap) { Ref out = createEmpty(wrap); out->copyArray(ptr, w, h); return out; } Image1::Ref Image1::fromArray(const class Color3* ptr, int w, int h, WrapMode wrap) { Ref out = createEmpty(wrap); out->copyArray(ptr, w, h); return out; } Image1::Ref Image1::fromArray(const class Color4uint8* ptr, int w, int h, WrapMode wrap) { Ref out = createEmpty(wrap); out->copyArray(ptr, w, h); return out; } Image1::Ref Image1::fromArray(const class Color4* ptr, int w, int h, WrapMode wrap) { Ref out = createEmpty(wrap); out->copyArray(ptr, w, h); return out; } void Image1::copyGImage(const GImage& im) { switch (im.channels()) { case 1: copyArray(im.pixel1(), im.width(), im.height()); break; case 3: copyArray(im.pixel3(), im.width(), im.height()); break; case 4: copyArray(im.pixel4(), im.width(), im.height()); break; } } void Image1::copyArray(const Color3uint8* src, int w, int h) { resize(w, h); int N = w * h; Color1* dst = data.getCArray(); // Convert int8 -> float for (int i = 0; i < N; ++i) { dst[i] = Color1(Color3(src[i]).average()); } } void Image1::copyArray(const Color4uint8* src, int w, int h) { resize(w, h); int N = w * h; Color1* dst = data.getCArray(); // Strip alpha and convert for (int i = 0; i < N; ++i) { dst[i] = Color1(Color3(src[i].rgb()).average()); } } void Image1::copyArray(const Color1* src, int w, int h) { resize(w, h); System::memcpy(getCArray(), src, w * h * sizeof(Color1)); } void Image1::copyArray(const Color4* src, int w, int h) { resize(w, h); int N = w * h; Color1* dst = data.getCArray(); // Strip alpha for (int i = 0; i < N; ++i) { dst[i] = Color1(src[i].rgb().average()); } } void Image1::copyArray(const Color1uint8* src, int w, int h) { resize(w, h); int N = w * h; Color1* dst = getCArray(); for (int i = 0; i < N; ++i) { dst[i]= Color1(src[i]); } } void Image1::copyArray(const Color3* src, int w, int h) { resize(w, h); int N = w * h; Color1* dst = getCArray(); for (int i = 0; i < N; ++i) { dst[i] = Color1(src[i].average()); } } /** Saves in any of the formats supported by G3D::GImage. */ void Image1::save(const std::string& filename, GImage::Format fmt) { GImage im(width(), height(), 1); int N = im.width() * im.height(); Color1uint8* dst = im.pixel1(); for (int i = 0; i < N; ++i) { dst[i] = Color1uint8(data[i]); } im.save(filename, fmt); } const ImageFormat* Image1::format() const { return ImageFormat::L32F(); } } // G3D
5,042
1,959
/* LSOracle: A learning based Oracle for Logic Synthesis * Copyright 2021 Laboratory for Nano Integrated Systems (LNIS) * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <assert.h> #include <algorithm> #include <iterator> #include <numeric> #include <optional> #include <stdexcept> #include <unordered_map> #include <unordered_set> #include <variant> #include <vector> #include <kitty/kitty.hpp> #include <mockturtle/mockturtle.hpp> namespace oracle { namespace techmap { struct cut { explicit cut(size_t node) : inputs{std::vector<size_t>{node}}, output{node} { } explicit cut(std::vector<size_t> _inputs, size_t _output, kitty::dynamic_truth_table _truth_table) : inputs{std::move(_inputs)}, output{_output}, truth_table{std::move(_truth_table)} { std::sort(inputs.begin(), inputs.end()); } cut merge(cut const& rhs, size_t new_output) const { std::vector<size_t> new_inputs; /*std::cout << "Merging ["; for (size_t input : inputs) { std::cout << input << ", "; } std::cout << "] with ["; for (size_t input : rhs.inputs) { std::cout << input << ", "; } std::cout << "] => [";*/ std::set_union(inputs.begin(), inputs.end(), rhs.inputs.begin(), rhs.inputs.end(), std::back_inserter(new_inputs)); /*for (size_t input : new_inputs) { std::cout << input << ", "; } std::cout << "]\n";*/ return cut(std::move(new_inputs), new_output, kitty::dynamic_truth_table{}); } int input_count() const { size_t input_count = inputs.size(); if (std::find(inputs.begin(), inputs.end(), 0) != inputs.end()) { input_count -= 1; } if (std::find(inputs.begin(), inputs.end(), 1) != inputs.end()) { input_count -= 1; } return input_count; } bool is_trivial() const { return inputs.size() == 1 && inputs[0] == output; } bool operator==(cut const& rhs) const { return output == rhs.output && inputs == rhs.inputs; } std::vector<size_t> inputs; size_t output; kitty::dynamic_truth_table truth_table; }; struct cell { explicit cell(size_t _index, std::vector<kitty::dynamic_truth_table> _truth_table) : index{_index}, truth_table{std::move(_truth_table)} { } explicit cell(std::vector<kitty::dynamic_truth_table> _truth_table) : index{}, truth_table{std::move(_truth_table)} { } size_t index; std::vector<kitty::dynamic_truth_table> truth_table; }; struct lut { explicit lut(kitty::dynamic_truth_table _truth_table) : truth_table{std::move(_truth_table)} { } kitty::dynamic_truth_table truth_table; }; struct constant_zero {}; struct constant_one {}; struct primary_input { explicit primary_input(size_t index) : index{index} { } size_t index; }; struct primary_output { explicit primary_output(size_t index) : index{index} { } size_t index; }; struct connection { explicit connection(size_t from, size_t to, size_t index) : from{from}, to{to}, index{index} { } size_t from; size_t to; size_t index; }; template<class cell_type> struct graph { size_t add_constant_zero() { assert(!frozen); size_t index = nodes.size(); nodes.push_back(constant_zero{}); return index; } size_t add_constant_one() { assert(!frozen); size_t index = nodes.size(); nodes.push_back(constant_one{}); return index; } bool is_constant(size_t index) const { return std::holds_alternative<constant_zero>(nodes[index]) || std::holds_alternative<constant_one>(nodes[index]); } size_t add_primary_input() { assert(!frozen); size_t index = nodes.size(); nodes.push_back(primary_input{index}); primary_inputs.push_back(index); return index; } bool is_primary_input(size_t index) const { return std::holds_alternative<primary_input>(nodes[index]); } size_t add_primary_output() { assert(!frozen); size_t index = nodes.size(); nodes.push_back(primary_output{index}); primary_outputs.push_back(index); return index; } bool is_primary_output(size_t index) const { return std::holds_alternative<primary_output>(nodes[index]); } size_t add_cell(cell_type const& c) { assert(!frozen); size_t index = nodes.size(); nodes.push_back(c); return index; } size_t add_connection(size_t from, size_t to) { assert(!frozen); auto index = connections.size(); connections.push_back(connection(from, to, index)); return index; } void remove_connection(size_t index) { assert(!frozen && "Attempted to remove connection from frozen graph"); connections[index].reset(); } void freeze() { std::cout << "freezing graph..."; fflush(stdout); node_fanin_nodes = std::vector<std::vector<size_t>>{nodes.size()}; node_fanout_nodes = std::vector<std::vector<size_t>>{nodes.size()}; // Populate the caches by computing topological orderings. compute_topological_ordering(); compute_reverse_topological_ordering(); frozen = true; std::cout << "done\n"; } void unfreeze() { frozen = false; } void dump_to_stdout() const { std::cout << "digraph {\n"; // TODO: assuming constant drivers are always first two nodes is probably not smart. assert(std::holds_alternative<constant_zero>(nodes[0])); assert(std::holds_alternative<constant_one>(nodes[1])); std::cout << "0 [shape=box label=\"Zero\"]\n"; std::cout << "1 [shape=box label=\"One\"]\n"; for (size_t pi : primary_inputs) { std::cout << pi << " [shape=box label=\"PI " << std::get<primary_input>(nodes[pi]).index << "\"]\n"; } for (size_t po : primary_outputs) { std::cout << po << " [shape=box label=\"PO " << std::get<primary_output>(nodes[po]).index << "\"]\n"; } for (size_t node = 0; node < nodes.size(); node++) { if constexpr (std::is_same_v<cell_type, cell>) { if (std::holds_alternative<cell>(nodes[node])) { std::cout << node << " [label=\"Node " << node << " 0x"; kitty::print_hex(std::get<cell>(nodes[node]).truth_table[0]); std::cout << "\"]\n"; } } else if constexpr (std::is_same_v<cell_type, lut>) { if (std::holds_alternative<lut>(nodes[node])) { std::cout << node << " [label=\"Node " << node << " 0x"; kitty::print_hex(std::get<lut>(nodes[node]).truth_table); std::cout << "\"]\n"; } } } for (std::optional<connection> conn : connections) { if (conn.has_value()) { std::cout << conn->from << " -> " << conn->to << '\n'; } } std::cout << "}\n"; } std::vector<connection> compute_node_fanin_connections(size_t node) const { std::vector<connection> fanin; for (std::optional<connection> const& conn : connections) { if (conn && conn->to == node) { fanin.push_back(*conn); } } return fanin; } std::vector<size_t> compute_node_fanin_nodes(size_t node) { if (frozen && !node_fanin_nodes[node].empty()) { return node_fanin_nodes[node]; } std::vector<size_t> fanin; for (std::optional<connection> const& conn : connections) { if (conn && conn->to == node) { fanin.push_back(conn->from); } } if (frozen) { node_fanin_nodes[node] = fanin; } return fanin; } std::vector<size_t> compute_node_fanin_nodes(size_t node) const { if (frozen && !node_fanin_nodes[node].empty()) { return node_fanin_nodes[node]; } std::vector<size_t> fanin; for (std::optional<connection> const& conn : connections) { if (conn && conn->to == node) { fanin.push_back(conn->from); } } return fanin; } std::vector<connection> compute_node_fanout_connections(size_t node) const { std::vector<connection> fanout; for (std::optional<connection> const& conn : connections) { if (conn && conn->from == node) { fanout.push_back(*conn); } } return fanout; } std::vector<size_t> compute_node_fanout_nodes(size_t node) { if (frozen && !node_fanout_nodes[node].empty()) { return node_fanout_nodes[node]; } std::vector<size_t> fanout; for (std::optional<connection> const& conn : connections) { if (conn && conn->from == node) { fanout.push_back(conn->to); } } if (frozen) { node_fanout_nodes[node] = fanout; } return fanout; } std::vector<size_t> compute_node_fanout_nodes(size_t node) const { if (frozen && !node_fanout_nodes[node].empty()) { return node_fanout_nodes[node]; } std::vector<size_t> fanout; for (std::optional<connection> const& conn : connections) { if (conn && conn->from == node) { fanout.push_back(conn->to); } } return fanout; } std::vector<size_t> compute_topological_ordering() { if (frozen && !forward_topological_ordering.empty()) { return forward_topological_ordering; } std::vector<size_t> ordering; std::vector<size_t> no_incoming{primary_inputs}; graph g{*this}; g.unfreeze(); no_incoming.push_back(0); no_incoming.push_back(1); while (!no_incoming.empty()) { size_t node = no_incoming.back(); ordering.push_back(node); no_incoming.pop_back(); for (connection conn : g.compute_node_fanout_connections(node)) { g.remove_connection(conn.index); if (g.compute_node_fanin_connections(conn.to).empty()) { no_incoming.push_back(conn.to); } } } // If `g` still has edges this is a cyclic graph, which cannot be topologically ordered. bool remaining_edges = false; for (std::optional<connection> const& conn : g.connections) { if (conn) { remaining_edges = true; std::cout << conn->from << " -> " << conn->to << '\n'; } } if (remaining_edges) { throw std::logic_error{"input graph is cyclic or has nodes not reachable from primary inputs"}; } if (frozen) { forward_topological_ordering = ordering; } return ordering; } std::vector<size_t> compute_topological_ordering() const { if (frozen && !forward_topological_ordering.empty()) { return forward_topological_ordering; } std::vector<size_t> ordering; std::vector<size_t> no_incoming{primary_inputs}; graph g{*this}; g.unfreeze(); no_incoming.push_back(0); no_incoming.push_back(1); while (!no_incoming.empty()) { size_t node = no_incoming.back(); ordering.push_back(node); no_incoming.pop_back(); for (connection conn : g.compute_node_fanout_connections(node)) { g.remove_connection(conn.index); if (g.compute_node_fanin_connections(conn.to).empty()) { no_incoming.push_back(conn.to); } } } // If `g` still has edges this is a cyclic graph, which cannot be topologically ordered. bool remaining_edges = false; for (std::optional<connection> const& conn : g.connections) { if (conn) { remaining_edges = true; std::cout << conn->from << " -> " << conn->to << '\n'; } } if (remaining_edges) { throw std::logic_error("input graph is cyclic or has nodes not reachable from primary inputs"); } return ordering; } std::vector<size_t> compute_reverse_topological_ordering() { if (frozen && !reverse_topological_ordering.empty()) { return reverse_topological_ordering; } std::vector<size_t> ordering; std::vector<size_t> no_outgoing{primary_outputs}; graph g{*this}; g.unfreeze(); while (!no_outgoing.empty()) { size_t node = no_outgoing.back(); ordering.push_back(node); no_outgoing.pop_back(); for (connection conn : g.compute_node_fanin_connections(node)) { g.remove_connection(conn.index); if (g.compute_node_fanout_connections(conn.from).empty()) { no_outgoing.push_back(conn.from); } } } // If `g` still has edges this is a cyclic graph, which cannot be topologically ordered. bool remaining_edges = false; for (std::optional<connection> const& conn : g.connections) { if (conn) { remaining_edges = true; std::cout << conn->from << " -> " << conn->to << '\n'; } } if (remaining_edges) { throw std::logic_error("input graph is cyclic or has nodes not reachable from primary inputs"); } if (frozen) { reverse_topological_ordering = ordering; } return ordering; } std::vector<size_t> nodes_in_cut(cut const& c) const { // Perform a reverse topological ordering to discover nodes in the cut // and then a forward topological ordering to produce useful output. std::vector<size_t> ordering; std::vector<size_t> no_outgoing{c.output}; graph g{*this}; g.unfreeze(); while (!no_outgoing.empty()) { size_t node = no_outgoing.back(); no_outgoing.pop_back(); if (std::find(c.inputs.begin(), c.inputs.end(), node) == c.inputs.end()) { ordering.push_back(node); for (connection conn : g.compute_node_fanin_connections(node)) { no_outgoing.push_back(conn.from); } } } // ordering now contains a reverse topological order of the nodes. // TODO: does this actually produce a forward topological order? std::reverse(ordering.begin(), ordering.end()); return ordering; } kitty::dynamic_truth_table simulate(cut const& c) const { const std::vector<size_t> cut_nodes{nodes_in_cut(c)}; kitty::dynamic_truth_table result{static_cast<uint32_t>(c.inputs.size())}; // TODO: skip constant drivers when found. const int limit = 1 << c.inputs.size(); for (unsigned int mask = 0; mask < limit; mask++) { std::unordered_map<size_t, bool> values{}; // Constant drivers. values.insert({0, false}); values.insert({1, true}); for (int input = 0; input < c.inputs.size(); input++) { values.insert({c.inputs[input], ((1 << input) & mask) != 0}); } for (size_t node : cut_nodes) { if (std::holds_alternative<cell>(nodes[node])) { cell const& n = std::get<cell>(nodes[node]); std::vector<size_t> fanin = compute_node_fanin_nodes(node); uint64_t node_mask = 0; for (unsigned int fanin_node = 0; fanin_node < fanin.size(); fanin_node++) { if (values.find(fanin[fanin_node]) == values.end()) { std::cout << "while simulating cut ["; for (size_t input : c.inputs) { std::cout << input << ", "; } std::cout << "] -> " << c.output << ":\n"; std::cout << "at node " << fanin[fanin_node] << ":\n"; throw std::logic_error{"fanin node not in simulation values"}; } node_mask |= int{values.at(fanin[fanin_node])} << fanin_node; } // TODO: assumes cell has a single output. values.insert({node, kitty::get_bit(n.truth_table[0], node_mask)}); } else if (is_constant(node)) { continue; } } if (values.at(c.output)) { kitty::set_bit(result, mask); } } return result; } std::vector<size_t> primary_inputs; std::vector<size_t> primary_outputs; std::vector<std::variant<constant_zero, constant_one, primary_input, primary_output, cell_type>> nodes; std::vector<std::optional<connection>> connections; bool frozen; std::vector<size_t> forward_topological_ordering; std::vector<size_t> reverse_topological_ordering; std::vector<std::vector<size_t>> node_fanin_nodes; std::vector<std::vector<size_t>> node_fanout_nodes; }; struct mapping_settings { unsigned int cut_input_limit; unsigned int node_cut_count; unsigned int lut_area[8]; unsigned int lut_delay[8]; unsigned int wire_delay; }; struct mapping_info { std::optional<cut> selected_cut; std::optional<kitty::dynamic_truth_table> truth_table; unsigned int depth; int references; // Signed to detect underflow. float area_flow; unsigned int required; }; struct frontier_info { explicit frontier_info(size_t node) : cuts{std::vector<cut>{cut{node}}} { } explicit frontier_info(std::vector<cut> _cuts) : cuts{std::move(_cuts)} { } std::vector<cut> cuts; }; class mapper { public: explicit mapper(graph<cell> _g, mapping_settings _settings) : g{std::move(_g)}, info{g.nodes.size()}, settings{_settings} { assert(settings.cut_input_limit >= 2 && "invalid argument: mapping for less than 2 inputs is impossible"); assert(settings.node_cut_count >= 1 && "invalid argument: must store at least one cut per node"); // For now: std::fill(settings.lut_area, settings.lut_area + 9, 1); settings.lut_area[5] = 2; settings.lut_area[6] = 4; settings.lut_area[7] = 8; settings.lut_area[8] = 16; std::fill(settings.lut_delay, settings.lut_delay + 9, 1); settings.lut_delay[1] = 141; settings.lut_delay[2] = 275; settings.lut_delay[3] = 379; settings.lut_delay[4] = 379; settings.lut_delay[5] = 477; settings.lut_delay[6] = 618; settings.lut_delay[7] = 759; settings.wire_delay = 300; std::fill(info.begin(), info.end(), mapping_info{}); } graph<lut> map() { g.freeze(); std::cout << "Input graph has " << g.nodes.size() << " nodes and " << g.connections.size() << " edges.\n"; std::cout << "Mapping phase 1: prioritise depth.\n"; enumerate_cuts(false, false); // After depth mapping, recalculate node slacks. recalculate_slack(); //derive_mapping(); std::cout << "Mapping phase 2: prioritise global area.\n"; enumerate_cuts(true, false); //derive_mapping(); enumerate_cuts(true, false); //derive_mapping(); std::cout << "Mapping phase 3: prioritise local area.\n"; enumerate_cuts(true, true); //derive_mapping(); enumerate_cuts(true, true); print_stats(); std::cout << "Deriving the final mapping of the network.\n"; return derive_mapping(true); } private: void enumerate_cuts(bool area_optimisation, bool local_area) { std::unordered_map<size_t, frontier_info> frontier; // TODO: ABC computes the graph crosscut to pre-allocate frontier memory. // Initialise frontier with the trivial cuts of primary inputs. frontier.insert({0, frontier_info{0}}); frontier.insert({1, frontier_info{1}}); for (size_t pi : g.primary_inputs) { frontier.insert({pi, frontier_info{pi}}); } for (size_t node : g.compute_topological_ordering()) { // Skip primary inputs, primary outputs, and constants. if (g.is_primary_input(node) || g.is_primary_output(node) || g.is_constant(node)) { continue; } // Find the node cut set. std::vector<cut> cut_set = node_cut_set(node, frontier); // Sort the cuts by desired characteristics. if (!area_optimisation) { std::sort(cut_set.begin(), cut_set.end(), [&](cut const& a, cut const& b) { return cut_depth(a, info) < cut_depth(b, info) || (cut_depth(a, info) == cut_depth(b, info) && cut_input_count(a, info) < cut_input_count(b, info)) || (cut_depth(a, info) == cut_depth(b, info) && cut_input_count(a, info) == cut_input_count(b, info) && cut_area_flow(a, info) < cut_area_flow(b, info)); }); } else if (!local_area) { std::sort(cut_set.begin(), cut_set.end(), [&](cut const& a, cut const& b) { return cut_area_flow(a, info) < cut_area_flow(b, info) || (cut_area_flow(a, info) == cut_area_flow(b, info) && cut_fanin_refs(a, info) < cut_fanin_refs(b, info)) || (cut_area_flow(a, info) == cut_area_flow(b, info) && cut_fanin_refs(a, info) == cut_fanin_refs(b, info) && cut_depth(a, info) < cut_depth(b, info)); }); } else { std::sort(cut_set.begin(), cut_set.end(), [&](cut const& a, cut const& b) { return cut_exact_area(a) < cut_exact_area(b) || (cut_exact_area(a) == cut_exact_area(b) && cut_fanin_refs(a, info) < cut_fanin_refs(b, info)) || (cut_exact_area(a) == cut_exact_area(b) && cut_fanin_refs(a, info) == cut_fanin_refs(b, info) && cut_depth(a, info) < cut_depth(b, info)); }); } // Deduplicate cuts to ensure diversity. cut_set.erase(std::unique(cut_set.begin(), cut_set.end()), cut_set.end()); // Prune cuts which exceed the node slack in area optimisation mode. if (area_optimisation) { if (std::all_of(cut_set.begin(), cut_set.end(), [&](cut const& c) { return cut_depth(c, info) > info[node].required; })) { std::cout << "Required time of node " << node << " is " << info[node].required << '\n'; std::cout << "Depth of cuts:\n"; for (cut const& c : cut_set) { std::cout << "["; for (size_t input : c.inputs) { std::cout << input << " @ " << cut_depth(*info[input].selected_cut, info) << ", "; } std::cout << "] -> " << c.output << " = " << cut_depth(c, info) << '\n'; } fflush(stdout); } cut_set.erase(std::remove_if(cut_set.begin(), cut_set.end(), [&](cut const& c) { return cut_depth(c, info) > info[node].required; }), cut_set.end()); // Because the previous cut is included in the set and must meet required times // we must have at least one cut left from this. if (cut_set.empty()) { throw std::logic_error{"bug: no cuts meet node required time"}; } } // Keep only the specified good cuts. if (cut_set.size() > settings.node_cut_count) { cut_set.erase(cut_set.begin()+settings.node_cut_count, cut_set.end()); } // We should have at least one cut provided by the trivial cut. if (cut_set.empty()) { throw std::logic_error{"bug: node has no cuts"};// TODO: maybe this is redundant given the assert in area_optimisation? } // If there's a representative cut for this node already, decrement its references first. if (info[node].selected_cut.has_value()) { cut_deref(*info[node].selected_cut); } // Choose the best cut as the representative cut for this node. cut_ref(cut_set[0]); // Add the cut set of this node to the frontier. info[node].selected_cut = std::make_optional(cut_set[0]); info[node].depth = cut_depth(cut_set[0], info); info[node].area_flow = cut_area_flow(cut_set[0], info); frontier.insert({node, frontier_info{std::move(cut_set)}}); // Erase fan-in nodes that have their fan-out completely mapped as they will never be used again. for (size_t fanin_node : g.compute_node_fanin_nodes(node)) { std::vector<size_t> node_fanout{g.compute_node_fanout_nodes(fanin_node)}; if (std::all_of(node_fanout.begin(), node_fanout.end(), [&](size_t node) { return info[node].selected_cut.has_value(); })) { //frontier.erase(fanin_node); } } } } void recalculate_slack() { // First find the maximum depth of the mapping. unsigned int max_depth = 0; for (size_t node = 0; node < g.nodes.size(); node++) { if (std::holds_alternative<cell>(g.nodes[node])) { if (info[node].depth > max_depth) { max_depth = info[node].depth; } } } std::cout << "Maximum depth of network is " << max_depth << '\n'; std::cout << "Propagating arrival times..."; fflush(stdout); // Next, initialise the node required times. for (mapping_info& node : info) { node.required = max_depth; } // Then work from PO to PI, propagating required times. for (size_t node : g.compute_reverse_topological_ordering()) { if (g.is_primary_output(node)) { info[node].required = max_depth; } else if (std::holds_alternative<cell>(g.nodes[node])) { if (!info[node].selected_cut.has_value()) { throw std::logic_error{"bug: cell has no selected cut"}; } unsigned int required = info[node].required - settings.lut_delay[info[node].selected_cut->input_count()]; for (size_t cut_input : info[node].selected_cut->inputs) { //std::cout << "Setting required time of node " << cut_input << " to " << std::min(info[cut_input].required, required) << '\n'; info[cut_input].required = std::min(info[cut_input].required, required); if (info[cut_input].required >= info[node].required) { throw std::logic_error{"bug: cut input has greater required time than cut output"}; } // If we end up with a negative required time, we have a bug. For instance, this might fire if: // - the maximum depth isn't actually the maximum depth // - the graph has a loop if (info[cut_input].required < 0) { throw std::logic_error{"bug: node has negative required time"}; } } } } std::cout << "done\n"; } void print_stats() const { // The mapping frontier is the list of all nodes which do not have selected cuts. // We start with the primary outputs and work downwards. std::vector<size_t> frontier; std::transform(g.primary_outputs.begin(), g.primary_outputs.end(), std::back_inserter(frontier), [](size_t po) { return po; }); std::unordered_map<size_t, bool> gate_graph_to_lut_graph; // Populate the LUT graph with the primary inputs and outputs of the gate graph. gate_graph_to_lut_graph.insert({0, true}); gate_graph_to_lut_graph.insert({1, true}); for (size_t pi : g.primary_inputs) { gate_graph_to_lut_graph.insert({pi, true}); } for (size_t po : g.primary_outputs) { gate_graph_to_lut_graph.insert({po, true}); } std::vector<size_t> lut_stats; for (int i = 0; i <= settings.cut_input_limit; i++) { lut_stats.push_back(0); } // While there are still nodes to be mapped: while (!frontier.empty()) { // Pop a node from the mapping frontier. size_t node = frontier.back(); frontier.pop_back(); // Add the node to the mapping graph. if (!g.is_primary_input(node) && !g.is_primary_output(node)) { gate_graph_to_lut_graph.insert({node, true}); lut_stats[info[node].selected_cut->input_count()]++; } // Add all the inputs in that cut which are not primary inputs or already-discovered nodes to the mapping frontier. if (g.is_primary_output(node)) { for (size_t input : g.compute_node_fanin_nodes(node)) { frontier.push_back(input); break; } } for (size_t input : info[node].selected_cut->inputs) { if (!g.is_primary_input(input) && !gate_graph_to_lut_graph.count(input)) { frontier.push_back(input); } } } size_t total_luts = 0; for (int lut_size = 1; lut_size <= settings.cut_input_limit; lut_size++) { std::cout << "LUT" << lut_size << ": " << lut_stats[lut_size] << '\n'; total_luts += lut_stats[lut_size]; } std::cout << "LUTs: " << total_luts << '\n'; } graph<lut> derive_mapping(bool simulate) const { // The mapping frontier is the list of all nodes which do not have selected cuts. // We start with the primary outputs and work downwards. std::vector<size_t> frontier; std::transform(g.primary_outputs.begin(), g.primary_outputs.end(), std::back_inserter(frontier), [](size_t po) { return po; }); std::unordered_map<size_t, size_t> gate_graph_to_lut_graph; graph<lut> mapping; // Populate the LUT graph with the primary inputs and outputs of the gate graph. gate_graph_to_lut_graph.insert({0, mapping.add_constant_zero()}); gate_graph_to_lut_graph.insert({1, mapping.add_constant_one()}); for (size_t pi : g.primary_inputs) { size_t index = mapping.add_primary_input(); gate_graph_to_lut_graph.insert({pi, index}); } for (size_t po : g.primary_outputs) { size_t index = mapping.add_primary_output(); gate_graph_to_lut_graph.insert({po, index}); } // While there are still nodes to be mapped: while (!frontier.empty()) { // Pop a node from the mapping frontier. size_t node = frontier.back(); frontier.pop_back(); // Add the node to the mapping graph. if (!g.is_primary_input(node) && !g.is_primary_output(node)) { kitty::dynamic_truth_table tt{}; if (simulate) { tt = g.simulate(*info[node].selected_cut); } size_t index = mapping.add_cell(lut{tt}); gate_graph_to_lut_graph.insert({node, index}); } // Add all the inputs in that cut which are not primary inputs or already-discovered nodes to the mapping frontier. if (g.is_primary_output(node)) { for (size_t input : g.compute_node_fanin_nodes(node)) { frontier.push_back(input); break; } } for (size_t input : info[node].selected_cut->inputs) { if (!g.is_primary_input(input) && !gate_graph_to_lut_graph.count(input)) { frontier.push_back(input); } } } // Walk the frontier again, but this time populating the graph with connections. std::transform(g.primary_outputs.begin(), g.primary_outputs.end(), std::back_inserter(frontier), [](size_t po) { return po; }); std::unordered_set<size_t> visited; while (!frontier.empty()) { // Pop a node from the mapping frontier. size_t node = frontier.back(); frontier.pop_back(); visited.insert(node); if (g.is_primary_output(node)) { for (size_t input : g.compute_node_fanin_nodes(node)) { frontier.push_back(input); mapping.add_connection(gate_graph_to_lut_graph.at(input), gate_graph_to_lut_graph.at(node)); break; } } else { for (size_t input : info[node].selected_cut->inputs) { if (!g.is_primary_input(input) && !visited.count(input)) { frontier.push_back(input); } mapping.add_connection(gate_graph_to_lut_graph.at(input), gate_graph_to_lut_graph.at(node)); } } } return mapping; } std::vector<cut> node_cut_set(size_t node, std::unordered_map<size_t, frontier_info> const& frontier) const { assert(std::holds_alternative<cell>(g.nodes[node])); assert(std::get<cell>(g.nodes[node]).truth_table.size() == 1 && "not implemented: multiple output gates"); std::vector<size_t> node_inputs{g.compute_node_fanin_nodes(node)}; // To calculate the cut set of a node, we need to compute the cartesian product of its child cuts. // This is implemented as performing a 2-way cartesian product N times. // Start with the cut set of input zero. if (node_inputs.empty()) { std::cout << "node: " << node << '\n'; throw std::logic_error{"node_cut_set called on node without fanin"}; } std::vector<cut> cut_set{frontier.at(node_inputs[0]).cuts}; // Append the trivial cut of input zero. cut_set.push_back(cut{node_inputs[0]}); // For each other input: if (node_inputs.size() > 1) { std::for_each(node_inputs.begin()+1, node_inputs.end(), [&](size_t node_input) { if (frontier.find(node_input) == frontier.end()) { throw std::logic_error("bug: mapping frontier does not contain node"); } std::vector<cut> new_cuts; // Merge the present cut set with the cuts of this input. for (cut const& c : cut_set) { for (int input_cut = 0; input_cut < frontier.at(node_input).cuts.size(); input_cut++) { new_cuts.push_back(c.merge(frontier.at(node_input).cuts[input_cut], node)); new_cuts.push_back(c.merge(cut{node_input}, node)); } } // Filter out cuts which exceed the cut input limit. new_cuts.erase(std::remove_if(new_cuts.begin(), new_cuts.end(), [=](cut const& candidate) { return candidate.input_count() > settings.cut_input_limit; }), new_cuts.end()); // TODO: is it sound to keep a running total of the N best cuts and prune cuts that are worse than the limit? // Or does that negatively affect cut quality? // Replace the present cut set with the new one. cut_set = std::move(new_cuts); }); } else { // When we have only a single input, we end up with the cut set of that input. // We need to patch the cut set to set the cut outputs as this node. for (cut& c : cut_set) { c.output = node; } } // Also include the previous-best cut in the cut set, if it exists, to avoid forgetting good cuts. if (info[node].selected_cut.has_value()) { cut_set.push_back(*info[node].selected_cut); } return cut_set; } // Ordering by cut depth is vital to find the best possible mapping for a network. unsigned int cut_depth(cut const& c, std::vector<mapping_info> const& info) { unsigned int depth = 0; for (size_t input : c.inputs) { if (info.at(input).depth > depth) { depth = info.at(input).depth; } } return depth + settings.lut_delay[c.input_count()]; } // It is better to prefer smaller cuts over bigger cuts because it allows more cuts to be mapped // for the same network depth. unsigned int cut_input_count(cut const& c, std::vector<mapping_info> const& info) { (void)info; return c.input_count(); } // Preferring cuts with lower fanin references aims to reduce mapping duplication // where a node is covered by multiple mappings at the same time. float cut_fanin_refs(cut const& c, std::vector<mapping_info> const& info) { float references = 0.0; for (size_t input : c.inputs) { references += float(info.at(input).references); } return references / float(c.input_count()); } // Area flow estimates how much this cone of logic is shared within the current mapping. float cut_area_flow(cut const& c, std::vector<mapping_info> const& info) { float sum_area_flow = float(settings.lut_area[c.input_count()]); for (size_t input : c.inputs) { sum_area_flow += info.at(input).area_flow; } return sum_area_flow / std::max(1.0f, float(info.at(c.output).references)); } // Exact area calculates the number of LUTs that would be added to the mapping if this cut was selected. unsigned int cut_exact_area(cut const& c) { if (info.at(c.output).selected_cut.has_value()) { if (c == *info.at(c.output).selected_cut) { auto area2 = exact_area_ref(c); auto area1 = exact_area_deref(c); if (area1 != area2) { throw std::logic_error("bug: mismatch between number of nodes referenced and dereferenced"); } return area1; } } auto area2 = exact_area_ref(c); auto area1 = exact_area_deref(c); if (area1 != area2) { throw std::logic_error("bug: mismatch between number of nodes referenced and dereferenced"); } return area1; } unsigned int exact_area_deref(cut const& c) { unsigned int area = settings.lut_area[c.input_count()]; for (size_t cut_input : c.inputs) { if (std::holds_alternative<cell>(g.nodes[cut_input])) { if (info.at(cut_input).references <= 0) { std::cout << "At node " << cut_input << ":\n"; fflush(stdout); throw std::logic_error{"exact_area_deref: bug: decremented node reference below zero"}; } info.at(cut_input).references--; if (info.at(cut_input).references == 0) { area += exact_area_deref(*info.at(cut_input).selected_cut); } } } return area; } unsigned int exact_area_ref(cut const& c) { unsigned int area = settings.lut_area[c.input_count()]; for (size_t cut_input : c.inputs) { if (std::holds_alternative<cell>(g.nodes[cut_input])) { if (info.at(cut_input).references == 0) { area += exact_area_ref(*info.at(cut_input).selected_cut); } info.at(cut_input).references++; } } return area; } void cut_deref(cut const& c) { for (size_t cut_input : c.inputs) { if (std::holds_alternative<cell>(g.nodes[cut_input])) { if (info.at(cut_input).references <= 0) { std::cout << "At node " << cut_input << ":\n"; fflush(stdout); throw std::logic_error{"cut_deref: bug: decremented node reference below zero"}; } info.at(cut_input).references--; info.at(cut_input).area_flow = cut_area_flow(*info.at(cut_input).selected_cut, info); if (info.at(cut_input).references == 0) { cut_deref(*info.at(cut_input).selected_cut); } } } } void cut_ref(cut const& c) { for (size_t cut_input : c.inputs) { if (std::holds_alternative<cell>(g.nodes[cut_input])) { if (info.at(cut_input).references == 0) { cut_ref(*info.at(cut_input).selected_cut); } info.at(cut_input).references++; info.at(cut_input).area_flow = cut_area_flow(*info.at(cut_input).selected_cut, info); } } } graph<cell> g; std::vector<mapping_info> info; mapping_settings settings; }; template<class Ntk> graph<cell> mockturtle_to_lut_graph(Ntk const& input_ntk) { static_assert(mockturtle::is_network_type_v<Ntk>); static_assert(mockturtle::has_foreach_pi_v<Ntk>); static_assert(mockturtle::has_foreach_po_v<Ntk>); static_assert(mockturtle::has_foreach_node_v<Ntk>); static_assert(mockturtle::has_cell_function_v<Ntk>); mockturtle::klut_network ntk = mockturtle::gates_to_nodes<mockturtle::klut_network, Ntk>(input_ntk); graph<cell> g{}; std::unordered_map<mockturtle::klut_network::node, size_t> mockturtle_to_node{}; mockturtle_to_node.insert({ntk.get_node(ntk.get_constant(false)), g.add_constant_zero()}); mockturtle_to_node.insert({ntk.get_node(ntk.get_constant(true)), g.add_constant_one()}); ntk.foreach_pi([&](mockturtle::klut_network::node const& node, uint32_t index) -> void { size_t pi = g.add_primary_input(); mockturtle_to_node.insert({node, pi}); }); ntk.foreach_node([&](mockturtle::klut_network::node const& node) -> void { if (!ntk.is_constant(node)) { std::vector<kitty::dynamic_truth_table> truth_table{}; truth_table.push_back(ntk.node_function(node)); size_t c = g.add_cell(cell{truth_table}); mockturtle_to_node.insert({node, c}); ntk.foreach_fanin(node, [&](mockturtle::klut_network::signal const& fanin) -> void { g.add_connection(mockturtle_to_node.at(ntk.get_node(fanin)), mockturtle_to_node.at(node)); }); } }); ntk.foreach_po([&](mockturtle::klut_network::signal const& signal, uint32_t index) -> void { size_t po = g.add_primary_output(); g.add_connection(mockturtle_to_node.at(ntk.get_node(signal)), po); }); mockturtle::write_blif(ntk, "c432.before.blif"); //g.dump_to_stdout(); return g; } mockturtle::klut_network lut_graph_to_mockturtle(graph<lut> const& g) { mockturtle::klut_network ntk{}; std::unordered_map<size_t, mockturtle::klut_network::signal> node_to_mockturtle{}; //g.dump_to_stdout(); node_to_mockturtle.insert({0, ntk.get_constant(0)}); node_to_mockturtle.insert({1, ntk.get_constant(1)}); for (size_t pi : g.primary_inputs) { node_to_mockturtle.insert({pi, ntk.create_pi()}); } for (size_t node : g.compute_topological_ordering()) { std::vector<mockturtle::klut_network::signal> children{}; for (size_t input : g.compute_node_fanin_nodes(node)) { children.push_back(node_to_mockturtle.at(input)); } if (!g.is_primary_input(node) && !g.is_primary_output(node) && !g.is_constant(node)) { node_to_mockturtle.insert({node, ntk.create_node(children, std::get<lut>(g.nodes[node]).truth_table)}); } } for (size_t po : g.primary_outputs) { for (size_t fanin : g.compute_node_fanin_nodes(po)) { if (node_to_mockturtle.find(fanin) == node_to_mockturtle.end()) { std::cout << "Node " << fanin << " not in node_to_mockturtle\n"; } node_to_mockturtle.insert({po, ntk.create_po(node_to_mockturtle.at(fanin))}); break; } } mockturtle::write_blif(ntk, "c432.after.blif"); return ntk; } } // namespace techmap } // namespace oracle
46,870
14,634
#include "TGUIscene.hpp" int setGod(sf::RenderWindow *); int setScene(Scene *); int PlayScene(Scene *); int PlayCurrentScene(); int PlayCurrentSceneFast();
166
65
#include "Log.h" #include <cstdarg> #include <cerrno> #include <cstdio> #include <cstring> #include <ctime> const char *gStrLevelString[] = { "ERROR", "WARNING", "NORMAL", "DEBUG", "DETAIL", }; LOG_LEVEL CLog::m_level = LL_NORMAL; FILE *CLog::m_pLog = NULL; string CLog::m_strLogFile = ""; const char* CLog::GetLevelString(LOG_LEVEL level) { int i = level; if((i>=0) && (i<=LL_DETAIL)) { return gStrLevelString[i]; } return "UNKNOWN"; } void CLog::Close() { if(m_pLog) { if((m_pLog!=stdout) && (m_pLog!=stderr)) { fclose(m_pLog); } m_pLog = NULL; } } int CLog::SetLogFile(const string &file) { FILE *pLog = fopen(file.c_str(), "a+"); int res = SetLogFile(pLog); if(res == 0) { m_strLogFile = file; } return res; } int CLog::SetLogFile(FILE *pF) { if(pF == NULL) { return -1; } Close(); m_pLog = pF; m_strLogFile = ""; return 0; } void CLog::Log(LOG_LEVEL level, const char *file, int line, int error, char *fmt, ...) { if(m_pLog == NULL) return; // no log file specified if(level > m_level) return; // too detail // format time char strtime[128]; time_t t = time(NULL); struct tm *tt = gmtime(&t); snprintf(strtime, sizeof(strtime)-1, "%d-%d-%d %d:%d:%d", 1900+tt->tm_year, tt->tm_mon, tt->tm_yday, tt->tm_hour, tt->tm_min, tt->tm_sec); // format message char buf[64*1024]; // max error message size in Windows va_list maker; va_start(maker, fmt); vsnprintf(buf, sizeof(buf)-1, fmt, maker); va_end(maker); fprintf(m_pLog, "[%s][%s][%s][line:%d]%s[errno=%d]", strtime, GetLevelString(level), file, line, buf, error); // format error strings buf[0] = '\0'; if(error != 0) { #ifdef WIN32 // Windows FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, DWORD(error), 0, buf, sizeof(buf)-1, NULL); fprintf(m_pLog, "%s.\n", buf); #else // Linux fprintf(m_pLog, "%s.\n", strerror(error)); #endif } else { fprintf(m_pLog, ".\n"); } // flush file for error message if(level == LL_ERROR) { fflush(m_pLog); } } void CLog::Log(LOG_LEVEL level, int error, char *fmt, ...) { if(m_pLog == NULL) return; // no log file specified if(level > m_level) return; // too detail // format time char strtime[128]; time_t t = time(NULL); struct tm *tt = gmtime(&t); snprintf(strtime, sizeof(strtime)-1, "%d-%d-%d %d:%d:%d", 1900+tt->tm_year, tt->tm_mon, tt->tm_yday, tt->tm_hour, tt->tm_min, tt->tm_sec); // format message char buf[64*1024]; // max error message size in Windows va_list maker; va_start(maker, fmt); vsnprintf(buf, sizeof(buf)-1, fmt, maker); va_end(maker); fprintf(m_pLog, "[%s][%s]%s[errno=%d]", strtime, GetLevelString(level), buf, error); // format error strings buf[0] = '\0'; if(error != 0) { #ifdef WIN32 // Windows FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, DWORD(error), 0, buf, sizeof(buf)-1, NULL); fprintf(m_pLog, "%s.\n", buf); #else // Linux fprintf(m_pLog, "%s.\n", strerror(error)); #endif } else { fprintf(m_pLog, ".\n"); } // flush file for error message if(level == LL_ERROR) { fflush(m_pLog); } }
3,289
1,466
/** * MetriSCA - A side-channel analysis library * Copyright 2021, School of Computer and Communication Sciences, EPFL. * * All rights reserved. Use of this source code is governed by a * BSD-style license that can be found in the LICENSE.md file. */ #pragma once #include "metrisca/forward.hpp" #include "metrisca/core/plugin.hpp" namespace metrisca { class ProfilerPlugin : public Plugin { public: ProfilerPlugin() : Plugin(PluginType::Profiler) {} virtual ~ProfilerPlugin() = default; virtual Result<void, Error> Init(const ArgumentList& args) override; virtual Result<Matrix<double>, Error> Profile() = 0; protected: std::shared_ptr<TraceDataset> m_Dataset{ nullptr }; uint8_t m_KnownKey{}; uint32_t m_ByteIndex{}; }; }
830
262
/* $Id: VideoRec.cpp 72014 2018-04-25 13:28:31Z vboxsync $ */ /** @file * Video capturing utility routines. */ /* * Copyright (C) 2012-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifdef LOG_GROUP # undef LOG_GROUP #endif #define LOG_GROUP LOG_GROUP_MAIN_DISPLAY #include "LoggingNew.h" #include <stdexcept> #include <vector> #include <iprt/asm.h> #include <iprt/assert.h> #include <iprt/critsect.h> #include <iprt/path.h> #include <iprt/semaphore.h> #include <iprt/thread.h> #include <iprt/time.h> #include <VBox/err.h> #include <VBox/com/VirtualBox.h> #include "WebMWriter.h" #include "VideoRec.h" #ifdef VBOX_WITH_LIBVPX # define VPX_CODEC_DISABLE_COMPAT 1 # include "vpx/vp8cx.h" # include "vpx/vpx_image.h" # include "vpx/vpx_encoder.h" #endif /* VBOX_WITH_LIBVPX */ struct VIDEORECVIDEOFRAME; typedef struct VIDEORECVIDEOFRAME *PVIDEORECVIDEOFRAME; static int videoRecEncodeAndWrite(PVIDEORECSTREAM pStream, PVIDEORECVIDEOFRAME pFrame); static int videoRecRGBToYUV(uint32_t uPixelFormat, uint8_t *paDst, uint32_t uDstWidth, uint32_t uDstHeight, uint8_t *paSrc, uint32_t uSrcWidth, uint32_t uSrcHeight); static int videoRecStreamCloseFile(PVIDEORECSTREAM pStream); static void videoRecStreamLock(PVIDEORECSTREAM pStream); static void videoRecStreamUnlock(PVIDEORECSTREAM pStream); using namespace com; #if 0 /** Enables support for encoding multiple audio / video data frames at once. */ #define VBOX_VIDEOREC_WITH_QUEUE #endif #ifdef DEBUG_andy /** Enables dumping audio / video data for debugging reasons. */ //# define VBOX_VIDEOREC_DUMP #endif /** * Enumeration for a video recording state. */ enum VIDEORECSTS { /** Not initialized. */ VIDEORECSTS_UNINITIALIZED = 0, /** Initialized. */ VIDEORECSTS_INITIALIZED = 1, /** The usual 32-bit hack. */ VIDEORECSTS_32BIT_HACK = 0x7fffffff }; /** * Enumeration for supported pixel formats. */ enum VIDEORECPIXELFMT { /** Unknown pixel format. */ VIDEORECPIXELFMT_UNKNOWN = 0, /** RGB 24. */ VIDEORECPIXELFMT_RGB24 = 1, /** RGB 24. */ VIDEORECPIXELFMT_RGB32 = 2, /** RGB 565. */ VIDEORECPIXELFMT_RGB565 = 3, /** The usual 32-bit hack. */ VIDEORECPIXELFMT_32BIT_HACK = 0x7fffffff }; /** * Structure for keeping specific video recording codec data. */ typedef struct VIDEORECVIDEOCODEC { union { #ifdef VBOX_WITH_LIBVPX struct { /** VPX codec context. */ vpx_codec_ctx_t Ctx; /** VPX codec configuration. */ vpx_codec_enc_cfg_t Cfg; /** VPX image context. */ vpx_image_t RawImage; } VPX; #endif /* VBOX_WITH_LIBVPX */ }; } VIDEORECVIDEOCODEC, *PVIDEORECVIDEOCODEC; /** * Structure for keeping a single video recording video frame. */ typedef struct VIDEORECVIDEOFRAME { /** X resolution of this frame. */ uint32_t uWidth; /** Y resolution of this frame. */ uint32_t uHeight; /** Pixel format of this frame. */ uint32_t uPixelFormat; /** Time stamp (in ms). */ uint64_t uTimeStampMs; /** RGB buffer containing the unmodified frame buffer data from Main's display. */ uint8_t *pu8RGBBuf; /** Size (in bytes) of the RGB buffer. */ size_t cbRGBBuf; } VIDEORECVIDEOFRAME, *PVIDEORECVIDEOFRAME; #ifdef VBOX_WITH_AUDIO_VIDEOREC /** * Structure for keeping a single video recording audio frame. */ typedef struct VIDEORECAUDIOFRAME { uint8_t abBuf[_64K]; /** @todo Fix! */ size_t cbBuf; /** Absolute time stamp (in ms). */ uint64_t uTimeStampMs; } VIDEORECAUDIOFRAME, *PVIDEORECAUDIOFRAME; #endif /** * Strucutre for maintaining a video recording stream. */ typedef struct VIDEORECSTREAM { /** Video recording context this stream is associated to. */ PVIDEORECCONTEXT pCtx; /** Destination where to write the stream to. */ VIDEORECDEST enmDst; union { struct { /** File handle to use for writing. */ RTFILE hFile; /** File name being used for this stream. */ char *pszFile; /** Pointer to WebM writer instance being used. */ WebMWriter *pWEBM; } File; }; #ifdef VBOX_WITH_AUDIO_VIDEOREC /** Track number of audio stream. */ uint8_t uTrackAudio; #endif /** Track number of video stream. */ uint8_t uTrackVideo; /** Screen ID. */ uint16_t uScreenID; /** Whether video recording is enabled or not. */ bool fEnabled; /** Critical section to serialize access. */ RTCRITSECT CritSect; struct { /** Codec-specific data. */ VIDEORECVIDEOCODEC Codec; /** Minimal delay (in ms) between two frames. */ uint32_t uDelayMs; /** Target X resolution (in pixels). */ uint32_t uWidth; /** Target Y resolution (in pixels). */ uint32_t uHeight; /** Time stamp (in ms) of the last video frame we encoded. */ uint64_t uLastTimeStampMs; /** Pointer to the codec's internal YUV buffer. */ uint8_t *pu8YuvBuf; #ifdef VBOX_VIDEOREC_WITH_QUEUE # error "Implement me!" #else VIDEORECVIDEOFRAME Frame; bool fHasVideoData; #endif /** Number of failed attempts to encode the current video frame in a row. */ uint16_t cFailedEncodingFrames; } Video; } VIDEORECSTREAM, *PVIDEORECSTREAM; /** Vector of video recording streams. */ typedef std::vector <PVIDEORECSTREAM> VideoRecStreams; /** * Structure for keeping a video recording context. */ typedef struct VIDEORECCONTEXT { /** Used recording configuration. */ VIDEORECCFG Cfg; /** The current state. */ uint32_t enmState; /** Critical section to serialize access. */ RTCRITSECT CritSect; /** Semaphore to signal the encoding worker thread. */ RTSEMEVENT WaitEvent; /** Whether this conext is in started state or not. */ bool fStarted; /** Shutdown indicator. */ bool fShutdown; /** Worker thread. */ RTTHREAD Thread; /** Vector of current recording stream contexts. */ VideoRecStreams vecStreams; /** Timestamp (in ms) of when recording has been started. */ uint64_t tsStartMs; #ifdef VBOX_WITH_AUDIO_VIDEOREC struct { bool fHasAudioData; VIDEORECAUDIOFRAME Frame; } Audio; #endif } VIDEORECCONTEXT, *PVIDEORECCONTEXT; #ifdef VBOX_VIDEOREC_DUMP #pragma pack(push) #pragma pack(1) typedef struct { uint16_t u16Magic; uint32_t u32Size; uint16_t u16Reserved1; uint16_t u16Reserved2; uint32_t u32OffBits; } VIDEORECBMPHDR, *PVIDEORECBMPHDR; AssertCompileSize(VIDEORECBMPHDR, 14); typedef struct { uint32_t u32Size; uint32_t u32Width; uint32_t u32Height; uint16_t u16Planes; uint16_t u16BitCount; uint32_t u32Compression; uint32_t u32SizeImage; uint32_t u32XPelsPerMeter; uint32_t u32YPelsPerMeter; uint32_t u32ClrUsed; uint32_t u32ClrImportant; } VIDEORECBMPDIBHDR, *PVIDEORECBMPDIBHDR; AssertCompileSize(VIDEORECBMPDIBHDR, 40); #pragma pack(pop) #endif /* VBOX_VIDEOREC_DUMP */ /** * Iterator class for running through a BGRA32 image buffer and converting * it to RGB. */ class ColorConvBGRA32Iter { private: enum { PIX_SIZE = 4 }; public: ColorConvBGRA32Iter(unsigned aWidth, unsigned aHeight, uint8_t *aBuf) { LogFlow(("width = %d height=%d aBuf=%lx\n", aWidth, aHeight, aBuf)); mPos = 0; mSize = aWidth * aHeight * PIX_SIZE; mBuf = aBuf; } /** * Convert the next pixel to RGB. * @returns true on success, false if we have reached the end of the buffer * @param aRed where to store the red value * @param aGreen where to store the green value * @param aBlue where to store the blue value */ bool getRGB(unsigned *aRed, unsigned *aGreen, unsigned *aBlue) { bool rc = false; if (mPos + PIX_SIZE <= mSize) { *aRed = mBuf[mPos + 2]; *aGreen = mBuf[mPos + 1]; *aBlue = mBuf[mPos ]; mPos += PIX_SIZE; rc = true; } return rc; } /** * Skip forward by a certain number of pixels * @param aPixels how many pixels to skip */ void skip(unsigned aPixels) { mPos += PIX_SIZE * aPixels; } private: /** Size of the picture buffer */ unsigned mSize; /** Current position in the picture buffer */ unsigned mPos; /** Address of the picture buffer */ uint8_t *mBuf; }; /** * Iterator class for running through an BGR24 image buffer and converting * it to RGB. */ class ColorConvBGR24Iter { private: enum { PIX_SIZE = 3 }; public: ColorConvBGR24Iter(unsigned aWidth, unsigned aHeight, uint8_t *aBuf) { mPos = 0; mSize = aWidth * aHeight * PIX_SIZE; mBuf = aBuf; } /** * Convert the next pixel to RGB. * @returns true on success, false if we have reached the end of the buffer * @param aRed where to store the red value * @param aGreen where to store the green value * @param aBlue where to store the blue value */ bool getRGB(unsigned *aRed, unsigned *aGreen, unsigned *aBlue) { bool rc = false; if (mPos + PIX_SIZE <= mSize) { *aRed = mBuf[mPos + 2]; *aGreen = mBuf[mPos + 1]; *aBlue = mBuf[mPos ]; mPos += PIX_SIZE; rc = true; } return rc; } /** * Skip forward by a certain number of pixels * @param aPixels how many pixels to skip */ void skip(unsigned aPixels) { mPos += PIX_SIZE * aPixels; } private: /** Size of the picture buffer */ unsigned mSize; /** Current position in the picture buffer */ unsigned mPos; /** Address of the picture buffer */ uint8_t *mBuf; }; /** * Iterator class for running through an BGR565 image buffer and converting * it to RGB. */ class ColorConvBGR565Iter { private: enum { PIX_SIZE = 2 }; public: ColorConvBGR565Iter(unsigned aWidth, unsigned aHeight, uint8_t *aBuf) { mPos = 0; mSize = aWidth * aHeight * PIX_SIZE; mBuf = aBuf; } /** * Convert the next pixel to RGB. * @returns true on success, false if we have reached the end of the buffer * @param aRed where to store the red value * @param aGreen where to store the green value * @param aBlue where to store the blue value */ bool getRGB(unsigned *aRed, unsigned *aGreen, unsigned *aBlue) { bool rc = false; if (mPos + PIX_SIZE <= mSize) { unsigned uFull = (((unsigned) mBuf[mPos + 1]) << 8) | ((unsigned) mBuf[mPos]); *aRed = (uFull >> 8) & ~7; *aGreen = (uFull >> 3) & ~3 & 0xff; *aBlue = (uFull << 3) & ~7 & 0xff; mPos += PIX_SIZE; rc = true; } return rc; } /** * Skip forward by a certain number of pixels * @param aPixels how many pixels to skip */ void skip(unsigned aPixels) { mPos += PIX_SIZE * aPixels; } private: /** Size of the picture buffer */ unsigned mSize; /** Current position in the picture buffer */ unsigned mPos; /** Address of the picture buffer */ uint8_t *mBuf; }; /** * Convert an image to YUV420p format. * * @return true on success, false on failure. * @param aDstBuf The destination image buffer. * @param aDstWidth Width (in pixel) of destination buffer. * @param aDstHeight Height (in pixel) of destination buffer. * @param aSrcBuf The source image buffer. * @param aSrcWidth Width (in pixel) of source buffer. * @param aSrcHeight Height (in pixel) of source buffer. */ template <class T> inline bool colorConvWriteYUV420p(uint8_t *aDstBuf, unsigned aDstWidth, unsigned aDstHeight, uint8_t *aSrcBuf, unsigned aSrcWidth, unsigned aSrcHeight) { RT_NOREF(aDstWidth, aDstHeight); AssertReturn(!(aSrcWidth & 1), false); AssertReturn(!(aSrcHeight & 1), false); bool fRc = true; T iter1(aSrcWidth, aSrcHeight, aSrcBuf); T iter2 = iter1; iter2.skip(aSrcWidth); unsigned cPixels = aSrcWidth * aSrcHeight; unsigned offY = 0; unsigned offU = cPixels; unsigned offV = cPixels + cPixels / 4; unsigned const cyHalf = aSrcHeight / 2; unsigned const cxHalf = aSrcWidth / 2; for (unsigned i = 0; i < cyHalf && fRc; ++i) { for (unsigned j = 0; j < cxHalf; ++j) { unsigned red, green, blue; fRc = iter1.getRGB(&red, &green, &blue); AssertReturn(fRc, false); aDstBuf[offY] = ((66 * red + 129 * green + 25 * blue + 128) >> 8) + 16; unsigned u = (((-38 * red - 74 * green + 112 * blue + 128) >> 8) + 128) / 4; unsigned v = (((112 * red - 94 * green - 18 * blue + 128) >> 8) + 128) / 4; fRc = iter1.getRGB(&red, &green, &blue); AssertReturn(fRc, false); aDstBuf[offY + 1] = ((66 * red + 129 * green + 25 * blue + 128) >> 8) + 16; u += (((-38 * red - 74 * green + 112 * blue + 128) >> 8) + 128) / 4; v += (((112 * red - 94 * green - 18 * blue + 128) >> 8) + 128) / 4; fRc = iter2.getRGB(&red, &green, &blue); AssertReturn(fRc, false); aDstBuf[offY + aSrcWidth] = ((66 * red + 129 * green + 25 * blue + 128) >> 8) + 16; u += (((-38 * red - 74 * green + 112 * blue + 128) >> 8) + 128) / 4; v += (((112 * red - 94 * green - 18 * blue + 128) >> 8) + 128) / 4; fRc = iter2.getRGB(&red, &green, &blue); AssertReturn(fRc, false); aDstBuf[offY + aSrcWidth + 1] = ((66 * red + 129 * green + 25 * blue + 128) >> 8) + 16; u += (((-38 * red - 74 * green + 112 * blue + 128) >> 8) + 128) / 4; v += (((112 * red - 94 * green - 18 * blue + 128) >> 8) + 128) / 4; aDstBuf[offU] = u; aDstBuf[offV] = v; offY += 2; ++offU; ++offV; } iter1.skip(aSrcWidth); iter2.skip(aSrcWidth); offY += aSrcWidth; } return true; } /** * Convert an image to RGB24 format * @returns true on success, false on failure * @param aWidth width of image * @param aHeight height of image * @param aDestBuf an allocated memory buffer large enough to hold the * destination image (i.e. width * height * 12bits) * @param aSrcBuf the source image as an array of bytes */ template <class T> inline bool colorConvWriteRGB24(unsigned aWidth, unsigned aHeight, uint8_t *aDestBuf, uint8_t *aSrcBuf) { enum { PIX_SIZE = 3 }; bool rc = true; AssertReturn(0 == (aWidth & 1), false); AssertReturn(0 == (aHeight & 1), false); T iter(aWidth, aHeight, aSrcBuf); unsigned cPixels = aWidth * aHeight; for (unsigned i = 0; i < cPixels && rc; ++i) { unsigned red, green, blue; rc = iter.getRGB(&red, &green, &blue); if (rc) { aDestBuf[i * PIX_SIZE ] = red; aDestBuf[i * PIX_SIZE + 1] = green; aDestBuf[i * PIX_SIZE + 2] = blue; } } return rc; } /** * Worker thread for all streams of a video recording context. * * Does RGB/YUV conversion and encoding. */ static DECLCALLBACK(int) videoRecThread(RTTHREAD hThreadSelf, void *pvUser) { PVIDEORECCONTEXT pCtx = (PVIDEORECCONTEXT)pvUser; /* Signal that we're up and rockin'. */ RTThreadUserSignal(hThreadSelf); for (;;) { int rc = RTSemEventWait(pCtx->WaitEvent, RT_INDEFINITE_WAIT); AssertRCBreak(rc); if (ASMAtomicReadBool(&pCtx->fShutdown)) break; #ifdef VBOX_WITH_AUDIO_VIDEOREC VIDEORECAUDIOFRAME audioFrame; RT_ZERO(audioFrame); int rc2 = RTCritSectEnter(&pCtx->CritSect); AssertRC(rc2); const bool fEncodeAudio = pCtx->Audio.fHasAudioData; if (fEncodeAudio) { /* * Every recording stream needs to get the same audio data at a certain point in time. * Do the multiplexing here to not block EMT for too long. * * For now just doing a simple copy of the current audio frame should be good enough. */ memcpy(&audioFrame, &pCtx->Audio.Frame, sizeof(VIDEORECAUDIOFRAME)); pCtx->Audio.fHasAudioData = false; } rc2 = RTCritSectLeave(&pCtx->CritSect); AssertRC(rc2); #endif /** @todo r=andy This is inefficient -- as we already wake up this thread * for every screen from Main, we here go again (on every wake up) through * all screens. */ for (VideoRecStreams::iterator it = pCtx->vecStreams.begin(); it != pCtx->vecStreams.end(); it++) { PVIDEORECSTREAM pStream = (*it); videoRecStreamLock(pStream); if (!pStream->fEnabled) { videoRecStreamUnlock(pStream); continue; } PVIDEORECVIDEOFRAME pVideoFrame = &pStream->Video.Frame; const bool fEncodeVideo = pStream->Video.fHasVideoData; if (fEncodeVideo) { rc = videoRecRGBToYUV(pVideoFrame->uPixelFormat, /* Destination */ pStream->Video.pu8YuvBuf, pVideoFrame->uWidth, pVideoFrame->uHeight, /* Source */ pVideoFrame->pu8RGBBuf, pStream->Video.uWidth, pStream->Video.uHeight); if (RT_SUCCESS(rc)) rc = videoRecEncodeAndWrite(pStream, pVideoFrame); pStream->Video.fHasVideoData = false; } videoRecStreamUnlock(pStream); if (RT_FAILURE(rc)) { static unsigned s_cErrEncVideo = 0; if (s_cErrEncVideo < 32) { LogRel(("VideoRec: Error %Rrc encoding / writing video frame\n", rc)); s_cErrEncVideo++; } } #ifdef VBOX_WITH_AUDIO_VIDEOREC /* Each (enabled) screen has to get the same audio data. */ if (fEncodeAudio) { Assert(audioFrame.cbBuf); Assert(audioFrame.cbBuf <= _64K); /** @todo Fix. */ WebMWriter::BlockData_Opus blockData = { audioFrame.abBuf, audioFrame.cbBuf, audioFrame.uTimeStampMs }; rc = pStream->File.pWEBM->WriteBlock(pStream->uTrackAudio, &blockData, sizeof(blockData)); if (RT_FAILURE(rc)) { static unsigned s_cErrEncAudio = 0; if (s_cErrEncAudio < 32) { LogRel(("VideoRec: Error %Rrc encoding audio frame\n", rc)); s_cErrEncAudio++; } } } #endif } /* Keep going in case of errors. */ } /* for */ return VINF_SUCCESS; } /** * Creates a video recording context. * * @returns IPRT status code. * @param cScreens Number of screens to create context for. * @param pVideoRecCfg Pointer to video recording configuration to use. * @param ppCtx Pointer to created video recording context on success. */ int VideoRecContextCreate(uint32_t cScreens, PVIDEORECCFG pVideoRecCfg, PVIDEORECCONTEXT *ppCtx) { AssertReturn(cScreens, VERR_INVALID_PARAMETER); AssertPtrReturn(pVideoRecCfg, VERR_INVALID_POINTER); AssertPtrReturn(ppCtx, VERR_INVALID_POINTER); PVIDEORECCONTEXT pCtx = (PVIDEORECCONTEXT)RTMemAllocZ(sizeof(VIDEORECCONTEXT)); if (!pCtx) return VERR_NO_MEMORY; int rc = RTCritSectInit(&pCtx->CritSect); if (RT_FAILURE(rc)) { RTMemFree(pCtx); return rc; } for (uint32_t uScreen = 0; uScreen < cScreens; uScreen++) { PVIDEORECSTREAM pStream = (PVIDEORECSTREAM)RTMemAllocZ(sizeof(VIDEORECSTREAM)); if (!pStream) { rc = VERR_NO_MEMORY; break; } rc = RTCritSectInit(&pStream->CritSect); if (RT_FAILURE(rc)) break; try { pStream->uScreenID = uScreen; pCtx->vecStreams.push_back(pStream); pStream->File.pWEBM = new WebMWriter(); } catch (std::bad_alloc) { rc = VERR_NO_MEMORY; break; } } if (RT_SUCCESS(rc)) { pCtx->tsStartMs = RTTimeMilliTS(); pCtx->enmState = VIDEORECSTS_UNINITIALIZED; pCtx->fStarted = false; pCtx->fShutdown = false; /* Copy the configuration to our context. */ pCtx->Cfg = *pVideoRecCfg; rc = RTSemEventCreate(&pCtx->WaitEvent); AssertRCReturn(rc, rc); rc = RTThreadCreate(&pCtx->Thread, videoRecThread, (void *)pCtx, 0, RTTHREADTYPE_MAIN_WORKER, RTTHREADFLAGS_WAITABLE, "VideoRec"); if (RT_SUCCESS(rc)) /* Wait for the thread to start. */ rc = RTThreadUserWait(pCtx->Thread, 30 * 1000 /* 30s timeout */); if (RT_SUCCESS(rc)) { pCtx->enmState = VIDEORECSTS_INITIALIZED; pCtx->fStarted = true; if (ppCtx) *ppCtx = pCtx; } } if (RT_FAILURE(rc)) { int rc2 = VideoRecContextDestroy(pCtx); AssertRC(rc2); } return rc; } /** * Destroys a video recording context. * * @param pCtx Video recording context to destroy. */ int VideoRecContextDestroy(PVIDEORECCONTEXT pCtx) { if (!pCtx) return VINF_SUCCESS; if (pCtx->enmState == VIDEORECSTS_INITIALIZED) { /* Set shutdown indicator. */ ASMAtomicWriteBool(&pCtx->fShutdown, true); /* Signal the thread. */ RTSemEventSignal(pCtx->WaitEvent); int rc = RTThreadWait(pCtx->Thread, 10 * 1000 /* 10s timeout */, NULL); if (RT_FAILURE(rc)) return rc; /* Disable the context. */ ASMAtomicWriteBool(&pCtx->fStarted, false); rc = RTSemEventDestroy(pCtx->WaitEvent); AssertRC(rc); pCtx->WaitEvent = NIL_RTSEMEVENT; } int rc = RTCritSectEnter(&pCtx->CritSect); if (RT_SUCCESS(rc)) { VideoRecStreams::iterator it = pCtx->vecStreams.begin(); while (it != pCtx->vecStreams.end()) { PVIDEORECSTREAM pStream = (*it); videoRecStreamLock(pStream); if (pStream->fEnabled) { switch (pStream->enmDst) { case VIDEORECDEST_FILE: { if (pStream->File.pWEBM) pStream->File.pWEBM->Close(); break; } default: AssertFailed(); /* Should never happen. */ break; } vpx_img_free(&pStream->Video.Codec.VPX.RawImage); vpx_codec_err_t rcv = vpx_codec_destroy(&pStream->Video.Codec.VPX.Ctx); Assert(rcv == VPX_CODEC_OK); RT_NOREF(rcv); #ifdef VBOX_VIDEOREC_WITH_QUEUE # error "Implement me!" #else PVIDEORECVIDEOFRAME pFrame = &pStream->Video.Frame; #endif if (pFrame->pu8RGBBuf) { Assert(pFrame->cbRGBBuf); RTMemFree(pFrame->pu8RGBBuf); pFrame->pu8RGBBuf = NULL; } pFrame->cbRGBBuf = 0; LogRel(("VideoRec: Recording screen #%u stopped\n", pStream->uScreenID)); } switch (pStream->enmDst) { case VIDEORECDEST_FILE: { int rc2 = videoRecStreamCloseFile(pStream); AssertRC(rc2); if (pStream->File.pWEBM) { delete pStream->File.pWEBM; pStream->File.pWEBM = NULL; } break; } default: AssertFailed(); /* Should never happen. */ break; } it = pCtx->vecStreams.erase(it); videoRecStreamUnlock(pStream); RTCritSectDelete(&pStream->CritSect); RTMemFree(pStream); pStream = NULL; } Assert(pCtx->vecStreams.empty()); int rc2 = RTCritSectLeave(&pCtx->CritSect); AssertRC(rc2); RTCritSectDelete(&pCtx->CritSect); RTMemFree(pCtx); pCtx = NULL; } return rc; } /** * Retrieves a specific recording stream of a recording context. * * @returns Pointer to recording stream if found, or NULL if not found. * @param pCtx Recording context to look up stream for. * @param uScreen Screen number of recording stream to look up. */ DECLINLINE(PVIDEORECSTREAM) videoRecStreamGet(PVIDEORECCONTEXT pCtx, uint32_t uScreen) { AssertPtrReturn(pCtx, NULL); PVIDEORECSTREAM pStream; try { pStream = pCtx->vecStreams.at(uScreen); } catch (std::out_of_range) { pStream = NULL; } return pStream; } /** * Locks a recording stream. * * @param pStream Recording stream to lock. */ static void videoRecStreamLock(PVIDEORECSTREAM pStream) { int rc = RTCritSectEnter(&pStream->CritSect); AssertRC(rc); } /** * Unlocks a locked recording stream. * * @param pStream Recording stream to unlock. */ static void videoRecStreamUnlock(PVIDEORECSTREAM pStream) { int rc = RTCritSectLeave(&pStream->CritSect); AssertRC(rc); } /** * Opens a file for a given recording stream to capture to. * * @returns IPRT status code. * @param pStream Recording stream to open file for. * @param pCfg Recording configuration to use. */ static int videoRecStreamOpenFile(PVIDEORECSTREAM pStream, PVIDEORECCFG pCfg) { AssertPtrReturn(pStream, VERR_INVALID_POINTER); AssertPtrReturn(pCfg, VERR_INVALID_POINTER); Assert(pStream->enmDst == VIDEORECDEST_INVALID); Assert(pCfg->enmDst == VIDEORECDEST_FILE); Assert(pCfg->File.strName.isNotEmpty()); char *pszAbsPath = RTPathAbsDup(com::Utf8Str(pCfg->File.strName).c_str()); AssertPtrReturn(pszAbsPath, VERR_NO_MEMORY); RTPathStripSuffix(pszAbsPath); char *pszSuff = RTStrDup(".webm"); if (!pszSuff) { RTStrFree(pszAbsPath); return VERR_NO_MEMORY; } char *pszFile = NULL; int rc; if (pCfg->aScreens.size() > 1) rc = RTStrAPrintf(&pszFile, "%s-%u%s", pszAbsPath, pStream->uScreenID + 1, pszSuff); else rc = RTStrAPrintf(&pszFile, "%s%s", pszAbsPath, pszSuff); if (RT_SUCCESS(rc)) { uint64_t fOpen = RTFILE_O_WRITE | RTFILE_O_DENY_WRITE; /* Play safe: the file must not exist, overwriting is potentially * hazardous as nothing prevents the user from picking a file name of some * other important file, causing unintentional data loss. */ fOpen |= RTFILE_O_CREATE; RTFILE hFile; rc = RTFileOpen(&hFile, pszFile, fOpen); if (rc == VERR_ALREADY_EXISTS) { RTStrFree(pszFile); pszFile = NULL; RTTIMESPEC ts; RTTimeNow(&ts); RTTIME time; RTTimeExplode(&time, &ts); if (pCfg->aScreens.size() > 1) rc = RTStrAPrintf(&pszFile, "%s-%04d-%02u-%02uT%02u-%02u-%02u-%09uZ-%u%s", pszAbsPath, time.i32Year, time.u8Month, time.u8MonthDay, time.u8Hour, time.u8Minute, time.u8Second, time.u32Nanosecond, pStream->uScreenID + 1, pszSuff); else rc = RTStrAPrintf(&pszFile, "%s-%04d-%02u-%02uT%02u-%02u-%02u-%09uZ%s", pszAbsPath, time.i32Year, time.u8Month, time.u8MonthDay, time.u8Hour, time.u8Minute, time.u8Second, time.u32Nanosecond, pszSuff); if (RT_SUCCESS(rc)) rc = RTFileOpen(&hFile, pszFile, fOpen); } if (RT_SUCCESS(rc)) { pStream->enmDst = VIDEORECDEST_FILE; pStream->File.hFile = hFile; pStream->File.pszFile = pszFile; /* Assign allocated string to our stream's config. */ } } RTStrFree(pszSuff); RTStrFree(pszAbsPath); if (RT_FAILURE(rc)) { LogRel(("VideoRec: Failed to open file '%s' for screen %RU32, rc=%Rrc\n", pszFile ? pszFile : "<Unnamed>", pStream->uScreenID, rc)); RTStrFree(pszFile); } return rc; } /** * Closes a recording stream's file again. * * @returns IPRT status code. * @param pStream Recording stream to close file for. */ static int videoRecStreamCloseFile(PVIDEORECSTREAM pStream) { Assert(pStream->enmDst == VIDEORECDEST_FILE); pStream->enmDst = VIDEORECDEST_INVALID; AssertPtr(pStream->File.pszFile); if (RTFileIsValid(pStream->File.hFile)) { RTFileClose(pStream->File.hFile); LogRel(("VideoRec: Closed file '%s'\n", pStream->File.pszFile)); } RTStrFree(pStream->File.pszFile); pStream->File.pszFile = NULL; return VINF_SUCCESS; } /** * VideoRec utility function to initialize video recording context. * * @returns IPRT status code. * @param pCtx Pointer to video recording context. * @param uScreen Screen number to record. */ int VideoRecStreamInit(PVIDEORECCONTEXT pCtx, uint32_t uScreen) { AssertPtrReturn(pCtx, VERR_INVALID_POINTER); PVIDEORECSTREAM pStream = videoRecStreamGet(pCtx, uScreen); if (!pStream) return VERR_NOT_FOUND; int rc = videoRecStreamOpenFile(pStream, &pCtx->Cfg); if (RT_FAILURE(rc)) return rc; PVIDEORECCFG pCfg = &pCtx->Cfg; pStream->pCtx = pCtx; /** @todo Make the following parameters configurable on a per-stream basis? */ pStream->Video.uWidth = pCfg->Video.uWidth; pStream->Video.uHeight = pCfg->Video.uHeight; pStream->Video.cFailedEncodingFrames = 0; #ifndef VBOX_VIDEOREC_WITH_QUEUE /* When not using a queue, we only use one frame per stream at once. * So do the initialization here. */ PVIDEORECVIDEOFRAME pFrame = &pStream->Video.Frame; const size_t cbRGBBuf = pStream->Video.uWidth * pStream->Video.uHeight * 4 /* 32 BPP maximum */; AssertReturn(cbRGBBuf, VERR_INVALID_PARAMETER); pFrame->pu8RGBBuf = (uint8_t *)RTMemAllocZ(cbRGBBuf); AssertReturn(pFrame->pu8RGBBuf, VERR_NO_MEMORY); pFrame->cbRGBBuf = cbRGBBuf; #endif PVIDEORECVIDEOCODEC pVC = &pStream->Video.Codec; pStream->Video.uDelayMs = 1000 / pCfg->Video.uFPS; switch (pStream->enmDst) { case VIDEORECDEST_FILE: { rc = pStream->File.pWEBM->OpenEx(pStream->File.pszFile, &pStream->File.hFile, #ifdef VBOX_WITH_AUDIO_VIDEOREC pCfg->Audio.fEnabled ? WebMWriter::AudioCodec_Opus : WebMWriter::AudioCodec_None, #else WebMWriter::AudioCodec_None, #endif pCfg->Video.fEnabled ? WebMWriter::VideoCodec_VP8 : WebMWriter::VideoCodec_None); if (RT_FAILURE(rc)) { LogRel(("VideoRec: Failed to create the capture output file '%s' (%Rrc)\n", pStream->File.pszFile, rc)); break; } const char *pszFile = pStream->File.pszFile; if (pCfg->Video.fEnabled) { rc = pStream->File.pWEBM->AddVideoTrack(pCfg->Video.uWidth, pCfg->Video.uHeight, pCfg->Video.uFPS, &pStream->uTrackVideo); if (RT_FAILURE(rc)) { LogRel(("VideoRec: Failed to add video track to output file '%s' (%Rrc)\n", pszFile, rc)); break; } LogRel(("VideoRec: Recording screen #%u with %RU32x%RU32 @ %RU32 kbps, %RU32 FPS\n", uScreen, pCfg->Video.uWidth, pCfg->Video.uHeight, pCfg->Video.uRate, pCfg->Video.uFPS)); } #ifdef VBOX_WITH_AUDIO_VIDEOREC if (pCfg->Audio.fEnabled) { rc = pStream->File.pWEBM->AddAudioTrack(pCfg->Audio.uHz, pCfg->Audio.cChannels, pCfg->Audio.cBits, &pStream->uTrackAudio); if (RT_FAILURE(rc)) { LogRel(("VideoRec: Failed to add audio track to output file '%s' (%Rrc)\n", pszFile, rc)); break; } LogRel(("VideoRec: Recording audio in %RU16Hz, %RU8 bit, %RU8 %s\n", pCfg->Audio.uHz, pCfg->Audio.cBits, pCfg->Audio.cChannels, pCfg->Audio.cChannels ? "channel" : "channels")); } #endif if ( pCfg->Video.fEnabled #ifdef VBOX_WITH_AUDIO_VIDEOREC || pCfg->Audio.fEnabled #endif ) { char szWhat[32] = { 0 }; if (pCfg->Video.fEnabled) RTStrCat(szWhat, sizeof(szWhat), "video"); #ifdef VBOX_WITH_AUDIO_VIDEOREC if (pCfg->Audio.fEnabled) { if (pCfg->Video.fEnabled) RTStrCat(szWhat, sizeof(szWhat), " + "); RTStrCat(szWhat, sizeof(szWhat), "audio"); } #endif LogRel(("VideoRec: Recording %s to '%s'\n", szWhat, pszFile)); } break; } default: AssertFailed(); /* Should never happen. */ rc = VERR_NOT_IMPLEMENTED; break; } if (RT_FAILURE(rc)) return rc; #ifdef VBOX_WITH_LIBVPX # ifdef VBOX_WITH_LIBVPX_VP9 vpx_codec_iface_t *pCodecIface = vpx_codec_vp9_cx(); # else /* Default is using VP8. */ vpx_codec_iface_t *pCodecIface = vpx_codec_vp8_cx(); # endif vpx_codec_err_t rcv = vpx_codec_enc_config_default(pCodecIface, &pVC->VPX.Cfg, 0 /* Reserved */); if (rcv != VPX_CODEC_OK) { LogRel(("VideoRec: Failed to get default config for VPX encoder: %s\n", vpx_codec_err_to_string(rcv))); return VERR_AVREC_CODEC_INIT_FAILED; } /* Target bitrate in kilobits per second. */ pVC->VPX.Cfg.rc_target_bitrate = pCfg->Video.uRate; /* Frame width. */ pVC->VPX.Cfg.g_w = pCfg->Video.uWidth; /* Frame height. */ pVC->VPX.Cfg.g_h = pCfg->Video.uHeight; /* 1ms per frame. */ pVC->VPX.Cfg.g_timebase.num = 1; pVC->VPX.Cfg.g_timebase.den = 1000; /* Disable multithreading. */ pVC->VPX.Cfg.g_threads = 0; /* Initialize codec. */ rcv = vpx_codec_enc_init(&pVC->VPX.Ctx, pCodecIface, &pVC->VPX.Cfg, 0 /* Flags */); if (rcv != VPX_CODEC_OK) { LogRel(("VideoRec: Failed to initialize VPX encoder: %s\n", vpx_codec_err_to_string(rcv))); return VERR_AVREC_CODEC_INIT_FAILED; } if (!vpx_img_alloc(&pVC->VPX.RawImage, VPX_IMG_FMT_I420, pCfg->Video.uWidth, pCfg->Video.uHeight, 1)) { LogRel(("VideoRec: Failed to allocate image %RU32x%RU32\n", pCfg->Video.uWidth, pCfg->Video.uHeight)); return VERR_NO_MEMORY; } /* Save a pointer to the first raw YUV plane. */ pStream->Video.pu8YuvBuf = pVC->VPX.RawImage.planes[0]; #endif pStream->fEnabled = true; return VINF_SUCCESS; } /** * Returns which recording features currently are enabled for a given configuration. * * @returns Enabled video recording features. * @param pCfg Pointer to recording configuration. */ VIDEORECFEATURES VideoRecGetFeatures(PVIDEORECCFG pCfg) { if (!pCfg) return VIDEORECFEATURE_NONE; VIDEORECFEATURES fFeatures = VIDEORECFEATURE_NONE; if (pCfg->Video.fEnabled) fFeatures |= VIDEORECFEATURE_VIDEO; #ifdef VBOX_WITH_AUDIO_VIDEOREC if (pCfg->Audio.fEnabled) fFeatures |= VIDEORECFEATURE_AUDIO; #endif return fFeatures; } /** * Checks if recording engine is ready to accept a new frame for the given screen. * * @returns true if recording engine is ready. * @param pCtx Pointer to video recording context. * @param uScreen Screen ID. * @param uTimeStampMs Current time stamp (in ms). */ bool VideoRecIsReady(PVIDEORECCONTEXT pCtx, uint32_t uScreen, uint64_t uTimeStampMs) { AssertPtrReturn(pCtx, false); if (ASMAtomicReadU32(&pCtx->enmState) != VIDEORECSTS_INITIALIZED) return false; PVIDEORECSTREAM pStream = videoRecStreamGet(pCtx, uScreen); if ( !pStream || !pStream->fEnabled) { return false; } PVIDEORECVIDEOFRAME pLastFrame = &pStream->Video.Frame; if (uTimeStampMs < pLastFrame->uTimeStampMs + pStream->Video.uDelayMs) return false; return true; } /** * Returns whether a given recording context has been started or not. * * @returns true if active, false if not. * @param pCtx Pointer to video recording context. */ bool VideoRecIsStarted(PVIDEORECCONTEXT pCtx) { if (!pCtx) return false; return ASMAtomicReadBool(&pCtx->fStarted); } /** * Checks if a specified limit for recording has been reached. * * @returns true if any limit has been reached. * @param pCtx Pointer to video recording context. * @param uScreen Screen ID. * @param tsNowMs Current time stamp (in ms). */ bool VideoRecIsLimitReached(PVIDEORECCONTEXT pCtx, uint32_t uScreen, uint64_t tsNowMs) { PVIDEORECSTREAM pStream = videoRecStreamGet(pCtx, uScreen); if ( !pStream || !pStream->fEnabled) { return false; } const PVIDEORECCFG pCfg = &pCtx->Cfg; if ( pCfg->uMaxTimeS && tsNowMs >= pCtx->tsStartMs + (pCfg->uMaxTimeS * 1000)) { return true; } if (pCfg->enmDst == VIDEORECDEST_FILE) { if (pCfg->File.uMaxSizeMB) { uint64_t sizeInMB = pStream->File.pWEBM->GetFileSize() / (1024 * 1024); if(sizeInMB >= pCfg->File.uMaxSizeMB) return true; } /* Check for available free disk space */ if ( pStream->File.pWEBM && pStream->File.pWEBM->GetAvailableSpace() < 0x100000) /** @todo r=andy WTF? Fix this. */ { LogRel(("VideoRec: Not enough free storage space available, stopping video capture\n")); return true; } } return false; } /** * Encodes the source image and write the encoded image to the stream's destination. * * @returns IPRT status code. * @param pStream Stream to encode and submit to. * @param pFrame Frame to encode and submit. */ static int videoRecEncodeAndWrite(PVIDEORECSTREAM pStream, PVIDEORECVIDEOFRAME pFrame) { AssertPtrReturn(pStream, VERR_INVALID_POINTER); AssertPtrReturn(pFrame, VERR_INVALID_POINTER); int rc; AssertPtr(pStream->pCtx); PVIDEORECCFG pCfg = &pStream->pCtx->Cfg; PVIDEORECVIDEOCODEC pVC = &pStream->Video.Codec; #ifdef VBOX_WITH_LIBVPX /* Presentation Time Stamp (PTS). */ vpx_codec_pts_t pts = pFrame->uTimeStampMs; vpx_codec_err_t rcv = vpx_codec_encode(&pVC->VPX.Ctx, &pVC->VPX.RawImage, pts /* Time stamp */, pStream->Video.uDelayMs /* How long to show this frame */, 0 /* Flags */, pCfg->Video.Codec.VPX.uEncoderDeadline /* Quality setting */); if (rcv != VPX_CODEC_OK) { if (pStream->Video.cFailedEncodingFrames++ < 64) { LogRel(("VideoRec: Failed to encode video frame: %s\n", vpx_codec_err_to_string(rcv))); return VERR_GENERAL_FAILURE; } } pStream->Video.cFailedEncodingFrames = 0; vpx_codec_iter_t iter = NULL; rc = VERR_NO_DATA; for (;;) { const vpx_codec_cx_pkt_t *pPacket = vpx_codec_get_cx_data(&pVC->VPX.Ctx, &iter); if (!pPacket) break; switch (pPacket->kind) { case VPX_CODEC_CX_FRAME_PKT: { WebMWriter::BlockData_VP8 blockData = { &pVC->VPX.Cfg, pPacket }; rc = pStream->File.pWEBM->WriteBlock(pStream->uTrackVideo, &blockData, sizeof(blockData)); break; } default: AssertFailed(); LogFunc(("Unexpected video packet type %ld\n", pPacket->kind)); break; } } #else RT_NOREF(pStream); rc = VERR_NOT_SUPPORTED; #endif /* VBOX_WITH_LIBVPX */ return rc; } /** * Converts a RGB to YUV buffer. * * @returns IPRT status code. * TODO */ static int videoRecRGBToYUV(uint32_t uPixelFormat, uint8_t *paDst, uint32_t uDstWidth, uint32_t uDstHeight, uint8_t *paSrc, uint32_t uSrcWidth, uint32_t uSrcHeight) { switch (uPixelFormat) { case VIDEORECPIXELFMT_RGB32: if (!colorConvWriteYUV420p<ColorConvBGRA32Iter>(paDst, uDstWidth, uDstHeight, paSrc, uSrcWidth, uSrcHeight)) return VERR_INVALID_PARAMETER; break; case VIDEORECPIXELFMT_RGB24: if (!colorConvWriteYUV420p<ColorConvBGR24Iter>(paDst, uDstWidth, uDstHeight, paSrc, uSrcWidth, uSrcHeight)) return VERR_INVALID_PARAMETER; break; case VIDEORECPIXELFMT_RGB565: if (!colorConvWriteYUV420p<ColorConvBGR565Iter>(paDst, uDstWidth, uDstHeight, paSrc, uSrcWidth, uSrcHeight)) return VERR_INVALID_PARAMETER; break; default: AssertFailed(); return VERR_NOT_SUPPORTED; } return VINF_SUCCESS; } /** * Sends an audio frame to the video encoding thread. * * @thread EMT * * @returns IPRT status code. * @param pCtx Pointer to the video recording context. * @param pvData Audio frame data to send. * @param cbData Size (in bytes) of audio frame data. * @param uTimeStampMs Time stamp (in ms) of audio playback. */ int VideoRecSendAudioFrame(PVIDEORECCONTEXT pCtx, const void *pvData, size_t cbData, uint64_t uTimeStampMs) { #ifdef VBOX_WITH_AUDIO_VIDEOREC AssertReturn(cbData <= _64K, VERR_INVALID_PARAMETER); int rc = RTCritSectEnter(&pCtx->CritSect); if (RT_FAILURE(rc)) return rc; /* To save time spent in EMT, do the required audio multiplexing in the encoding thread. * * The multiplexing is needed to supply all recorded (enabled) screens with the same * audio data at the same given point in time. */ PVIDEORECAUDIOFRAME pFrame = &pCtx->Audio.Frame; memcpy(pFrame->abBuf, pvData, RT_MIN(_64K /** @todo Fix! */, cbData)); pFrame->cbBuf = cbData; pFrame->uTimeStampMs = uTimeStampMs; pCtx->Audio.fHasAudioData = true; rc = RTCritSectLeave(&pCtx->CritSect); if (RT_SUCCESS(rc)) rc = RTSemEventSignal(pCtx->WaitEvent); return rc; #else RT_NOREF(pCtx, pvData, cbData, uTimeStampMs); return VINF_SUCCESS; #endif } /** * Copies a source video frame to the intermediate RGB buffer. * This function is executed only once per time. * * @thread EMT * * @returns IPRT status code. * @param pCtx Pointer to the video recording context. * @param uScreen Screen number. * @param x Starting x coordinate of the video frame. * @param y Starting y coordinate of the video frame. * @param uPixelFormat Pixel format. * @param uBPP Bits Per Pixel (BPP). * @param uBytesPerLine Bytes per scanline. * @param uSrcWidth Width of the video frame. * @param uSrcHeight Height of the video frame. * @param puSrcData Pointer to video frame data. * @param uTimeStampMs Time stamp (in ms). */ int VideoRecSendVideoFrame(PVIDEORECCONTEXT pCtx, uint32_t uScreen, uint32_t x, uint32_t y, uint32_t uPixelFormat, uint32_t uBPP, uint32_t uBytesPerLine, uint32_t uSrcWidth, uint32_t uSrcHeight, uint8_t *puSrcData, uint64_t uTimeStampMs) { AssertPtrReturn(pCtx, VERR_INVALID_POINTER); AssertReturn(uSrcWidth, VERR_INVALID_PARAMETER); AssertReturn(uSrcHeight, VERR_INVALID_PARAMETER); AssertReturn(puSrcData, VERR_INVALID_POINTER); PVIDEORECSTREAM pStream = videoRecStreamGet(pCtx, uScreen); if (!pStream) return VERR_NOT_FOUND; videoRecStreamLock(pStream); int rc = VINF_SUCCESS; do { if (!pStream->fEnabled) { rc = VINF_TRY_AGAIN; /* Not (yet) enabled. */ break; } if (uTimeStampMs < pStream->Video.uLastTimeStampMs + pStream->Video.uDelayMs) { rc = VINF_TRY_AGAIN; /* Respect maximum frames per second. */ break; } pStream->Video.uLastTimeStampMs = uTimeStampMs; int xDiff = ((int)pStream->Video.uWidth - (int)uSrcWidth) / 2; uint32_t w = uSrcWidth; if ((int)w + xDiff + (int)x <= 0) /* Nothing visible. */ { rc = VERR_INVALID_PARAMETER; break; } uint32_t destX; if ((int)x < -xDiff) { w += xDiff + x; x = -xDiff; destX = 0; } else destX = x + xDiff; uint32_t h = uSrcHeight; int yDiff = ((int)pStream->Video.uHeight - (int)uSrcHeight) / 2; if ((int)h + yDiff + (int)y <= 0) /* Nothing visible. */ { rc = VERR_INVALID_PARAMETER; break; } uint32_t destY; if ((int)y < -yDiff) { h += yDiff + (int)y; y = -yDiff; destY = 0; } else destY = y + yDiff; if ( destX > pStream->Video.uWidth || destY > pStream->Video.uHeight) { rc = VERR_INVALID_PARAMETER; /* Nothing visible. */ break; } if (destX + w > pStream->Video.uWidth) w = pStream->Video.uWidth - destX; if (destY + h > pStream->Video.uHeight) h = pStream->Video.uHeight - destY; #ifdef VBOX_VIDEOREC_WITH_QUEUE # error "Implement me!" #else PVIDEORECVIDEOFRAME pFrame = &pStream->Video.Frame; #endif /* Calculate bytes per pixel and set pixel format. */ const unsigned uBytesPerPixel = uBPP / 8; if (uPixelFormat == BitmapFormat_BGR) { switch (uBPP) { case 32: pFrame->uPixelFormat = VIDEORECPIXELFMT_RGB32; break; case 24: pFrame->uPixelFormat = VIDEORECPIXELFMT_RGB24; break; case 16: pFrame->uPixelFormat = VIDEORECPIXELFMT_RGB565; break; default: AssertMsgFailed(("Unknown color depth (%RU32)\n", uBPP)); break; } } else AssertMsgFailed(("Unknown pixel format (%RU32)\n", uPixelFormat)); #ifndef VBOX_VIDEOREC_WITH_QUEUE /* If we don't use a queue then we have to compare the dimensions * of the current frame with the previous frame: * * If it's smaller than before then clear the entire buffer to prevent artifacts * from the previous frame. */ if ( uSrcWidth < pFrame->uWidth || uSrcHeight < pFrame->uHeight) { /** @todo r=andy Only clear dirty areas. */ RT_BZERO(pFrame->pu8RGBBuf, pFrame->cbRGBBuf); } #endif /* Calculate start offset in source and destination buffers. */ uint32_t offSrc = y * uBytesPerLine + x * uBytesPerPixel; uint32_t offDst = (destY * pStream->Video.uWidth + destX) * uBytesPerPixel; #ifdef VBOX_VIDEOREC_DUMP VIDEORECBMPHDR bmpHdr; RT_ZERO(bmpHdr); VIDEORECBMPDIBHDR bmpDIBHdr; RT_ZERO(bmpDIBHdr); bmpHdr.u16Magic = 0x4d42; /* Magic */ bmpHdr.u32Size = (uint32_t)(sizeof(VIDEORECBMPHDR) + sizeof(VIDEORECBMPDIBHDR) + (w * h * uBytesPerPixel)); bmpHdr.u32OffBits = (uint32_t)(sizeof(VIDEORECBMPHDR) + sizeof(VIDEORECBMPDIBHDR)); bmpDIBHdr.u32Size = sizeof(VIDEORECBMPDIBHDR); bmpDIBHdr.u32Width = w; bmpDIBHdr.u32Height = h; bmpDIBHdr.u16Planes = 1; bmpDIBHdr.u16BitCount = uBPP; bmpDIBHdr.u32XPelsPerMeter = 5000; bmpDIBHdr.u32YPelsPerMeter = 5000; RTFILE fh; int rc2 = RTFileOpen(&fh, "/tmp/VideoRecFrame.bmp", RTFILE_O_CREATE_REPLACE | RTFILE_O_WRITE | RTFILE_O_DENY_NONE); if (RT_SUCCESS(rc2)) { RTFileWrite(fh, &bmpHdr, sizeof(bmpHdr), NULL); RTFileWrite(fh, &bmpDIBHdr, sizeof(bmpDIBHdr), NULL); } #endif Assert(pFrame->cbRGBBuf >= w * h * uBytesPerPixel); /* Do the copy. */ for (unsigned int i = 0; i < h; i++) { /* Overflow check. */ Assert(offSrc + w * uBytesPerPixel <= uSrcHeight * uBytesPerLine); Assert(offDst + w * uBytesPerPixel <= pStream->Video.uHeight * pStream->Video.uWidth * uBytesPerPixel); memcpy(pFrame->pu8RGBBuf + offDst, puSrcData + offSrc, w * uBytesPerPixel); #ifdef VBOX_VIDEOREC_DUMP if (RT_SUCCESS(rc2)) RTFileWrite(fh, pFrame->pu8RGBBuf + offDst, w * uBytesPerPixel, NULL); #endif offSrc += uBytesPerLine; offDst += pStream->Video.uWidth * uBytesPerPixel; } #ifdef VBOX_VIDEOREC_DUMP if (RT_SUCCESS(rc2)) RTFileClose(fh); #endif pFrame->uTimeStampMs = uTimeStampMs; pFrame->uWidth = uSrcWidth; pFrame->uHeight = uSrcHeight; pStream->Video.fHasVideoData = true; } while (0); videoRecStreamUnlock(pStream); if ( RT_SUCCESS(rc) && rc != VINF_TRY_AGAIN) /* Only signal the thread if operation was successful. */ { int rc2 = RTSemEventSignal(pCtx->WaitEvent); AssertRC(rc2); } return rc; }
52,773
18,873
#include <iostream> #include <cmath> int aproxTan(int angle) { return sin(angle) / cos(angle); } int main() { double angle = 0.2; double pi = 3.14159265358979; std::cout << "The tangent of " << angle << "pi " << "is aprox. " << aproxTan(pi*angle) << std::endl; return 0; }
299
135
// Copyright (c) 2016 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <WinSock2.h> #include <Windows.h> #include <stdint.h> #include <time.h> #include <iostream> #include <system_error> #define UNUSED(x) ((void)x) void __libnet_throw_error(int ec, const char* what) { throw std::system_error(std::error_code(ec, std::system_category()), what); } void __libnet_init(void) { WSADATA wd; int ec = WSAStartup(MAKEWORD(2, 2), &wd); if (0 != ec) __libnet_throw_error(ec, "winsock library startup failed"); } void __libnet_destroy(void) { WSACleanup(); } void server_main(const char* ip, uint16_t port) { SOCKET listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == listener) { int ec = WSAGetLastError(); __libnet_throw_error(ec, "create server socket failed"); } struct sockaddr_in host_addr; host_addr.sin_addr.s_addr = inet_addr(ip); host_addr.sin_family = AF_INET; host_addr.sin_port = htons(port); if (SOCKET_ERROR == bind(listener, (struct sockaddr*)&host_addr, sizeof(host_addr))) { int ec = WSAGetLastError(); __libnet_throw_error(ec, "socket bind failed"); } if (SOCKET_ERROR == listen(listener, SOMAXCONN)) { int ec = WSAGetLastError(); __libnet_throw_error(ec, "socket listen failed"); } std::cout << "server{" << ip << ":" << port << "} startup success ..." << std::endl; while (true) { struct sockaddr_in remote_addr; int addrlen = sizeof(remote_addr); SOCKET s = accept(listener, (struct sockaddr*)&remote_addr, &addrlen); std::cout << "accept remote client: " << s << ", from: " << inet_ntoa(remote_addr.sin_addr) << std::endl; time_t tick = time(nullptr); char buf[256]; snprintf(buf, sizeof(buf), "current time: %.24s", ctime(&tick)); WSABUF wbuf; wbuf.buf = buf; wbuf.len = strlen(buf); DWORD wbytes = 0; int rc = WSASend(s, &wbuf, 1, &wbytes, 0, nullptr, nullptr); if (SOCKET_ERROR == rc) break; shutdown(s, 2); closesocket(s); } shutdown(listener, 2); closesocket(listener); } void client_main(const char* ip, uint16_t port) { SOCKET connector = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == connector) { int ec = WSAGetLastError(); __libnet_throw_error(ec, "create client socket failed"); } struct sockaddr_in host_addr; host_addr.sin_addr.s_addr = inet_addr(ip); host_addr.sin_family = AF_INET; host_addr.sin_port = htons(port); if (SOCKET_ERROR == connect(connector, (struct sockaddr*)&host_addr, sizeof(host_addr))) { int ec = WSAGetLastError(); __libnet_throw_error(ec, "socket connect failed"); } DWORD flags = 0, rbytes = 0; char buf[256] = {0}; WSABUF wbuf; wbuf.len = sizeof(buf); wbuf.buf = buf; int ec = WSARecv(connector, &wbuf, 1, &rbytes, &flags, nullptr, nullptr); if (SOCKET_ERROR != ec) std::cout << "recv bytes: " << rbytes << ", recv data: " << buf << std::endl; shutdown(connector, 2); closesocket(connector); } int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "usage: ws.exe [options] ..." << std::endl; return 0; } __libnet_init(); if (0 == strcmp(argv[1], "s")) server_main("127.0.0.1", 5555); else if (0 == strcmp(argv[1], "c")) client_main("127.0.0.1", 5555); __libnet_destroy(); return 0; }
4,651
1,827
// Copyright (C) 2003, Fernando Luis Cacciola Carballal. // // Use, modification, and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/lib/optional for documentation. // // You are welcome to contact the author at: // fernando_cacciola@hotmail.com // #include<iostream> #include<stdexcept> #include<string> #define BOOST_ENABLE_ASSERT_HANDLER #include "boost/optional.hpp" #include "boost/tuple/tuple.hpp" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "boost/test/minimal.hpp" #include "optional_test_common.cpp" // Test boost::tie() interoperabiliy. int test_main( int, char* [] ) { typedef X T ; try { TRACE( std::endl << BOOST_CURRENT_FUNCTION ); T z(0); T a(1); T b(2); optional<T> oa, ob ; // T::T( T const& x ) is used set_pending_dtor( ARG(T) ) ; set_pending_copy( ARG(T) ) ; boost::tie(oa,ob) = std::make_pair(a,b) ; check_is_not_pending_dtor( ARG(T) ) ; check_is_not_pending_copy( ARG(T) ) ; check_initialized(oa); check_initialized(ob); check_value(oa,a,z); check_value(ob,b,z); } catch ( ... ) { BOOST_ERROR("Unexpected Exception caught!"); } return 0; }
1,396
579
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: LIV.SDK.Unity.SDKVector3 #include "LIV/SDK/Unity/SDKVector3.hpp" // Including type: LIV.SDK.Unity.SDKQuaternion #include "LIV/SDK/Unity/SDKQuaternion.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Type namespace: LIV.SDK.Unity namespace LIV::SDK::Unity { // Forward declaring type: SDKControllerState struct SDKControllerState; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::LIV::SDK::Unity::SDKControllerState, "LIV.SDK.Unity", "SDKControllerState"); // Type namespace: LIV.SDK.Unity namespace LIV::SDK::Unity { // Size: 0x8C #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: LIV.SDK.Unity.SDKControllerState // [TokenAttribute] Offset: FFFFFFFF struct SDKControllerState/*, public ::System::ValueType*/ { public: public: // public LIV.SDK.Unity.SDKVector3 hmdposition // Size: 0xC // Offset: 0x0 ::LIV::SDK::Unity::SDKVector3 hmdposition; // Field size check static_assert(sizeof(::LIV::SDK::Unity::SDKVector3) == 0xC); // public LIV.SDK.Unity.SDKQuaternion hmdrotation // Size: 0x10 // Offset: 0xC ::LIV::SDK::Unity::SDKQuaternion hmdrotation; // Field size check static_assert(sizeof(::LIV::SDK::Unity::SDKQuaternion) == 0x10); // public LIV.SDK.Unity.SDKVector3 calibrationcameraposition // Size: 0xC // Offset: 0x1C ::LIV::SDK::Unity::SDKVector3 calibrationcameraposition; // Field size check static_assert(sizeof(::LIV::SDK::Unity::SDKVector3) == 0xC); // public LIV.SDK.Unity.SDKQuaternion calibrationcamerarotation // Size: 0x10 // Offset: 0x28 ::LIV::SDK::Unity::SDKQuaternion calibrationcamerarotation; // Field size check static_assert(sizeof(::LIV::SDK::Unity::SDKQuaternion) == 0x10); // public LIV.SDK.Unity.SDKVector3 cameraposition // Size: 0xC // Offset: 0x38 ::LIV::SDK::Unity::SDKVector3 cameraposition; // Field size check static_assert(sizeof(::LIV::SDK::Unity::SDKVector3) == 0xC); // public LIV.SDK.Unity.SDKQuaternion camerarotation // Size: 0x10 // Offset: 0x44 ::LIV::SDK::Unity::SDKQuaternion camerarotation; // Field size check static_assert(sizeof(::LIV::SDK::Unity::SDKQuaternion) == 0x10); // public LIV.SDK.Unity.SDKVector3 leftposition // Size: 0xC // Offset: 0x54 ::LIV::SDK::Unity::SDKVector3 leftposition; // Field size check static_assert(sizeof(::LIV::SDK::Unity::SDKVector3) == 0xC); // public LIV.SDK.Unity.SDKQuaternion leftrotation // Size: 0x10 // Offset: 0x60 ::LIV::SDK::Unity::SDKQuaternion leftrotation; // Field size check static_assert(sizeof(::LIV::SDK::Unity::SDKQuaternion) == 0x10); // public LIV.SDK.Unity.SDKVector3 rightposition // Size: 0xC // Offset: 0x70 ::LIV::SDK::Unity::SDKVector3 rightposition; // Field size check static_assert(sizeof(::LIV::SDK::Unity::SDKVector3) == 0xC); // public LIV.SDK.Unity.SDKQuaternion rightrotation // Size: 0x10 // Offset: 0x7C ::LIV::SDK::Unity::SDKQuaternion rightrotation; // Field size check static_assert(sizeof(::LIV::SDK::Unity::SDKQuaternion) == 0x10); public: // Creating value type constructor for type: SDKControllerState constexpr SDKControllerState(::LIV::SDK::Unity::SDKVector3 hmdposition_ = {}, ::LIV::SDK::Unity::SDKQuaternion hmdrotation_ = {}, ::LIV::SDK::Unity::SDKVector3 calibrationcameraposition_ = {}, ::LIV::SDK::Unity::SDKQuaternion calibrationcamerarotation_ = {}, ::LIV::SDK::Unity::SDKVector3 cameraposition_ = {}, ::LIV::SDK::Unity::SDKQuaternion camerarotation_ = {}, ::LIV::SDK::Unity::SDKVector3 leftposition_ = {}, ::LIV::SDK::Unity::SDKQuaternion leftrotation_ = {}, ::LIV::SDK::Unity::SDKVector3 rightposition_ = {}, ::LIV::SDK::Unity::SDKQuaternion rightrotation_ = {}) noexcept : hmdposition{hmdposition_}, hmdrotation{hmdrotation_}, calibrationcameraposition{calibrationcameraposition_}, calibrationcamerarotation{calibrationcamerarotation_}, cameraposition{cameraposition_}, camerarotation{camerarotation_}, leftposition{leftposition_}, leftrotation{leftrotation_}, rightposition{rightposition_}, rightrotation{rightrotation_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Get instance field reference: public LIV.SDK.Unity.SDKVector3 hmdposition ::LIV::SDK::Unity::SDKVector3& dyn_hmdposition(); // Get instance field reference: public LIV.SDK.Unity.SDKQuaternion hmdrotation ::LIV::SDK::Unity::SDKQuaternion& dyn_hmdrotation(); // Get instance field reference: public LIV.SDK.Unity.SDKVector3 calibrationcameraposition ::LIV::SDK::Unity::SDKVector3& dyn_calibrationcameraposition(); // Get instance field reference: public LIV.SDK.Unity.SDKQuaternion calibrationcamerarotation ::LIV::SDK::Unity::SDKQuaternion& dyn_calibrationcamerarotation(); // Get instance field reference: public LIV.SDK.Unity.SDKVector3 cameraposition ::LIV::SDK::Unity::SDKVector3& dyn_cameraposition(); // Get instance field reference: public LIV.SDK.Unity.SDKQuaternion camerarotation ::LIV::SDK::Unity::SDKQuaternion& dyn_camerarotation(); // Get instance field reference: public LIV.SDK.Unity.SDKVector3 leftposition ::LIV::SDK::Unity::SDKVector3& dyn_leftposition(); // Get instance field reference: public LIV.SDK.Unity.SDKQuaternion leftrotation ::LIV::SDK::Unity::SDKQuaternion& dyn_leftrotation(); // Get instance field reference: public LIV.SDK.Unity.SDKVector3 rightposition ::LIV::SDK::Unity::SDKVector3& dyn_rightposition(); // Get instance field reference: public LIV.SDK.Unity.SDKQuaternion rightrotation ::LIV::SDK::Unity::SDKQuaternion& dyn_rightrotation(); // static public LIV.SDK.Unity.SDKControllerState get_empty() // Offset: 0x29FBB10 static ::LIV::SDK::Unity::SDKControllerState get_empty(); // public override System.String ToString() // Offset: 0x29FBB80 // Implemented from: System.ValueType // Base method: System.String ValueType::ToString() ::StringW ToString(); }; // LIV.SDK.Unity.SDKControllerState #pragma pack(pop) static check_size<sizeof(SDKControllerState), 124 + sizeof(::LIV::SDK::Unity::SDKQuaternion)> __LIV_SDK_Unity_SDKControllerStateSizeCheck; static_assert(sizeof(SDKControllerState) == 0x8C); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: LIV::SDK::Unity::SDKControllerState::get_empty // Il2CppName: get_empty template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::LIV::SDK::Unity::SDKControllerState (*)()>(&LIV::SDK::Unity::SDKControllerState::get_empty)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(LIV::SDK::Unity::SDKControllerState), "get_empty", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: LIV::SDK::Unity::SDKControllerState::ToString // Il2CppName: ToString template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (LIV::SDK::Unity::SDKControllerState::*)()>(&LIV::SDK::Unity::SDKControllerState::ToString)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(LIV::SDK::Unity::SDKControllerState), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
7,901
2,768
// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com #include "..\hooks.hpp" #include "..\..\cheats\visuals\GrenadePrediction.h" #include "..\..\cheats\misc\fakelag.h" #include "..\..\cheats\lagcompensation\local_animations.h" using OverrideView_t = void(__stdcall*)(CViewSetup*); void thirdperson(bool fakeducking); void __stdcall hooks::hooked_overrideview(CViewSetup* viewsetup) { static auto original_fn = clientmode_hook->get_func_address <OverrideView_t> (18); g_ctx.local((player_t*)m_entitylist()->GetClientEntity(m_engine()->GetLocalPlayer()), true); if (!viewsetup) return original_fn(viewsetup); if (g_ctx.local()) { static auto fakeducking = false; if (!fakeducking && g_ctx.globals.fakeducking) fakeducking = true; else if (fakeducking && !g_ctx.globals.fakeducking && (!g_ctx.local()->get_animation_state()->m_fDuckAmount || g_ctx.local()->get_animation_state()->m_fDuckAmount == 1.0f)) //-V550 fakeducking = false; if (!g_ctx.local()->is_alive()) //-V807 fakeducking = false; auto weapon = g_ctx.local()->m_hActiveWeapon().Get(); if (weapon) { if (!g_ctx.local()->m_bIsScoped() && g_cfg.player.enable) viewsetup->fov += g_cfg.esp.fov; else if (g_cfg.esp.removals[REMOVALS_ZOOM] && g_cfg.player.enable) { if (weapon->m_zoomLevel() == 1) viewsetup->fov = 90.0f + (float)g_cfg.esp.fov; else viewsetup->fov += (float)g_cfg.esp.fov; } } else if (g_cfg.player.enable) viewsetup->fov += g_cfg.esp.fov; if (weapon) { auto viewmodel = (entity_t*)m_entitylist()->GetClientEntityFromHandle(g_ctx.local()->m_hViewModel()); if (viewmodel) { auto eyeAng = viewsetup->angles; eyeAng.z -= (float)g_cfg.esp.viewmodel_roll; viewmodel->set_abs_angles(eyeAng); } if (weapon->is_grenade() && g_cfg.esp.grenade_prediction && g_cfg.player.enable) GrenadePrediction::get().View(viewsetup, weapon); } if (g_cfg.player.enable && (g_cfg.misc.thirdperson_toggle.key > KEY_NONE && g_cfg.misc.thirdperson_toggle.key < KEY_MAX || g_cfg.misc.thirdperson_when_spectating)) thirdperson(fakeducking); else { g_ctx.globals.in_thirdperson = false; m_input()->m_fCameraInThirdPerson = false; } original_fn(viewsetup); if (fakeducking) { viewsetup->origin = g_ctx.local()->GetAbsOrigin() + Vector(0.0f, 0.0f, m_gamemovement()->GetPlayerViewOffset(false).z + 0.064f); if (m_input()->m_fCameraInThirdPerson) { auto camera_angles = Vector(m_input()->m_vecCameraOffset.x, m_input()->m_vecCameraOffset.y, 0.0f); //-V807 auto camera_forward = ZERO; math::angle_vectors(camera_angles, camera_forward); math::VectorMA(viewsetup->origin, -m_input()->m_vecCameraOffset.z, camera_forward, viewsetup->origin); } } } else return original_fn(viewsetup); } void thirdperson(bool fakeducking) { static auto current_fraction = 0.0f; static auto in_thirdperson = false; if (!in_thirdperson && g_ctx.globals.in_thirdperson) { current_fraction = 0.0f; in_thirdperson = true; } else if (in_thirdperson && !g_ctx.globals.in_thirdperson) in_thirdperson = false; if (g_ctx.local()->is_alive() && in_thirdperson) //-V807 { auto distance = (float)g_cfg.misc.thirdperson_distance; Vector angles; m_engine()->GetViewAngles(angles); Vector inverse_angles; m_engine()->GetViewAngles(inverse_angles); inverse_angles.z = distance; Vector forward, right, up; math::angle_vectors(inverse_angles, &forward, &right, &up); Ray_t ray; CTraceFilterWorldAndPropsOnly filter; trace_t trace; auto eye_pos = fakeducking ? g_ctx.local()->GetAbsOrigin() + m_gamemovement()->GetPlayerViewOffset(false) : g_ctx.local()->GetAbsOrigin() + g_ctx.local()->m_vecViewOffset(); auto offset = eye_pos + forward * -distance + right + up; ray.Init(eye_pos, offset, Vector(-16.0f, -16.0f, -16.0f), Vector(16.0f, 16.0f, 16.0f)); m_trace()->TraceRay(ray, MASK_SHOT_HULL, &filter, &trace); if (current_fraction > trace.fraction) current_fraction = trace.fraction; else if (current_fraction > 0.9999f) current_fraction = 1.0f; current_fraction = math::interpolate(current_fraction, trace.fraction, m_globals()->m_frametime * 10.0f); angles.z = distance * current_fraction; m_input()->m_fCameraInThirdPerson = current_fraction > 0.1f; m_input()->m_vecCameraOffset = angles; } else if (m_input()->m_fCameraInThirdPerson) { g_ctx.globals.in_thirdperson = false; m_input()->m_fCameraInThirdPerson = false; } static auto require_reset = false; if (g_ctx.local()->is_alive()) { require_reset = false; return; } if (g_cfg.misc.thirdperson_when_spectating) { if (require_reset) g_ctx.local()->m_iObserverMode() = OBS_MODE_CHASE; if (g_ctx.local()->m_iObserverMode() == OBS_MODE_IN_EYE) require_reset = true; } }
4,935
2,119
/* * LatticeExpand.cc -- * Lattice expansion and LM rescoring algorithms * */ #ifndef lint static char Copyright[] = "Copyright (c) 1997-2012 SRI International. All Rights Reserved."; static char RcsId[] = "@(#)$Header: /home/srilm/CVS/srilm/lattice/src/LatticeExpand.cc,v 1.11 2012/10/18 20:55:21 mcintyre Exp $"; #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "Lattice.h" #include "LHash.cc" #include "Map2.cc" #include "Array.cc" #ifdef INSTANTIATE_TEMPLATES INSTANTIATE_MAP2(NodeIndex, VocabContext, NodeIndex); INSTANTIATE_LHASH(VocabIndex,PackedNode); #endif /* * If the intlog weights of two transitions differ by no more than this * they are considered identical in PackedNodeList::packNodes(). */ #define PACK_TOLERANCE 0 #define DebugPrintFatalMessages 0 #define DebugPrintFunctionality 1 // for large functionality listed in options of the program #define DebugPrintOutLoop 2 // for out loop of the large functions or small functions #define DebugPrintInnerLoop 3 // for inner loop of the large functions or outloop of small functions #ifndef USE_SARRAY_MAP2 /* * Word ngram sorting function * (used to iterate over contexts in node expansion maps in same order * regardless of underlying datastructure) */ static int ngramCompare(const VocabIndex *n1, const VocabIndex *n2) { return SArray_compareKey(n1, n2); } #endif /* USE_SARRAY_MAP2 */ /* this code is to replace weights on the links of a given lattice with * the LM weights. */ Boolean Lattice::replaceWeights(LM &lm) { if (debug(DebugPrintFunctionality)) { dout() << "Lattice::replaceWeights: " << "replacing weights with new LM\n"; } LHashIter<NodeIndex, LatticeNode> nodeIter(nodes); NodeIndex nodeIndex; while (LatticeNode *node = nodeIter.next(nodeIndex)) { NodeIndex toNodeIndex; VocabIndex wordIndex; if (nodeIndex == initial) { wordIndex = vocab.ssIndex(); } else { wordIndex = node->word; } // need to check to see whether the word is in the vocab TRANSITER_T<NodeIndex,LatticeTransition> transIter(node->outTransitions); while (transIter.next(toNodeIndex)) { LatticeNode * toNode = nodes.find(toNodeIndex); VocabIndex toWordIndex; LogP weight; if (toNodeIndex == final) { toWordIndex = vocab.seIndex(); } else { toWordIndex = toNode->word; } if (toWordIndex == Vocab_None || toWordIndex == lm.vocab.pauseIndex()) { /* * NULL and pause nodes don't receive an language model weight */ weight = LogP_One; } else { VocabIndex context[2]; context[0] = wordIndex; context[1] = Vocab_None; weight = lm.wordProb(toWordIndex, context); } setWeightTrans(nodeIndex, toNodeIndex, weight); } } return true; } /* * Compute outgoing transition prob on demand. This saves LM computation * for transitions that are cached. */ static Boolean computeOutWeight(PackInput &packInput) { if (packInput.lm != 0) { VocabIndex context[3]; context[0] = packInput.wordName; context[1] = packInput.fromWordName; context[2] = Vocab_None; packInput.outWeight = packInput.lm->wordProb(packInput.toWordName, context); packInput.lm = 0; } return true; } /* this function tries to pack together nodes in lattice * 1) for non-self loop case: only when trigram prob exists, * the from nodes with the same wordName will be packed; * 2) for self loop case: * the from nodes with the same wordName will be packed, * regardless whether the trigram prob exists. * But, the bigram and trigram will have separate nodes, * which is reflected in two different out transitions from * the mid node to the two different toNodes (bigram and trigram) */ Boolean PackedNodeList::packNodes(Lattice &lat, PackInput &packInput) { PackedNode *packedNode = packedNodesByFromNode.find(packInput.fromWordName); if (!packedNode && lastPackedNode != 0 && (packInput.toNodeIndex == lastPackedNode->toNode && computeOutWeight(packInput) && abs(LogPtoIntlog(packInput.outWeight) - LogPtoIntlog(lastPackedNode->outWeight)) <= PACK_TOLERANCE)) { packedNode = lastPackedNode; NodeIndex midNode = packedNode->midNodeIndex; // the fromNode could be different this time around, so we need to // re-cache the mid-node packedNode = packedNodesByFromNode.insert(packInput.fromWordName); packedNode->midNodeIndex = midNode; packedNode->toNode = packInput.toNodeIndex; packedNode->outWeight = packInput.outWeight; if (packInput.toNodeId == 2) { packedNode->toNodeId = 2; } else if (packInput.toNodeId == 3) { packedNode->toNodeId = 3; } else { packedNode->toNodeId = 0; } lastPackedNode = packedNode; } if (packedNode) { // only one transition is needed; LatticeTransition t(packInput.inWeight, packInput.inFlag); lat.insertTrans(packInput.fromNodeIndex, packedNode->midNodeIndex, t); if (!packInput.toNodeId) { // this is for non-self-loop node, no additional outgoing trans // need to be added. LatticeNode *midNode = lat.findNode(packedNode->midNodeIndex); LatticeTransition * trans = midNode->outTransitions.find(packInput.toNodeIndex); // if it is another toNode, we need to create a link to it. if (!trans) { // it indicates that there is another ngram node needed. computeOutWeight(packInput); LatticeTransition t(packInput.outWeight, packInput.outFlag); lat.insertTrans(packedNode->midNodeIndex, packInput.toNodeIndex, t); if (debug(DebugPrintInnerLoop)) { dout() << "PackedNodeList::packNodes: \n" << "insert (" << packInput.fromNodeIndex << ", " << packedNode->midNodeIndex << ", " << packInput.toNodeIndex << ")\n"; } } return true; } else { if (debug(DebugPrintInnerLoop)) { dout() << "PackedNodeList::packNodes: \n" << "reusing (" << packInput.fromNodeIndex << ", " << packedNode->midNodeIndex << ", " << packInput.toNodeIndex << ")\n"; } } // the following part is for selfLoop case // the toNode is for p(a | a, x) doesn't exist. if (packInput.toNodeId == 2) { if (!packedNode->toNode) { computeOutWeight(packInput); LatticeTransition t(packInput.outWeight, packInput.outFlag); lat.insertTrans(packedNode->midNodeIndex, packInput.toNodeIndex, t); packedNode->toNode = packInput.toNodeIndex; } return true; } // the toNode is for p(a | a, x) exists. if (packInput.toNodeId == 3) { if (!packedNode->toNode) { computeOutWeight(packInput); LatticeTransition t(packInput.outWeight, packInput.outFlag); lat.insertTrans(packedNode->midNodeIndex, packInput.toNodeIndex, t); packedNode->toNode = packInput.toNodeIndex; } return true; } } else { // this is the first time to create triple. NodeIndex newNodeIndex = lat.dupNode(packInput.wordName, markedFlag); LatticeTransition t1(packInput.inWeight, packInput.inFlag); lat.insertTrans(packInput.fromNodeIndex, newNodeIndex, t1); computeOutWeight(packInput); LatticeTransition t2(packInput.outWeight, packInput.outFlag); lat.insertTrans(newNodeIndex, packInput.toNodeIndex, t2); if (debug(DebugPrintInnerLoop)) { dout() << "PackedNodeList::packNodes: \n" << "insert (" << packInput.fromNodeIndex << ", " << newNodeIndex << ", " << packInput.toNodeIndex << ")\n"; } packedNode = packedNodesByFromNode.insert(packInput.fromWordName); packedNode->midNodeIndex = newNodeIndex; packedNode->toNode = packInput.toNodeIndex; packedNode->outWeight = packInput.outWeight; if (packInput.toNodeId == 2) { packedNode->toNodeId = 2; } else if (packInput.toNodeId == 3) { packedNode->toNodeId = 3; } else { packedNode->toNodeId = 0; } lastPackedNode = packedNode; } return true; } // ************************************************* // compact expansion to trigram // ************************************************* /* Basic Algorithm: * Try to expand self loop to accomodate trigram * the basic idea has two steps: * 1) ignore the loop edge and process other edge combinations * just like in other cases, this is done in the main expandNodeToTrigram * program * 2) IN THIS PROGRAM: * a) duplicate the loop node (called postNode); * b) add an additional node (called preNode) between fromNode and the * loop node (postNode); * c) create links between fromNode, preNode, postNode and toNode; and * create the loop edge on the loop node (postNode). */ void Lattice::initASelfLoopDB(SelfLoopDB &selfLoopDB, LM &lm, NodeIndex nodeIndex, LatticeNode *node, LatticeTransition *trans) { selfLoopDB.preNodeIndex = selfLoopDB.postNodeIndex2 = selfLoopDB.postNodeIndex3 = 0; selfLoopDB.nodeIndex = nodeIndex; selfLoopDB.selfTransFlags = trans->flags; selfLoopDB.wordName = node->word; VocabIndex context[3]; context[0] = selfLoopDB.wordName; context[1] = selfLoopDB.wordName; context[2] = Vocab_None; selfLoopDB.loopProb = lm.wordProb(selfLoopDB.wordName, context); } void Lattice::initBSelfLoopDB(SelfLoopDB &selfLoopDB, LM &lm, NodeIndex fromNodeIndex, LatticeNode * fromNode, LatticeTransition *fromTrans) { // reinitialize the preNode selfLoopDB.preNodeIndex = 0; // selfLoopDB.fromNodeIndex = fromNodeIndex; selfLoopDB.fromWordName = fromNode->word; // selfLoopDB.fromSelfTransFlags = fromTrans->flags; // compute prob for the link between preNode and postNode VocabIndex context[3]; context[0] = selfLoopDB.wordName; context[1] = selfLoopDB.fromWordName; context[2] = Vocab_None; selfLoopDB.prePostProb = lm.wordProb(selfLoopDB.wordName, context); // compute prob for fromPreProb; context[0] = selfLoopDB.fromWordName; context[1] = Vocab_None; selfLoopDB.fromPreProb = lm.wordProb(selfLoopDB.wordName, context); } void Lattice::initCSelfLoopDB(SelfLoopDB &selfLoopDB, NodeIndex toNodeIndex, LatticeTransition *toTrans) { selfLoopDB.toNodeIndex = toNodeIndex; selfLoopDB.selfToTransFlags = toTrans->flags; } /* * creating an expansion network for a self loop node. * the order in which the network is created is reverse: * 1) build the part of the network starting from postNode to toNode * 2) use PackedNodeList class function to build the part of * the network starting from fromNode to PostNode. * */ Boolean Lattice::expandSelfLoop(LM &lm, SelfLoopDB &selfLoopDB, PackedNodeList &packedSelfLoopNodeList) { unsigned id = 0; NodeIndex postNodeIndex, toNodeIndex = selfLoopDB.toNodeIndex; LogP fromPreProb = selfLoopDB.fromPreProb; LogP prePostProb = selfLoopDB.prePostProb; VocabIndex wordName = selfLoopDB.wordName; if (debug(DebugPrintOutLoop)) { dout() << "Lattice::expandSelfLoop: " << "nodeIndex (" << selfLoopDB.nodeIndex << ")\n"; } // create the part of the network from postNode to toNode // if it doesn't exist. // first compute the probs of the links in that part. VocabIndex context[3]; context[0] = wordName; context[1] = wordName; context[2] = Vocab_None; LatticeNode *toNode = findNode(toNodeIndex); VocabIndex toWordName = toNode->word; LogP triProb = lm.wordProb(toWordName, context); unsigned usedContextLength; lm.contextID(context, usedContextLength); context[1] = Vocab_None; LogP biProb = lm.wordProb(toWordName, context); LogP postToProb; if (usedContextLength > 1) { // get trigram prob for (post, to) edge: p(c|a, a) postToProb = triProb; // create post node and loop if it doesn't exist; if (!selfLoopDB.postNodeIndex3) { selfLoopDB.postNodeIndex3 = postNodeIndex = dupNode(wordName, markedFlag); // create the loop, put trigram prob p(a|a,a) on the loop LatticeTransition t(selfLoopDB.loopProb, selfLoopDB.selfTransFlags); insertTrans(postNodeIndex, postNodeIndex, t); // end of creating of loop } postNodeIndex = selfLoopDB.postNodeIndex3; id = 3; } else { // get an adjusted weight for the link between preNode to postNode LogP wordBOW = triProb - biProb; prePostProb = combWeights(prePostProb, wordBOW); // get existing weight of (node, toNode) as the weight for (post, to). LatticeNode *node = findNode(selfLoopDB.nodeIndex); if (!node) { if (debug(DebugPrintFatalMessages)) { dout() << "Fatal Error in Lattice::expandSelfLoop: " << "can't find node " << selfLoopDB.nodeIndex << "\n"; } exit(-1); } // compute postToProb postToProb = biProb; // create post node and loop if it doesn't exist; if (!selfLoopDB.postNodeIndex2) { selfLoopDB.postNodeIndex2 = postNodeIndex = dupNode(wordName, markedFlag); // create the loop, put trigram prob p(a|a,a) on the loop LatticeTransition t(selfLoopDB.loopProb, selfLoopDB.selfTransFlags); insertTrans(postNodeIndex, postNodeIndex, t); // end of creating loop } postNodeIndex = selfLoopDB.postNodeIndex2; id = 2; } // create link from postNode to toNode if (postNode, toNode) doesn't exist; toNode = findNode(toNodeIndex); LatticeTransition *postToTrans = toNode->inTransitions.find(postNodeIndex); if (!postToTrans) { // create link from postNode to toNode; LatticeTransition t(postToProb, selfLoopDB.selfToTransFlags); insertTrans(postNodeIndex, toNodeIndex, t); } // done with first part of the network. // create the part of the network from fromNode to postNode. // create preNode and (from, pre) edge. NodeIndex preNodeIndex = selfLoopDB.preNodeIndex; PackInput packSelfLoop; packSelfLoop.wordName = wordName; packSelfLoop.fromWordName = selfLoopDB.fromWordName; packSelfLoop.toWordName = toNode->word; packSelfLoop.fromNodeIndex = selfLoopDB.fromNodeIndex; packSelfLoop.toNodeIndex = postNodeIndex; packSelfLoop.inWeight = selfLoopDB.fromPreProb; packSelfLoop.inFlag = selfLoopDB.fromSelfTransFlags; packSelfLoop.outWeight = prePostProb; packSelfLoop.toNodeId = id; packSelfLoop.lm = 0; packedSelfLoopNodeList.packNodes(*this, packSelfLoop); return true; } Boolean Lattice::expandNodeToTrigram(NodeIndex nodeIndex, LM &lm, unsigned maxNodes) { SelfLoopDB selfLoopDB; PackedNodeList packedNodeList, packedSelfLoopNodeList; LatticeTransition *outTrans; NodeIndex fromNodeIndex; NodeIndex toNodeIndex; LatticeTransition *inTrans; LatticeNode *fromNode; VocabIndex context[3]; LatticeNode *node = findNode(nodeIndex); if (!node) { if (debug(DebugPrintFatalMessages)) { dout() << "Lattice::expandNodeToTrigram: " << "Fatal Error: current node doesn't exist!\n"; } exit(-1); } LatticeTransition * selfLoop = node->inTransitions.find(nodeIndex); Boolean selfLoopFlag; if (selfLoop) { selfLoopFlag = true; initASelfLoopDB(selfLoopDB, lm, nodeIndex, node, selfLoop); } else { selfLoopFlag = false; } TRANSITER_T<NodeIndex,LatticeTransition> inTransIter(node->inTransitions); TRANSITER_T<NodeIndex,LatticeTransition> outTransIter(node->outTransitions); VocabIndex wordName = node->word; if (debug(DebugPrintOutLoop)) { dout() << "Lattice::expandNodeToTrigram: " << "processing word name: " << getWord(wordName) << ", Index: " << nodeIndex << "\n"; } // going through all its incoming edges while ((inTrans = inTransIter.next(fromNodeIndex))) { if (nodeIndex == fromNodeIndex) { if (debug(DebugPrintOutLoop)) { dout() << "Lattice::expandNodeToTrigram: jump over self loop: " << fromNodeIndex << "\n"; } continue; } fromNode = findNode(fromNodeIndex); if (!fromNode) { if (debug(DebugPrintFatalMessages)) { dout() << "Lattice::expandNodeToTrigram: " << "Fatal Error: fromNode " << fromNodeIndex << " doesn't exist!\n"; } exit(-1); } VocabIndex fromWordName = fromNode->word; if (debug(DebugPrintOutLoop)) { dout() << "Lattice::expandNodeToTrigram: processing incoming edge: (" << fromNodeIndex << ", " << nodeIndex << ")\n" << " (" << getWord(fromWordName) << ", " << getWord(wordName) << ")\n"; } // compute in bigram prob LogP inWeight; if (fromNodeIndex == getInitial()) { context[0] = fromWordName; context[1] = Vocab_None; inWeight = lm.wordProb(wordName, context); } else { inWeight = inTrans->weight; } context[0] = wordName; context[1] = fromWordName; context[2] = Vocab_None; unsigned inFlag = inTrans->flags; // initialize it for self loop processing. if (selfLoopFlag) { initBSelfLoopDB(selfLoopDB, lm, fromNodeIndex, fromNode, inTrans); } // going through all the outgoing edges // node = findNode(nodeIndex); outTransIter.init(); while (LatticeTransition * outTrans = outTransIter.next(toNodeIndex)) { if (nodeIndex == toNodeIndex) { dout() << " In expandNodeToTrigram: self loop: " << toNodeIndex << "\n"; continue; } LatticeNode * toNode = findNode(toNodeIndex); if (!toNode) { if (debug(DebugPrintFatalMessages)) { dout() << "Lattice::expandNodeToTrigram: " << "Fatal Error: toNode " << toNode << " doesn't exist!\n"; } exit(-1); } if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToTrigram: the toNodeIndex (" << toNodeIndex << " has name " << getWord(toNode->word) << ")\n"; } // initialize selfLoopDB; if (selfLoopFlag) { initCSelfLoopDB(selfLoopDB, toNodeIndex, outTrans); } // duplicate a node if the trigram exists. // computed on demand in packNodes(), saving work for cached transitions // LogP logProb = lm.wordProb(toNode->word, context); if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToTrigram: tripleIndex (" << toNodeIndex << " | " << nodeIndex << ", " << fromNodeIndex << ")\n" << " trigram prob: (" << getWord(toNode->word) << " | " << context << ") found!!!!!!!!\n"; } // create one node and two edges to place trigram prob // I need to do packing nodes here. PackInput packInput; packInput.fromWordName = fromWordName; packInput.wordName = wordName; packInput.toWordName = toNode->word; packInput.fromNodeIndex = fromNodeIndex; packInput.toNodeIndex = toNodeIndex; packInput.inWeight = inWeight; // computed on demand in packNodes() //packInput.outWeight = logProb; packInput.lm = &lm; packInput.inFlag = inFlag; packInput.outFlag = outTrans->flags; packInput.nodeIndex = nodeIndex; packInput.toNodeId = 0; if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToTrigram: " << "outgoing edge for first incoming edge: (" << nodeIndex << ", " << toNodeIndex << ") is reused\n"; } packedNodeList.packNodes(*this, packInput); if (maxNodes > 0 && getNumNodes() > maxNodes) { dout() << "Lattice::expandNodeToTrigram: " << "aborting with number of nodes exceeding " << maxNodes << endl; return false; } // processing selfLoop if (selfLoopFlag) { expandSelfLoop(lm, selfLoopDB, packedSelfLoopNodeList); } } // end of inter-loop } // end of out-loop // processing selfLoop case if (selfLoopFlag) { node = findNode(nodeIndex); node->inTransitions.remove(nodeIndex); node = findNode(nodeIndex); if (!node->outTransitions.remove(nodeIndex)) { dout() << "Lattice::expandNodeToTrigram: " << "nonFatal Error: non symetric setting\n"; exit(-1); } } // remove bigram transitions along with the old node removeNode(nodeIndex); return true; } Boolean Lattice::expandToTrigram(LM &lm, unsigned maxNodes) { if (debug(DebugPrintFunctionality)) { dout() << "Lattice::expandToTrigram: " << "starting expansion to conventional trigram lattice ...\n"; } unsigned numNodes = getNumNodes(); NodeIndex *sortedNodes = new NodeIndex[numNodes]; assert(sortedNodes != 0); unsigned numReachable = sortNodes(sortedNodes); if (numReachable != numNodes) { if (debug(DebugPrintOutLoop)) { dout() << "Lattice::expandToTrigram: warning: called with unreachable nodes\n"; } } for (unsigned i = 0; i < numReachable; i++) { NodeIndex nodeIndex = sortedNodes[i]; if (nodeIndex == initial || nodeIndex == final) { continue; } if (!expandNodeToTrigram(nodeIndex, lm, maxNodes)) { delete [] sortedNodes; return false; } } delete [] sortedNodes; return true; } /* * Expand bigram lattice to trigram, with bigram packing * (just like in nodearray.) * * BASIC ALGORITHM: * 1) foreach node u connecting with the initial NULL node, * let W be the set of nodes that have edge go into * node u. * a) get the set of outgoing edges e(u) of node u whose * the other ends of nodes are not marked as processed. * * b) for each edge e = (u, v) in e(u): * for each node w in W do: * i) if p(v | u, w) exists, * duplicate u to get u' ( word name ), * and edge (w, u') and (u', v) * with all the attributes. * place p(v | u, w) on edge (u', v) * * ii) if p(v | u, w) does not exist, * add p(v | u) on edge (u, v) * multiply bo(w,u) to p(u | w) on (w, u) * * reservedFlag: to indicate that not all the outGoing nodes from the * current node have trigram probs and this bigram edge needs to be * preserved for bigram prob. */ static /*const*/ LogP zerobow = 0.0; Boolean Lattice::expandNodeToCompactTrigram(NodeIndex nodeIndex, Ngram &ngram, unsigned maxNodes) { if (debug(DebugPrintOutLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: \n"; } SelfLoopDB selfLoopDB; PackedNodeList packedNodeList, packedSelfLoopNodeList; LatticeTransition *outTrans; NodeIndex fromNodeIndex, backoffNodeIndex; NodeIndex toNodeIndex; LatticeNode *fromNode; VocabIndex * bowContext = 0; int inBOW = 0; VocabIndex context[3]; LatticeNode *node = findNode(nodeIndex); if (!node) { if (debug(DebugPrintFatalMessages)) { dout() << "Fatal Error in Lattice::expandNodeToCompactTrigram: " << "current node has lost!\n"; } exit(-1); } LatticeTransition * selfLoop = node->inTransitions.find(nodeIndex); Boolean selfLoopFlag; if (selfLoop) { selfLoopFlag = true; initASelfLoopDB(selfLoopDB, ngram, nodeIndex, node, selfLoop); } else { selfLoopFlag = false; } TRANSITER_T<NodeIndex,LatticeTransition> inTransIter(node->inTransitions); TRANSITER_T<NodeIndex,LatticeTransition> outTransIter(node->outTransitions); VocabIndex wordName = node->word; if (debug(DebugPrintOutLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: " << " processing word name: " << getWord(wordName) << ", Index: " << nodeIndex << "\n"; } // going through all its incoming edges unsigned numInTrans = node->inTransitions.numEntries(); while (LatticeTransition *inTrans = inTransIter.next(fromNodeIndex)) { if (nodeIndex == fromNodeIndex) { if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: " << "jump over self loop: " << fromNodeIndex << "\n"; } continue; } fromNode = findNode(fromNodeIndex); if (!fromNode) { if (debug(DebugPrintFatalMessages)) { dout() << "Fatal Error in Lattice::expandNodeToCompactTrigram: " << "fromNode " << fromNodeIndex << " doesn't exist!\n"; } exit(-1); } VocabIndex fromWordName = fromNode->word; if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: " << "processing incoming edge: (" << fromNodeIndex << ", " << nodeIndex << ")\n" << " (" << getWord(fromWordName) << ", " << getWord(wordName) << ")\n"; } // compute in-coming bigram prob LogP inWeight; if (fromNodeIndex == getInitial()) { context[0] = fromWordName; context[1] = Vocab_None; // this transition can have never been processed. inWeight = ngram.wordProb(wordName, context); inTrans->weight = inWeight; if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: " << "processing incoming edge: (" << fromNodeIndex << ", " << nodeIndex << ")\n" << " (" << getWord(fromWordName) << ", " << getWord(wordName) << ") = " << " " << inWeight << ";\n"; } } else { // the in-coming trans has been processed and // we should preserve this value. inWeight = inTrans->weight; } context[0] = wordName; context[1] = fromWordName; context[2] = Vocab_None; // LogP inWeight = ngram.wordProb(wordName, context); unsigned inFlag = inTrans->flags; // initialize it for self loop processing. if (selfLoopFlag) { initBSelfLoopDB(selfLoopDB, ngram, fromNodeIndex, fromNode, inTrans); } // going through all the outgoing edges outTransIter.init(); while (LatticeTransition *outTrans = outTransIter.next(toNodeIndex)) { if (nodeIndex == toNodeIndex) { if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: " << "self loop: " << toNodeIndex << "\n"; } continue; } LatticeNode * toNode = findNode(toNodeIndex); if (!toNode) { if (debug(DebugPrintFatalMessages)) { dout() << "Fatal Error in Lattice::expandNodeToCompactTrigram: " << "toNode " << toNode << " doesn't exist!\n"; } exit(-1); } if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: " << "the toNodeIndex (" << toNodeIndex << " has name " << getWord(toNode->word) << ")\n"; } // initialize selfLoopDB; if (selfLoopFlag) { initCSelfLoopDB(selfLoopDB, toNodeIndex, outTrans); } // duplicate a node if the trigram exists. // see class Ngram in file /home/srilm/devel/lm/src/Ngram.h LogP * triProb; if ((triProb = ngram.findProb(toNode->word, context))) { LogP logProb = *triProb; if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: " << "tripleIndex (" << toNodeIndex << " | " << nodeIndex << ", " << fromNodeIndex << ")\n" << " trigram prob: (" << getWord(toNode->word) << " | " << context << ") found!\n"; } // create one node and two edges to place trigram prob PackInput packInput; packInput.fromWordName = fromWordName; packInput.wordName = wordName; packInput.toWordName = toNode->word; packInput.fromNodeIndex = fromNodeIndex; packInput.toNodeIndex = toNodeIndex; packInput.inWeight = inWeight; packInput.inFlag = inFlag; packInput.outWeight = logProb; packInput.outFlag = outTrans->flags; packInput.nodeIndex = nodeIndex; packInput.toNodeId = 0; packInput.lm = 0; packedNodeList.packNodes(*this, packInput); // to remove the outGoing edge if all the outgoing nodes have // trigram probs. if (numInTrans == 1 && !(outTrans->getFlag(reservedTFlag))) { if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: " << "outgoing edge: (" << nodeIndex << ", " << toNodeIndex << ") is removed\n"; } removeTrans(nodeIndex, toNodeIndex); } if (maxNodes > 0 && getNumNodes() > maxNodes) { dout() << "Lattice::expandNodeToCompactTrigram: " << "aborting with number of nodes exceeding " << maxNodes << endl; return false; } } else { // there is no trigram prob for this context if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: " << "no trigram context (" << context << ") has been found -- keep " << fromNodeIndex << "\n"; } // note down backoff context and in-coming node for // preservation, in case explicit trigram does not exist. bowContext = context; outTrans->markTrans(reservedTFlag); backoffNodeIndex = fromNodeIndex; } // processing selfLoop if (selfLoopFlag) { expandSelfLoop(ngram, selfLoopDB, packedSelfLoopNodeList); } } // end of inter-loop // processing incoming bigram cases. if (!bowContext) { // for this context, all the toNodes have trigram probs if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: " << "incoming edge (" << fromNodeIndex << ", " << nodeIndex << ") is removed\n"; } removeTrans(fromNodeIndex, nodeIndex); } else { if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: " << "updating trigram backoffs on edge(" << fromNodeIndex << ", " << nodeIndex << ")\n"; } LogP * wordBOW = ngram.findBOW(bowContext); if (!(wordBOW)) { if (debug(DebugPrintOutLoop)) { dout() << "nonFatal Error in Lattice::expandNodeToCompactTrigram: " << "language model - BOW (" << bowContext << ") missing!\n"; } wordBOW = &zerobow; } LogP logProbW = *wordBOW; LogP weight = combWeights(inWeight, logProbW); setWeightTrans(backoffNodeIndex, nodeIndex, weight); bowContext = 0; inBOW = 1; } numInTrans--; } // end of out-loop // if trigram prob exist for all the tri-node paths if (!inBOW) { if (debug(DebugPrintInnerLoop)) { dout() << "Lattice::expandNodeToCompactTrigram: " << "node " << getWord(wordName) << " (" << nodeIndex << ") has trigram probs for all its contexts\n" << " and its bigram lattice node is removed\n"; } removeNode(nodeIndex); } else { node = findNode(nodeIndex); if (selfLoopFlag) { node->inTransitions.remove(nodeIndex); node = findNode(nodeIndex); if (!node->outTransitions.remove(nodeIndex)) { if (debug(DebugPrintFatalMessages)) { dout() << "nonFatal Error in Lattice::expandNodeToCompactTrigram: " << "non symetric setting \n"; } exit(-1); } } // process backoff to bigram weights. TRANSITER_T<NodeIndex,LatticeTransition> outTransIter(node->outTransitions); while (LatticeTransition *outTrans = outTransIter.next(toNodeIndex)) { LatticeNode * toNode = findNode(toNodeIndex); context[0] = wordName; context[1] = Vocab_None; LogP weight = ngram.wordProb(toNode->word, context); setWeightTrans(nodeIndex, toNodeIndex, weight); } } return true; } Boolean Lattice::expandToCompactTrigram(Ngram &ngram, unsigned maxNodes) { if (debug(DebugPrintFunctionality)) { dout() << "Lattice::expandToCompactTrigram: " << "starting expansion to compact trigram lattice ...\n"; } unsigned numNodes = getNumNodes(); NodeIndex *sortedNodes = new NodeIndex[numNodes]; assert(sortedNodes != 0); unsigned numReachable = sortNodes(sortedNodes); if (numReachable != numNodes) { if (debug(DebugPrintOutLoop)) { dout() << "Lattice::expandToCompactTrigram: warning: called with unreachable nodes\n"; } } for (unsigned i = 0; i < numReachable; i++) { NodeIndex nodeIndex = sortedNodes[i]; if (nodeIndex == initial || nodeIndex == final) { continue; } if (!expandNodeToCompactTrigram(nodeIndex, ngram, maxNodes)) { delete [] sortedNodes; return false; } } delete [] sortedNodes; return true; } /* * Expand lattice to implement general LMs * Algorithm: replace each node in lattice with copies that are * associated with specific LM contexts. The mapping * (original node, context) -> new node * is constructed incrementally as the lattice is traversed in topological * order. * * expandMap[startNode, <s>] := newStartNode; * expandMap[endNode, </s>] := newEndNode; * * for oldNode in topological order * for expandMap[oldNode, c] = newNode * for oldNode2 in successors(oldNode) * c2 = lmcontext(c + word(oldNode2)); * find or create expandMap[oldNode2, c2] = newNode2; * word(newNode2) := word(oldNodes2); * prob(newNode->newNode2) := P(word(newNode2) | c); * delete oldNode; * delete expandMap[oldNode]; # to save space * * As an optimization, we let * * lmcontext(c + word(oldNode2)) be the longest context used by the LM * for predicting words following oldNode2 in the lattice, and * BOW(c2) be the backoff weight associated with backing off from the * full LM context (c + word(oldNode2)) to c2 * * Nodes with NULL or pause are handled by ignoring them in context * construction, but otherwise handling (i.e., duplicating) them as above. */ Boolean Lattice::expandNodeToLM(VocabIndex oldIndex, LM &lm, unsigned maxNodes, Map2<NodeIndex, VocabContext, NodeIndex> &expandMap) { unsigned insufficientLookaheadNodes = 0; Map2Iter2<NodeIndex, VocabContext, NodeIndex> #ifdef USE_SARRAY_MAP2 expandIter(expandMap, oldIndex); #else expandIter(expandMap, oldIndex, ngramCompare); #endif NodeIndex *newIndex; VocabContext context; while ((newIndex = expandIter.next(context))) { // node structure might have been moved as a result of insertions LatticeNode *oldNode = findNode(oldIndex); assert(oldNode != 0); unsigned contextLength = Vocab::length(context); makeArray(VocabIndex, newContext, contextLength + 2); Vocab::copy(&newContext[1], context); TRANSITER_T<NodeIndex,LatticeTransition> transIter(oldNode->outTransitions); NodeIndex oldIndex2; while (LatticeTransition *oldTrans = transIter.next(oldIndex2)) { LatticeNode *oldNode2 = findNode(oldIndex2); assert(oldNode2 != 0); VocabIndex word = oldNode2->word; // determine context used by LM unsigned usedLength = 0; VocabIndex *usedContext; LogP wordProb; // The old context is extended by word on this node, unless // it is null or pause, which are both ignored by the LM. // Non-events are added to the context but aren't evaluated. if (ignoreWord(word)) { usedContext = &newContext[1]; wordProb = LogP_One; } else if (vocab.isNonEvent(word)) { newContext[0] = word; usedContext = newContext; wordProb = LogP_One; } else { newContext[0] = word; usedContext = newContext; wordProb = lm.wordProb(word, context); } // find all possible following words and determine maximal context // needed for wordProb computation // skip pause and null nodes up to some depth LatticeFollowIter followIter(*this, *oldNode2); NodeIndex oldIndex3; LatticeNode *oldNode3; LogP weight; while ((oldNode3 = followIter.next(oldIndex3, weight))) { // if one of the following nodes has null or pause as word then // we don't attempt any further look-ahead and use the maximal // context from the LM VocabIndex nextWord = oldNode3->word; if (ignoreWord(nextWord)) { insufficientLookaheadNodes += 1; nextWord = Vocab_None; } unsigned usedLength2; lm.contextID(nextWord, usedContext, usedLength2); if (usedLength2 > usedLength) { usedLength = usedLength2; } } if (!expandAddTransition(usedContext, usedLength, word, wordProb, lm, oldIndex2, *newIndex, oldTrans, maxNodes, expandMap)) return false; } } if (insufficientLookaheadNodes > 0) { dout() << "Lattice::expandNodeToLM: insufficient lookahead on " << insufficientLookaheadNodes << " nodes\n"; } // old node (and transitions) is fully replaced by expanded nodes // (and transitions) removeNode(oldIndex); // save space in expandMap by deleting entries that are no longer used expandMap.remove(oldIndex); return true; } /* * The "compact expansion" version makes two changes * * - add outgoing transitions to node duplicates with shorter contexts, * not just the maximal context. * - only transition out of an expanded node if the LM uses the full context * associated with that node (*** A *** below). * This is possible because of the first change, and it's * where the savings compared to the general expansion are realized. * * The resulting algorithm is a generalization of expandToCompactTrigram(). */ Boolean Lattice::expandNodeToCompactLM(VocabIndex oldIndex, LM &lm, unsigned maxNodes, Map2<NodeIndex, VocabContext, NodeIndex> &expandMap) { unsigned insufficientLookaheadNodes = 0; Map2Iter2<NodeIndex, VocabContext, NodeIndex> #ifdef USE_SARRAY_MAP2 expandIter(expandMap, oldIndex); #else expandIter(expandMap, oldIndex, ngramCompare); #endif NodeIndex *newIndex; VocabContext context; while ((newIndex = expandIter.next(context))) { // node structure might have been moved as a result of insertions LatticeNode *oldNode = findNode(oldIndex); assert(oldNode != 0); Boolean ignoreOldNodeWord = ignoreWord(oldNode->word); unsigned contextLength = Vocab::length(context); makeArray(VocabIndex, newContext, contextLength + 2); Vocab::copy(&newContext[1], context); TRANSITER_T<NodeIndex,LatticeTransition> transIter(oldNode->outTransitions); NodeIndex oldIndex2; while (LatticeTransition *oldTrans = transIter.next(oldIndex2)) { LatticeNode *oldNode2 = findNode(oldIndex2); assert(oldNode2 != 0); VocabIndex word = oldNode2->word; // Find the context length used for LM transition oldNode->oldNode2. // Because each LM context gets its own node duplicate // in this expansion algorithm, we only need to process // transitions where the LM context fully matches the context // associated with the specific oldNode duplicate we're working on. unsigned usedLength0; lm.contextID(word, context, usedLength0); // if the node we're coming from has a real word then // there is no point in using a null context // (so we can collapse null and unigram contexts) if (usedLength0 == 0 && !ignoreOldNodeWord) { usedLength0 = 1; } // *** A *** if (!ignoreWord(word) && context[0] != vocab.ssIndex() && usedLength0 != contextLength) { continue; } // determine context used by LM VocabIndex *usedContext; LogP wordProb; // The old context is extended by word on this node, unless // it is null or pause, which are both ignored by the LM. // Non-events are added to the context by aren't evaluated. if (ignoreWord(word)) { usedContext = &newContext[1]; wordProb = LogP_One; } else if (vocab.isNonEvent(word)) { newContext[0] = word; usedContext = newContext; wordProb = LogP_One; } else { newContext[0] = word; usedContext = newContext; wordProb = lm.wordProb(word, context); } // find all possible following words and compute LM context // used for their prediction. // then create duplicate nodes for each context length // needed for wordProb computation LatticeFollowIter followIter(*this, *oldNode2); NodeIndex oldIndex3; LatticeNode *oldNode3; LogP weight; unsigned lastUsedLength = (unsigned)-1; while ((oldNode3 = followIter.next(oldIndex3, weight))) { unsigned usedLength; // if one of the following nodes has null or pause as word then // we have to back off to null context to make sure // further expansion can connect above at *** A *** VocabIndex nextWord = oldNode3->word; if (ignoreWord(nextWord)) { insufficientLookaheadNodes += 1; usedLength = 0; } else { lm.contextID(nextWord, usedContext, usedLength); } // if the node we're going to has a real word then // there is no point in using a null context (same as above) if (usedLength == 0 && !ignoreWord(word)) { usedLength = 1; } // optimization: no need to re-add transition if usedLength // is same as on previous pass through if (usedLength == lastUsedLength) { continue; } else { lastUsedLength = usedLength; } if (!expandAddTransition(usedContext, usedLength, word, wordProb, lm, oldIndex2, *newIndex, oldTrans, maxNodes, expandMap)) return false; } // transitions to the final node have to be handled specially // because the above loop won't apply to it, since the final node // has no outgoing transitions! if (oldIndex2 == final) { // by convention, the final node always uses context of length 0 if (!expandAddTransition(usedContext, 0, word, wordProb, lm, oldIndex2, *newIndex, oldTrans, maxNodes, expandMap)) return false; } } } if (insufficientLookaheadNodes > 0) { dout() << "Lattice::expandNodeToCompactLM: insufficient lookahead on " << insufficientLookaheadNodes << " nodes\n"; } // old node (and transitions) is fully replaced by expanded nodes // (and transitions) removeNode(oldIndex); // save space in expandMap by deleting entries that are no longer used expandMap.remove(oldIndex); return true; } /* * Helper for expandNodeToLM() and expandNodeToCompactLM() */ Boolean Lattice::expandAddTransition(VocabIndex *usedContext, unsigned usedLength, VocabIndex word, LogP wordProb, LM &lm, NodeIndex oldIndex2, NodeIndex newIndex, LatticeTransition *oldTrans, unsigned maxNodes, Map2<NodeIndex, VocabContext, NodeIndex> &expandMap) { LogP transProb; if (ignoreWord(word)) { transProb = LogP_One; } else { transProb = wordProb; } if (!noBackoffWeights && usedContext[0] != vocab.seIndex()) { // back-off weight to truncate the context // (needs to be called before context truncation below) // Note: we check above that this is not a backoff weight after </s>, // which some LMs contain but should be ignored for our purposes // since lattices all end implictly in </s>. transProb += lm.contextBOW(usedContext, usedLength); } // truncate context to what LM uses VocabIndex saved = usedContext[usedLength]; usedContext[usedLength] = Vocab_None; Boolean found; NodeIndex *newIndex2 = expandMap.insert(oldIndex2, (VocabContext)usedContext, found); if (!found) { LatticeNode *oldNode2 = findNode(oldIndex2); assert(oldNode2 != 0); // create new node copy and store it in map *newIndex2 = dupNode(word, oldNode2->flags, oldNode2->htkinfo); if (maxNodes > 0 && getNumNodes() > maxNodes) { dout() << "Lattice::expandAddTransition: " << "aborting with number of nodes exceeding " << maxNodes << endl; return false; } } LatticeTransition newTrans(transProb, oldTrans->flags); insertTrans(newIndex, *newIndex2, newTrans, 0); // restore full context usedContext[usedLength] = saved; return true; } Boolean Lattice::expandToLM(LM &lm, unsigned maxNodes, Boolean compact) { if (debug(DebugPrintFunctionality)) { dout() << "Lattice::expandToLM: " << "starting " << (compact ? "compact " : "") << "expansion to general LM (maxNodes = " << maxNodes << ") ...\n"; } unsigned numNodes = getNumNodes(); NodeIndex *sortedNodes = new NodeIndex[numNodes]; assert(sortedNodes != 0); unsigned numReachable = sortNodes(sortedNodes); if (numReachable != numNodes) { if (debug(DebugPrintOutLoop)) { dout() << "Lattice::expandToLM: warning: called with unreachable nodes\n"; } } Map2<NodeIndex, VocabContext, NodeIndex> expandMap; // prime expansion map with initial/final nodes LatticeNode *startNode = findNode(initial); assert(startNode != 0); VocabIndex newStartIndex = dupNode(startNode->word, startNode->flags, startNode->htkinfo); VocabIndex context[2]; context[1] = Vocab_None; context[0] = vocab.ssIndex(); *expandMap.insert(initial, context) = newStartIndex; LatticeNode *endNode = findNode(final); assert(endNode != 0); VocabIndex newEndIndex = dupNode(endNode->word, endNode->flags, endNode->htkinfo); context[0] = Vocab_None; *expandMap.insert(final, context) = newEndIndex; for (unsigned i = 0; i < numReachable; i++) { NodeIndex nodeIndex = sortedNodes[i]; if (nodeIndex == final) { removeNode(final); } else if (compact) { if (!expandNodeToCompactLM(nodeIndex, lm, maxNodes, expandMap)) { delete [] sortedNodes; return false; } } else { if (!expandNodeToLM(nodeIndex, lm, maxNodes, expandMap)) { delete [] sortedNodes; return false; } } } initial = newStartIndex; final = newEndIndex; delete [] sortedNodes; return true; }
45,788
15,714
#include<iostream> #include<queue> #include<math.h> using namespace std; void KNearestCord(int arr[][2], int n, int k){ priority_queue<pair<int, pair<int,int> > > pq; for(int i=0;i<n;i++){ int v = pow(arr[i][0],2) + pow(arr[i][1],2); pq.push(make_pair(v, make_pair(arr[i][0], arr[i][1]))); if(pq.size()>k) pq.pop(); } cout<<"Printing Pairs"<<endl; while(!pq.empty()){ pair<int,int> p= pq.top().second; cout<<p.first<<" "<<p.second<<endl; //cout<<pq.top().second.first<<" "<<pq.top().second.second<<endl; pq.pop(); } } int main(){ int n; cin>>n; int arr[n][2]; int k; cin>>k; int i=0; for(i=0;i<n;i++) for(int j=0;j<2;j++) cin>>arr[i][j]; KNearestCord(arr, n,k); return 0; }
727
389
/** * @file mod_debug.cpp * @brief boost::python debug module * @author Simon Steele * @note Copyright (c) 2009 Simon Steele - http://untidy.net/ * * Programmers Notepad 2 : The license file (license.[txt|html]) describes * the conditions under which this source may be modified / distributed. */ #include "stdafx.h" void pyOutputDebugString(const char* message) { OutputDebugString(message); } using namespace boost::python; BOOST_PYTHON_MODULE(debug) { boost::python::docstring_options docstring_options(true); def("OutputDebugString", pyOutputDebugString); }
577
187
// Copyright 2015 by Intigua, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning (disable: 4996) // copy unsafe #include "objects.h" #include "PyVM.h" #include "OpImp.h" #include <cstring> using namespace std; const char* Object::typeName(Type type) { switch (type) { case NONE: return "NoneType"; case BOOL: return "bool"; case INT: return "int"; case UINT: return "uint"; case INT64: return "int64"; case UINT64: return "uint64"; case STR: return "str"; case TUPLE: return "tuple"; case LIST: return "list"; case DICT: return "dict"; case CODE: return "code"; case MODULE: return "module"; case FUNC: return "function"; case CLASS: return "classobj"; case INSTANCE: return "instance"; case METHOD: return "method"; case USTR: return "unicode"; case SLICE: return "slice"; default: return "<unknown>"; } } template<typename T> static Object::Type typeValue() { class NoType; return sizeof(NoType); // compile error for types that are not instantiated in object.cpp } #define MAKE_TYPEVALUE(obj, val) template<> Object::Type Object::typeValue<obj >() { return Object::val; } MAKE_TYPEVALUE(BoolObject, BOOL) MAKE_TYPEVALUE(StrObject, STR) MAKE_TYPEVALUE(IntObject, INT) MAKE_TYPEVALUE(UIntObject, UINT) MAKE_TYPEVALUE(Int64Object, INT64) MAKE_TYPEVALUE(UInt64Object, UINT64) MAKE_TYPEVALUE(TupleObject, TUPLE) MAKE_TYPEVALUE(ListObject, LIST) MAKE_TYPEVALUE(DictObject, DICT) MAKE_TYPEVALUE(StrDictObject, STRDICT) MAKE_TYPEVALUE(CodeObject, CODE) MAKE_TYPEVALUE(ModuleObject, MODULE) MAKE_TYPEVALUE(FuncObject, FUNC) MAKE_TYPEVALUE(CFuncObject, FUNC) MAKE_TYPEVALUE(ClassObject, CLASS) MAKE_TYPEVALUE(InstanceObject, INSTANCE) MAKE_TYPEVALUE(MethodObject, METHOD) MAKE_TYPEVALUE(IteratorObject, ITERATOR) //MAKE_TYPEVALUE(GenericIterObject, ITERATOR) #if (defined(_WIN32) || defined(_WIN64)) MAKE_TYPEVALUE(UnicodeObject, USTR) #endif MAKE_TYPEVALUE(Object, NONE) MAKE_TYPEVALUE(FloatObject, FLOAT) MAKE_TYPEVALUE(SliceObject, SLICE) #undef MAKE_TYPEVALUE InstanceObjRef ClassObject::createInstance() { InstanceObjRef i(m_vm->alloct(new InstanceObject(ClassObjRef(this)))); //makeMethods(i); return i; } ObjRef ModuleObject::defIc(const string& name, const ICWrapPtr& ic) { ic->setName(name); return addGlobal(m_vm->alloc(new CFuncObject(ic)), name); } ClassObjRef ModuleObject::emptyClass(const string& name) { ClassObjRef ret = m_vm->alloct(new ClassObject(m_vm->alloct(new StrDictObject()), vector<ObjRef>(/*bases*/), name, ModuleObjRef(this), m_vm)); addGlobal(ObjRef(ret), name); return ret; } string MethodObject::funcname() const { if (m_self.isNull()) return "nullptrSELF." + m_func->funcname(); if (m_self->m_class.isNull()) return "nullptrCLASS." + m_func->funcname(); return m_self->m_class->funcname() + "." + m_func->funcname(); } void Builtins::add(const string& name, const ObjRef& v) { addGlobal(v, name);; } // see "All about co_lnotab" http://svn.python.org/projects/python/branches/pep-0384/Objects/lnotab_notes.txt int CodeObject::lineFromIndex(int qi) const { const string& tab = m_co.co_lnotab; if ((tab.size() % 2) != 0) return -1; //strange format int lineno = m_co.co_firstlineno, addr = 0; for(int i = 0; i < (int)tab.size(); i += 2) { addr += tab[i]; if (addr > qi) return lineno; lineno += tab[i + 1]; } return lineno; } int ISubscriptable::extractIndex(const ObjRef& key, size_t size) { int i = extract<int>(key); if (i < 0) i = (int)size + i; CHECK(i >= 0 && i < (int)size, "Out of range index " << i << ":" << size); return i; } //------------------------------------------------------------------------------------------ #if (defined(_WIN32) || defined(_WIN64)) ObjRef UnicodeObject::fromStr(const ObjRef& s, PyVM* vm) { return vm->alloc(new UnicodeObject(checked_dynamic_pcast<StrObject>(s))); } #endif ObjRef ClassObject::attr(const string& name) { ObjRef v = tryLookup(m_dict->v, name); if (!v.isNull()) return v; if (!m_base.isNull()) return m_base->attr(name); return v; } PoolPtr<MethodObject> MethodObject::bind(const InstanceObjRef& newself) { CHECK(m_self.isNull(), "Can't bind an already bound method"); CHECK(!newself.isNull(), "Can't bind to a nullptr reference"); // get to the vm through the class return newself->m_class->m_vm->alloct(new MethodObject(m_func, newself)); } ObjRef InstanceObject::simple_attr(const string& name) { // try in the instance ObjRef v = tryLookup(m_dict, name); if (!v.isNull()) return v; // try in the class if (!m_class.isNull()) { v = m_class->attr(name); if (!v.isNull()) { // if it's a method, need to create a new bounded method object // the methods are not saved in the instance object to avoid a cycle instance->method->(m_self)instance // this is the way it is done in CPython if (v->type == Object::METHOD) { MethodObjRef m = checked_cast<MethodObject>(v); // same as bind(), without the checks return m_class->m_vm->alloc(new MethodObject(m->m_func, InstanceObjRef(this))); } return v; } } return ObjRef(); } ObjRef InstanceObject::attr(const string& name) { ObjRef v = simple_attr(name); if (!v.isNull()) return v; ObjRef getatt = simple_attr("__getattr__"); if (!getatt.isNull()) { vector<ObjRef> gargs; gargs.push_back(m_class->m_vm->makeFromT(name)); try { return m_class->m_vm->callv(getatt, gargs); } catch (const PyRaisedException& e) { auto inst = checked_cast<InstanceObject>(e.inst); if (inst->m_class->m_name == "AttributeError") return ObjRef(); // indicates the attribute does not exist throw; } } return v; } int toSlash(int c) { if (c == '\\') return '/'; return c; } template<typename T, typename TOp> static T transformed(const T& str, TOp& op) { T ret = str; transform(ret.begin(), ret.end(), ret.begin(), op); return ret; } enum StrOp { SO_EQUALS, SO_CONTAINS, SO_BEGINS, SO_ENDS }; static void checkArgCountS(Object::Type t, const CallArgs::TPosVector& args, int c, const string& name) { CHECK(args.size() == c, "method " << Object::typeName(t) << "." << name << " takes exactly " << c << "arguments (" << args.size() << " given)"); } void PrimitiveAttrAdapter::checkArgCount(const ObjRef obj, const CallArgs::TPosVector& args, int c) { checkArgCountS(obj->type, args, c, m_name); } // casei: case insensitive compare // slashi: slash insensitive compare template<typename TC> static bool stringQuery(const ObjRef& thisv, const CallArgs::TPosVector& args, StrOp op, StrModifier mod) { checkArgCountS(Object::STR, args, 1, "cmp"); // STR is just for logging const basic_string<TC>* a = extractStrPtr<TC>(args[0], mod); const basic_string<TC>* v = extractStrPtr<TC>(thisv, mod); if (a->size() > v->size()) return false; switch (op) { case SO_CONTAINS: return v->find(*a) != basic_string<TC>::npos; case SO_BEGINS: return memcmp(v->data(), a->data(), a->size() * sizeof(TC)) == 0; case SO_ENDS: return memcmp(v->data() + v->size() - a->size(), a->data(), a->size() * sizeof(TC)) == 0; case SO_EQUALS: return *a == *v; } return false; } // takes 2 optional arguments // arg 1: separator (if not given, using white-space) // arg 2: if separator is given, should we add empty elements. default is true (while-space split always ignores empty elements) template<typename TC> static ObjRef split(const ObjRef& o, const CallArgs::TPosVector& args, PyVM* vm) { basic_string<TC> s = extract<basic_string<TC>>(o); ListObjRef ret = vm->alloct(new ListObject); if (args.size() == 1 || args.size() == 2) { basic_string<TC> sep = extract<basic_string<TC> >(args[0]); bool addEmpty = true; // the default documented behaviour if (args.size() == 2) addEmpty = extract<bool>(args[1]); size_t next = 0, current = 0; do { next = s.find(sep, current); basic_string<TC> v = s.substr(current, next - current); if (!v.empty() || addEmpty) { ret->append(vm->alloc(new PSTROBJ_TYPE(TC)(v))); } current = next + sep.size(); } while (next != string::npos); } else if (args.size() == 0) { size_t next = 0, current = 0; do { next = s.find_first_of( LITERAL_TSTR(TC, " \t\n\r"), current); basic_string<TC> v = s.substr(current, next - current); if (!v.empty()) { ret->append(vm->alloc(new PSTROBJ_TYPE(TC)(v))); } current = next + 1; } while (next != string::npos); } else THROW("Unexpected number of arguments (" << args.size() << ") in split()"); return ObjRef(ret); } template<typename TC> static ObjRef join(const ObjRef& s, const CallArgs::TPosVector& args, PyVM* vm) { checkArgCountS(Object::STR, args, 1, "join"); auto ito = args[0]->as<IIterable>()->iter(vm); // save a reference to the object auto it = ito->as<IIterator>(); ObjRef o; if (!it->next(o)) return vm->makeFromT(basic_string<TC>()); ObjRef result = o; OpImp ops(vm); while (it->next(o)) { CHECK(o->type == Object::STR || o->type == Object::USTR, "join(): wrong type expected: str or unicode got:" << o->typeName()); result = ops.add(result, s); result = ops.add(result, o); } return result; } #ifdef _WINDOWS #define PATH_MODIFIER_ STRMOD_PATH #else #define PATH_MODIFIER_ STRMOD_NONE #endif // to add a string method name, // - add it to "string_method_names.txt", // - enable it in the build (set "Exclude from build to 'No') doesn't matter which build config // - compile "string_method_names.txt" to create a new "gen_string_method_names.h" // - disable it again in the build (set "Exclude from build to 'Yes') // the custom build step that generates this file is currently only generated in the windows build since there is still no scons rule for it // this is why "gen_string_method_names.h" is in source control. // after re-generating this file, make sure you commit the change in the genrated file as well. #include "gen_string_method_names.h" template<typename TC> ObjRef PrimitiveAttrAdapter::stringMethod(const ObjRef& obj, const CallArgs::TPosVector& args) { EStringMethods nameEnum = stringMethod_enumFromStr(m_name); switch(nameEnum) { case STRM_CONTAINS: return m_vm->makeFromT(stringQuery<TC>(obj, args, SO_CONTAINS, STRMOD_NONE)); case STRM_BEGINSWITH: case STRM_STARTSWITH: return m_vm->makeFromT(stringQuery<TC>(obj, args, SO_BEGINS, STRMOD_NONE)); case STRM_ENDSWITH: return m_vm->makeFromT(stringQuery<TC>(obj, args, SO_ENDS, STRMOD_NONE)); case STRM_EQUALS: return m_vm->makeFromT(stringQuery<TC>(obj, args, SO_EQUALS, STRMOD_NONE)); case STRM_PATHCONTAINS: return m_vm->makeFromT(stringQuery<TC>(obj, args, SO_CONTAINS, PATH_MODIFIER_)); case STRM_PATHBEGINSWITH: return m_vm->makeFromT(stringQuery<TC>(obj, args, SO_BEGINS, PATH_MODIFIER_)); case STRM_PATHENDSWITH: return m_vm->makeFromT(stringQuery<TC>(obj, args, SO_ENDS, PATH_MODIFIER_)); case STRM_PATHEQUALS: return m_vm->makeFromT(stringQuery<TC>(obj, args, SO_EQUALS, PATH_MODIFIER_)); case STRM_ICONTAINS: return m_vm->makeFromT(stringQuery<TC>(obj, args, SO_CONTAINS, STRMOD_CASEI)); case STRM_IBEGINSWITH: return m_vm->makeFromT(stringQuery<TC>(obj, args, SO_BEGINS, STRMOD_CASEI)); case STRM_IENDSWITH: return m_vm->makeFromT(stringQuery<TC>(obj, args, SO_ENDS, STRMOD_CASEI)); case STRM_IEQUALS: return m_vm->makeFromT(stringQuery<TC>(obj, args, SO_EQUALS, STRMOD_CASEI)); case STRM_SPLIT: return split<TC>(obj, args, m_vm); case STRM_JOIN: return join<TC>(obj, args, m_vm); case STRM_LOWER: return m_vm->makeFromT(toLower(extract<basic_string<TC>>(obj))); case STRM_C_PTR: return m_vm->makeFromT( static_cast<StrBaseObject*>(m_obj.get())->ptr()); case STRM_GLOB_PTR: { // leak this string basic_string<TC> *new_st = new basic_string<TC>(extract<basic_string<TC>>(obj)); return m_vm->makeFromT((size_t)new_st->data()); } case STRM_STRIP: { basic_string<TC> nonConstS = extract<basic_string<TC>>(obj); if (args.size() == 0){ trimSpaces(nonConstS); return m_vm->makeFromT(nonConstS); } strip<TC>(nonConstS, extract<basic_string<TC>>(args[0])); return m_vm->makeFromT(nonConstS); } } // switch THROW("Unknown string method " << m_name); } // if anything is unicode, everything should be unicode ObjRef PrimitiveAttrAdapter::stringMethodConv(const ObjRef& obj, CallArgs::TPosVector& args) { #if (defined(_WIN32) || defined(_WIN64)) bool uni = obj->type == Object::USTR; for(auto ait = args.begin(); !uni && ait != args.end(); ++ait) uni |= (*ait)->type == Object::USTR; if (uni) return stringMethod<wchar_t>(obj, args); #endif return stringMethod<char>(obj, args); } ObjRef PrimitiveAttrAdapter::listMethod(const ObjRef& obj, CallArgs::TPosVector& args) { auto l = static_pcast<ListObject>(obj); if (m_name == "append") { checkArgCount(obj, args, 1); l->append(args[0]); return m_vm->makeNone(); } if(m_name == "pop"){ checkArgCount(obj, args, 1); return l->pop(extract<int>(args[0])); } if (m_name == "extend") { checkArgCount(obj, args, 1); auto ito = args[0]->as<IIterable>()->iter(m_vm); // save the iterator reference auto it = ito->as<IIterator>(); ObjRef o; while (it->next(o)) l->v.push_back(o); return m_vm->makeNone(); } THROW("Unknown list method " << m_name); } template<typename TDict> ObjRef PrimitiveAttrAdapter::dictMethod(const ObjRef& obj, CallArgs::TPosVector& args) { auto d = static_pcast<TDict>(obj); if (m_name == "keys") { auto ret = m_vm->alloct(new ListObject); for(auto it = d->v.begin(); it != d->v.end(); ++it) ret->append(m_vm->makeFromT(it->first)); return ObjRef(ret); } if (m_name == "values"){ auto ret = m_vm->alloct(new ListObject); for (auto it = d->v.begin(); it != d->v.end(); ++it) ret->append(m_vm->makeFromT(it->second)); return ObjRef(ret); } if (m_name == "pop") { checkArgCount(obj, args, 1); return d->pop((args[0])); } if (m_name == "iteritems") { return m_vm->alloc(new MapKeyValueIterObject<TDict>(d, m_vm)); } THROW("Unknown strdict method " << m_name); } ObjRef PrimitiveAttrAdapter::call(Frame& from, Frame& frame, int posCount, int kwCount, const ObjRef& self) { CallArgs args; frame.argsFromStack(from, posCount, kwCount, args); args.posReverse(); // arguments come in reverse order, we can just edit in place since it's not used after. switch (m_obj->type) { case Object::STR: #if (defined(_WIN32) || defined(_WIN64)) case Object::USTR: #endif return stringMethodConv(m_obj, args.pos); case Object::LIST: return listMethod(m_obj, args.pos); case Object::STRDICT: return dictMethod<StrDictObject>(m_obj, args.pos); case Object::DICT: return dictMethod<DictObject>(m_obj, args.pos); // if you add a case here, you also need to at it in adaptedType() default: THROW("Unknown primitive method " << m_name << " of " << Object::typeName(m_obj->type)); } };
16,664
5,801
//================================================================ // PROGRAMMER : 潘廣霖 // DATE : 2015-10-22 // FILENAME : HW03D002.CPP // DESCRIPTION : GCD table of number 1 to 20 //================================================================ #include "stdafx.h" #include<iostream> #include<iomanip> #include<cstdlib> using namespace std; // my favorite GCD implementation int gcd(int a, int b) { return a ? gcd(b%a, a) : b; } int main(int argc, _TCHAR* argv[]) { // table header cout << setw(6) << ""; for (int i = 1; i <= 20; i++) { cout << setw(3) << right << i; } // horizonal line cout << endl << setw(68) << setfill('=') << "" << endl; cout << setfill(' '); // table body for (int i = 1; i <= 20; i++) { cout << setw(3) << right << i << " | "; for (int j = 1; j <= 20; j++) { cout << setw(3) << right << gcd(i, j); } cout << endl; } system("pause"); }
1,019
385
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/libaddressinput/chromium/addressinput_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h" namespace autofill { namespace addressinput { using ::i18n::addressinput::AddressData; using ::i18n::addressinput::AddressField; using ::i18n::addressinput::AddressProblem; TEST(AddressinputUtilTest, AddressRequiresRegionCode) { AddressData address; EXPECT_FALSE(HasAllRequiredFields(address)); } TEST(AddressinputUtilTest, UsRequiresState) { AddressData address; address.region_code = "US"; address.postal_code = "90291"; // Leave state empty. address.locality = "Los Angeles"; address.address_line.push_back("340 Main St."); EXPECT_FALSE(HasAllRequiredFields(address)); } TEST(AddressinputUtilTest, CompleteAddressReturnsTrue) { AddressData address; address.region_code = "US"; address.postal_code = "90291"; address.administrative_area = "CA"; address.locality = "Los Angeles"; address.address_line.push_back("340 Main St."); EXPECT_TRUE(HasAllRequiredFields(address)); } TEST(AddressinputUtilTest, MissingFieldsAreAddedToProblems) { AddressData address; address.region_code = "US"; // Leave postal code empty. // Leave state empty. address.locality = "Los Angeles"; address.address_line.push_back("340 Main St."); std::multimap<AddressField, AddressProblem> empty_filter; std::multimap<AddressField, AddressProblem> problems; ValidateRequiredFields(address, &empty_filter, &problems); EXPECT_EQ(problems.size(), 2); } TEST(AddressinputUtilTest, OnlyFieldsContainedInFilterAreAddedToProblems) { AddressData address; address.region_code = "US"; // Leave postal code empty. // Leave state empty. address.locality = "Los Angeles"; address.address_line.push_back("340 Main St."); std::multimap<AddressField, AddressProblem> include_postal_code_filter; include_postal_code_filter.insert(std::make_pair( AddressField::POSTAL_CODE, AddressProblem::MISSING_REQUIRED_FIELD)); std::multimap<AddressField, AddressProblem> problems; ValidateRequiredFields(address, &include_postal_code_filter, &problems); ASSERT_EQ(problems.size(), 1); EXPECT_EQ(problems.begin()->first, AddressField::POSTAL_CODE); EXPECT_EQ(problems.begin()->second, AddressProblem::MISSING_REQUIRED_FIELD); } TEST(AddressinputUtilTest, AllMissingFieldsAreAddedToProblems) { AddressData address; address.region_code = "US"; // Leave postal code empty. // Leave state empty. address.locality = "Los Angeles"; address.address_line.push_back("340 Main St."); std::multimap<AddressField, AddressProblem> empty_filter; std::multimap<AddressField, AddressProblem> problems; ValidateRequiredFieldsExceptFilteredOut(address, &empty_filter, &problems); EXPECT_EQ(problems.size(), 2); } TEST(AddressinputUtilTest, FieldsContainedInFilterAreExcludedFromProblems) { AddressData address; address.region_code = "US"; // Leave postal code empty. // Leave state empty. address.locality = "Los Angeles"; address.address_line.push_back("340 Main St."); std::multimap<AddressField, AddressProblem> exclude_postal_code_filter; exclude_postal_code_filter.insert(std::make_pair( AddressField::POSTAL_CODE, AddressProblem::MISSING_REQUIRED_FIELD)); std::multimap<AddressField, AddressProblem> problems; ValidateRequiredFieldsExceptFilteredOut(address, &exclude_postal_code_filter, &problems); ASSERT_EQ(problems.size(), 1); EXPECT_EQ(problems.begin()->first, AddressField::ADMIN_AREA); EXPECT_EQ(problems.begin()->second, AddressProblem::MISSING_REQUIRED_FIELD); } } // namespace addressinput } // namespace autofill
3,920
1,303
/* * ctkNetworkConnectorZeroMQTest.cpp * ctkNetworkConnectorZeroMQTest * * Created by Daniele Giunchi on 27/03/09. * Copyright 2009 B3C. All rights reserved. * * See Licence at: http://tiny.cc/QXJ4D * */ #include "ctkTestSuite.h" #include <ctkNetworkConnectorZeroMQ.h> #include <ctkEventBusManager.h> #include <QApplication> using namespace ctkEventBus; //------------------------------------------------------------------------- /** Class name: ctkObjectCustom Custom object needed for testing. */ class testObjectCustomForNetworkConnectorZeroMQ : public QObject { Q_OBJECT public: /// constructor. testObjectCustomForNetworkConnectorZeroMQ(); /// Return tha var's value. int var() {return m_Var;} public Q_SLOTS: /// Test slot that will increment the value of m_Var when an UPDATE_OBJECT event is raised. void updateObject(); void setObjectValue(int v); Q_SIGNALS: void valueModified(int v); void objectModified(); private: int m_Var; ///< Test var. }; testObjectCustomForNetworkConnectorZeroMQ::testObjectCustomForNetworkConnectorZeroMQ() : m_Var(0) { } void testObjectCustomForNetworkConnectorZeroMQ::updateObject() { m_Var++; } void testObjectCustomForNetworkConnectorZeroMQ::setObjectValue(int v) { m_Var = v; } /** Class name: ctkNetworkConnectorZeroMQTest This class implements the test suite for ctkNetworkConnectorZeroMQ. */ //! <title> //ctkNetworkConnectorZeroMQ //! </title> //! <description> //ctkNetworkConnectorZeroMQ provides the connection with 0MQ library. //It has been used qxmlrpc library. //! </description> class ctkNetworkConnectorZeroMQTest : public QObject { Q_OBJECT private Q_SLOTS: /// Initialize test variables void initTestCase() { m_EventBus = ctkEventBusManager::instance(); m_NetWorkConnectorZeroMQ = new ctkEventBus::ctkNetworkConnectorZeroMQ(); m_ObjectTest = new testObjectCustomForNetworkConnectorZeroMQ(); } /// Cleanup tes variables memory allocation. void cleanupTestCase() { if(m_ObjectTest) { delete m_ObjectTest; m_ObjectTest = NULL; } delete m_NetWorkConnectorZeroMQ; m_EventBus->shutdown(); } /// Check the existence of the ctkNetworkConnectorZeroMQe singletone creation. void ctkNetworkConnectorZeroMQConstructorTest(); /// Check the existence of the ctkNetworkConnectorZeroMQe singletone creation. void ctkNetworkConnectorZeroMQCommunictionTest(); private: ctkEventBusManager *m_EventBus; ///< event bus instance ctkNetworkConnectorZeroMQ *m_NetWorkConnectorZeroMQ; ///< EventBus test variable instance. testObjectCustomForNetworkConnectorZeroMQ *m_ObjectTest; }; void ctkNetworkConnectorZeroMQTest::ctkNetworkConnectorZeroMQConstructorTest() { QVERIFY(m_NetWorkConnectorZeroMQ != NULL); } void ctkNetworkConnectorZeroMQTest::ctkNetworkConnectorZeroMQCommunictionTest() { QTime dieTime = QTime::currentTime().addSecs(3); while(QTime::currentTime() < dieTime) { QCoreApplication::processEvents(QEventLoop::AllEvents, 3); } } CTK_REGISTER_TEST(ctkNetworkConnectorZeroMQTest); #include "ctkNetworkConnectorZeroMQTest.moc"
3,225
1,011
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; sort(arr,arr+n); for(int i=1;i<n-1;i+=2) swap(arr[i],arr[i+1]); for(int i=0;i<n;i++) cout<<arr[i]<<' '; cout<<endl; } return 0; }
318
194
/* Copyright (c) 2018-2019 Oleg Linkin <maledictusdemagog@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "bookquotesmodel.h" #include "../sailreadsmanager.h" namespace Sailreads { BookQuotesModel::BookQuotesModel(QObject *parent) : QuotesBaseModel(parent) , m_WorkId(0) { } void BookQuotesModel::classBegin() { auto sm = SailreadsManager::Instance(); connect(sm, &SailreadsManager::gotBookQuotes, this, &BookQuotesModel::handleGotBookQuotes); } void BookQuotesModel::componentComplete() { } quint64 BookQuotesModel::GetWorkId() const { return m_WorkId; } void BookQuotesModel::SetWorkId(quint64 workId) { if (m_WorkId != workId) { m_WorkId = workId; m_CurrentPage = 1; SetHasMore(true); emit workIdChanged(); } } void BookQuotesModel::fetchMoreContent() { if (!m_WorkId) { return; } SailreadsManager::Instance()->loadBookQuotes(this, m_WorkId, m_CurrentPage); SetFetching(true); } void BookQuotesModel::loadBookQuotes() { if (!m_WorkId) { return; } Clear(); m_HasMore = true; m_CurrentPage = 1; SailreadsManager::Instance()->loadBookQuotes(this, m_WorkId, m_CurrentPage, false); SetFetching(true); } void BookQuotesModel::handleGotBookQuotes(quint64 workId, const PageCountedItems<Quote>& quotes) { if (m_WorkId != workId || !quotes.m_Items.count()) { return; } if (!quotes.m_Page && !quotes.m_PagesCount) { Clear(); } else if (quotes.m_Page == 1) { m_CurrentPage = quotes.m_Page; SetItems(quotes.m_Items); } else { AddItems(quotes.m_Items); } SetHasMore(quotes.m_Page != quotes.m_PagesCount); if (m_HasMore) { ++m_CurrentPage; } SetFetching(false); } } // namespace Sailreads
2,814
995
#include "chapter_08_design_patterns/problem_071_observable_vector_container.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include <sstream> // ostringstream TEST(problem_71_main, DISABLED_output) { std::ostringstream oss{}; problem_71_main(oss); EXPECT_THAT(oss.str(), ::testing::HasSubstr( "Creating the observable vectors:\n" "\tov_0: []\n" "\tov_1: [0, 3.14, 6.28, 9.42, 12.56]\n" "\tov_2: [1.5, 1.5, 1.5]\n" "\tov_3: ['o', ',', ' ', 'u']\n" "\tov_4: []\n" "\n" "Pushing back to ov_0:\n" "\t[observer 0] received notification: <id : 0, type : push_back(0)>\n" "\t[observer 0] observable vector 0: [\"Tush! Never tell me;\"]\n" "\t[observer 0] received notification: <id : 1, type : push_back(1)>\n" "\t[observer 0] observable vector 0: [\"Tush! Never tell me;\", \"I take it much unkindly.\"]\n" "\n" "Copy assigning from ov_3:\n" "Popping back from the copied-to vector:\n" "\n" "Move assigning from ov_1:\n" "Pushing back to the moved-to vector:\n" "\n" "Copy assigning to ov_3:\n" "\t[observer 3] received notification: <id : 2, type : copy_assignment()>\n" "\t[observer 3] observable vector 3: ['o', ',', ' ']\n" "\n" "Move assigning to ov_4:\n" "\t[observer 4] received notification: <id : 3, type : move_assignment()>\n" "\t[observer 4] sum of elements of observable vector 4: 12\n" "\n" "Detaching from ov_0:\n" "Pushing back to ov_0:\n" )); }
1,616
634
/* * ref: https://github.com/onestraw/epoll-example */ #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <fcntl.h> //#include <sys/epoll.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <stdbool.h> #include <time.h> #include <fcntl.h> #include "emapi.h" #include <sstream> #include <cstring> #include "EmapiTagwireWrapper.h" using namespace emapi; using std::string; using std::stringstream; using std::cout; EmapiTagwireWrapper tpl_req; #define DEFAULT_PORT 6565 // 8080 #define DEFAULT_HOST "127.0.0.1" //#define MAX_CONN 16 //#define MAX_EVENTS 32 //#define BUF_SIZE 16 #define MAX_LINE 512 bool g_interactive = true; unsigned short g_port= DEFAULT_PORT; char g_host[HOST_NAME_MAX]=DEFAULT_HOST; char g_send_string[MAX_LINE-1]="test send"; int g_send_repeats = 1 ; // default -1 = send once struct timespec g_send_wait; void print_twstring(char * s) { if( !s ) { printf("null string\n"); return; } char * copy = strdup(s); string tpl_str{copy}; try { cout << "got tagwire string before: \"" << tpl_str << "\"\n"; TagwireDecoder decoder{ (const unsigned char *)tpl_str.c_str(), 0,(unsigned int) tpl_str.size()}; //cout << "got tagwire string : \"" << tpl_str << "\"\n"; tpl_req.unpack(decoder); cout << "unpacked:\n" << tpl_req.to_string(""); } catch ( std::exception e ) { printf("Tagwire Decode failed\n"); } free(copy); } void test_tpl() { stringstream ss; ss << EmapiMessageType_EmapiTaxPreLogonReq << "=[" << "1=T" << "|2=member" << "|3=user" << "|4=1" << "|5=2" << "|6=3" << "]"; string tpl_str{ss.str()}; TagwireDecoder decoder{ (const unsigned char *)tpl_str.c_str(), 0,(unsigned int) tpl_str.size()}; cout << "test string : \"" << tpl_str << "\"\n"; tpl_req.unpack(decoder); cout << "wrapper\n" << tpl_req.to_string(""); TagwireEncoder encoder(tpl_req.getMessageType()); tpl_req.pack(encoder); cout << "packed: " << encoder.getBuffer() << "\n"; } /** Returns true on success, or false if there was an error */ bool set_socket_blocking(int fd, bool blocking) { if (fd < 0) return false; #ifdef _WIN32 unsigned long mode = blocking ? 0 : 1; return (ioctlsocket(fd, FIONBIO, &mode) == 0) ? true : false; #else int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) return false; flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK); return (fcntl(fd, F_SETFL, flags) == 0) ? true : false; #endif } static void set_sockaddr(struct sockaddr_in *addr) { bzero((char *)addr, sizeof(struct sockaddr_in)); addr->sin_family = AF_INET; addr->sin_addr.s_addr = INADDR_ANY; addr->sin_port = htons(g_port); } void print_menu_options() { printf("options:\n*1 send taxprelogonreq\n"); printf("options:\n*2 send taxconnnectorentry\n"); printf("options:\n*3 send taxprelogonrsp\n"); printf("options:\n*4 send abstractmeevent\n"); printf("options:\n*5 send proteusrefdatamessage\n"); printf("options:\n*6 send requestmessage\n"); printf("options:\n*7 send simpleresponse\n"); printf("options:\n*8 send responsemessage\n"); printf("options:\n*9 send msg_publicmulticastaddress\n"); printf("options:\n*a send msg_publicmulticastpartition\n"); printf("options:\n*b send msg_publicmulticastcontent\n"); printf("options:\n*c send msg_taxlogonreq\n"); printf("options:\n*d send msg_taxlogonrsp\n"); } void client_run() { int n; int c; int sockfd; char buf[MAX_LINE]; struct sockaddr_in srv_addr; sockfd = socket(AF_INET, SOCK_STREAM, 0); set_sockaddr(&srv_addr); bool success = set_socket_blocking( sockfd, false ); printf("set socket non-blocking returned %d\n",success ); success = connect(sockfd, (struct sockaddr *)&srv_addr, sizeof(srv_addr)); //while( errno == EINPROGRESS ){ printf("waiting to connect...\n"); usleep(1000000); //} // perror("connect()"); // exit(1); //} printf("connected\n"); char msg_abstractmeevent[]="238=[1=1|2=2|3=timeofevent|4=T]"; char msg_proteusrefdatamessage[]="236=[1=key|2=cacheid|3=3|4=4|5=uniqueobjectid|6=timestamp|7=F]"; char msg_taxprelogonreq[]="66=[1=T|2=member|3=user|4=1|5=2|6=3]"; string msg_taxconnectorentry= "68=[1=1|2=ipaddress|3=3|4=[4|4]|5=[5|5]]"; string tce = msg_taxconnectorentry; string msg_taxprelogonrsp="64=[1=1|2=message|3=[3|3]|4=requestid|5=reply|6=address|7=7|8=8|" "9=[" + tce + "|" + tce + "]|10=messagref]"; char msg_requestmessage[]="237=[1=T]"; char msg_simpleresp[]="231=[1=1|2=message|3=[3|3]|4=requestid|5=reply|6=messagereference]"; char msg_responsemessage[]="230=[1=1|2=message|3=[3|3]|4=requestid|5=messagereference]"; string msg_publicmulticastaddress = "110=[1=key|2=cacheid|3=3|4=4|5=uniqueobjectid|6=timestamp|7=pmcaddress|8=8|9=pmcsourceaddress|10=pmcpartitionid|11=F]"; string pma = msg_publicmulticastaddress; string msg_publicmulticastpartition = "109=[1=key|2=cacheid|3=3|4=4|5=uniqueobjectid|6=timestamp|7=pmcpartitionid|8=payloadcontenttype|10=10|11=11|12=12|13=pmccontentid|14=[" + pma + "|" + pma + "]|15=F]"; string pmp = msg_publicmulticastpartition; string msg_publicmulticastcontent = "108=[1=key|2=cacheid|3=3|4=4|5=uniqueobjectid|6=timestamp|7=pmccontentid|8=flowidlist" "|9=subscriptiongrouplist|10=[" + pmp + "|" + pmp + "]|11=F]"; string pmc = msg_publicmulticastcontent; string msg_taxlogonreq="63=[1=T|2=member|3=user|4=password|5=5|6=6|7=7|8=8|9=9]"; string msg_taxlogonrsp="64=[1=1|2=message|3=[3|3]|4=requestid|5=reply|6=T|7=7|8=T|" "9=systemname|10=10|11=11|12=12|13=[" + pmc + "|" + pmc + "]|14=messagref]"; if( g_interactive ) { printf("Interactive mode.\n" "Enter q[+newline] to quit\n"); char copy_recv_buffer[MAX_LINE+1]; char send_buffer[MAX_LINE+1]; for (;;) { memset( send_buffer, 0 , MAX_LINE+1 ); memset( copy_recv_buffer, 0 , MAX_LINE+1 ); char * p = copy_recv_buffer; printf("> "); fgets(buf, sizeof(buf), stdin); if( buf[0]=='q') { break; } else if (buf[0]=='*') { if( buf[1]=='?' ) { print_menu_options(); continue; } else if ( buf[1]=='1' ) { strcpy( send_buffer, msg_taxprelogonreq ); //c = strlen( send_buffer ); } else if ( buf[1]=='2' ) { strcpy( send_buffer, msg_taxconnectorentry.c_str()); //c = strlen( send_buffer ); } else if ( buf[1]=='3' ) { strcpy( send_buffer, msg_taxprelogonrsp.c_str()); } else if ( buf[1]=='4' ) { strcpy( send_buffer,msg_abstractmeevent ); } else if ( buf[1]=='5' ) { strcpy( send_buffer, msg_proteusrefdatamessage ); } else if ( buf[1]=='6' ) { strcpy( send_buffer, msg_requestmessage ); } else if ( buf[1]=='7' ) { strcpy( send_buffer, msg_simpleresp ); } else if ( buf[1]=='8' ) { strcpy( send_buffer, msg_responsemessage ); } else if ( buf[1]=='9' ) { strcpy( send_buffer, msg_publicmulticastaddress.c_str()); } else if ( buf[1]=='a' ) { strcpy( send_buffer, msg_publicmulticastpartition.c_str()); } else if ( buf[1]=='b' ) { strcpy( send_buffer, msg_publicmulticastcontent.c_str()); } else if ( buf[1]=='c' ) { strcpy( send_buffer, msg_taxlogonreq.c_str()); } else if ( buf[1]=='d' ) { strcpy( send_buffer, msg_taxlogonrsp.c_str()); } else { printf("unrecognised option\n"); print_menu_options(); continue; } } else { strcpy( send_buffer, buf ) ; c = strlen( send_buffer ) - 1; send_buffer[c] = '\0'; } printf("sending message: \"%s\"\n", send_buffer ); print_twstring( send_buffer ); write(sockfd, send_buffer, strlen(send_buffer) + 1); int countdown = 1000; bzero(buf, sizeof(buf)); do { n = read(sockfd, buf, sizeof(buf)); if(n>1) { printf("recv %d bytes: %s\n", n, buf); memcpy( p, buf, n); p+= n; bzero(buf, sizeof(buf)); } usleep(1000); //c -= n; //if (c <= 0) { // break; //} } while( errno == EWOULDBLOCK && ( n<1 ) && countdown-->0 ); *p=0; // add null terminator printf("recv message:\"%s\"\n",copy_recv_buffer); print_twstring( copy_recv_buffer ); } } else { const char * send_array[17]; int i=0; send_array[i++]=msg_abstractmeevent; send_array[i++]=msg_proteusrefdatamessage; send_array[i++]=msg_taxprelogonreq; send_array[i++]= msg_requestmessage; send_array[i++]= msg_simpleresp; send_array[i++]= msg_responsemessage; send_array[i++]= msg_taxconnectorentry.c_str(); //send_array[i++]= msg_taxconnectorentry.c_str(); send_array[i++]= msg_publicmulticastaddress.c_str(); //send_array[i++]= msg_publicmulticastaddress.c_str(); //send_array[i++]= msg_publicmulticastpartition.c_str(); //send_array[i++]= msg_publicmulticastpartition.c_str(); //send_array[i++]= msg_publicmulticastcontent.c_str(); //send_array[i++]= msg_publicmulticastcontent.c_str(); send_array[i++]= msg_taxlogonreq.c_str(); //send_array[i++]= msg_taxlogonrsp.c_str(); send_array[i++]= msg_taxprelogonrsp.c_str(); int last_index = i; char copy_recv_buffer[MAX_LINE+1]; for( i = 0 ; i <= last_index ; i++ ) { strcpy( g_send_string, send_array[i]); int sent_count = 0 ; while( g_send_repeats == -1 || sent_count < g_send_repeats ) { printf("\n============================================================\n"); //print_twstring( g_send_string ); printf("sending message: \"%s\"\n", g_send_string ); strncpy(buf, g_send_string, sizeof(buf)-1); c = strlen(buf) - 1; write(sockfd, buf, c + 1); memset( copy_recv_buffer, 0 , MAX_LINE+1 ); char * p = copy_recv_buffer; int countdown = 1000; bzero(buf, sizeof(buf)); do { n = read(sockfd, buf, sizeof(buf)); if(n>1) { printf("recv %d bytes: %s\n", n, buf); memcpy( p, buf, n); p+= n; bzero(buf, sizeof(buf)); } usleep(1000); //c -= n; //if (c <= 0) { // break; //} } while( errno == EWOULDBLOCK && ( n<1 ) && countdown-->0 ); *p=0; // add null terminator printf("recv message:\"%s\"\n",copy_recv_buffer); //print_twstring( copy_recv_buffer ); nanosleep( &g_send_wait, 0 ); sent_count++; } } printf("exiting batch mode ... ok\n"); } close(sockfd); } int main(int argc, char *argv[]) { test_tpl(); g_send_wait.tv_sec=0; g_send_wait.tv_nsec=999999999; int opt; while ((opt = getopt(argc, argv, "bih:p:s:r:w:")) != -1) { switch (opt) { case 'b': g_interactive = false; break; case 'i': g_interactive = true; break; case 'h': strcpy(g_host,optarg); break; case 'p': g_port = atoi(optarg); break; case 's': memset(g_send_string, 0, sizeof(g_send_string)); strncpy(g_send_string,optarg,sizeof(g_send_string)-1); break; case 'r': g_send_repeats = atoi(optarg); break; case 'w': g_send_wait.tv_nsec = atol(optarg); if( g_send_wait.tv_nsec > 999999999 ) g_send_wait.tv_nsec = 999999999; break; default: printf("usage: %s [-s send-string] [-w wait time (nanos)]\n" "[-r repeats (number of repeats)] [-i (interactive)]\n" "[h HOST] -p PORT\n", argv[0]); exit(1); } } printf("client using host %s port %hu %s\n",g_host,g_port, g_interactive?"(interactive mode)":"(batch mode)"); client_run(); return 0; }
11,357
5,335
/*############################################################################## VSQLite++ - virtuosic bytes SQLite3 C++ wrapper Copyright (c) 2014 mickey mickey.mouse-1985@libero.it 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 virtuosic bytes nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ##############################################################################*/ #include <sqlite/connection.hpp> #include <sqlite/savepoint.hpp> #include <sqlite/execute.hpp> namespace sqlite{ savepoint::savepoint(connection & con, std::string const & name) : m_con(con) , m_name(name){ exec("SAVEPOINT " + m_name); m_isActive = true; } savepoint::~savepoint(){ if (m_isActive) release(); } void savepoint::release(){ exec("RELEASE SAVEPOINT " + m_name); m_isActive = false; } void savepoint::rollback() { exec("ROLLBACK TRANSACTION TO SAVEPOINT " + m_name); } void savepoint::exec(std::string const & cmd){ execute(m_con,cmd,true); } }
2,417
783
// // Created by Jason Mohoney on 7/9/20. // #include "batch.h" #include "config.h" using std::get; Batch::Batch(bool train) : device_transfer_(0), host_transfer_(0), timer_(false) { status_ = BatchStatus::Waiting; train_ = train; device_id_ = -1; } void Batch::localSample() { int num_deg; if (train_) { num_deg = (int) (marius_options.training.negatives * marius_options.training.degree_fraction); } else { num_deg = (int) (marius_options.evaluation.negatives * marius_options.evaluation.degree_fraction); if (marius_options.evaluation.negative_sampling_access == NegativeSamplingAccess::All) { // no need to sample by degree when using all nodes for sampling negatives src_all_neg_embeddings_ = src_global_neg_embeddings_; dst_all_neg_embeddings_ = dst_global_neg_embeddings_; return; } } if (num_deg == 0) { src_all_neg_embeddings_ = src_global_neg_embeddings_; dst_all_neg_embeddings_ = dst_global_neg_embeddings_; return; } int num_chunks = src_global_neg_embeddings_.size(0); int num_per_chunk = (int) ceil((float) batch_size_ / num_chunks); // Sample for src and update filter int src_neg_size = src_global_neg_embeddings_.size(1); Indices src_sample = torch::randint(0, batch_size_, {num_chunks, num_deg}, src_global_neg_embeddings_.device()).to(torch::kInt64); auto chunk_ids = (src_sample.floor_divide(num_per_chunk)).view({num_chunks, -1}); auto inv_mask = chunk_ids - torch::arange(0, num_chunks, src_global_neg_embeddings_.device()).view({num_chunks, -1}); auto mask = (inv_mask == 0); auto temp_idx = torch::nonzero(mask); auto id_offset = src_sample.flatten(0, 1).index_select(0, (temp_idx.select(1, 0) * num_deg + temp_idx.select(1, 1))); auto sample_offset = temp_idx.select(1, 1); src_all_neg_embeddings_ = torch::cat({src_global_neg_embeddings_, src_pos_embeddings_.index_select(0, src_sample.flatten(0, 1)).view({num_chunks, num_deg, -1})}, 1); src_neg_filter_ = id_offset * src_all_neg_embeddings_.size(1) + (src_neg_size + sample_offset); // Sample for dst and update filter int dst_neg_size = dst_global_neg_embeddings_.size(1); Indices dst_sample = torch::randint(0, batch_size_, {num_chunks, num_deg}, dst_global_neg_embeddings_.device()).to(torch::kInt64); chunk_ids = (dst_sample.floor_divide(num_per_chunk)).view({num_chunks, -1}); inv_mask = chunk_ids - torch::arange(0, num_chunks, dst_global_neg_embeddings_.device()).view({num_chunks, -1}); mask = (inv_mask == 0); temp_idx = torch::nonzero(mask); id_offset = dst_sample.flatten(0, 1).index_select(0, (temp_idx.select(1, 0) * num_deg + temp_idx.select(1, 1))); sample_offset = temp_idx.select(1, 1); dst_all_neg_embeddings_ = torch::cat({dst_global_neg_embeddings_, dst_pos_embeddings_.index_select(0, dst_sample.flatten(0, 1)).view({num_chunks, num_deg, -1})}, 1); dst_neg_filter_ = id_offset * dst_all_neg_embeddings_.size(1) + (dst_neg_size + sample_offset); } void Batch::accumulateUniqueIndices() { Indices emb_idx = torch::cat({src_pos_indices_, dst_pos_indices_, src_neg_indices_, dst_neg_indices_}); auto unique_tup = torch::_unique2(emb_idx, true, true, false); unique_node_indices_ = get<0>(unique_tup); Indices emb_mapping = get<1>(unique_tup); int64_t curr = 0; int64_t size = batch_size_; src_pos_indices_mapping_ = emb_mapping.narrow(0, curr, size); curr += size; dst_pos_indices_mapping_ = emb_mapping.narrow(0, curr, size); curr += size; size = src_neg_indices_.size(0); src_neg_indices_mapping_ = emb_mapping.narrow(0, curr, size); curr += size; dst_neg_indices_mapping_ = emb_mapping.narrow(0, curr, size); SPDLOG_TRACE("Batch: {} Accumulated {} unique embeddings", batch_id_, unique_node_indices_.size(0)); if (marius_options.general.num_relations > 1) { auto rel_unique_tup = torch::_unique2(rel_indices_, true, true, false); unique_relation_indices_ = get<0>(rel_unique_tup); rel_indices_mapping_ = get<1>(rel_unique_tup); SPDLOG_TRACE("Batch: {} Accumulated {} unique relations", batch_id_, unique_relation_indices_.size(0)); } status_ = BatchStatus::AccumulatedIndices; } void Batch::embeddingsToDevice(int device_id) { device_id_ = device_id; if (marius_options.general.device == torch::kCUDA) { device_transfer_ = CudaEvent(device_id); host_transfer_ = CudaEvent(device_id); string device_string = "cuda:" + std::to_string(device_id); src_pos_indices_mapping_ = src_pos_indices_mapping_.to(device_string); dst_pos_indices_mapping_ = dst_pos_indices_mapping_.to(device_string); src_neg_indices_mapping_ = src_neg_indices_mapping_.to(device_string); dst_neg_indices_mapping_ = dst_neg_indices_mapping_.to(device_string); SPDLOG_TRACE("Batch: {} Indices sent to device", batch_id_); if (marius_options.storage.embeddings != BackendType::DeviceMemory) { unique_node_embeddings_ = unique_node_embeddings_.to(device_string); SPDLOG_TRACE("Batch: {} Embeddings sent to device", batch_id_); if (train_) { unique_node_embeddings_state_ = unique_node_embeddings_state_.to(device_string); SPDLOG_TRACE("Batch: {} Node State sent to device", batch_id_); } } if (marius_options.general.num_relations > 1) { if (marius_options.storage.relations != BackendType::DeviceMemory) { unique_relation_embeddings_ = unique_relation_embeddings_.to(device_string); rel_indices_mapping_ = rel_indices_mapping_.to(device_string); SPDLOG_TRACE("Batch: {} Relations sent to device", batch_id_); if (train_) { unique_relation_embeddings_state_ = unique_relation_embeddings_state_.to(device_string); SPDLOG_TRACE("Batch: {} Relation State sent to device", batch_id_); } } else { unique_relation_indices_ = unique_relation_indices_.to(device_string); rel_indices_mapping_ = rel_indices_mapping_.to(device_string); } } } device_transfer_.record(); status_ = BatchStatus::TransferredToDevice; } void Batch::prepareBatch() { device_transfer_.synchronize(); int64_t num_chunks = 0; int64_t negatives = 0; if (train_) { num_chunks = marius_options.training.number_of_chunks; negatives = marius_options.training.negatives * (1 - marius_options.training.degree_fraction); } else { num_chunks = marius_options.evaluation.number_of_chunks; negatives = marius_options.evaluation.negatives * (1 - marius_options.evaluation.degree_fraction); if (marius_options.evaluation.negative_sampling_access == NegativeSamplingAccess::All) { num_chunks = 1; negatives = marius_options.general.num_nodes; } } src_pos_embeddings_ = unique_node_embeddings_.index_select(0, src_pos_indices_mapping_); dst_pos_embeddings_ = unique_node_embeddings_.index_select(0, dst_pos_indices_mapping_); src_global_neg_embeddings_ = unique_node_embeddings_.index_select(0, src_neg_indices_mapping_).reshape({num_chunks, negatives, marius_options.model.embedding_size}); dst_global_neg_embeddings_ = unique_node_embeddings_.index_select(0, dst_neg_indices_mapping_).reshape({num_chunks, negatives, marius_options.model.embedding_size}); if (marius_options.general.num_relations > 1) { src_relation_emebeddings_ = unique_relation_embeddings_.index_select(1, rel_indices_mapping_).select(0, 0); dst_relation_emebeddings_ = unique_relation_embeddings_.index_select(1, rel_indices_mapping_).select(0, 1); } if (train_) { src_pos_embeddings_.requires_grad_(); dst_pos_embeddings_.requires_grad_(); src_global_neg_embeddings_.requires_grad_(); dst_global_neg_embeddings_.requires_grad_(); if (marius_options.general.num_relations > 1) { src_relation_emebeddings_.requires_grad_(); dst_relation_emebeddings_.requires_grad_(); } } SPDLOG_TRACE("Batch: {} prepared for compute", batch_id_); status_ = BatchStatus::PreparedForCompute; } void Batch::accumulateGradients() { auto grad_opts = torch::TensorOptions().dtype(torch::kFloat32).device(src_pos_embeddings_.device()); unique_node_gradients_ = torch::zeros({unique_node_indices_.size(0), marius_options.model.embedding_size}, grad_opts); unique_node_gradients_.index_add_(0, src_pos_indices_mapping_, src_pos_embeddings_.grad()); unique_node_gradients_.index_add_(0, src_neg_indices_mapping_, src_global_neg_embeddings_.grad().flatten(0, 1)); unique_node_gradients_.index_add_(0, dst_pos_indices_mapping_, dst_pos_embeddings_.grad()); unique_node_gradients_.index_add_(0, dst_neg_indices_mapping_, dst_global_neg_embeddings_.grad().flatten(0, 1)); SPDLOG_TRACE("Batch: {} accumulated node gradients", batch_id_); if (marius_options.general.num_relations > 1) { unique_relation_gradients_ = torch::zeros({2, unique_relation_indices_.size(0), marius_options.model.embedding_size}, grad_opts); unique_relation_gradients_.index_add_(1, rel_indices_mapping_, torch::stack({src_relation_emebeddings_.grad(), dst_relation_emebeddings_.grad()})); SPDLOG_TRACE("Batch: {} accumulated relation gradients", batch_id_); unique_relation_gradients2_ = unique_relation_gradients_.pow(2); unique_relation_embeddings_state_.add_(unique_relation_gradients2_); unique_relation_gradients_ = -marius_options.training.learning_rate * (unique_relation_gradients_ / ((unique_relation_embeddings_state_).sqrt().add_(1e-9))); } unique_node_gradients2_ = unique_node_gradients_.pow(2); unique_node_embeddings_state_.add_(unique_node_gradients2_); unique_node_gradients_ = -marius_options.training.learning_rate * (unique_node_gradients_ / ((unique_node_embeddings_state_).sqrt().add_(1e-9))); SPDLOG_TRACE("Batch: {} adjusted gradients", batch_id_); src_pos_embeddings_ = torch::Tensor(); dst_pos_embeddings_ = torch::Tensor(); src_global_neg_embeddings_ = torch::Tensor(); dst_global_neg_embeddings_ = torch::Tensor(); src_all_neg_embeddings_ = torch::Tensor(); dst_all_neg_embeddings_ = torch::Tensor(); src_relation_emebeddings_ = torch::Tensor(); dst_relation_emebeddings_ = torch::Tensor(); unique_node_embeddings_state_ = torch::Tensor(); unique_relation_embeddings_state_ = torch::Tensor(); src_neg_filter_ = torch::Tensor(); dst_neg_filter_ = torch::Tensor(); SPDLOG_TRACE("Batch: {} cleared gpu embeddings and gradients", batch_id_); status_ = BatchStatus::AccumulatedGradients; } void Batch::embeddingsToHost() { torch::DeviceType emb_device = torch::kCPU; if (marius_options.storage.embeddings == BackendType::DeviceMemory) { // only single gpu setup SPDLOG_TRACE("Batch: {} embedding storage on device", batch_id_); emb_device = marius_options.general.device; } if (emb_device == torch::kCPU && unique_node_gradients_.device().type() == torch::kCUDA) { auto grad_opts = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCPU).pinned_memory(true); Gradients temp_grads = torch::empty(unique_node_gradients_.sizes(), grad_opts); temp_grads.copy_(unique_node_gradients_, true); Gradients temp_grads2 = torch::empty(unique_node_gradients2_.sizes(), grad_opts); temp_grads2.copy_(unique_node_gradients2_, true); unique_node_gradients_ = temp_grads; unique_node_gradients2_ = temp_grads2; SPDLOG_TRACE("Batch: {} transferred node embeddings to host", batch_id_); } if (marius_options.general.num_relations > 1) { torch::DeviceType rel_device = torch::kCPU; if (marius_options.storage.relations == BackendType::DeviceMemory) { SPDLOG_TRACE("Batch: {} relation storage on device", batch_id_); rel_device = marius_options.general.device; } if (rel_device == torch::kCPU && unique_relation_gradients_.device().type() == torch::kCUDA) { auto grad_opts = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCPU).pinned_memory(true); Gradients temp_grads = torch::empty(unique_relation_gradients_.sizes(), grad_opts); temp_grads.copy_(unique_relation_gradients_, true); Gradients temp_grads2 = torch::empty(unique_relation_gradients2_.sizes(), grad_opts); temp_grads2.copy_(unique_relation_gradients2_, true); unique_relation_gradients_ = temp_grads; unique_relation_gradients2_ = temp_grads2; SPDLOG_TRACE("Batch: {} transferred relation embeddings to host", batch_id_); } } host_transfer_.record(); host_transfer_.synchronize(); status_ = BatchStatus::TransferredToHost; } void Batch::clear() { unique_node_indices_ = torch::Tensor(); unique_node_embeddings_ = torch::Tensor(); unique_node_gradients_ = torch::Tensor(); unique_node_gradients2_ = torch::Tensor(); unique_node_embeddings_state_ = torch::Tensor(); unique_relation_indices_ = torch::Tensor(); unique_relation_embeddings_ = torch::Tensor(); unique_relation_gradients_ = torch::Tensor(); unique_relation_gradients2_ = torch::Tensor(); unique_relation_embeddings_state_ = torch::Tensor(); src_pos_indices_mapping_ = torch::Tensor(); dst_pos_indices_mapping_ = torch::Tensor(); rel_indices_mapping_ = torch::Tensor(); src_neg_indices_mapping_ = torch::Tensor(); dst_neg_indices_mapping_ = torch::Tensor(); src_pos_indices_ = torch::Tensor(); dst_pos_indices_ = torch::Tensor(); rel_indices_ = torch::Tensor(); src_neg_indices_ = torch::Tensor(); dst_neg_indices_ = torch::Tensor(); src_pos_embeddings_ = torch::Tensor(); dst_pos_embeddings_ = torch::Tensor(); src_relation_emebeddings_ = torch::Tensor(); dst_relation_emebeddings_ = torch::Tensor(); src_global_neg_embeddings_ = torch::Tensor(); dst_global_neg_embeddings_ = torch::Tensor(); src_all_neg_embeddings_ = torch::Tensor(); dst_all_neg_embeddings_ = torch::Tensor(); src_neg_filter_ = torch::Tensor(); dst_neg_filter_ = torch::Tensor(); SPDLOG_TRACE("Batch: {} cleared", batch_id_); status_ = BatchStatus::Done; } PartitionBatch::PartitionBatch(bool train) : Batch(train) {} // TODO optionally keep unique index data around so it doesn't need to be recomputed in future epochs void PartitionBatch::clear() { Batch::clear(); pos_uniques_idx_ = torch::Tensor(); src_pos_uniques_idx_ = torch::Tensor(); dst_pos_uniques_idx_ = torch::Tensor(); neg_uniques_idx_ = torch::Tensor(); } void PartitionBatch::accumulateUniqueIndices() { NegativeSamplingAccess negative_sampling_access = marius_options.training.negative_sampling_access; if (!train_) { negative_sampling_access = marius_options.evaluation.negative_sampling_access; } if (negative_sampling_access == NegativeSamplingAccess::Uniform) { if (src_partition_idx_ == dst_partition_idx_) { Indices emb_idx = torch::cat({src_pos_indices_, dst_pos_indices_, src_neg_indices_, dst_neg_indices_}); auto unique_tup = torch::_unique2(emb_idx, true, true, false); unique_node_indices_ = get<0>(unique_tup); Indices emb_mapping = get<1>(unique_tup); int64_t curr = 0; int64_t size = batch_size_; src_pos_indices_mapping_ = emb_mapping.narrow(0, curr, size); curr += size; dst_pos_indices_mapping_ = emb_mapping.narrow(0, curr, size); curr += size; size = src_neg_indices_.size(0); src_neg_indices_mapping_ = emb_mapping.narrow(0, curr, size); curr += size; dst_neg_indices_mapping_ = emb_mapping.narrow(0, curr, size); } else { Indices src_emb_idx = torch::cat({src_pos_indices_, src_neg_indices_}); auto src_pos_unique_tup = torch::_unique2(src_emb_idx, true, true, false); auto src_pos_uniques_idx = get<0>(src_pos_unique_tup); auto src_emb_mapping = get<1>(src_pos_unique_tup); int64_t curr = 0; int64_t size = batch_size_; src_pos_indices_mapping_ = src_emb_mapping.narrow(0, curr, size); curr += size; size = src_neg_indices_.size(0); src_neg_indices_mapping_ = src_emb_mapping.narrow(0, curr, size); Indices dst_emb_idx = torch::cat({dst_pos_indices_, dst_neg_indices_}); auto dst_pos_unique_tup = torch::_unique2(dst_emb_idx, true, true, false); auto dst_pos_uniques_idx = get<0>(dst_pos_unique_tup); auto dst_emb_mapping = get<1>(dst_pos_unique_tup) + src_pos_uniques_idx.size(0); curr = 0; size = batch_size_; dst_pos_indices_mapping_ = dst_emb_mapping.narrow(0, curr, size); curr += size; size = dst_neg_indices_.size(0); dst_neg_indices_mapping_ = dst_emb_mapping.narrow(0, curr, size); unique_node_indices_ = torch::cat({src_pos_uniques_idx, dst_pos_uniques_idx}); pos_uniques_idx_ = unique_node_indices_.narrow(0, 0, src_pos_uniques_idx.size(0) + dst_pos_uniques_idx.size(0)); src_pos_uniques_idx_ = unique_node_indices_.narrow(0, 0, src_pos_uniques_idx.size(0)); dst_pos_uniques_idx_ = unique_node_indices_.narrow(0, src_pos_uniques_idx.size(0), dst_pos_uniques_idx.size(0)); } } else { if (src_partition_idx_ == dst_partition_idx_) { // calculate uniques for positives Indices pos_emb_idx = torch::cat({src_pos_indices_, dst_pos_indices_}); auto pos_unique_tup = torch::_unique2(pos_emb_idx, true, true, false); auto pos_uniques_idx = get<0>(pos_unique_tup); Indices pos_emb_mapping = get<1>(pos_unique_tup); int64_t curr = 0; int64_t size = batch_size_; src_pos_indices_mapping_ = pos_emb_mapping.narrow(0, curr, size); curr += size; dst_pos_indices_mapping_ = pos_emb_mapping.narrow(0, curr, size); // calculate uniques for negatives Indices neg_uniques_idx; Indices neg_emb_idx = torch::cat({src_neg_indices_, dst_neg_indices_}); auto neg_unique_tup = torch::_unique2(neg_emb_idx, true, true, false); neg_uniques_idx = get<0>(neg_unique_tup); Indices neg_emb_mapping = get<1>(neg_unique_tup); curr = 0; size = src_neg_indices_.size(0); src_neg_indices_mapping_ = neg_emb_mapping.narrow(0, curr, size); curr += size; dst_neg_indices_mapping_ = neg_emb_mapping.narrow(0, curr, size); // add offset to negative mapping to account for the torch::cat src_neg_indices_mapping_ += pos_uniques_idx.size(0); dst_neg_indices_mapping_ += pos_uniques_idx.size(0); unique_node_indices_ = torch::cat({pos_uniques_idx, neg_uniques_idx}); pos_uniques_idx_ = unique_node_indices_.narrow(0, 0, pos_uniques_idx.size(0)); neg_uniques_idx_ = unique_node_indices_.narrow(0, pos_uniques_idx.size(0), neg_uniques_idx.size(0)); } else { auto src_pos_unique_tup = torch::_unique2(src_pos_indices_, true, true, false); auto src_pos_uniques_idx = get<0>(src_pos_unique_tup); src_pos_indices_mapping_ = get<1>(src_pos_unique_tup); auto dst_pos_unique_tup = torch::_unique2(dst_pos_indices_, true, true, false); auto dst_pos_uniques_idx = get<0>(dst_pos_unique_tup); dst_pos_indices_mapping_ = get<1>(dst_pos_unique_tup) + src_pos_uniques_idx.size(0); Indices neg_uniques_idx; int64_t size; int64_t curr; Indices neg_emb_idx = torch::cat({src_neg_indices_, dst_neg_indices_}); auto neg_unique_tup = torch::_unique2(neg_emb_idx, true, true, false); neg_uniques_idx = get<0>(neg_unique_tup); Indices neg_emb_mapping = get<1>(neg_unique_tup); curr = 0; size = src_neg_indices_.size(0); src_neg_indices_mapping_ = neg_emb_mapping.narrow(0, curr, size); curr += size; dst_neg_indices_mapping_ = neg_emb_mapping.narrow(0, curr, size); // add offset to negative mapping to account for the torch::cat src_neg_indices_mapping_ += src_pos_uniques_idx.size(0) + dst_pos_uniques_idx.size(0); dst_neg_indices_mapping_ += src_pos_uniques_idx.size(0) + dst_pos_uniques_idx.size(0); unique_node_indices_ = torch::cat({src_pos_uniques_idx, dst_pos_uniques_idx, neg_uniques_idx}); pos_uniques_idx_ = unique_node_indices_.narrow(0, 0, src_pos_uniques_idx.size(0) + dst_pos_uniques_idx.size(0)); src_pos_uniques_idx_ = unique_node_indices_.narrow(0, 0, src_pos_uniques_idx.size(0)); dst_pos_uniques_idx_ = unique_node_indices_.narrow(0, src_pos_uniques_idx.size(0), dst_pos_uniques_idx.size(0)); neg_uniques_idx_ = unique_node_indices_.narrow(0, src_pos_uniques_idx.size(0) + dst_pos_uniques_idx.size(0), neg_uniques_idx.size(0)); } } rel_indices_mapping_ = torch::zeros({1}, torch::kInt64); unique_relation_indices_ = torch::zeros({1}, torch::kInt64); if (marius_options.general.num_relations > 1) { auto rel_unique_tup = torch::_unique2(rel_indices_, true, true, false); unique_relation_indices_ = get<0>(rel_unique_tup); rel_indices_mapping_ = get<1>(rel_unique_tup); } status_ = BatchStatus::AccumulatedIndices; }
22,148
7,777
#include <cryptopp/osrng.h> using CryptoPP::AutoSeededRandomPool; #include <iostream> using std::cout; using std::cin; using std::cerr; using std::endl; #include <string> using std::string; #include <cstdlib> using std::exit; #include <cryptopp/cryptlib.h> using CryptoPP::Exception; #include <cryptopp/hex.h> using CryptoPP::HexEncoder; using CryptoPP::HexDecoder; #include <cryptopp/filters.h> using CryptoPP::StringSink; using CryptoPP::StringSource; using CryptoPP::StreamTransformationFilter; #include <cryptopp/aes.h> using CryptoPP::AES; #include <cryptopp/ccm.h> using CryptoPP::CTR_Mode; #include "assert.h" int main(int argc, char* argv[]) { // Seed Pseudo Random Number Generator AutoSeededRandomPool prng; // Build AES Key byte key[32]; prng.GenerateBlock(key, sizeof(key)); // Build IV byte iv[AES::BLOCKSIZE]; prng.GenerateBlock(iv, sizeof(iv)); string plain; string cipher, encoded, recovered; // Get Message From User cout << "Message:" << endl; getline(cin, plain); /*********************************\ \*********************************/ // Pretty print key encoded.clear(); StringSource(key, sizeof(key), true, new HexEncoder(new StringSink(encoded))); cout << "key: " << encoded << endl; // Pretty print iv encoded.clear(); StringSource(iv, sizeof(iv), true, new HexEncoder(new StringSink(encoded))); cout << "iv: " << encoded << endl; /*********************************\ \*********************************/ try { // Create the cipher text CTR_Mode< AES >::Encryption e; e.SetKeyWithIV(key, sizeof(key), iv); // The StreamTransformationFilter adds padding as required. StringSource(plain, true, new StreamTransformationFilter(e, new StringSink(cipher))); } catch(const CryptoPP::Exception& e) { cerr << e.what() << endl; exit(1); } /*********************************\ \*********************************/ // Print cipher text (represenstened in its hex form) encoded.clear(); StringSource(cipher, true, new HexEncoder(new StringSink(encoded))); cout << "cipher text: " << encoded << endl; /*********************************\ \*********************************/ return 0; }
2,284
816
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _COMPHELPER_UNO3_HXX_ #define _COMPHELPER_UNO3_HXX_ #include <osl/interlck.h> #include <comphelper/types.hxx> #include <com/sun/star/uno/XAggregation.hpp> #include <comphelper/sequence.hxx> #include <cppuhelper/typeprovider.hxx> //......................................................................... namespace comphelper { //......................................................................... //========================================================================= /// manipulate ref counts without calling acquire/release inline oslInterlockedCount increment(oslInterlockedCount& _counter) { return osl_incrementInterlockedCount(&_counter); } inline oslInterlockedCount decrement(oslInterlockedCount& _counter) { return osl_decrementInterlockedCount(&_counter); } //========================================================================= /** used for declaring UNO3-Defaults, i.e. acquire/release */ #define DECLARE_UNO3_DEFAULTS(classname, baseclass) \ virtual void SAL_CALL acquire() throw() { baseclass::acquire(); } \ virtual void SAL_CALL release() throw() { baseclass::release(); } \ void SAL_CALL PUT_SEMICOLON_AT_THE_END() /** used for declaring UNO3-Defaults, i.e. acquire/release if you want to forward all queryInterfaces to the base class, (e.g. if you overload queryAggregation) */ #define DECLARE_UNO3_AGG_DEFAULTS(classname, baseclass) \ virtual void SAL_CALL acquire() throw() { baseclass::acquire(); } \ virtual void SAL_CALL release() throw() { baseclass::release(); } \ virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(const ::com::sun::star::uno::Type& _rType) throw (::com::sun::star::uno::RuntimeException) \ { return baseclass::queryInterface(_rType); } \ void SAL_CALL PUT_SEMICOLON_AT_THE_END() /** Use this macro to forward XComponent methods to base class When using the ::cppu::WeakComponentImplHelper base classes to implement a UNO interface, a problem occurs when the interface itself already derives from XComponent (like e.g. awt::XWindow or awt::XControl): ::cppu::WeakComponentImplHelper is then still abstract. Using this macro in the most derived class definition provides overrides for the XComponent methods, forwarding them to the given baseclass. @param classname Name of the class this macro is issued within @param baseclass Name of the baseclass that should have the XInterface methods forwarded to - that's usually the WeakComponentImplHelperN base @param implhelper Name of the baseclass that should have the XComponent methods forwarded to - in the case of the WeakComponentImplHelper, that would be ::cppu::WeakComponentImplHelperBase */ #define DECLARE_UNO3_XCOMPONENT_DEFAULTS(classname, baseclass, implhelper) \ virtual void SAL_CALL acquire() throw() { baseclass::acquire(); } \ virtual void SAL_CALL release() throw() { baseclass::release(); } \ virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException) \ { \ implhelper::dispose(); \ } \ virtual void SAL_CALL addEventListener( \ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > const & xListener ) throw (::com::sun::star::uno::RuntimeException) \ { \ implhelper::addEventListener(xListener); \ } \ virtual void SAL_CALL removeEventListener( \ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > const & xListener ) throw (::com::sun::star::uno::RuntimeException) \ { \ implhelper::removeEventListener(xListener); \ } \ void SAL_CALL PUT_SEMICOLON_AT_THE_END() /** Use this macro to forward XComponent methods to base class When using the ::cppu::WeakComponentImplHelper base classes to implement a UNO interface, a problem occurs when the interface itself already derives from XComponent (like e.g. awt::XWindow or awt::XControl): ::cppu::WeakComponentImplHelper is then still abstract. Using this macro in the most derived class definition provides overrides for the XComponent methods, forwarding them to the given baseclass. @param classname Name of the class this macro is issued within @param baseclass Name of the baseclass that should have the XInterface methods forwarded to - that's usually the WeakComponentImplHelperN base @param implhelper Name of the baseclass that should have the XComponent methods forwarded to - in the case of the WeakComponentImplHelper, that would be ::cppu::WeakComponentImplHelperBase */ #define DECLARE_UNO3_XCOMPONENT_AGG_DEFAULTS(classname, baseclass, implhelper) \ virtual void SAL_CALL acquire() throw() { baseclass::acquire(); } \ virtual void SAL_CALL release() throw() { baseclass::release(); } \ virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(const ::com::sun::star::uno::Type& _rType) throw (::com::sun::star::uno::RuntimeException) \ { return baseclass::queryInterface(_rType); } \ virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException) \ { \ implhelper::dispose(); \ } \ virtual void SAL_CALL addEventListener( \ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > const & xListener ) throw (::com::sun::star::uno::RuntimeException) \ { \ implhelper::addEventListener(xListener); \ } \ virtual void SAL_CALL removeEventListener( \ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener > const & xListener ) throw (::com::sun::star::uno::RuntimeException) \ { \ implhelper::removeEventListener(xListener); \ } \ void SAL_CALL PUT_SEMICOLON_AT_THE_END() //===================================================================== //= deriving from multiple XInterface-derived classes //===================================================================== //= forwarding/merging XInterface funtionality //===================================================================== #define DECLARE_XINTERFACE( ) \ virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); \ virtual void SAL_CALL acquire() throw(); \ virtual void SAL_CALL release() throw(); #define IMPLEMENT_FORWARD_REFCOUNT( classname, refcountbase ) \ void SAL_CALL classname::acquire() throw() { refcountbase::acquire(); } \ void SAL_CALL classname::release() throw() { refcountbase::release(); } #define IMPLEMENT_FORWARD_XINTERFACE2( classname, refcountbase, baseclass2 ) \ IMPLEMENT_FORWARD_REFCOUNT( classname, refcountbase ) \ ::com::sun::star::uno::Any SAL_CALL classname::queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException) \ { \ ::com::sun::star::uno::Any aReturn = refcountbase::queryInterface( _rType ); \ if ( !aReturn.hasValue() ) \ aReturn = baseclass2::queryInterface( _rType ); \ return aReturn; \ } #define IMPLEMENT_FORWARD_XINTERFACE3( classname, refcountbase, baseclass2, baseclass3 ) \ IMPLEMENT_FORWARD_REFCOUNT( classname, refcountbase ) \ ::com::sun::star::uno::Any SAL_CALL classname::queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException) \ { \ ::com::sun::star::uno::Any aReturn = refcountbase::queryInterface( _rType ); \ if ( !aReturn.hasValue() ) \ { \ aReturn = baseclass2::queryInterface( _rType ); \ if ( !aReturn.hasValue() ) \ aReturn = baseclass3::queryInterface( _rType ); \ } \ return aReturn; \ } //===================================================================== //= forwarding/merging XTypeProvider funtionality //===================================================================== #define DECLARE_XTYPEPROVIDER( ) \ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException); \ virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw (::com::sun::star::uno::RuntimeException); #define IMPLEMENT_GET_IMPLEMENTATION_ID( classname ) \ ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL classname::getImplementationId( ) throw (::com::sun::star::uno::RuntimeException) \ { \ static ::cppu::OImplementationId* pId = NULL; \ if (!pId) \ { \ ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); \ if (!pId) \ { \ static ::cppu::OImplementationId aId; \ pId = &aId; \ } \ } \ return pId->getImplementationId(); \ } #define IMPLEMENT_FORWARD_XTYPEPROVIDER2( classname, baseclass1, baseclass2 ) \ ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL classname::getTypes( ) throw (::com::sun::star::uno::RuntimeException) \ { \ return ::comphelper::concatSequences( \ baseclass1::getTypes(), \ baseclass2::getTypes() \ ); \ } \ \ IMPLEMENT_GET_IMPLEMENTATION_ID( classname ) #define IMPLEMENT_FORWARD_XTYPEPROVIDER3( classname, baseclass1, baseclass2, baseclass3 ) \ ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL classname::getTypes( ) throw (::com::sun::star::uno::RuntimeException) \ { \ return ::comphelper::concatSequences( \ baseclass1::getTypes(), \ baseclass2::getTypes(), \ baseclass3::getTypes() \ ); \ } \ \ IMPLEMENT_GET_IMPLEMENTATION_ID( classname ) //========================================================================= /** ask for an iface of an aggregated object usage:<br/> Reference<XFoo> xFoo;<br/> if (query_aggregation(xAggregatedObject, xFoo))<br/> .... */ template <class iface> sal_Bool query_aggregation(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >& _rxAggregate, ::com::sun::star::uno::Reference<iface>& _rxOut) { _rxOut = static_cast<iface*>(NULL); if (_rxAggregate.is()) { ::com::sun::star::uno::Any aCheck = _rxAggregate->queryAggregation( iface::static_type()); if (aCheck.hasValue()) _rxOut = *(::com::sun::star::uno::Reference<iface>*)aCheck.getValue(); } return _rxOut.is(); } /** ask for an iface of an object usage:<br/> Reference<XFoo> xFoo;<br/> if (query_interface(xAnything, xFoo))<br/> .... */ template <class iface> sal_Bool query_interface(const InterfaceRef& _rxObject, ::com::sun::star::uno::Reference<iface>& _rxOut) { _rxOut = static_cast<iface*>(NULL); if (_rxObject.is()) { ::com::sun::star::uno::Any aCheck = _rxObject->queryInterface( iface::static_type()); if(aCheck.hasValue()) { _rxOut = *(::com::sun::star::uno::Reference<iface>*)aCheck.getValue(); return _rxOut.is(); } } return sal_False; } #define FORWARD_DECLARE_INTERFACE(NAME,XFACE) \ namespace com \ { \ namespace sun \ {\ namespace star \ {\ namespace NAME \ {\ class XFACE; \ }\ }\ }\ }\ //......................................................................... } // namespace comphelper //......................................................................... #endif // _COMPHELPER_UNO3_HXX_
13,025
4,389
//===----------------------------------------------------------------------===// // DuckDB // // duckdb/storage/statistics/distinct_statistics.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/common/atomic.hpp" #include "duckdb/common/types/hyperloglog.hpp" #include "duckdb/storage/statistics/base_statistics.hpp" namespace duckdb { class Serializer; class Deserializer; class Vector; class DistinctStatistics : public BaseStatistics { public: DistinctStatistics(); explicit DistinctStatistics(unique_ptr<HyperLogLog> log, idx_t sample_count, idx_t total_count); //! The HLL of the table unique_ptr<HyperLogLog> log; //! How many values have been sampled into the HLL atomic<idx_t> sample_count; //! How many values have been inserted (before sampling) atomic<idx_t> total_count; public: void Merge(const BaseStatistics &other) override; unique_ptr<BaseStatistics> Copy() const override; void Serialize(Serializer &serializer) const override; void Serialize(FieldWriter &writer) const override; static unique_ptr<DistinctStatistics> Deserialize(Deserializer &source); static unique_ptr<DistinctStatistics> Deserialize(FieldReader &reader); void Update(Vector &update, idx_t count); void Update(VectorData &update_data, const LogicalType &ptype, idx_t count); string ToString() const override; idx_t GetCount() const; private: //! For distinct statistics we sample the input to speed up insertions static constexpr const double SAMPLE_RATE = 0.1; }; } // namespace duckdb
1,601
485
// __BEGIN_LICENSE__ // Copyright (c) 2006-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NASA Vision Workbench is licensed under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ // TestPinholeModel.h #include <gtest/gtest_VW.h> #include <test/Helpers.h> #include <vw/Math/EulerAngles.h> #include <vw/Camera/PinholeModel.h> #include <vw/Camera/LensDistortion.h> using namespace vw; using namespace vw::camera; using namespace vw::test; TEST( AdjustedCameraModel, StandardConstruct ) { Matrix<double,3,3> pose; pose.set_identity(); // Create an imaginary 1000x1000 pixel imager boost::shared_ptr<CameraModel> pinhole( new PinholeModel( Vector3(0,0,0), // camera center pose, // camera pose 500,500, // fx, fy 500,500, // cx, cy NullLensDistortion()) ); AdjustedCameraModel adjcam( pinhole ); EXPECT_STREQ( "Adjusted", adjcam.type().c_str() ); // No mods, so should have equal results EXPECT_VECTOR_NEAR( pinhole->camera_center(Vector2()), adjcam.camera_center(Vector2()), 1e-5 ); EXPECT_VECTOR_NEAR( pinhole->pixel_to_vector( Vector2(750,750) ), adjcam.pixel_to_vector( Vector2(750,750) ), 1e-5 ); EXPECT_VECTOR_NEAR( pinhole->pixel_to_vector( Vector2(55,677) ), adjcam.pixel_to_vector( Vector2(55,677) ), 1e-5 ); EXPECT_NEAR( pinhole->camera_pose(Vector2())[0], adjcam.camera_pose(Vector2())[0], 1e-5 ); EXPECT_NEAR( pinhole->camera_pose(Vector2())[1], adjcam.camera_pose(Vector2())[1], 1e-5 ); EXPECT_NEAR( pinhole->camera_pose(Vector2())[2], adjcam.camera_pose(Vector2())[2], 1e-5 ); } TEST( AdjustedCameraModel, AdjustedConstruct ) { Matrix<double,3,3> pose = math::euler_to_rotation_matrix(1.3,2.0,-.7,"xyz"); // Create an imaginary 1000x1000 pixel imager boost::shared_ptr<CameraModel> pinhole( new PinholeModel( Vector3(0,0,0), // camera center pose, // camera pose 500,500, // fx, fy 500,500, // cx, cy NullLensDistortion()) ); AdjustedCameraModel adjcam( pinhole, Vector3(1,0,0), Quat(1,0,0,0) ); EXPECT_VECTOR_NEAR( Vector3(1,0,0), adjcam.camera_center(Vector2()) - pinhole->camera_center(Vector2()), 1e-5 ); EXPECT_VECTOR_NEAR( pinhole->pixel_to_vector( Vector2(750,750) ), adjcam.pixel_to_vector( Vector2(750,750) ), 1e-5 ); EXPECT_VECTOR_DOUBLE_EQ( Vector3(1,0,0), adjcam.translation() ); UnlinkName adjustment("adjust.txt"); adjcam.write( adjustment ); // Read back in adjustment AdjustedCameraModel adjcam2( pinhole ); adjcam2.read( adjustment ); EXPECT_VECTOR_NEAR( adjcam.translation(), adjcam2.translation(), 1e-5 ); EXPECT_MATRIX_NEAR( adjcam.rotation_matrix(), adjcam2.rotation_matrix(), 1e-5 ); EXPECT_VECTOR_NEAR( adjcam.axis_angle_rotation(), adjcam2.axis_angle_rotation(), 1e-5 ); // check enforcement that pose returns the rotation from camera // frame to world frame. Vector2 center_pixel(500,500); Quaternion<double> center_pose = adjcam2.camera_pose(center_pixel); double angle_from_z = acos(dot_prod(Vector3(0,0,1),inverse(center_pose).rotate(adjcam2.pixel_to_vector(center_pixel)))); EXPECT_LT( angle_from_z, 0.5 ); }
4,181
1,514
// Copyright 2020 TensorFlow Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "absl/strings/str_format.h" #include "tensorflow/compiler/tf2xla/xla_tensor/ops/token.h" #include "tensorflow/compiler/tf2xla/xla_tensor/tensor.h" #include "tensorflow/compiler/tf2xla/xla_tensor/tensor_util.h" // clang-format off // For TPU, run with: // export XRT_TPU_CONFIG="tpu_worker;0;localhost:<tfrc port>" // clang-format on using swift_xla::Device; using swift_xla::DeviceType; using swift_xla::GetDefaultDevice; using swift_xla::XLATensor; namespace { void WithAllDevices( DeviceType device_type, const std::function<void(const std::vector<Device>&, const std::vector<Device>&)>& devfn) { std::vector<Device> devices; std::vector<Device> all_devices; for (const auto& device_str : xla::ComputationClient::Get()->GetLocalDevices()) { Device device(device_str); if (device.hw_type == device_type) { devices.push_back(device); } } for (const auto& device_str : xla::ComputationClient::Get()->GetAllDevices()) { Device device(device_str); if (device.hw_type == device_type) { all_devices.push_back(device); } } if (!devices.empty()) { devfn(devices, all_devices); } } void TestSingleReplication(const std::vector<Device>& all_devices) { // Simulates N threads executing the same computation, using separated XRT // executions, and issuing CRS operations. std::vector<xla::string> device_strings; device_strings.reserve(all_devices.size()); for (auto& device : all_devices) { device_strings.push_back(device.ToString()); } float content = 1; std::vector<XLATensor> inputs; for (const auto& device : all_devices) { at::Tensor c({content, content + 1}, {2}); inputs.push_back(XLATensor::Create(c, device)); content += 2; } auto token = swift_xla::ir::MakeNode<swift_xla::ir::ops::Token>(); std::vector<XLATensor> results; results.reserve(device_strings.size()); for (const auto& input : inputs) { auto reduced_and_token = XLATensor::all_reduce(std::vector<XLATensor>{input}, token, swift_xla::AllReduceType::kSum, 1., {}); results.push_back(reduced_and_token.first.back()); } xla::util::MultiWait mwait(device_strings.size()); for (size_t i = 0; i < results.size(); ++i) { auto executor = [&, i]() { XLATensor::SyncLiveTensorsGraph(/*device=*/&results[i].GetDevice(), /*devices=*/device_strings, /*wait=*/true); }; xla::env::ScheduleIoClosure(mwait.Completer(std::move(executor))); } mwait.Wait(); for (XLATensor& result : results) { at::Tensor cpu_result = result.ToTensor(); auto data = cpu_result.data<float>(); absl::PrintF("crs result: [%g, %g]\n", data[0], data[1]); } } } // namespace int main(int argc, char** argv) { at::Tensor a({1, 2}, {2}); at::Tensor b({7, 19}, {2}); auto tena = XLATensor::Create(a, *GetDefaultDevice()); auto tenb = XLATensor::Create(b, *GetDefaultDevice()); auto tmp = XLATensor::add(tena, tenb, at::Scalar(1.0)); auto result = tmp.ToTensor(); auto data = result.data<float>(); if (data.size() == 2) { // TODO(parkers): Better printing... absl::PrintF("result: [%g, %g]\n", data[0], data[1]); } else { absl::PrintF("result; ??x%d\n", static_cast<int>(data.size())); } WithAllDevices(DeviceType::TPU, [&](const std::vector<Device>& /*devices*/, const std::vector<Device>& all_devices) { TestSingleReplication(all_devices); }); return 0; }
4,188
1,449
/* Copyright (c) 2012-2014 The SSDB Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include <sys/types.h> #include <unistd.h> #include <errno.h> #include "io_cache.h" int WriteCache::append(const char *data, int size) { // flush cache to file if (space() < size && flush_to_file() != 0) { return -1; } // write file directly if (size > cap) { int writebytes = writen(fd, data, size); if (writebytes != size) return -1; return 0; } // append to cache memcpy(end, data, size); end += size; return 0; } int WriteCache::append(const std::string &s) { return append(s.data(), s.size()); } int WriteCache::flush_to_file() { int len = data_len(); int ret = writen(fd, buf, len); if (ret != len) return -1; reset(); return 0; } int WriteCache::sync_file() { int ret = fsync(fd); return ret; } int WriteCache::writen(int fd, const char *buf, size_t n) { int left = n; int err = 0; while (left > 0) { int ret = write(fd, buf+n-left, left); if (ret < 0 && (err = errno) == EINTR) continue; if (ret < 0) { return ret; } left -= ret; } return (int)(n - left); } int ReadCache::readn(char *dst, int n) { assert (n > 0); if (this->left() >= n) { memcpy(dst, cur, n); cur += n; return n; } int left = n; if (this->left() > 0) { memcpy(dst, cur, this->left()); left -= this->left(); } offset += (uint64_t)(end-buf); reset(); int ret = 0; if (left > cap / 2) { // decrease data copy ret = readn(fd, dst+n-left, left); if (ret < 0) { return ret; } left -= ret; offset += ret; } else { ret = readn(fd, buf, cap); if (ret < 0) { return ret; } if (ret > 0) { cur = buf; end = cur + ret; int bytes2read = left < this->left() ? left : this->left(); memcpy(dst+n-left, cur, bytes2read); cur += bytes2read; left -= bytes2read; } } return n - left; } int ReadCache::readn(int fd, char *buf, int n) { int err = 0; int left = n; while (left > 0) { int ret = read(fd, buf+n-left, left); if (ret < 0 && (err=errno) == EINTR) continue; if (ret < 0) { return -1; } if (ret == 0) //EOF break; left -= ret; } return n - left; } int ReadCache::seek(uint64_t pos) { if (pos < offset) { return -1; } while (offset+(uint64_t)(end-buf) < pos) { offset += (uint64_t)(end-buf); reset(); int ret = readn(fd, buf, cap); if (ret < 0) { return -1; } if (ret == 0) break; if (ret > 0) { end += ret; } } if (offset+(uint64_t)(end-buf) < pos) { return -1; } cur += (pos - offset) - (cur - buf); assert (cur <= end); return 0; }
2,668
1,242
/* $Id: binary_or_text.cpp 48153 2011-01-01 15:57:50Z mordante $ */ /* Copyright (C) 2003 by David White <dave@whitevine.net> Copyright (C) 2005 - 2011 by Guillaume Melquiond <guillaume.melquiond@gmail.com> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ /** * @file * Read/Write file in binary (compressed) or text-format (uncompressed). */ #include "global.hpp" #include "binary_or_text.hpp" #include "config.hpp" #include "log.hpp" #include "wesconfig.h" #include "serialization/parser.hpp" #include <boost/iostreams/filter/gzip.hpp> static lg::log_domain log_config("config"); #define ERR_CF LOG_STREAM(err, log_config) config_writer::config_writer( std::ostream &out, bool compress, int level) : filter_(), out_ptr_(compress ? &filter_ : &out), //ternary indirection creates a temporary out_(*out_ptr_), //now MSVC will allow binding to the reference member compress_(compress), level_(0), textdomain_(PACKAGE) { if(compress_) { if (level >=0) filter_.push(boost::iostreams::gzip_compressor(boost::iostreams::gzip_params(level))); else filter_.push(boost::iostreams::gzip_compressor(boost::iostreams::gzip_params())); filter_.push(out); } } config_writer::~config_writer() { } void config_writer::write(const config &cfg) { ::write(out_, cfg, level_); } void config_writer::write_child(const std::string &key, const config &cfg) { open_child(key); ::write(out_, cfg, level_); close_child(key); } void config_writer::write_key_val(const std::string &key, const std::string &value) { config::attribute_value v; v = value; ::write_key_val(out_, key, v, level_, textdomain_); } void config_writer::open_child(const std::string &key) { ::write_open_child(out_, key, level_++); } void config_writer::close_child(const std::string &key) { ::write_close_child(out_, key, --level_); } bool config_writer::good() const { return out_.good(); }
2,405
890
// Leka - LekaOS // Copyright 2022 APF France handicap // SPDX-License-Identifier: Apache-2.0 #include "CoreLED.h" #include "CoreSPI.h" #include "gtest/gtest.h" #include "mocks/leka/SPI.h" using namespace leka; class CoreLedSetColorTest : public ::testing::Test { protected: CoreLedSetColorTest() = default; // void SetUp() override {} // void TearDown() override {} static constexpr int number_of_leds = 20; std::array<RGB, number_of_leds> expected_colors {}; CoreSPI spi {NC, NC, NC, NC}; CoreLED<number_of_leds> leds {spi}; }; TEST_F(CoreLedSetColorTest, setColorPredefinedForAll) { auto color = RGB::pure_red; std::fill(expected_colors.begin(), expected_colors.end(), color); leds.setColor(color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorUserDefinedForAll) { auto color = RGB {120, 12, 56}; std::fill(expected_colors.begin(), expected_colors.end(), color); leds.setColor(color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorAtIndexFirst) { auto index = 0; auto color = RGB::pure_green; expected_colors.at(index) = color; leds.setColorAtIndex(index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorAtIndexMiddle) { auto index = number_of_leds / 2 - 1; auto color = RGB::pure_green; expected_colors.at(index) = color; leds.setColorAtIndex(index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorAtIndexLast) { auto index = number_of_leds - 1; auto color = RGB::pure_green; expected_colors.at(index) = color; leds.setColorAtIndex(index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorAtIndexEqualNumberOfLeds) { auto index = number_of_leds; auto color = RGB::pure_green; leds.setColorAtIndex(index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorAtIndexHigherThanNumberOfLeds) { auto index = number_of_leds + 100; auto color = RGB::pure_green; leds.setColorAtIndex(index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorAtIndexFirstMiddleEnd) { auto first_index = 0; auto middle_index = number_of_leds / 2 - 1; auto end_index = number_of_leds - 1; auto first_color = RGB::pure_red; auto middle_color = RGB::pure_green; auto end_color = RGB::pure_blue; expected_colors.at(first_index) = first_color; expected_colors.at(middle_index) = middle_color; expected_colors.at(end_index) = end_color; leds.setColorAtIndex(first_index, first_color); leds.setColorAtIndex(middle_index, middle_color); leds.setColorAtIndex(end_index, end_color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorFromArray) { auto expected_colors = std::to_array<RGB>( {RGB::pure_blue, RGB::pure_green, RGB::pure_red, RGB::pure_blue, RGB::yellow, RGB::cyan, RGB::magenta, RGB::pure_green, RGB::pure_red, RGB::pure_blue, RGB::yellow, RGB::cyan, RGB::magenta, RGB::pure_green, RGB::pure_red, RGB::pure_blue, RGB::yellow, RGB::cyan, RGB::magenta, RGB::black}); leds.setColorWithArray(expected_colors); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorRange) { RGB color = RGB::pure_green; int range_begin_index = 2; int range_end_index = 5; for (auto i = range_begin_index; i <= range_end_index; ++i) { expected_colors.at(i) = color; } leds.setColorRange(range_begin_index, range_end_index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorRangeFirstLast) { RGB color = RGB::pure_green; int range_begin_index = 0; int range_end_index = number_of_leds - 1; for (auto i = range_begin_index; i <= range_end_index; ++i) { expected_colors.at(i) = color; } leds.setColorRange(range_begin_index, range_end_index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorRangeFirstMiddle) { RGB color = RGB::pure_green; int range_begin_index = 0; int range_end_index = number_of_leds / 2 - 1; for (auto i = range_begin_index; i <= range_end_index; ++i) { expected_colors.at(i) = color; } leds.setColorRange(range_begin_index, range_end_index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorRangeMiddleLast) { RGB color = RGB::pure_green; int range_begin_index = number_of_leds / 2 - 1; int range_end_index = number_of_leds - 1; for (auto i = range_begin_index; i <= range_end_index; ++i) { expected_colors.at(i) = color; } leds.setColorRange(range_begin_index, range_end_index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorRangeMiddleLastEqualNumberOfLeds) { RGB color = RGB::pure_green; int range_begin_index = number_of_leds / 2 - 1; int range_end_index = number_of_leds; for (auto i = range_begin_index; i < number_of_leds; ++i) { expected_colors.at(i) = color; } leds.setColorRange(range_begin_index, range_end_index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorRangeMiddleLastHigherThanNumberOfLeds) { RGB color = RGB::pure_green; int range_begin_index = number_of_leds / 2 - 1; int range_end_index = number_of_leds + 100; for (auto i = range_begin_index; i < number_of_leds; ++i) { expected_colors.at(i) = color; } leds.setColorRange(range_begin_index, range_end_index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorRangeInverted) { RGB color = RGB::pure_green; int range_begin_index = 3; int range_end_index = 0; for (auto i = range_end_index; i <= range_begin_index; ++i) { expected_colors.at(i) = color; } leds.setColorRange(range_begin_index, range_end_index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorBeginEqualsEndFirst) { RGB color = RGB::pure_green; int range_begin_index = 0; int range_end_index = 0; expected_colors.at(range_begin_index) = color; leds.setColorRange(range_begin_index, range_end_index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorBeginEqualsEndMiddle) { RGB color = RGB::pure_green; int range_begin_index = number_of_leds / 2 - 1; int range_end_index = number_of_leds / 2 - 1; expected_colors.at(range_begin_index) = color; leds.setColorRange(range_begin_index, range_end_index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorBeginEqualsEndLast) { RGB color = RGB::pure_green; int range_begin_index = number_of_leds - 1; int range_end_index = number_of_leds - 1; expected_colors.at(range_begin_index) = color; leds.setColorRange(range_begin_index, range_end_index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorBeginEqualsEndLastEqualNumberOfLeds) { RGB color = RGB::pure_green; int range_begin_index = number_of_leds; int range_end_index = number_of_leds; // nothing to do for this test leds.setColorRange(range_begin_index, range_end_index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorBeginEqualsEndLastHigherThanNumberOfLeds) { RGB color = RGB::pure_green; int range_begin_index = number_of_leds + 100; int range_end_index = number_of_leds + 100; // nothing to do for this test leds.setColorRange(range_begin_index, range_end_index, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); } TEST_F(CoreLedSetColorTest, setColorRangeUpperLimite) { RGB color = RGB::pure_green; // nothing to do for this test leds.setColorRange(20, 20, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); leds.setColorRange(21, 20, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); leds.setColorRange(20, 21, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); leds.setColorRange(21, 21, color); EXPECT_TRUE(std::equal(expected_colors.begin(), expected_colors.end(), leds.getColor().begin())); }
9,467
3,742
#include <mos/io/keyboard.hpp> namespace mos::io{ }
52
22
// Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "carla/road/Lane.h" #include <limits> #include "carla/Debug.h" #include "carla/geom/Math.h" #include "carla/road/element/Geometry.h" #include "carla/road/element/RoadInfoElevation.h" #include "carla/road/element/RoadInfoGeometry.h" #include "carla/road/element/RoadInfoLaneOffset.h" #include "carla/road/element/RoadInfoLaneWidth.h" #include "carla/road/LaneSection.h" #include "carla/road/MapData.h" #include "carla/road/Road.h" namespace carla { namespace road { const LaneSection *Lane::GetLaneSection() const { return _lane_section; } Road *Lane::GetRoad() const { DEBUG_ASSERT(_lane_section != nullptr); return _lane_section->GetRoad(); } LaneId Lane::GetId() const { return _id; } Lane::LaneType Lane::GetType() const { return _type; } bool Lane::GetLevel() const { return _level; } double Lane::GetDistance() const { DEBUG_ASSERT(_lane_section != nullptr); return _lane_section->GetDistance(); } double Lane::GetLength() const { const auto *road = GetRoad(); DEBUG_ASSERT(road != nullptr); const auto s = GetDistance(); return road->UpperBound(s) - s; } double Lane::GetWidth(const double s) const { RELEASE_ASSERT(s <= GetRoad()->GetLength()); const auto width_info = GetInfo<element::RoadInfoLaneWidth>(s); RELEASE_ASSERT(width_info != nullptr); return width_info->GetPolynomial().Evaluate(s); } bool Lane::IsStraight() const { Road *road = GetRoad(); RELEASE_ASSERT(road != nullptr); auto *geometry = road->GetInfo<element::RoadInfoGeometry>(GetDistance()); DEBUG_ASSERT(geometry != nullptr); auto geometry_type = geometry->GetGeometry().GetType(); if (geometry_type != element::GeometryType::LINE) { return false; } if(GetDistance() < geometry->GetDistance() || GetDistance() + GetLength() > geometry->GetDistance() + geometry->GetGeometry().GetLength()) { return false; } auto lane_offsets = GetInfos<element::RoadInfoLaneOffset>(); for (auto *lane_offset : lane_offsets) { if (std::abs(lane_offset->GetPolynomial().GetC()) > 0 || std::abs(lane_offset->GetPolynomial().GetD()) > 0) { return false; } } auto elevations = road->GetInfos<element::RoadInfoElevation>(); for (auto *elevation : elevations) { if (std::abs(elevation->GetPolynomial().GetC()) > 0 || std::abs(elevation->GetPolynomial().GetD()) > 0) { return false; } } return true; } /// Returns a pair containing first = width, second = tangent, /// for an specific Lane given an s and a iterator over lanes template <typename T> static std::pair<double, double> ComputeTotalLaneWidth( const T container, const double s, const LaneId lane_id) { // lane_id can't be 0 RELEASE_ASSERT(lane_id != 0); const bool negative_lane_id = lane_id < 0; double dist = 0.0; double tangent = 0.0; for (const auto &lane : container) { auto info = lane.second.template GetInfo<element::RoadInfoLaneWidth>(s); RELEASE_ASSERT(info != nullptr); const auto current_polynomial = info->GetPolynomial(); auto current_dist = current_polynomial.Evaluate(s); auto current_tang = current_polynomial.Tangent(s); if (lane.first != lane_id) { dist += negative_lane_id ? current_dist : -current_dist; tangent += negative_lane_id ? current_tang : -current_tang; } else { current_dist *= 0.5; dist += negative_lane_id ? current_dist : -current_dist; tangent += (negative_lane_id ? current_tang : -current_tang) * 0.5; break; } } return std::make_pair(dist, tangent); } geom::Transform Lane::ComputeTransform(const double s) const { const Road *road = GetRoad(); DEBUG_ASSERT(road != nullptr); // must s be smaller (or eq) than road length and bigger (or eq) than 0? RELEASE_ASSERT(s <= road->GetLength()); RELEASE_ASSERT(s >= 0.0); const auto *lane_section = GetLaneSection(); DEBUG_ASSERT(lane_section != nullptr); const std::map<LaneId, Lane> &lanes = lane_section->GetLanes(); // check that lane_id exists on the current s RELEASE_ASSERT(!lanes.empty()); RELEASE_ASSERT(GetId() >= lanes.begin()->first); RELEASE_ASSERT(GetId() <= lanes.rbegin()->first); // These will accumulate the lateral offset (t) and lane heading of all // the lanes in between the current lane and lane 0, where the main road // geometry is described float lane_t_offset = 0.0f; float lane_tangent = 0.0f; if (GetId() < 0) { // right lane const auto side_lanes = MakeListView( std::make_reverse_iterator(lanes.lower_bound(0)), lanes.rend()); const auto computed_width = ComputeTotalLaneWidth(side_lanes, s, GetId()); lane_t_offset = static_cast<float>(computed_width.first); lane_tangent = static_cast<float>(computed_width.second); } else if (GetId() > 0) { // left lane const auto side_lanes = MakeListView(lanes.lower_bound(1), lanes.end()); const auto computed_width = ComputeTotalLaneWidth(side_lanes, s, GetId()); lane_t_offset = static_cast<float>(computed_width.first); lane_tangent = static_cast<float>(computed_width.second); } // Compute the tangent of the road's (lane 0) "laneOffset" on the current s const auto lane_offset_info = road->GetInfo<element::RoadInfoLaneOffset>(s); const auto lane_offset_tangent = static_cast<float>(lane_offset_info->GetPolynomial().Tangent(s)); // Update the road tangent with the "laneOffset" information at current s lane_tangent -= lane_offset_tangent; // Get a directed point on the center of the current lane given an s element::DirectedPoint dp = road->GetDirectedPointIn(s); // Transform from the center of the road to the center of the lane dp.ApplyLateralOffset(lane_t_offset); // Update the lane tangent with the road "laneOffset" at current s dp.tangent -= lane_tangent; // Unreal's Y axis hack dp.location.y *= -1; dp.tangent *= -1; geom::Rotation rot( geom::Math::ToDegrees(static_cast<float>(dp.pitch)), geom::Math::ToDegrees(static_cast<float>(dp.tangent)), 0.0f); // Fix the direction of the possitive lanes if (GetId() > 0) { rot.yaw += 180.0f; rot.pitch = 360.0f - rot.pitch; } return geom::Transform(dp.location, rot); } std::pair<geom::Vector3D, geom::Vector3D> Lane::GetCornerPositions( const double s, const float extra_width) const { const Road *road = GetRoad(); DEBUG_ASSERT(road != nullptr); const auto *lane_section = GetLaneSection(); DEBUG_ASSERT(lane_section != nullptr); const std::map<LaneId, Lane> &lanes = lane_section->GetLanes(); // check that lane_id exists on the current s RELEASE_ASSERT(!lanes.empty()); RELEASE_ASSERT(GetId() >= lanes.begin()->first); RELEASE_ASSERT(GetId() <= lanes.rbegin()->first); float lane_t_offset = 0.0f; if (GetId() < 0) { // right lane const auto side_lanes = MakeListView( std::make_reverse_iterator(lanes.lower_bound(0)), lanes.rend()); const auto computed_width = ComputeTotalLaneWidth(side_lanes, s, GetId()); lane_t_offset = static_cast<float>(computed_width.first); } else if (GetId() > 0) { // left lane const auto side_lanes = MakeListView(lanes.lower_bound(1), lanes.end()); const auto computed_width = ComputeTotalLaneWidth(side_lanes, s, GetId()); lane_t_offset = static_cast<float>(computed_width.first); } float lane_width = static_cast<float>(GetWidth(s)) / 2.0f; if (extra_width != 0.f && road->IsJunction() && GetType() == Lane::LaneType::Driving) { lane_width += extra_width; } // Get two points on the center of the road on given s element::DirectedPoint dp_r, dp_l; dp_r = dp_l = road->GetDirectedPointIn(s); // Transform from the center of the road to each of lane corners dp_r.ApplyLateralOffset(lane_t_offset + lane_width); dp_l.ApplyLateralOffset(lane_t_offset - lane_width); // Unreal's Y axis hack dp_r.location.y *= -1; dp_l.location.y *= -1; // Apply an offset to the Sidewalks if (GetType() == LaneType::Sidewalk) { // RoadRunner doesn't export it right now and as a workarround where 15.24 cm // is the exact height that match with most of the RoadRunner sidewalks dp_r.location.z += 0.1524f; dp_l.location.z += 0.1524f; /// @TODO: use the OpenDRIVE 5.3.7.2.1.1.9 Lane Height Record } return std::make_pair(dp_r.location, dp_l.location); } } // road } // carla
9,036
3,138
/************************************************************************* > File Name: test_08.cpp > Author: @Yoghourt->ilvcr, Cn,Sx,Ty > Mail: ilvcr@outlook.com || liyaoliu@foxmail.com > Created Time: 2018年06月27日 星期三 21时25分24秒 > Description: ************************************************************************/ #include<iostream> using namespace std; int min( int*, int* ); int (*pf)(int*, int) = min; const int iaSize = 5; int ia[ iaSize ] = {7, 4, 9, 2, 5}; int main(){ cout << " Direct call: min: " << min( ia, iaSize ) << endl; cout << "Indirect call: min: " << pf( ia, iaSize ) << endl; return 0; } int min( int* ia, int sz ){ int minVal = ia[ 0 ]; for( int ix = 1; ix < sz; ++ix ){ if( minVal > ia[ ix ] ){ minVal = iz[ ix ]; } } return minVal; }
851
339
#ifndef TINYTMX_TINYTMXWANGTILE_HPP #define TINYTMX_TINYTMXWANGTILE_HPP #include <vector> namespace tinyxml2 { class XMLElement; } namespace tinytmx { class WangTile { public: WangTile(); void Parse(tinyxml2::XMLElement const *wangTileElement); /// Get the tile ID. [[nodiscard]] uint32_t GetTileId() const { return tileID; } /// Get the wang ID. [[nodiscard]] std::vector<uint32_t> const &GetWangID() const { return wangID; } private: uint32_t tileID; std::vector<uint32_t> wangID; }; } #endif //TINYTMX_TINYTMXWANGTILE_HPP
620
254
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. Note: A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules. Example 1: Input: board = [["5","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] Output: true Example 2: Input: board = [["8","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] Output: false Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. Solution : Time Complexity : O(n*n) Using set: class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { vector<set<int>>rows(9),cols(9),blocks(9); for(int i=0;i<9;i++) //rows { for(int j=0;j<9;j++) //coloumns { if(board[i][j]=='.') continue; int curr = board[i][j]-'0'; if(rows[i].count(curr) || cols[j].count(curr) || blocks[(i/3)*3+j/3].count(curr)) return false; rows[i].insert(curr); cols[j].insert(curr); blocks[(i/3)*3+j/3].insert(curr); } } return true; } };
2,279
892
//======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //======================================================================================== //! \file fft_driver.cpp // \brief implementation of functions in class FFTDriver // C headers // C++ headers #include <cmath> #include <iostream> // endl #include <sstream> // sstream #include <stdexcept> // runtime_error #include <string> // c_str() // Athena++ headers #include "../athena.hpp" #include "../athena_arrays.hpp" #include "../coordinates/coordinates.hpp" #include "../mesh/mesh.hpp" #include "../parameter_input.hpp" #include "athena_fft.hpp" #ifdef MPI_PARALLEL #include <mpi.h> #endif // constructor, initializes data structures and parameters FFTDriver::FFTDriver(Mesh *pm, ParameterInput *pin) : nranks_(Globals::nranks), pmy_mesh_(pm), dim_(pm->ndim) { if (!(pm->use_uniform_meshgen_fn_[X1DIR]) || !(pm->use_uniform_meshgen_fn_[X2DIR]) || !(pm->use_uniform_meshgen_fn_[X3DIR])) { std::stringstream msg; msg << "### FATAL ERROR in FFTDriver::FFTDriver" << std::endl << "Non-uniform mesh spacing is not supported." << std::endl; ATHENA_ERROR(msg); return; } // Setting up the MPI information // *** this part should be modified when dedicate processes are allocated *** // *** we also need to construct another neighbor list for Multigrid *** ranklist_ = new int[pm->nbtotal]; for (int n=0; n<pm->nbtotal; n++) ranklist_[n] = pm->ranklist[n]; nslist_ = new int[nranks_]; nblist_ = new int[nranks_]; #ifdef MPI_PARALLEL MPI_Comm_dup(MPI_COMM_WORLD, &MPI_COMM_FFT); #endif for (int n=0; n<nranks_; n++) { nslist_[n] = pm->nslist[n]; nblist_[n] = pm->nblist[n]; } int ns = nslist_[Globals::my_rank]; int ne = ns + nblist_[Globals::my_rank]; std::int64_t &lx1min = pm->loclist[ns].lx1; std::int64_t &lx2min = pm->loclist[ns].lx2; std::int64_t &lx3min = pm->loclist[ns].lx3; std::int64_t lx1max = lx1min; std::int64_t lx2max = lx2min; std::int64_t lx3max = lx3min; int current_level = pm->root_level; for (int n=ns; n<ne; n++) { std::int64_t &lx1 = pm->loclist[n].lx1; std::int64_t &lx2 = pm->loclist[n].lx2; std::int64_t &lx3 = pm->loclist[n].lx3; lx1min = lx1min < lx1 ? lx1min : lx1; lx2min = lx2min < lx2 ? lx2min : lx2; lx3min = lx3min < lx3 ? lx3min : lx3; lx1max = lx1max > lx1 ? lx1min : lx1; lx2max = lx2max > lx2 ? lx2min : lx2; lx3max = lx3max > lx3 ? lx3min : lx3; if(pm->loclist[n].level > current_level) current_level = pm->loclist[n].level; } int ref_lev = current_level - pm->root_level; // KGF: possible underflow from std::int64_t int nbx1 = static_cast<int>(lx1max-lx1min+1); int nbx2 = static_cast<int>(lx2max-lx2min+1); int nbx3 = static_cast<int>(lx3max-lx3min+1); nmb = nbx1*nbx2*nbx3; // number of MeshBlock to be loaded to the FFT block if (pm->nbtotal/nmb != nranks_) { // this restriction (to a single cuboid FFTBlock that covers the union of all // MeshBlocks owned by an MPI rank) should be relaxed in the future std::stringstream msg; msg << "### FATAL ERROR in FFTDriver::FFTDriver" << std::endl << nmb << " MeshBlocks will be loaded to the FFT block." << std::endl << "Number of FFT blocks " << pm->nbtotal/nmb << " are not matched with " << "Number of processors " << nranks_ << std::endl; ATHENA_ERROR(msg); return; } // There should be only one FFTBlock per processor. // MeshBlocks in the same processor will be gathered into FFTBlock of the processor. fft_loclist_ = new LogicalLocation[nranks_]; for (int n=0; n<nranks_; n++) { int ns_inner = nslist_[n]; fft_loclist_[n] = pm->loclist[ns_inner]; fft_loclist_[n].lx1 = fft_loclist_[n].lx1/nbx1; fft_loclist_[n].lx2 = fft_loclist_[n].lx2/nbx2; fft_loclist_[n].lx3 = fft_loclist_[n].lx3/nbx3; } npx1 = (pm->nrbx1*(1 << ref_lev))/nbx1; npx2 = (pm->nrbx2*(1 << ref_lev))/nbx2; npx3 = (pm->nrbx3*(1 << ref_lev))/nbx3; fft_mesh_size_ = pm->mesh_size; fft_mesh_size_.nx1 = pm->mesh_size.nx1*(1<<ref_lev); fft_mesh_size_.nx2 = pm->mesh_size.nx2*(1<<ref_lev); fft_mesh_size_.nx3 = pm->mesh_size.nx3*(1<<ref_lev); fft_block_size_.nx1 = fft_mesh_size_.nx1/npx1; fft_block_size_.nx2 = fft_mesh_size_.nx2/npx2; fft_block_size_.nx3 = fft_mesh_size_.nx3/npx3; gcnt_ = fft_mesh_size_.nx1*fft_mesh_size_.nx2*fft_mesh_size_.nx3; #ifdef MPI_PARALLEL decomp_ = 0; pdim_ = 0; if (npx1 > 1) { decomp_ = decomp_ | DecompositionNames::x_decomp; pdim_++; } if (npx2 > 1) { decomp_ = decomp_ | DecompositionNames::y_decomp; pdim_++; } if (npx3 > 1) { decomp_ = decomp_ | DecompositionNames::z_decomp; pdim_++; } #endif } // destructor FFTDriver::~FFTDriver() { delete [] ranklist_; delete [] nslist_; delete [] nblist_; delete [] fft_loclist_; delete pmy_fb; } void FFTDriver::InitializeFFTBlock(bool set_norm) { int igid = Globals::my_rank; pmy_fb = new FFTBlock(this, fft_loclist_[igid], igid, fft_mesh_size_, fft_block_size_); if (set_norm) pmy_fb->SetNormFactor(1./gcnt_); } void FFTDriver::QuickCreatePlan() { pmy_fb->fplan_ = pmy_fb->QuickCreatePlan( pmy_fb->in_, FFTBlock::AthenaFFTDirection::forward); pmy_fb->bplan_ = pmy_fb->QuickCreatePlan( pmy_fb->in_, FFTBlock::AthenaFFTDirection::backward); return; }
5,688
2,443
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <assert.h> #include <dlfcn.h> //dlopen #include <sys/time.h> #include <tvm/runtime/c_runtime_api.h> #include <iostream> #include <random> #include <vector> template <typename F> auto getFunc(void* bundle, const char* name) { dlerror(); auto* f = reinterpret_cast<typename std::add_pointer<F>::type>(dlsym(bundle, name)); assert(!dlerror()); return f; } static int read_all(const char* file_description, const char* file_path, char** out_params, size_t* params_size) { FILE* fp = fopen(file_path, "rb"); if (fp == NULL) { return 2; } int error = 0; error = fseek(fp, 0, SEEK_END); if (error < 0) { return error; } long file_size = ftell(fp); if (file_size < 0) { return (int)file_size; } else if (file_size == 0 || file_size > (10 << 20)) { // file size should be in (0, 20MB]. char buf[128]; snprintf(buf, sizeof(buf), "determing file size: %s", file_path); perror(buf); return 2; } if (params_size != NULL) { *params_size = file_size; } error = fseek(fp, 0, SEEK_SET); if (error < 0) { return error; } *out_params = (char*)malloc((unsigned long)file_size); if (fread(*out_params, file_size, 1, fp) != 1) { free(*out_params); *out_params = NULL; char buf[128]; snprintf(buf, sizeof(buf), "reading: %s", file_path); perror(buf); return 2; } error = fclose(fp); if (error != 0) { free(*out_params); *out_params = NULL; } return 0; } int main(int argc, char** argv) { assert(argc == 5 && "Usage: demo <bundle.so> <graph.json> <params.bin> <cat.bin>"); auto* bundle = dlopen(argv[1], RTLD_LAZY | RTLD_LOCAL); assert(bundle); char* json_data; int error = read_all("graph.json", argv[2], &json_data, NULL); if (error != 0) { return error; } char* params_data; size_t params_size; error = read_all("params.bin", argv[3], &params_data, &params_size); if (error != 0) { return error; } struct timeval t0, t1, t2, t3, t4, t5; gettimeofday(&t0, 0); auto* handle = getFunc<void*(char*, char*, int)>(bundle, "tvm_runtime_create")( json_data, params_data, params_size); gettimeofday(&t1, 0); float input_storage[1 * 3 * 224 * 224]; FILE* fp = fopen(argv[4], "rb"); fread(input_storage, 3 * 224 * 224, 4, fp); fclose(fp); std::vector<int64_t> input_shape = {1, 3, 224, 224}; DLTensor input; input.data = input_storage; input.ctx = DLContext{kDLCPU, 0}; input.ndim = 4; input.dtype = DLDataType{kDLFloat, 32, 1}; input.shape = input_shape.data(); input.strides = nullptr; input.byte_offset = 0; getFunc<void(void*, const char*, void*)>(bundle, "tvm_runtime_set_input")(handle, "data", &input); gettimeofday(&t2, 0); auto* ftvm_runtime_run = (auto (*)(void*)->void)dlsym(bundle, "tvm_runtime_run"); assert(!dlerror()); ftvm_runtime_run(handle); gettimeofday(&t3, 0); float output_storage[1000]; std::vector<int64_t> output_shape = {1, 1000}; DLTensor output; output.data = output_storage; output.ctx = DLContext{kDLCPU, 0}; output.ndim = 2; output.dtype = DLDataType{kDLFloat, 32, 1}; output.shape = output_shape.data(); output.strides = nullptr; output.byte_offset = 0; getFunc<void(void*, int, void*)>(bundle, "tvm_runtime_get_output")(handle, 0, &output); gettimeofday(&t4, 0); float max_iter = -std::numeric_limits<float>::max(); int32_t max_index = -1; for (auto i = 0; i < 1000; ++i) { if (output_storage[i] > max_iter) { max_iter = output_storage[i]; max_index = i; } } getFunc<void(void*)>(bundle, "tvm_runtime_destroy")(handle); gettimeofday(&t5, 0); printf("The maximum position in output vector is: %d, with max-value %f.\n", max_index, max_iter); printf( "timing: %.2f ms (create), %.2f ms (set_input), %.2f ms (run), " "%.2f ms (get_output), %.2f ms (destroy)\n", (t1.tv_sec - t0.tv_sec) * 1000.0f + (t1.tv_usec - t0.tv_usec) / 1000.f, (t2.tv_sec - t1.tv_sec) * 1000.0f + (t2.tv_usec - t1.tv_usec) / 1000.f, (t3.tv_sec - t2.tv_sec) * 1000.0f + (t3.tv_usec - t2.tv_usec) / 1000.f, (t4.tv_sec - t3.tv_sec) * 1000.0f + (t4.tv_usec - t3.tv_usec) / 1000.f, (t5.tv_sec - t4.tv_sec) * 1000.0f + (t5.tv_usec - t4.tv_usec) / 1000.f); dlclose(bundle); return 0; }
5,128
2,143
/*_____________________________________________________________________________ The MIT License (https://opensource.org/licenses/MIT) Copyright (c) 2017, Jonathan D. Lettvin, All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. _____________________________________________________________________________*/ //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC //.............................................................................. //.............................................................................. #include <fmt/printf.h> // modern printf //.............................................................................. #include <sys/mman.h> // Memory mapping #include <sys/stat.h> // File status via descriptor #include <errno.h> // EMFILE //.............................................................................. #include <unistd.h> // file descriptor open/write/close #include <fcntl.h> // file descriptor open O_RDONLY //.............................................................................. #include <string_view> // Improve performance on mmap of file #include <iostream> // sync_with_stdio (mix printf with cout) #include <sstream> // string_stream #include <iomanip> // setw and other cout formatting #include <thread> #include <mutex> #include <regex> //.............................................................................. #include <string> // container #include <vector> // container #include <map> // container #include <set> // container //.............................................................................. #include "catch.hpp" // Testing framework //.............................................................................. #include "gg_version.h" // s_version and s_synopsis #include "gg_utility.h" // tokenize #include "gg_tqueue.h" // filename distribution to threads #include "gg_state.h" // Mechanism for finite state machine #include "gg.h" // declarations //.............................................................................. #include "gg_variant.h" // variant implementations static std::mutex open_mtx; //AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA //------------------------------------------------------------------------------ /// @brief ctor Lettvin::GreasedGrep:: GreasedGrep (int32_t a_argc, char** a_argv) // ctor //------------------------------------------------------------------------------ { while (--a_argc) { //debugf (1, "CTOR: '%s' '%s'\n", *a_argv, *(a_argv + 1)); ingest (*++a_argv); } } // ctor //------------------------------------------------------------------------------ /// @brief ftor void Lettvin::GreasedGrep:: operator ()() //------------------------------------------------------------------------------ { // Run unit and timing tests. if (s_test) { printf ("TESTS\n"); double minimized{1.0}; static const size_t overhead_loop_count{10}; for (size_t i=overhead_loop_count; i; --i) { minimized = min (minimized, interval (noop)); } s_overhead = minimized; cout << " # overhead min: " << s_overhead << endl; return; } // Validate sufficient args. if (s_target.size () < 1 && ((s_accept.size () < 2) && (s_reject.size () < 2))) { Lettvin::syntax ("pattern(s) and directory required."); } // Find filename regexes debugf (1, "Initial target: %s\n", s_target.data ()); size_t brace = s_target.find_first_of ('{'); if (brace != string_view::npos) { string patterns{s_target.substr (brace)}; s_target = s_target.substr (0, brace); tokenize (s_filesx, patterns, "{,}"); for (size_t I=s_filesx.size (), i=1; i<I; ++i) { auto& restriction{s_filesx[i]}; s_regex.emplace_back (regex (restriction.data ())); debugf (1, "Target restriction: '%s'\n", restriction.data ()); } } debugf (1, "Final target: %s\n", s_target.data ()); // Validate ingested args if (s_accept.size () < 2 && s_reject.size () < 2) { syntax ("specify at least one accept or reject str"); } // Compile and check for collisions between accept and reject lists compile (); // Initialize firsts to enable buffer skipping debugf (1, "FIRSTS B: '%s'\n", s_firsts.c_str ()); sort (s_firsts.begin (), s_firsts.end ()); auto last = unique (s_firsts.begin (), s_firsts.end ()); s_firsts.erase (last, s_firsts.end ()); debugf (1, "FIRSTS A: '%s'\n", s_firsts.c_str ()); // Visually inspect planes if (s_debug) { dump ("temp.dump", "Trial dump"); show_tables (cout); show_tokens (cout); } debugf (1, "FIRSTS: %s\n", s_firsts.c_str ()); bool https {s_target.substr (0, 8) == "https://"}; bool http {s_target.substr (0, 7) == "http://"}; bool ftp {s_target.substr (0, 6) == "ftp://"}; if (https || http || ftp) { netsearch (s_target); } else { // Find files and search contents walk (s_target); } } // operator () //------------------------------------------------------------------------------ /// @brief ingest inserts state-transition table data bool Lettvin::GreasedGrep:: option (string_view a_str) //------------------------------------------------------------------------------ { size_t size {a_str.size ()}; bool two {size == 2}; bool more {size > 2}; bool minus1 {a_str[0] == '-'}; bool opt {two && minus1}; bool bad {!(two || more)}; bool strs {s_accept.size () > 1 || s_reject.size () > 1}; bool nbls {s_shape.nibbles ()}; char letter {two ? a_str[1] : '\0'}; if (!minus1) { return false; } if (strs) { syntax ("(%s) options must precede other args", a_str.data ()); } if (bad) { syntax ("command-line options must be two or more chars"); } // Doing debug first is special //s_debug += (a_str == "--debug"); //s_debug += (two && (letter == 'd')); if (a_str.size () == 2 && isdigit(a_str[1])) { s_oversize = (size_t)(a_str[1] - '0'); s_oversize = s_oversize ? s_oversize : 1; debugf (1, "CORE MULTIPLIER (%u)\n", s_oversize); return true; } debugf (1, "OPTION: preparse: '%s'\n", a_str.data ()); bool l_nibbles{false}; if (a_str == "--case" || (opt && letter == 'c')) s_caseless = false; else if (a_str == "--debug" || (opt && letter == 'd')) s_debug += 1; else if (a_str == "--nibbles" || (opt && letter == 'n')) l_nibbles = true; else if (a_str == "--quicktree"|| (opt && letter == 'q')) s_quicktree= true; else if (a_str == "--suppress" || (opt && letter == 's')) s_suppress = true; else if (a_str == "--test" || (opt && letter == 't')) s_test = true; else if (a_str == "--variant" || (opt && letter == 'v')) s_variant = true; else if (a_str[0] == a_str[1] && a_str[1] == '-') { debugf (1, "OPTIONS:\n"); for (size_t I=a_str.size (), i=2; i < I; ++i) { char opt{a_str[i]}; debugf (1, "OPTION: '%c'\n", opt); switch (opt) { case 'c': option ("-c"); break; case 'd': option ("-d"); break; case 'n': option ("-n"); break; case 's': option ("-s"); break; case 't': option ("-t"); break; case 'v': option ("-v"); break; default: syntax ("OPTION: '%c' is illegal", a_str[i]); break; } } } else if (opt) { syntax ("unknown arg '%s'", a_str.data ()); } else { return false; } if (l_nibbles && !nbls) { /// This is where command-line option -n causes plane size to change. s_shape (true); } return true; } //------------------------------------------------------------------------------ /// @brief ingest inserts state-transition table data // // For now, gg fails when GG_COMPILE is defined void Lettvin::GreasedGrep:: ingest (string_view a_str) //------------------------------------------------------------------------------ { // Handle options size_t size{a_str.size ()}; bool minus1{size == 2 && a_str[0] == '-'}; bool minus2{size >= 2 && a_str[0] == '-' && a_str[1] == '-'}; debugf (1, "INGEST: %d %d %s\n", minus1, minus2, a_str.data ()); if ((minus1 || minus2) && option (a_str)) return; if (s_target.size ()) { string_view candidate {s_target}; char c0 {candidate[0]}; bool rejecting {c0 == '-'}; auto& field {rejecting ? s_reject : s_accept}; candidate.remove_prefix ((c0=='+' || c0=='-') ? 1 : 0); if (candidate.size () < 2) { syntax ("pattern strings must be longer than 1 byte"); } field.push_back (candidate); #ifndef GG_COMPILE // This compile passes i24_t sign {rejecting?-1:+1}; compile (sign, candidate); #endif } s_target = a_str; } // ingest //------------------------------------------------------------------------------ /// @brief ingest inserts state-transition table data void Lettvin::GreasedGrep:: compile (int32_t a_sign) //------------------------------------------------------------------------------ { if (!a_sign) { compile (+1); compile (-1); return; } bool rejecting {a_sign == -1}; auto& field {rejecting ? s_reject : s_accept}; size_t I {field.size ()}; //< s_noreject optimizes inner loop if (rejecting && I > 1) { s_noreject = false; } #ifdef GG_COMPILE // This compile fails for (size_t i = 1; i < I; ++i) { compile (a_sign, field[i]); } #endif } //------------------------------------------------------------------------------ /// @brief compile a single string argument /// /// Distribute characters into state tables for searching. void Lettvin::GreasedGrep:: compile (int32_t a_sign, string_view a_sv) //------------------------------------------------------------------------------ { debugf (1, "COMPILE %+d: %s\n", a_sign, a_sv.data ()); bool rejecting {a_sign == -1}; auto from {s_root}; auto next {from}; char last[2] {0,0}; auto& field {rejecting ? s_reject : s_accept}; i24_t id {a_sign*static_cast<i24_t> (field.size () - 1)}; string b_str {}; string a_str {a_sv}; TODO(setindex is used as an indirect forward reference from an Transition.) // s_set[setindex] are the direct forward references of candidates which // terminate on a particular Transition. // When using variants, the probability of token identity drops with // each addition to the set. size_t setindex = insert (a_str, id); set<int32_t>& setterminal{s_set[setindex]}; ///< 1st & variant terminals vs_t variant_names; vs_t strs; bool caseless{s_caseless}; if (s_variant) { size_t bracket_init{a_sv.find_first_of ('[')}; if (bracket_init != string_view::npos) { size_t bracket_fini{a_sv.find_first_of (']', bracket_init + 1)}; if (bracket_fini == string_view::npos) { syntax ("bracketd variants"); } debugf (1, "BR %zu %zu\n", bracket_init, bracket_fini); b_str = a_sv.substr (bracket_init + 1, bracket_fini - bracket_init - 1); a_str = a_sv.substr (0, bracket_init); debugf (1, "Bracketed [%s][%s]\n", a_str.c_str (), b_str.c_str ()); TODO(use gg_utility.h tokenize here) size_t comma = b_str.find_first_of (','); while (comma != string::npos) { string token = b_str.substr (0, comma); b_str = b_str.substr (comma + 1); comma = b_str.find_first_of (','); is_variant (token.c_str ()) ? register_variant (variant_names, token) : descramble_variants (variant_names, token); } if (b_str.size ()) { is_variant (b_str.c_str ()) ? register_variant (variant_names, b_str) : descramble_variants (variant_names, b_str); } } // Have all specified variant functions add to the alternatives. for (auto& variant:variant_names) { const auto& generator_iter = s_variant_generator.find (variant); if (generator_iter != s_variant_generator.end ()) { generator_iter->second (strs, a_str); } } } // Reduce the alternatives to the set of uniques set<string> unique; for (auto& item:strs) unique.insert (item); strs.clear (); for (auto& item:unique) strs.emplace_back (item); // Insert variants into transition tree for (auto& str: strs) { insert (str, id, setindex); } s_caseless = caseless; } //------------------------------------------------------------------------------ /// @brief map file into memory and call search /// /// https://techoverflow.net/2013/08/21/a-simple-mmap-readonly-example/ void Lettvin::GreasedGrep:: mapped_search (const char* a_filename) //------------------------------------------------------------------------------ { struct stat st; stat (a_filename, &st); auto filesize{st.st_size}; if (!filesize) { return; // Can't search an empty file } int32_t fd{0}; int err{0}; if (s_quicktree) { printf ("gg:quicktree (%s)\n", a_filename); return; } if (s_regex.size ()) { TODO(return if filename pattern does not match a filesx) bool matched{false}; for (auto& matcher:s_regex) { matched |= regex_search (a_filename, matcher); } if (!matched) { return; } } try { std::unique_lock<std::mutex> lck (open_mtx, std::defer_lock); lck.lock (); errno = 0; fd = open (a_filename, O_RDONLY, 0); err = errno; lck.unlock (); } catch (...) { if (fd > 0) close (fd); if (!s_suppress) { printf ("gg:mapped_search OPEN EXCEPTION: %s\n", a_filename); } return; } if (fd >= 0) { std::unique_lock<std::mutex> lck (open_mtx, std::defer_lock); lck.lock (); errno = 0; void* contents = mmap ( NULL, filesize, PROT_READ, // Optimize out dirty pages MAP_PRIVATE | MAP_POPULATE, // Allow preload fd, 0); err = errno; lck.unlock (); if (contents == MAP_FAILED) { if (err == ENODEV) { if (fd > 0) close (fd); return; // TODO discover why this ever occurs. } if (!s_suppress) { printf ("gg:mapped_search MAP FAILED(%d): %s\n", err, a_filename); } } else { track (contents, filesize, a_filename); int32_t rc = munmap (contents, filesize); if (rc != 0) synopsis ("munmap failed"); } close (fd); } else if (!s_suppress) { // TODO eliminate EMFILE (24) printf ("gg:mapped_search OPEN FAILED(%d): %s\n", err, a_filename); } } // mapped_search //------------------------------------------------------------------------------ /// @brief run search on incoming packets void Lettvin::GreasedGrep:: netsearch (string_view a_URL) { a_URL = a_URL; } //------------------------------------------------------------------------------ /// @brief walk organizes search for strings in memory-mapped file void Lettvin::GreasedGrep:: walk (const string& a_path) { // Don't attempt to assess validity of filenames... just fail. // Treat directories like files and search filenames in directories. // This enables gg to work on sshfs mounted filesystems. auto d{a_path}; auto s{d.size ()}; if (s && d[s - 1] == '/') d.resize (s-1); errno = 0; if (auto dir = opendir (d.c_str ())) { while (!errno) { if (auto f = readdir (dir)) { if (auto p = f->d_name) { if (auto q = p) { if (!(*q++ == '.' && (!*q || (*q++ == '.' && !*q)))) { auto e = d + "/" + p; walk (e); mapped_search (e.c_str ()); errno = 0; } } else break; } else break; } else break; } } } //------------------------------------------------------------------------------ void Lettvin::GreasedGrep:: show_tokens (ostream& a_os) //------------------------------------------------------------------------------ { a_os << " # ACCEPT:" << endl; for (size_t i=1; i < s_accept.size (); ++i) { a_os << " # " << setw (2) << i << ": " << s_accept[i] << endl; } a_os << " # REJECT:" << endl; for (size_t i=1; i < s_reject.size (); ++i) { a_os << " # " << setw (2) << i << ": " << s_reject[i] << endl; } } // show_tokens
17,049
6,418
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" // INCLUDE ------------------------------------------------------------------- #include "scitems.hxx" #include <editeng/boxitem.hxx> #include <svl/srchitem.hxx> #include <sfx2/linkmgr.hxx> #include <sfx2/bindings.hxx> #include <vcl/virdev.hxx> #include <sfx2/app.hxx> #include "undoblk.hxx" #include "sc.hrc" #include "globstr.hrc" #include "global.hxx" #include "rangenam.hxx" #include "arealink.hxx" #include "patattr.hxx" #include "target.hxx" #include "document.hxx" #include "docpool.hxx" #include "table.hxx" #include "docsh.hxx" #include "tabvwsh.hxx" #include "undoolk.hxx" #include "undoutil.hxx" #include "chgtrack.hxx" #include "dociter.hxx" #include "cell.hxx" #include "paramisc.hxx" #include "postit.hxx" #include "docuno.hxx" // STATIC DATA --------------------------------------------------------------- TYPEINIT1(ScUndoDeleteContents, SfxUndoAction); TYPEINIT1(ScUndoFillTable, SfxUndoAction); TYPEINIT1(ScUndoSelectionAttr, SfxUndoAction); TYPEINIT1(ScUndoAutoFill, SfxUndoAction); TYPEINIT1(ScUndoMerge, SfxUndoAction); TYPEINIT1(ScUndoAutoFormat, SfxUndoAction); TYPEINIT1(ScUndoReplace, SfxUndoAction); TYPEINIT1(ScUndoTabOp, SfxUndoAction); TYPEINIT1(ScUndoConversion, SfxUndoAction); TYPEINIT1(ScUndoRefConversion, SfxUndoAction); TYPEINIT1(ScUndoRefreshLink, SfxUndoAction); TYPEINIT1(ScUndoInsertAreaLink, SfxUndoAction); TYPEINIT1(ScUndoRemoveAreaLink, SfxUndoAction); TYPEINIT1(ScUndoUpdateAreaLink, SfxUndoAction); // To Do: /*A*/ // SetOptimalHeight auf Dokument, wenn keine View //============================================================================ // class ScUndoDeleteContents // // Inhalte loeschen //---------------------------------------------------------------------------- ScUndoDeleteContents::ScUndoDeleteContents( ScDocShell* pNewDocShell, const ScMarkData& rMark, const ScRange& rRange, ScDocument* pNewUndoDoc, sal_Bool bNewMulti, sal_uInt16 nNewFlags, sal_Bool bObjects ) // : ScSimpleUndo( pNewDocShell ), // aRange ( rRange ), aMarkData ( rMark ), pUndoDoc ( pNewUndoDoc ), pDrawUndo ( NULL ), nFlags ( nNewFlags ), bMulti ( bNewMulti ) // ueberliquid { if (bObjects) pDrawUndo = GetSdrUndoAction( pDocShell->GetDocument() ); if ( !(aMarkData.IsMarked() || aMarkData.IsMultiMarked()) ) // keine Zelle markiert: aMarkData.SetMarkArea( aRange ); // Zelle unter Cursor markieren SetChangeTrack(); } //---------------------------------------------------------------------------- __EXPORT ScUndoDeleteContents::~ScUndoDeleteContents() { delete pUndoDoc; DeleteSdrUndoAction( pDrawUndo ); } //---------------------------------------------------------------------------- String __EXPORT ScUndoDeleteContents::GetComment() const { return ScGlobal::GetRscString( STR_UNDO_DELETECONTENTS ); // "Loeschen" } void ScUndoDeleteContents::SetChangeTrack() { ScChangeTrack* pChangeTrack = pDocShell->GetDocument()->GetChangeTrack(); if ( pChangeTrack && (nFlags & IDF_CONTENTS) ) pChangeTrack->AppendContentRange( aRange, pUndoDoc, nStartChangeAction, nEndChangeAction ); else nStartChangeAction = nEndChangeAction = 0; } //---------------------------------------------------------------------------- void ScUndoDeleteContents::DoChange( const sal_Bool bUndo ) { ScDocument* pDoc = pDocShell->GetDocument(); SetViewMarkData( aMarkData ); sal_uInt16 nExtFlags = 0; if (bUndo) // nur Undo { sal_uInt16 nUndoFlags = IDF_NONE; // entweder alle oder keine Inhalte kopieren if (nFlags & IDF_CONTENTS) // (es sind nur die richtigen ins UndoDoc kopiert worden) nUndoFlags |= IDF_CONTENTS; if (nFlags & IDF_ATTRIB) nUndoFlags |= IDF_ATTRIB; if (nFlags & IDF_EDITATTR) // Edit-Engine-Attribute nUndoFlags |= IDF_STRING; // -> Zellen werden geaendert // do not create clones of note captions, they will be restored via drawing undo nUndoFlags |= IDF_NOCAPTIONS; ScRange aCopyRange = aRange; SCTAB nTabCount = pDoc->GetTableCount(); aCopyRange.aStart.SetTab(0); aCopyRange.aEnd.SetTab(nTabCount-1); pUndoDoc->CopyToDocument( aCopyRange, nUndoFlags, bMulti, pDoc, &aMarkData ); DoSdrUndoAction( pDrawUndo, pDoc ); ScChangeTrack* pChangeTrack = pDoc->GetChangeTrack(); if ( pChangeTrack ) pChangeTrack->Undo( nStartChangeAction, nEndChangeAction ); pDocShell->UpdatePaintExt( nExtFlags, aRange ); // content after the change } else // nur Redo { pDocShell->UpdatePaintExt( nExtFlags, aRange ); // content before the change aMarkData.MarkToMulti(); RedoSdrUndoAction( pDrawUndo ); // do not delete objects and note captions, they have been removed via drawing undo sal_uInt16 nRedoFlags = (nFlags & ~IDF_OBJECTS) | IDF_NOCAPTIONS; pDoc->DeleteSelection( nRedoFlags, aMarkData ); aMarkData.MarkToSimple(); SetChangeTrack(); } ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if ( !( (pViewShell) && pViewShell->AdjustRowHeight( aRange.aStart.Row(), aRange.aEnd.Row() ) ) ) /*A*/ pDocShell->PostPaint( aRange, PAINT_GRID | PAINT_EXTRAS, nExtFlags ); pDocShell->PostDataChanged(); if (pViewShell) pViewShell->CellContentChanged(); ShowTable( aRange ); } //---------------------------------------------------------------------------- void __EXPORT ScUndoDeleteContents::Undo() { BeginUndo(); DoChange( sal_True ); EndUndo(); // #i97876# Spreadsheet data changes are not notified ScModelObj* pModelObj = ScModelObj::getImplementation( pDocShell->GetModel() ); if ( pModelObj && pModelObj->HasChangesListeners() ) { ScRangeList aChangeRanges; aChangeRanges.Append( aRange ); pModelObj->NotifyChanges( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "cell-change" ) ), aChangeRanges ); } } //---------------------------------------------------------------------------- void __EXPORT ScUndoDeleteContents::Redo() { BeginRedo(); DoChange( sal_False ); EndRedo(); // #i97876# Spreadsheet data changes are not notified ScModelObj* pModelObj = ScModelObj::getImplementation( pDocShell->GetModel() ); if ( pModelObj && pModelObj->HasChangesListeners() ) { ScRangeList aChangeRanges; aChangeRanges.Append( aRange ); pModelObj->NotifyChanges( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "cell-change" ) ), aChangeRanges ); } } //---------------------------------------------------------------------------- void __EXPORT ScUndoDeleteContents::Repeat(SfxRepeatTarget& rTarget) { if (rTarget.ISA(ScTabViewTarget)) ((ScTabViewTarget&)rTarget).GetViewShell()->DeleteContents( nFlags, sal_True ); } //---------------------------------------------------------------------------- sal_Bool __EXPORT ScUndoDeleteContents::CanRepeat(SfxRepeatTarget& rTarget) const { return (rTarget.ISA(ScTabViewTarget)); } //============================================================================ // class ScUndoFillTable // // Tabellen ausfuellen // (Bearbeiten|Ausfuellen|...) //---------------------------------------------------------------------------- ScUndoFillTable::ScUndoFillTable( ScDocShell* pNewDocShell, const ScMarkData& rMark, SCCOL nStartX, SCROW nStartY, SCTAB nStartZ, SCCOL nEndX, SCROW nEndY, SCTAB nEndZ, ScDocument* pNewUndoDoc, sal_Bool bNewMulti, SCTAB nSrc, sal_uInt16 nFlg, sal_uInt16 nFunc, sal_Bool bSkip, sal_Bool bLink ) // : ScSimpleUndo( pNewDocShell ), // aRange ( nStartX, nStartY, nStartZ, nEndX, nEndY, nEndZ ), aMarkData ( rMark ), pUndoDoc ( pNewUndoDoc ), nFlags ( nFlg ), nFunction ( nFunc ), nSrcTab ( nSrc ), bMulti ( bNewMulti ), bSkipEmpty ( bSkip ), bAsLink ( bLink ) { SetChangeTrack(); } //---------------------------------------------------------------------------- __EXPORT ScUndoFillTable::~ScUndoFillTable() { delete pUndoDoc; } //---------------------------------------------------------------------------- String __EXPORT ScUndoFillTable::GetComment() const { return ScGlobal::GetRscString( STR_FILL_TAB ); } void ScUndoFillTable::SetChangeTrack() { ScChangeTrack* pChangeTrack = pDocShell->GetDocument()->GetChangeTrack(); if ( pChangeTrack ) { SCTAB nTabCount = pDocShell->GetDocument()->GetTableCount(); ScRange aWorkRange(aRange); nStartChangeAction = 0; sal_uLong nTmpAction; for ( SCTAB i = 0; i < nTabCount; i++ ) { if (i != nSrcTab && aMarkData.GetTableSelect(i)) { aWorkRange.aStart.SetTab(i); aWorkRange.aEnd.SetTab(i); pChangeTrack->AppendContentRange( aWorkRange, pUndoDoc, nTmpAction, nEndChangeAction ); if ( !nStartChangeAction ) nStartChangeAction = nTmpAction; } } } else nStartChangeAction = nEndChangeAction = 0; } //---------------------------------------------------------------------------- void ScUndoFillTable::DoChange( const sal_Bool bUndo ) { ScDocument* pDoc = pDocShell->GetDocument(); SetViewMarkData( aMarkData ); if (bUndo) // nur Undo { SCTAB nTabCount = pDoc->GetTableCount(); ScRange aWorkRange(aRange); for ( SCTAB i = 0; i < nTabCount; i++ ) if (i != nSrcTab && aMarkData.GetTableSelect(i)) { aWorkRange.aStart.SetTab(i); aWorkRange.aEnd.SetTab(i); if (bMulti) pDoc->DeleteSelectionTab( i, IDF_ALL, aMarkData ); else pDoc->DeleteAreaTab( aWorkRange, IDF_ALL ); pUndoDoc->CopyToDocument( aWorkRange, IDF_ALL, bMulti, pDoc, &aMarkData ); } ScChangeTrack* pChangeTrack = pDoc->GetChangeTrack(); if ( pChangeTrack ) pChangeTrack->Undo( nStartChangeAction, nEndChangeAction ); } else // nur Redo { aMarkData.MarkToMulti(); pDoc->FillTabMarked( nSrcTab, aMarkData, nFlags, nFunction, bSkipEmpty, bAsLink ); aMarkData.MarkToSimple(); SetChangeTrack(); } pDocShell->PostPaint(0,0,0,MAXCOL,MAXROW,MAXTAB, PAINT_GRID|PAINT_EXTRAS); pDocShell->PostDataChanged(); // CellContentChanged kommt mit der Markierung ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) { SCTAB nTab = pViewShell->GetViewData()->GetTabNo(); if ( !aMarkData.GetTableSelect(nTab) ) pViewShell->SetTabNo( nSrcTab ); pViewShell->DoneBlockMode(); // gibt sonst Probleme, weil Markierung auf falscher Tabelle } } //---------------------------------------------------------------------------- void __EXPORT ScUndoFillTable::Undo() { BeginUndo(); DoChange( sal_True ); EndUndo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoFillTable::Redo() { BeginRedo(); DoChange( sal_False ); EndRedo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoFillTable::Repeat(SfxRepeatTarget& rTarget) { if (rTarget.ISA(ScTabViewTarget)) ((ScTabViewTarget&)rTarget).GetViewShell()->FillTab( nFlags, nFunction, bSkipEmpty, bAsLink ); } //---------------------------------------------------------------------------- sal_Bool __EXPORT ScUndoFillTable::CanRepeat(SfxRepeatTarget& rTarget) const { return (rTarget.ISA(ScTabViewTarget)); } //============================================================================ // class ScUndoSelectionAttr // // Zellformat aendern //---------------------------------------------------------------------------- ScUndoSelectionAttr::ScUndoSelectionAttr( ScDocShell* pNewDocShell, const ScMarkData& rMark, SCCOL nStartX, SCROW nStartY, SCTAB nStartZ, SCCOL nEndX, SCROW nEndY, SCTAB nEndZ, ScDocument* pNewUndoDoc, sal_Bool bNewMulti, const ScPatternAttr* pNewApply, const SvxBoxItem* pNewOuter, const SvxBoxInfoItem* pNewInner ) // : ScSimpleUndo( pNewDocShell ), // aMarkData ( rMark ), aRange ( nStartX, nStartY, nStartZ, nEndX, nEndY, nEndZ ), pUndoDoc ( pNewUndoDoc ), bMulti ( bNewMulti ) { ScDocumentPool* pPool = pDocShell->GetDocument()->GetPool(); pApplyPattern = (ScPatternAttr*) &pPool->Put( *pNewApply ); pLineOuter = pNewOuter ? (SvxBoxItem*) &pPool->Put( *pNewOuter ) : NULL; pLineInner = pNewInner ? (SvxBoxInfoItem*) &pPool->Put( *pNewInner ) : NULL; } //---------------------------------------------------------------------------- __EXPORT ScUndoSelectionAttr::~ScUndoSelectionAttr() { ScDocumentPool* pPool = pDocShell->GetDocument()->GetPool(); pPool->Remove(*pApplyPattern); if (pLineOuter) pPool->Remove(*pLineOuter); if (pLineInner) pPool->Remove(*pLineInner); delete pUndoDoc; } //---------------------------------------------------------------------------- String __EXPORT ScUndoSelectionAttr::GetComment() const { //"Attribute" "/Linien" return ScGlobal::GetRscString( pLineOuter ? STR_UNDO_SELATTRLINES : STR_UNDO_SELATTR ); } //---------------------------------------------------------------------------- void ScUndoSelectionAttr::DoChange( const sal_Bool bUndo ) { ScDocument* pDoc = pDocShell->GetDocument(); SetViewMarkData( aMarkData ); ScRange aEffRange( aRange ); if ( pDoc->HasAttrib( aEffRange, HASATTR_MERGED ) ) // zusammengefasste Zellen? pDoc->ExtendMerge( aEffRange ); sal_uInt16 nExtFlags = 0; pDocShell->UpdatePaintExt( nExtFlags, aEffRange ); if (bUndo) // nur bei Undo { ScRange aCopyRange = aRange; SCTAB nTabCount = pDoc->GetTableCount(); aCopyRange.aStart.SetTab(0); aCopyRange.aEnd.SetTab(nTabCount-1); pUndoDoc->CopyToDocument( aCopyRange, IDF_ATTRIB, bMulti, pDoc, &aMarkData ); } else // nur bei Redo { aMarkData.MarkToMulti(); pDoc->ApplySelectionPattern( *pApplyPattern, aMarkData ); aMarkData.MarkToSimple(); if (pLineOuter) pDoc->ApplySelectionFrame( aMarkData, pLineOuter, pLineInner ); } ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if ( !( (pViewShell) && pViewShell->AdjustBlockHeight() ) ) /*A*/ pDocShell->PostPaint( aEffRange, PAINT_GRID | PAINT_EXTRAS, nExtFlags ); ShowTable( aRange ); } //---------------------------------------------------------------------------- void __EXPORT ScUndoSelectionAttr::Undo() { BeginUndo(); DoChange( sal_True ); EndUndo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoSelectionAttr::Redo() { BeginRedo(); DoChange( sal_False ); EndRedo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoSelectionAttr::Repeat(SfxRepeatTarget& rTarget) { if (rTarget.ISA(ScTabViewTarget)) { ScTabViewShell& rViewShell = *((ScTabViewTarget&)rTarget).GetViewShell(); if (pLineOuter) rViewShell.ApplyPatternLines( *pApplyPattern, pLineOuter, pLineInner, sal_True ); else rViewShell.ApplySelectionPattern( *pApplyPattern, sal_True ); } } //---------------------------------------------------------------------------- sal_Bool __EXPORT ScUndoSelectionAttr::CanRepeat(SfxRepeatTarget& rTarget) const { return (rTarget.ISA(ScTabViewTarget)); } //============================================================================ // class ScUndoAutoFill // // Auto-Fill (nur einfache Bloecke) //---------------------------------------------------------------------------- ScUndoAutoFill::ScUndoAutoFill( ScDocShell* pNewDocShell, const ScRange& rRange, const ScRange& rSourceArea, ScDocument* pNewUndoDoc, const ScMarkData& rMark, FillDir eNewFillDir, FillCmd eNewFillCmd, FillDateCmd eNewFillDateCmd, double fNewStartValue, double fNewStepValue, double fNewMaxValue, sal_uInt16 nMaxShIndex ) // : ScBlockUndo( pNewDocShell, rRange, SC_UNDO_AUTOHEIGHT ), // aSource ( rSourceArea ), aMarkData ( rMark ), pUndoDoc ( pNewUndoDoc ), eFillDir ( eNewFillDir ), eFillCmd ( eNewFillCmd ), eFillDateCmd ( eNewFillDateCmd ), fStartValue ( fNewStartValue ), fStepValue ( fNewStepValue ), fMaxValue ( fNewMaxValue ), nMaxSharedIndex ( nMaxShIndex) { SetChangeTrack(); } //---------------------------------------------------------------------------- __EXPORT ScUndoAutoFill::~ScUndoAutoFill() { pDocShell->GetDocument()->EraseNonUsedSharedNames(nMaxSharedIndex); delete pUndoDoc; } //---------------------------------------------------------------------------- String __EXPORT ScUndoAutoFill::GetComment() const { return ScGlobal::GetRscString( STR_UNDO_AUTOFILL ); //"Ausfuellen" } void ScUndoAutoFill::SetChangeTrack() { ScChangeTrack* pChangeTrack = pDocShell->GetDocument()->GetChangeTrack(); if ( pChangeTrack ) pChangeTrack->AppendContentRange( aBlockRange, pUndoDoc, nStartChangeAction, nEndChangeAction ); else nStartChangeAction = nEndChangeAction = 0; } //---------------------------------------------------------------------------- void __EXPORT ScUndoAutoFill::Undo() { BeginUndo(); ScDocument* pDoc = pDocShell->GetDocument(); SCTAB nTabCount = pDoc->GetTableCount(); for (SCTAB nTab=0; nTab<nTabCount; nTab++) { if (aMarkData.GetTableSelect(nTab)) { ScRange aWorkRange = aBlockRange; aWorkRange.aStart.SetTab(nTab); aWorkRange.aEnd.SetTab(nTab); sal_uInt16 nExtFlags = 0; pDocShell->UpdatePaintExt( nExtFlags, aWorkRange ); pDoc->DeleteAreaTab( aWorkRange, IDF_AUTOFILL ); pUndoDoc->CopyToDocument( aWorkRange, IDF_AUTOFILL, sal_False, pDoc ); pDoc->ExtendMerge( aWorkRange, sal_True ); pDocShell->PostPaint( aWorkRange, PAINT_GRID, nExtFlags ); } } pDocShell->PostDataChanged(); ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) pViewShell->CellContentChanged(); // Shared-Names loeschen // Falls Undo ins Dokument gespeichert // => automatisches Loeschen am Ende // umarbeiten!! String aName = String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("___SC_")); aName += String::CreateFromInt32(nMaxSharedIndex); aName += '_'; ScRangeName* pRangeName = pDoc->GetRangeName(); sal_Bool bHasFound = sal_False; for (sal_uInt16 i = 0; i < pRangeName->GetCount(); i++) { ScRangeData* pRangeData = (*pRangeName)[i]; if (pRangeData) { String aRName; pRangeData->GetName(aRName); if (aRName.Search(aName) != STRING_NOTFOUND) { pRangeName->AtFree(i); bHasFound = sal_True; } } } if (bHasFound) pRangeName->SetSharedMaxIndex(pRangeName->GetSharedMaxIndex()-1); ScChangeTrack* pChangeTrack = pDoc->GetChangeTrack(); if ( pChangeTrack ) pChangeTrack->Undo( nStartChangeAction, nEndChangeAction ); EndUndo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoAutoFill::Redo() { BeginRedo(); //! Tabellen selektieren SCCOLROW nCount = 0; switch (eFillDir) { case FILL_TO_BOTTOM: nCount = aBlockRange.aEnd.Row() - aSource.aEnd.Row(); break; case FILL_TO_RIGHT: nCount = aBlockRange.aEnd.Col() - aSource.aEnd.Col(); break; case FILL_TO_TOP: nCount = aSource.aStart.Row() - aBlockRange.aStart.Row(); break; case FILL_TO_LEFT: nCount = aSource.aStart.Col() - aBlockRange.aStart.Col(); break; } ScDocument* pDoc = pDocShell->GetDocument(); if ( fStartValue != MAXDOUBLE ) { SCCOL nValX = (eFillDir == FILL_TO_LEFT) ? aSource.aEnd.Col() : aSource.aStart.Col(); SCROW nValY = (eFillDir == FILL_TO_TOP ) ? aSource.aEnd.Row() : aSource.aStart.Row(); SCTAB nTab = aSource.aStart.Tab(); pDoc->SetValue( nValX, nValY, nTab, fStartValue ); } pDoc->Fill( aSource.aStart.Col(), aSource.aStart.Row(), aSource.aEnd.Col(), aSource.aEnd.Row(), aMarkData, nCount, eFillDir, eFillCmd, eFillDateCmd, fStepValue, fMaxValue ); SetChangeTrack(); pDocShell->PostPaint( aBlockRange, PAINT_GRID ); pDocShell->PostDataChanged(); ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) pViewShell->CellContentChanged(); EndRedo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoAutoFill::Repeat(SfxRepeatTarget& rTarget) { if (rTarget.ISA(ScTabViewTarget)) { ScTabViewShell& rViewShell = *((ScTabViewTarget&)rTarget).GetViewShell(); if (eFillCmd==FILL_SIMPLE) rViewShell.FillSimple( eFillDir, sal_True ); else rViewShell.FillSeries( eFillDir, eFillCmd, eFillDateCmd, fStartValue, fStepValue, fMaxValue, sal_True ); } } //---------------------------------------------------------------------------- sal_Bool __EXPORT ScUndoAutoFill::CanRepeat(SfxRepeatTarget& rTarget) const { return (rTarget.ISA(ScTabViewTarget)); } //============================================================================ // class ScUndoMerge // // Zellen zusammenfassen / Zusammenfassung aufheben //---------------------------------------------------------------------------- ScUndoMerge::ScUndoMerge( ScDocShell* pNewDocShell, SCCOL nStartX, SCROW nStartY, SCTAB nStartZ, SCCOL nEndX, SCROW nEndY, SCTAB nEndZ, bool bMergeContents, ScDocument* pUndoDoc, SdrUndoAction* pDrawUndo ) // : ScSimpleUndo( pNewDocShell ), // maRange( nStartX, nStartY, nStartZ, nEndX, nEndY, nEndZ ), mbMergeContents( bMergeContents ), mpUndoDoc( pUndoDoc ), mpDrawUndo( pDrawUndo ) { } //---------------------------------------------------------------------------- ScUndoMerge::~ScUndoMerge() { delete mpUndoDoc; DeleteSdrUndoAction( mpDrawUndo ); } //---------------------------------------------------------------------------- String ScUndoMerge::GetComment() const { return ScGlobal::GetRscString( STR_UNDO_MERGE ); } //---------------------------------------------------------------------------- void ScUndoMerge::DoChange( bool bUndo ) const { ScDocument* pDoc = pDocShell->GetDocument(); ScUndoUtil::MarkSimpleBlock( pDocShell, maRange ); if (bUndo) // remove merge (contents are copied back below from undo document) pDoc->RemoveMerge( maRange.aStart.Col(), maRange.aStart.Row(), maRange.aStart.Tab() ); else // repeat merge, but do not remove note captions (will be done by drawing redo below) /*!*/ pDoc->DoMerge( maRange.aStart.Tab(), maRange.aStart.Col(), maRange.aStart.Row(), maRange.aEnd.Col(), maRange.aEnd.Row(), false ); // undo -> copy back deleted contents if (bUndo && mpUndoDoc) { pDoc->DeleteAreaTab( maRange, IDF_CONTENTS|IDF_NOCAPTIONS ); mpUndoDoc->CopyToDocument( maRange, IDF_ALL|IDF_NOCAPTIONS, sal_False, pDoc ); } // redo -> merge contents again else if (!bUndo && mbMergeContents) { /*!*/ pDoc->DoMergeContents( maRange.aStart.Tab(), maRange.aStart.Col(), maRange.aStart.Row(), maRange.aEnd.Col(), maRange.aEnd.Row() ); } if (bUndo) DoSdrUndoAction( mpDrawUndo, pDoc ); else RedoSdrUndoAction( mpDrawUndo ); sal_Bool bDidPaint = sal_False; ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if ( pViewShell ) { pViewShell->SetTabNo( maRange.aStart.Tab() ); bDidPaint = pViewShell->AdjustRowHeight( maRange.aStart.Row(), maRange.aEnd.Row() ); } if (!bDidPaint) ScUndoUtil::PaintMore( pDocShell, maRange ); ShowTable( maRange ); } //---------------------------------------------------------------------------- void ScUndoMerge::Undo() { BeginUndo(); DoChange( true ); EndUndo(); } //---------------------------------------------------------------------------- void ScUndoMerge::Redo() { BeginRedo(); DoChange( false ); EndRedo(); } //---------------------------------------------------------------------------- void ScUndoMerge::Repeat(SfxRepeatTarget& rTarget) { if (rTarget.ISA(ScTabViewTarget)) { ScTabViewShell& rViewShell = *((ScTabViewTarget&)rTarget).GetViewShell(); sal_Bool bCont = sal_False; rViewShell.MergeCells( sal_False, bCont, sal_True ); } } //---------------------------------------------------------------------------- sal_Bool ScUndoMerge::CanRepeat(SfxRepeatTarget& rTarget) const { return (rTarget.ISA(ScTabViewTarget)); } //============================================================================ // class ScUndoAutoFormat // // Auto-Format (nur einfache Bloecke) //---------------------------------------------------------------------------- ScUndoAutoFormat::ScUndoAutoFormat( ScDocShell* pNewDocShell, const ScRange& rRange, ScDocument* pNewUndoDoc, const ScMarkData& rMark, sal_Bool bNewSize, sal_uInt16 nNewFormatNo ) // : ScBlockUndo( pNewDocShell, rRange, bNewSize ? SC_UNDO_MANUALHEIGHT : SC_UNDO_AUTOHEIGHT ), // pUndoDoc ( pNewUndoDoc ), aMarkData ( rMark ), bSize ( bNewSize ), nFormatNo ( nNewFormatNo ) { } //---------------------------------------------------------------------------- __EXPORT ScUndoAutoFormat::~ScUndoAutoFormat() { delete pUndoDoc; } //---------------------------------------------------------------------------- String __EXPORT ScUndoAutoFormat::GetComment() const { return ScGlobal::GetRscString( STR_UNDO_AUTOFORMAT ); //"Auto-Format" } //---------------------------------------------------------------------------- void __EXPORT ScUndoAutoFormat::Undo() { BeginUndo(); ScDocument* pDoc = pDocShell->GetDocument(); // Attribute // pDoc->DeleteAreaTab( aBlockRange, IDF_ATTRIB ); // pUndoDoc->CopyToDocument( aBlockRange, IDF_ATTRIB, sal_False, pDoc ); SCTAB nTabCount = pDoc->GetTableCount(); pDoc->DeleteArea( aBlockRange.aStart.Col(), aBlockRange.aStart.Row(), aBlockRange.aEnd.Col(), aBlockRange.aEnd.Row(), aMarkData, IDF_ATTRIB ); ScRange aCopyRange = aBlockRange; aCopyRange.aStart.SetTab(0); aCopyRange.aEnd.SetTab(nTabCount-1); pUndoDoc->CopyToDocument( aCopyRange, IDF_ATTRIB, sal_False, pDoc, &aMarkData ); // Zellhoehen und -breiten (IDF_NONE) if (bSize) { SCCOL nStartX = aBlockRange.aStart.Col(); SCROW nStartY = aBlockRange.aStart.Row(); SCTAB nStartZ = aBlockRange.aStart.Tab(); SCCOL nEndX = aBlockRange.aEnd.Col(); SCROW nEndY = aBlockRange.aEnd.Row(); SCTAB nEndZ = aBlockRange.aEnd.Tab(); pUndoDoc->CopyToDocument( nStartX, 0, 0, nEndX, MAXROW, nTabCount-1, IDF_NONE, sal_False, pDoc, &aMarkData ); pUndoDoc->CopyToDocument( 0, nStartY, 0, MAXCOL, nEndY, nTabCount-1, IDF_NONE, sal_False, pDoc, &aMarkData ); pDocShell->PostPaint( 0, 0, nStartZ, MAXCOL, MAXROW, nEndZ, PAINT_GRID | PAINT_LEFT | PAINT_TOP, SC_PF_LINES ); } else pDocShell->PostPaint( aBlockRange, PAINT_GRID, SC_PF_LINES ); EndUndo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoAutoFormat::Redo() { BeginRedo(); ScDocument* pDoc = pDocShell->GetDocument(); SCCOL nStartX = aBlockRange.aStart.Col(); SCROW nStartY = aBlockRange.aStart.Row(); SCTAB nStartZ = aBlockRange.aStart.Tab(); SCCOL nEndX = aBlockRange.aEnd.Col(); SCROW nEndY = aBlockRange.aEnd.Row(); SCTAB nEndZ = aBlockRange.aEnd.Tab(); pDoc->AutoFormat( nStartX, nStartY, nEndX, nEndY, nFormatNo, aMarkData ); if (bSize) { VirtualDevice aVirtDev; Fraction aZoomX(1,1); Fraction aZoomY = aZoomX; double nPPTX,nPPTY; ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) { ScViewData* pData = pViewShell->GetViewData(); nPPTX = pData->GetPPTX(); nPPTY = pData->GetPPTY(); aZoomX = pData->GetZoomX(); aZoomY = pData->GetZoomY(); } else { // Zoom auf 100 lassen nPPTX = ScGlobal::nScreenPPTX; nPPTY = ScGlobal::nScreenPPTY; } sal_Bool bFormula = sal_False; //! merken for (SCTAB nTab=nStartZ; nTab<=nEndZ; nTab++) { ScMarkData aDestMark; aDestMark.SelectOneTable( nTab ); aDestMark.SetMarkArea( ScRange( nStartX, nStartY, nTab, nEndX, nEndY, nTab ) ); aDestMark.MarkToMulti(); // wie SC_SIZE_VISOPT SCROW nLastRow = -1; for (SCROW nRow=nStartY; nRow<=nEndY; nRow++) { sal_uInt8 nOld = pDoc->GetRowFlags(nRow,nTab); bool bHidden = pDoc->RowHidden(nRow, nTab, nLastRow); if ( !bHidden && ( nOld & CR_MANUALSIZE ) ) pDoc->SetRowFlags( nRow, nTab, nOld & ~CR_MANUALSIZE ); } pDoc->SetOptimalHeight( nStartY, nEndY, nTab, 0, &aVirtDev, nPPTX, nPPTY, aZoomX, aZoomY, sal_False ); SCCOL nLastCol = -1; for (SCCOL nCol=nStartX; nCol<=nEndX; nCol++) if (!pDoc->ColHidden(nCol, nTab, nLastCol)) { sal_uInt16 nThisSize = STD_EXTRA_WIDTH + pDoc->GetOptimalColWidth( nCol, nTab, &aVirtDev, nPPTX, nPPTY, aZoomX, aZoomY, bFormula, &aDestMark ); pDoc->SetColWidth( nCol, nTab, nThisSize ); pDoc->ShowCol( nCol, nTab, sal_True ); } } pDocShell->PostPaint( 0, 0, nStartZ, MAXCOL, MAXROW, nEndZ, PAINT_GRID | PAINT_LEFT | PAINT_TOP, SC_PF_LINES); } else pDocShell->PostPaint( aBlockRange, PAINT_GRID, SC_PF_LINES ); EndRedo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoAutoFormat::Repeat(SfxRepeatTarget& rTarget) { if (rTarget.ISA(ScTabViewTarget)) ((ScTabViewTarget&)rTarget).GetViewShell()->AutoFormat( nFormatNo, sal_True ); } //---------------------------------------------------------------------------- sal_Bool __EXPORT ScUndoAutoFormat::CanRepeat(SfxRepeatTarget& rTarget) const { return (rTarget.ISA(ScTabViewTarget)); } //============================================================================ // class ScUndoReplace // // Ersetzen //---------------------------------------------------------------------------- ScUndoReplace::ScUndoReplace( ScDocShell* pNewDocShell, const ScMarkData& rMark, SCCOL nCurX, SCROW nCurY, SCTAB nCurZ, const String& rNewUndoStr, ScDocument* pNewUndoDoc, const SvxSearchItem* pItem ) // : ScSimpleUndo( pNewDocShell ), // aCursorPos ( nCurX, nCurY, nCurZ ), aMarkData ( rMark ), aUndoStr ( rNewUndoStr ), pUndoDoc ( pNewUndoDoc ) { pSearchItem = new SvxSearchItem( *pItem ); SetChangeTrack(); } //---------------------------------------------------------------------------- __EXPORT ScUndoReplace::~ScUndoReplace() { delete pUndoDoc; delete pSearchItem; } //---------------------------------------------------------------------------- void ScUndoReplace::SetChangeTrack() { ScDocument* pDoc = pDocShell->GetDocument(); ScChangeTrack* pChangeTrack = pDoc->GetChangeTrack(); if ( pChangeTrack ) { if ( pUndoDoc ) { //! im UndoDoc stehen nur die geaenderten Zellen, // deswegen per Iterator moeglich pChangeTrack->AppendContentsIfInRefDoc( pUndoDoc, nStartChangeAction, nEndChangeAction ); } else { nStartChangeAction = pChangeTrack->GetActionMax() + 1; ScChangeActionContent* pContent = new ScChangeActionContent( ScRange( aCursorPos) ); pContent->SetOldValue( aUndoStr, pDoc ); pContent->SetNewValue( pDoc->GetCell( aCursorPos ), pDoc ); pChangeTrack->Append( pContent ); nEndChangeAction = pChangeTrack->GetActionMax(); } } else nStartChangeAction = nEndChangeAction = 0; } //---------------------------------------------------------------------------- String __EXPORT ScUndoReplace::GetComment() const { return ScGlobal::GetRscString( STR_UNDO_REPLACE ); // "Ersetzen" } //---------------------------------------------------------------------------- void __EXPORT ScUndoReplace::Undo() { BeginUndo(); ScDocument* pDoc = pDocShell->GetDocument(); ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); ShowTable( aCursorPos.Tab() ); if (pUndoDoc) // nur bei ReplaceAll !! { DBG_ASSERT(pSearchItem->GetCommand() == SVX_SEARCHCMD_REPLACE_ALL, "ScUndoReplace:: Falscher Modus"); SetViewMarkData( aMarkData ); //! markierte Tabellen //! Bereich merken ? // Undo-Dokument hat keine Zeilen-/Spalten-Infos, also mit bColRowFlags = FALSE // kopieren, um Outline-Gruppen nicht kaputtzumachen. sal_uInt16 nUndoFlags = (pSearchItem->GetPattern()) ? IDF_ATTRIB : IDF_CONTENTS; pUndoDoc->CopyToDocument( 0, 0, 0, MAXCOL, MAXROW, MAXTAB, nUndoFlags, sal_False, pDoc, NULL, sal_False ); // ohne Row-Flags pDocShell->PostPaintGridAll(); } else if (pSearchItem->GetPattern() && pSearchItem->GetCommand() == SVX_SEARCHCMD_REPLACE) { String aTempStr = pSearchItem->GetSearchString(); // vertauschen pSearchItem->SetSearchString(pSearchItem->GetReplaceString()); pSearchItem->SetReplaceString(aTempStr); pDoc->ReplaceStyle( *pSearchItem, aCursorPos.Col(), aCursorPos.Row(), aCursorPos.Tab(), aMarkData, sal_True); pSearchItem->SetReplaceString(pSearchItem->GetSearchString()); pSearchItem->SetSearchString(aTempStr); if (pViewShell) pViewShell->MoveCursorAbs( aCursorPos.Col(), aCursorPos.Row(), SC_FOLLOW_JUMP, sal_False, sal_False ); pDocShell->PostPaintGridAll(); } else if (pSearchItem->GetCellType() == SVX_SEARCHIN_NOTE) { ScPostIt* pNote = pDoc->GetNote( aCursorPos ); DBG_ASSERT( pNote, "ScUndoReplace::Undo - cell does not contain a note" ); if (pNote) pNote->SetText( aCursorPos, aUndoStr ); if (pViewShell) pViewShell->MoveCursorAbs( aCursorPos.Col(), aCursorPos.Row(), SC_FOLLOW_JUMP, sal_False, sal_False ); } else { // #78889# aUndoStr may contain line breaks if ( aUndoStr.Search('\n') != STRING_NOTFOUND ) pDoc->PutCell( aCursorPos, new ScEditCell( aUndoStr, pDoc ) ); else pDoc->SetString( aCursorPos.Col(), aCursorPos.Row(), aCursorPos.Tab(), aUndoStr ); if (pViewShell) pViewShell->MoveCursorAbs( aCursorPos.Col(), aCursorPos.Row(), SC_FOLLOW_JUMP, sal_False, sal_False ); pDocShell->PostPaintGridAll(); } ScChangeTrack* pChangeTrack = pDoc->GetChangeTrack(); if ( pChangeTrack ) pChangeTrack->Undo( nStartChangeAction, nEndChangeAction ); EndUndo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoReplace::Redo() { BeginRedo(); ScDocument* pDoc = pDocShell->GetDocument(); ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) pViewShell->MoveCursorAbs( aCursorPos.Col(), aCursorPos.Row(), SC_FOLLOW_JUMP, sal_False, sal_False ); if (pUndoDoc) { if (pViewShell) { SetViewMarkData( aMarkData ); pViewShell->SearchAndReplace( pSearchItem, sal_False, sal_True ); } } else if (pSearchItem->GetPattern() && pSearchItem->GetCommand() == SVX_SEARCHCMD_REPLACE) { pDoc->ReplaceStyle( *pSearchItem, aCursorPos.Col(), aCursorPos.Row(), aCursorPos.Tab(), aMarkData, sal_True); pDocShell->PostPaintGridAll(); } else if (pViewShell) pViewShell->SearchAndReplace( pSearchItem, sal_False, sal_True ); SetChangeTrack(); EndRedo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoReplace::Repeat(SfxRepeatTarget& rTarget) { if (rTarget.ISA(ScTabViewTarget)) ((ScTabViewTarget&)rTarget).GetViewShell()->SearchAndReplace( pSearchItem, sal_True, sal_False ); } //---------------------------------------------------------------------------- sal_Bool __EXPORT ScUndoReplace::CanRepeat(SfxRepeatTarget& rTarget) const { return (rTarget.ISA(ScTabViewTarget)); } //============================================================================ // class ScUndoTabOp // // Mehrfachoperation (nur einfache Bloecke) //---------------------------------------------------------------------------- ScUndoTabOp::ScUndoTabOp( ScDocShell* pNewDocShell, SCCOL nStartX, SCROW nStartY, SCTAB nStartZ, SCCOL nEndX, SCROW nEndY, SCTAB nEndZ, ScDocument* pNewUndoDoc, const ScRefAddress& rFormulaCell, const ScRefAddress& rFormulaEnd, const ScRefAddress& rRowCell, const ScRefAddress& rColCell, sal_uInt8 nMd ) // : ScSimpleUndo( pNewDocShell ), // aRange ( nStartX, nStartY, nStartZ, nEndX, nEndY, nEndZ ), pUndoDoc ( pNewUndoDoc ), theFormulaCell ( rFormulaCell ), theFormulaEnd ( rFormulaEnd ), theRowCell ( rRowCell ), theColCell ( rColCell ), nMode ( nMd ) { } //---------------------------------------------------------------------------- __EXPORT ScUndoTabOp::~ScUndoTabOp() { delete pUndoDoc; } //---------------------------------------------------------------------------- String __EXPORT ScUndoTabOp::GetComment() const { return ScGlobal::GetRscString( STR_UNDO_TABOP ); // "Mehrfachoperation" } //---------------------------------------------------------------------------- void __EXPORT ScUndoTabOp::Undo() { BeginUndo(); ScUndoUtil::MarkSimpleBlock( pDocShell, aRange ); sal_uInt16 nExtFlags = 0; pDocShell->UpdatePaintExt( nExtFlags, aRange ); ScDocument* pDoc = pDocShell->GetDocument(); pDoc->DeleteAreaTab( aRange,IDF_ALL & ~IDF_NOTE ); pUndoDoc->CopyToDocument( aRange, IDF_ALL & ~IDF_NOTE, sal_False, pDoc ); pDocShell->PostPaint( aRange, PAINT_GRID, nExtFlags ); pDocShell->PostDataChanged(); ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) pViewShell->CellContentChanged(); EndUndo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoTabOp::Redo() { BeginRedo(); ScUndoUtil::MarkSimpleBlock( pDocShell, aRange ); ScTabOpParam aParam( theFormulaCell, theFormulaEnd, theRowCell, theColCell, nMode ); ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) pViewShell->TabOp( aParam, sal_False); EndRedo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoTabOp::Repeat(SfxRepeatTarget& /* rTarget */) { } //---------------------------------------------------------------------------- sal_Bool __EXPORT ScUndoTabOp::CanRepeat(SfxRepeatTarget& /* rTarget */) const { return sal_False; } //============================================================================ // class ScUndoConversion // // Spelling //---------------------------------------------------------------------------- ScUndoConversion::ScUndoConversion( ScDocShell* pNewDocShell, const ScMarkData& rMark, SCCOL nCurX, SCROW nCurY, SCTAB nCurZ, ScDocument* pNewUndoDoc, SCCOL nNewX, SCROW nNewY, SCTAB nNewZ, ScDocument* pNewRedoDoc, const ScConversionParam& rConvParam ) : ScSimpleUndo( pNewDocShell ), aMarkData( rMark ), aCursorPos( nCurX, nCurY, nCurZ ), pUndoDoc( pNewUndoDoc ), aNewCursorPos( nNewX, nNewY, nNewZ ), pRedoDoc( pNewRedoDoc ), maConvParam( rConvParam ) { SetChangeTrack(); } //---------------------------------------------------------------------------- __EXPORT ScUndoConversion::~ScUndoConversion() { delete pUndoDoc; delete pRedoDoc; } //---------------------------------------------------------------------------- void ScUndoConversion::SetChangeTrack() { ScDocument* pDoc = pDocShell->GetDocument(); ScChangeTrack* pChangeTrack = pDoc->GetChangeTrack(); if ( pChangeTrack ) { if ( pUndoDoc ) pChangeTrack->AppendContentsIfInRefDoc( pUndoDoc, nStartChangeAction, nEndChangeAction ); else { DBG_ERROR( "ScUndoConversion::SetChangeTrack: kein UndoDoc" ); nStartChangeAction = nEndChangeAction = 0; } } else nStartChangeAction = nEndChangeAction = 0; } //---------------------------------------------------------------------------- String ScUndoConversion::GetComment() const { String aText; switch( maConvParam.GetType() ) { case SC_CONVERSION_SPELLCHECK: aText = ScGlobal::GetRscString( STR_UNDO_SPELLING ); break; case SC_CONVERSION_HANGULHANJA: aText = ScGlobal::GetRscString( STR_UNDO_HANGULHANJA ); break; case SC_CONVERSION_CHINESE_TRANSL: aText = ScGlobal::GetRscString( STR_UNDO_CHINESE_TRANSLATION ); break; default: DBG_ERRORFILE( "ScUndoConversion::GetComment - unknown conversion type" ); } return aText; } //---------------------------------------------------------------------------- void ScUndoConversion::DoChange( ScDocument* pRefDoc, const ScAddress& rCursorPos ) { if (pRefDoc) { ScDocument* pDoc = pDocShell->GetDocument(); ShowTable( rCursorPos.Tab() ); SetViewMarkData( aMarkData ); SCTAB nTabCount = pDoc->GetTableCount(); // Undo/Redo-doc has only selected tables sal_Bool bMulti = aMarkData.IsMultiMarked(); pRefDoc->CopyToDocument( 0, 0, 0, MAXCOL, MAXROW, nTabCount-1, IDF_CONTENTS, bMulti, pDoc, &aMarkData ); pDocShell->PostPaintGridAll(); } else { DBG_ERROR("Kein Un-/RedoDoc bei Un-/RedoSpelling"); } } //---------------------------------------------------------------------------- void ScUndoConversion::Undo() { BeginUndo(); DoChange( pUndoDoc, aCursorPos ); ScChangeTrack* pChangeTrack = pDocShell->GetDocument()->GetChangeTrack(); if ( pChangeTrack ) pChangeTrack->Undo( nStartChangeAction, nEndChangeAction ); EndUndo(); } //---------------------------------------------------------------------------- void ScUndoConversion::Redo() { BeginRedo(); DoChange( pRedoDoc, aNewCursorPos ); SetChangeTrack(); EndRedo(); } //---------------------------------------------------------------------------- void ScUndoConversion::Repeat( SfxRepeatTarget& rTarget ) { if( rTarget.ISA( ScTabViewTarget ) ) ((ScTabViewTarget&)rTarget).GetViewShell()->DoSheetConversion( maConvParam, sal_True ); } //---------------------------------------------------------------------------- sal_Bool ScUndoConversion::CanRepeat(SfxRepeatTarget& rTarget) const { return rTarget.ISA( ScTabViewTarget ); } //============================================================================ // class ScUndoRefConversion // // cell reference conversion //---------------------------------------------------------------------------- ScUndoRefConversion::ScUndoRefConversion( ScDocShell* pNewDocShell, const ScRange& aMarkRange, const ScMarkData& rMark, ScDocument* pNewUndoDoc, ScDocument* pNewRedoDoc, sal_Bool bNewMulti, sal_uInt16 nNewFlag) : ScSimpleUndo( pNewDocShell ), aMarkData ( rMark ), pUndoDoc ( pNewUndoDoc ), pRedoDoc ( pNewRedoDoc ), aRange ( aMarkRange ), bMulti ( bNewMulti ), nFlags ( nNewFlag ) { SetChangeTrack(); } __EXPORT ScUndoRefConversion::~ScUndoRefConversion() { delete pUndoDoc; delete pRedoDoc; } String __EXPORT ScUndoRefConversion::GetComment() const { return ScGlobal::GetRscString( STR_UNDO_ENTERDATA ); // "Eingabe" } void ScUndoRefConversion::SetChangeTrack() { ScChangeTrack* pChangeTrack = pDocShell->GetDocument()->GetChangeTrack(); if ( pChangeTrack && (nFlags & IDF_FORMULA) ) pChangeTrack->AppendContentsIfInRefDoc( pUndoDoc, nStartChangeAction, nEndChangeAction ); else nStartChangeAction = nEndChangeAction = 0; } void ScUndoRefConversion::DoChange( ScDocument* pRefDoc) { ScDocument* pDoc = pDocShell->GetDocument(); ShowTable(aRange); SetViewMarkData( aMarkData ); ScRange aCopyRange = aRange; SCTAB nTabCount = pDoc->GetTableCount(); aCopyRange.aStart.SetTab(0); aCopyRange.aEnd.SetTab(nTabCount-1); pRefDoc->CopyToDocument( aCopyRange, nFlags, bMulti, pDoc, &aMarkData ); pDocShell->PostPaint( aRange, PAINT_GRID); pDocShell->PostDataChanged(); ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) pViewShell->CellContentChanged(); } void __EXPORT ScUndoRefConversion::Undo() { BeginUndo(); if (pUndoDoc) DoChange(pUndoDoc); ScChangeTrack* pChangeTrack = pDocShell->GetDocument()->GetChangeTrack(); if ( pChangeTrack ) pChangeTrack->Undo( nStartChangeAction, nEndChangeAction ); EndUndo(); } void __EXPORT ScUndoRefConversion::Redo() { BeginRedo(); if (pRedoDoc) DoChange(pRedoDoc); SetChangeTrack(); EndRedo(); } void __EXPORT ScUndoRefConversion::Repeat(SfxRepeatTarget& rTarget) { if (rTarget.ISA(ScTabViewTarget)) ((ScTabViewTarget&)rTarget).GetViewShell()->DoRefConversion(); } sal_Bool __EXPORT ScUndoRefConversion::CanRepeat(SfxRepeatTarget& rTarget) const { return (rTarget.ISA(ScTabViewTarget)); } //============================================================================ // class ScUndoRefreshLink // // Link aktualisieren / aendern //---------------------------------------------------------------------------- ScUndoRefreshLink::ScUndoRefreshLink( ScDocShell* pNewDocShell, ScDocument* pNewUndoDoc ) // : ScSimpleUndo( pNewDocShell ), // pUndoDoc( pNewUndoDoc ), pRedoDoc( NULL ) { } //---------------------------------------------------------------------------- __EXPORT ScUndoRefreshLink::~ScUndoRefreshLink() { delete pUndoDoc; delete pRedoDoc; } //---------------------------------------------------------------------------- String __EXPORT ScUndoRefreshLink::GetComment() const { return ScGlobal::GetRscString( STR_UNDO_UPDATELINK ); } //---------------------------------------------------------------------------- void __EXPORT ScUndoRefreshLink::Undo() { BeginUndo(); sal_Bool bMakeRedo = !pRedoDoc; if (bMakeRedo) pRedoDoc = new ScDocument( SCDOCMODE_UNDO ); sal_Bool bFirst = sal_True; ScDocument* pDoc = pDocShell->GetDocument(); SCTAB nCount = pDoc->GetTableCount(); for (SCTAB nTab=0; nTab<nCount; nTab++) if (pUndoDoc->HasTable(nTab)) { ScRange aRange(0,0,nTab,MAXCOL,MAXROW,nTab); if (bMakeRedo) { if (bFirst) pRedoDoc->InitUndo( pDoc, nTab, nTab, sal_True, sal_True ); else pRedoDoc->AddUndoTab( nTab, nTab, sal_True, sal_True ); bFirst = sal_False; pDoc->CopyToDocument(aRange, IDF_ALL, sal_False, pRedoDoc); // pRedoDoc->TransferDrawPage( pDoc, nTab, nTab ); pRedoDoc->SetLink( nTab, pDoc->GetLinkMode(nTab), pDoc->GetLinkDoc(nTab), pDoc->GetLinkFlt(nTab), pDoc->GetLinkOpt(nTab), pDoc->GetLinkTab(nTab), pDoc->GetLinkRefreshDelay(nTab) ); pRedoDoc->SetTabBgColor( nTab, pDoc->GetTabBgColor(nTab) ); } pDoc->DeleteAreaTab( aRange,IDF_ALL ); pUndoDoc->CopyToDocument( aRange, IDF_ALL, sal_False, pDoc ); // pDoc->TransferDrawPage( pUndoDoc, nTab, nTab ); pDoc->SetLink( nTab, pUndoDoc->GetLinkMode(nTab), pUndoDoc->GetLinkDoc(nTab), pUndoDoc->GetLinkFlt(nTab), pUndoDoc->GetLinkOpt(nTab), pUndoDoc->GetLinkTab(nTab), pUndoDoc->GetLinkRefreshDelay(nTab) ); pDoc->SetTabBgColor( nTab, pUndoDoc->GetTabBgColor(nTab) ); } pDocShell->PostPaintGridAll(); pDocShell->PostPaintExtras(); EndUndo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoRefreshLink::Redo() { DBG_ASSERT(pRedoDoc, "Kein RedoDoc bei ScUndoRefreshLink::Redo"); BeginUndo(); ScDocument* pDoc = pDocShell->GetDocument(); SCTAB nCount = pDoc->GetTableCount(); for (SCTAB nTab=0; nTab<nCount; nTab++) if (pRedoDoc->HasTable(nTab)) { ScRange aRange(0,0,nTab,MAXCOL,MAXROW,nTab); pDoc->DeleteAreaTab( aRange, IDF_ALL ); pRedoDoc->CopyToDocument( aRange, IDF_ALL, sal_False, pDoc ); // pDoc->TransferDrawPage( pRedoDoc, nTab, nTab ); pDoc->SetLink( nTab, pRedoDoc->GetLinkMode(nTab), pRedoDoc->GetLinkDoc(nTab), pRedoDoc->GetLinkFlt(nTab), pRedoDoc->GetLinkOpt(nTab), pRedoDoc->GetLinkTab(nTab), pRedoDoc->GetLinkRefreshDelay(nTab) ); pDoc->SetTabBgColor( nTab, pRedoDoc->GetTabBgColor(nTab) ); } pDocShell->PostPaintGridAll(); pDocShell->PostPaintExtras(); EndUndo(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoRefreshLink::Repeat(SfxRepeatTarget& /* rTarget */) { // gippsnich } //---------------------------------------------------------------------------- sal_Bool __EXPORT ScUndoRefreshLink::CanRepeat(SfxRepeatTarget& /* rTarget */) const { return sal_False; } //---------------------------------------------------------------------------- ScAreaLink* lcl_FindAreaLink( sfx2::LinkManager* pLinkManager, const String& rDoc, const String& rFlt, const String& rOpt, const String& rSrc, const ScRange& rDest ) { const ::sfx2::SvBaseLinks& rLinks = pLinkManager->GetLinks(); sal_uInt16 nCount = pLinkManager->GetLinks().Count(); for (sal_uInt16 i=0; i<nCount; i++) { ::sfx2::SvBaseLink* pBase = *rLinks[i]; if (pBase->ISA(ScAreaLink)) if ( ((ScAreaLink*)pBase)->IsEqual( rDoc, rFlt, rOpt, rSrc, rDest ) ) return (ScAreaLink*)pBase; } DBG_ERROR("ScAreaLink nicht gefunden"); return NULL; } //============================================================================ // class ScUndoInsertAreaLink // // Bereichs-Verknuepfung einfuegen //---------------------------------------------------------------------------- ScUndoInsertAreaLink::ScUndoInsertAreaLink( ScDocShell* pShell, const String& rDoc, const String& rFlt, const String& rOpt, const String& rArea, const ScRange& rDestRange, sal_uLong nRefresh ) // : ScSimpleUndo ( pShell ), // aDocName ( rDoc ), aFltName ( rFlt ), aOptions ( rOpt ), aAreaName ( rArea ), aRange ( rDestRange ), nRefreshDelay ( nRefresh ) { } //---------------------------------------------------------------------------- __EXPORT ScUndoInsertAreaLink::~ScUndoInsertAreaLink() { } //---------------------------------------------------------------------------- String __EXPORT ScUndoInsertAreaLink::GetComment() const { return ScGlobal::GetRscString( STR_UNDO_INSERTAREALINK ); } //---------------------------------------------------------------------------- void __EXPORT ScUndoInsertAreaLink::Undo() { ScDocument* pDoc = pDocShell->GetDocument(); sfx2::LinkManager* pLinkManager = pDoc->GetLinkManager(); ScAreaLink* pLink = lcl_FindAreaLink( pLinkManager, aDocName, aFltName, aOptions, aAreaName, aRange ); if (pLink) pLinkManager->Remove( pLink ); SFX_APP()->Broadcast( SfxSimpleHint( SC_HINT_AREALINKS_CHANGED ) ); // Navigator } //---------------------------------------------------------------------------- void __EXPORT ScUndoInsertAreaLink::Redo() { ScDocument* pDoc = pDocShell->GetDocument(); sfx2::LinkManager* pLinkManager = pDoc->GetLinkManager(); ScAreaLink* pLink = new ScAreaLink( pDocShell, aDocName, aFltName, aOptions, aAreaName, aRange.aStart, nRefreshDelay ); pLink->SetInCreate( sal_True ); pLink->SetDestArea( aRange ); pLinkManager->InsertFileLink( *pLink, OBJECT_CLIENT_FILE, aDocName, &aFltName, &aAreaName ); pLink->Update(); pLink->SetInCreate( sal_False ); SFX_APP()->Broadcast( SfxSimpleHint( SC_HINT_AREALINKS_CHANGED ) ); // Navigator } //---------------------------------------------------------------------------- void __EXPORT ScUndoInsertAreaLink::Repeat(SfxRepeatTarget& /* rTarget */) { //! .... } //---------------------------------------------------------------------------- sal_Bool __EXPORT ScUndoInsertAreaLink::CanRepeat(SfxRepeatTarget& /* rTarget */) const { return sal_False; } //============================================================================ // class ScUndoRemoveAreaLink // // Bereichs-Verknuepfung loeschen //---------------------------------------------------------------------------- ScUndoRemoveAreaLink::ScUndoRemoveAreaLink( ScDocShell* pShell, const String& rDoc, const String& rFlt, const String& rOpt, const String& rArea, const ScRange& rDestRange, sal_uLong nRefresh ) // : ScSimpleUndo ( pShell ), // aDocName ( rDoc ), aFltName ( rFlt ), aOptions ( rOpt ), aAreaName ( rArea ), aRange ( rDestRange ), nRefreshDelay ( nRefresh ) { } //---------------------------------------------------------------------------- __EXPORT ScUndoRemoveAreaLink::~ScUndoRemoveAreaLink() { } //---------------------------------------------------------------------------- String __EXPORT ScUndoRemoveAreaLink::GetComment() const { return ScGlobal::GetRscString( STR_UNDO_REMOVELINK ); //! eigener Text ?? } //---------------------------------------------------------------------------- void __EXPORT ScUndoRemoveAreaLink::Undo() { ScDocument* pDoc = pDocShell->GetDocument(); sfx2::LinkManager* pLinkManager = pDoc->GetLinkManager(); ScAreaLink* pLink = new ScAreaLink( pDocShell, aDocName, aFltName, aOptions, aAreaName, aRange.aStart, nRefreshDelay ); pLink->SetInCreate( sal_True ); pLink->SetDestArea( aRange ); pLinkManager->InsertFileLink( *pLink, OBJECT_CLIENT_FILE, aDocName, &aFltName, &aAreaName ); pLink->Update(); pLink->SetInCreate( sal_False ); SFX_APP()->Broadcast( SfxSimpleHint( SC_HINT_AREALINKS_CHANGED ) ); // Navigator } //---------------------------------------------------------------------------- void __EXPORT ScUndoRemoveAreaLink::Redo() { ScDocument* pDoc = pDocShell->GetDocument(); sfx2::LinkManager* pLinkManager = pDoc->GetLinkManager(); ScAreaLink* pLink = lcl_FindAreaLink( pLinkManager, aDocName, aFltName, aOptions, aAreaName, aRange ); if (pLink) pLinkManager->Remove( pLink ); SFX_APP()->Broadcast( SfxSimpleHint( SC_HINT_AREALINKS_CHANGED ) ); // Navigator } //---------------------------------------------------------------------------- void __EXPORT ScUndoRemoveAreaLink::Repeat(SfxRepeatTarget& /* rTarget */) { // gippsnich } //---------------------------------------------------------------------------- sal_Bool __EXPORT ScUndoRemoveAreaLink::CanRepeat(SfxRepeatTarget& /* rTarget */) const { return sal_False; } //============================================================================ // class ScUndoUpdateAreaLink // // Bereichs-Verknuepfung aktualisieren //---------------------------------------------------------------------------- ScUndoUpdateAreaLink::ScUndoUpdateAreaLink( ScDocShell* pShell, const String& rOldD, const String& rOldF, const String& rOldO, const String& rOldA, const ScRange& rOldR, sal_uLong nOldRD, const String& rNewD, const String& rNewF, const String& rNewO, const String& rNewA, const ScRange& rNewR, sal_uLong nNewRD, ScDocument* pUndo, ScDocument* pRedo, sal_Bool bDoInsert ) // : ScSimpleUndo( pShell ), // aOldDoc ( rOldD ), aOldFlt ( rOldF ), aOldOpt ( rOldO ), aOldArea ( rOldA ), aOldRange ( rOldR ), aNewDoc ( rNewD ), aNewFlt ( rNewF ), aNewOpt ( rNewO ), aNewArea ( rNewA ), aNewRange ( rNewR ), pUndoDoc ( pUndo ), pRedoDoc ( pRedo ), nOldRefresh ( nOldRD ), nNewRefresh ( nNewRD ), bWithInsert ( bDoInsert ) { DBG_ASSERT( aOldRange.aStart == aNewRange.aStart, "AreaLink verschoben ?" ); } //---------------------------------------------------------------------------- __EXPORT ScUndoUpdateAreaLink::~ScUndoUpdateAreaLink() { delete pUndoDoc; delete pRedoDoc; } //---------------------------------------------------------------------------- String __EXPORT ScUndoUpdateAreaLink::GetComment() const { return ScGlobal::GetRscString( STR_UNDO_UPDATELINK ); //! eigener Text ?? } //---------------------------------------------------------------------------- void ScUndoUpdateAreaLink::DoChange( const sal_Bool bUndo ) const { ScDocument* pDoc = pDocShell->GetDocument(); SCCOL nEndX = Max( aOldRange.aEnd.Col(), aNewRange.aEnd.Col() ); SCROW nEndY = Max( aOldRange.aEnd.Row(), aNewRange.aEnd.Row() ); SCTAB nEndZ = Max( aOldRange.aEnd.Tab(), aNewRange.aEnd.Tab() ); //? if ( bUndo ) { if ( bWithInsert ) { pDoc->FitBlock( aNewRange, aOldRange ); pDoc->DeleteAreaTab( aOldRange, IDF_ALL & ~IDF_NOTE ); pUndoDoc->UndoToDocument( aOldRange, IDF_ALL & ~IDF_NOTE, sal_False, pDoc ); } else { ScRange aCopyRange( aOldRange.aStart, ScAddress(nEndX,nEndY,nEndZ) ); pDoc->DeleteAreaTab( aCopyRange, IDF_ALL & ~IDF_NOTE ); pUndoDoc->CopyToDocument( aCopyRange, IDF_ALL & ~IDF_NOTE, sal_False, pDoc ); } } else { if ( bWithInsert ) { pDoc->FitBlock( aOldRange, aNewRange ); pDoc->DeleteAreaTab( aNewRange, IDF_ALL & ~IDF_NOTE ); pRedoDoc->CopyToDocument( aNewRange, IDF_ALL & ~IDF_NOTE, sal_False, pDoc ); } else { ScRange aCopyRange( aOldRange.aStart, ScAddress(nEndX,nEndY,nEndZ) ); pDoc->DeleteAreaTab( aCopyRange, IDF_ALL & ~IDF_NOTE ); pRedoDoc->CopyToDocument( aCopyRange, IDF_ALL & ~IDF_NOTE, sal_False, pDoc ); } } ScRange aWorkRange( aNewRange.aStart, ScAddress( nEndX, nEndY, nEndZ ) ); pDoc->ExtendMerge( aWorkRange, sal_True ); // Paint if ( aNewRange.aEnd.Col() != aOldRange.aEnd.Col() ) aWorkRange.aEnd.SetCol(MAXCOL); if ( aNewRange.aEnd.Row() != aOldRange.aEnd.Row() ) aWorkRange.aEnd.SetRow(MAXROW); if ( !pDocShell->AdjustRowHeight( aWorkRange.aStart.Row(), aWorkRange.aEnd.Row(), aWorkRange.aStart.Tab() ) ) pDocShell->PostPaint( aWorkRange, PAINT_GRID ); pDocShell->PostDataChanged(); ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) pViewShell->CellContentChanged(); } //---------------------------------------------------------------------------- void __EXPORT ScUndoUpdateAreaLink::Undo() { ScDocument* pDoc = pDocShell->GetDocument(); sfx2::LinkManager* pLinkManager = pDoc->GetLinkManager(); ScAreaLink* pLink = lcl_FindAreaLink( pLinkManager, aNewDoc, aNewFlt, aNewOpt, aNewArea, aNewRange ); if (pLink) { pLink->SetSource( aOldDoc, aOldFlt, aOldOpt, aOldArea ); // alte Werte im Link pLink->SetDestArea( aOldRange ); pLink->SetRefreshDelay( nOldRefresh ); } DoChange(sal_True); } //---------------------------------------------------------------------------- void __EXPORT ScUndoUpdateAreaLink::Redo() { ScDocument* pDoc = pDocShell->GetDocument(); sfx2::LinkManager* pLinkManager = pDoc->GetLinkManager(); ScAreaLink* pLink = lcl_FindAreaLink( pLinkManager, aOldDoc, aOldFlt, aOldOpt, aOldArea, aOldRange ); if (pLink) { pLink->SetSource( aNewDoc, aNewFlt, aNewOpt, aNewArea ); // neue Werte im Link pLink->SetDestArea( aNewRange ); pLink->SetRefreshDelay( nNewRefresh ); } DoChange(sal_False); } //---------------------------------------------------------------------------- void __EXPORT ScUndoUpdateAreaLink::Repeat(SfxRepeatTarget& /* rTarget */) { // gippsnich } //---------------------------------------------------------------------------- sal_Bool __EXPORT ScUndoUpdateAreaLink::CanRepeat(SfxRepeatTarget& /* rTarget */) const { return sal_False; }
59,714
21,835
/* MIT License Copyright (c) 2020 Dominik Kopczynski - dominik.kopczynski {at} isas.de Nils Hoffmann - nils.hoffmann {at} isas.de Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "cppgoslin/cppgoslin.h" #include <iostream> #include <string> using namespace std; using namespace goslin; int main(){ /* create instance of lipid parser containing several grammars */ LipidParser lipid_parser; /* parsing lipid name into a lipid container data structure */ string lipid_name = "PA(12:0(2OH)/14:1(3Z))"; LipidAdduct* lipid = lipid_parser.parse(lipid_name); /* checking if parsing was successful, otherwise lipid reference remains NULL */ if (lipid != NULL){ /* creating lipid name according to the recent lipid nomenclature */ cout << "input:\t\t\t\t" << lipid_name << endl; cout << "Full structure level:\t\t" << lipid->get_lipid_string(FULL_STRUCTURE) << endl; cout << "Structure defined level:\t" << lipid->get_lipid_string(STRUCTURE_DEFINED) << endl; cout << "sn-position level:\t\t" << lipid->get_lipid_string(SN_POSITION) << endl; cout << "Molecular species level:\t" << lipid->get_lipid_string(MOLECULAR_SPECIES) << endl; cout << "Species level:\t\t\t" << lipid->get_lipid_string(SPECIES) << endl; cout << "Class name:\t\t\t" << lipid->get_class_name() << endl; /* important to delete lipid to avoid memory leaks */ delete lipid; } return 0; }
2,503
834
#ifndef CLIENT_CONNECTOR_HPP #define CLIENT_CONNECTOR_HPP #include <arpa/inet.h> #include <chrono> #include <cstdint> #include <cstring> #include <iostream> #include <mutex> #include <netinet/in.h> #include <pthread.h> #include <sstream> #include <stack> #include <stdio.h> #include <stdlib.h> #include <string> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <thread> #include <unistd.h> #include <vector> #include "Logging/Logger.hpp" #include "ObserverPattern/Subject.hpp" using namespace std; class ClientConnectorThread : public Subject<string> { private: string logtag = "ClientConnectorThread"; string clientPid; string ipcClientConnectionFile; int create_socket; int new_socket; socklen_t addrlen; struct sockaddr_un address; public: ClientConnectorThread(string ipcClientConnectionFile); ~ClientConnectorThread(); void createIpcSocket(); void runClientConnectionThread(); private: bool isClientDead(string message); }; #endif /* !CLIENT_CONNECTOR_HPP */
1,054
375